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
79bcfeedd234a6724d56bad94a0e57710ab9d9c0
1,348,619,765,297
9b58bb37395972a5003e3f85661c6cb9e38771e6
/src/main/java/pl/mg/ttt/configuration/SecurityWebApplicationInitializer.java
232e04253a3b23a26a8c24bafc9ff609103fd527
[]
no_license
maciejgz/TicTacToe
https://github.com/maciejgz/TicTacToe
c2808d9ae13d6d9b9831f8ac40d8ad2ba984fdf3
c5efe9c96b5161f70c085cf35fba43faff1b4a96
refs/heads/master
2021-01-10T07:42:11.794000
2016-01-24T21:35:35
2016-01-24T21:35:35
49,374,341
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.mg.ttt.configuration; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * Created by m on 2016-01-10. */ /** * Klasa wymagana do inicjalizacji ustawień security w przypadku niezawierania konfiguracji w web.xml. bez tego konfiguracja aplikacyjna nie działa */ public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
UTF-8
Java
425
java
SecurityWebApplicationInitializer.java
Java
[ { "context": "urityWebApplicationInitializer;\n\n/**\n * Created by m on 2016-01-10.\n */\n\n/**\n * Klasa wymagana do inic", "end": 145, "score": 0.9979949593544006, "start": 144, "tag": "USERNAME", "value": "m" } ]
null
[]
package pl.mg.ttt.configuration; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * Created by m on 2016-01-10. */ /** * Klasa wymagana do inicjalizacji ustawień security w przypadku niezawierania konfiguracji w web.xml. bez tego konfiguracja aplikacyjna nie działa */ public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
425
0.820331
0.801418
13
31.538462
46.69313
147
false
false
0
0
0
0
0
0
0.153846
false
false
3
3f9df0ceb900206bdf1033d7a3da8e18d1509c5c
30,605,936,980,067
b28a72ac69495375bb7cd770cc9104fb751ff23e
/Cw11/Car.java
755e9b1073b89686b514026c5438350870ccf7ea
[]
no_license
Dmytro175/pgo2020
https://github.com/Dmytro175/pgo2020
7d038d6de3a14e9b36accf0d4ec569efca3d4734
672343f4a2db0d354f3d45a2745cb5387ebe2f1c
refs/heads/master
2021-02-10T17:05:43.573000
2020-06-15T12:19:19
2020-06-15T12:19:19
244,401,761
3
0
null
false
2020-04-12T16:37:21
2020-03-02T15:12:15
2020-04-12T16:25:51
2020-04-12T16:35:36
18
0
0
0
Java
false
false
package Cw11; class Car implements Comparable<Car>{ Integer productionYer; String name; public Car(Integer productionYer, String name) { this.productionYer = productionYer; this.name = name; } public Integer getProductionYer() { return productionYer; } @Override public int compareTo(Car car) { if (productionYer == car.getProductionYer()){ return 0; }else if (productionYer>car.getProductionYer()){ return 1; }else{ return -1; } } @Override public String toString() { return super.toString(); } }
UTF-8
Java
688
java
Car.java
Java
[]
null
[]
package Cw11; class Car implements Comparable<Car>{ Integer productionYer; String name; public Car(Integer productionYer, String name) { this.productionYer = productionYer; this.name = name; } public Integer getProductionYer() { return productionYer; } @Override public int compareTo(Car car) { if (productionYer == car.getProductionYer()){ return 0; }else if (productionYer>car.getProductionYer()){ return 1; }else{ return -1; } } @Override public String toString() { return super.toString(); } }
688
0.547965
0.540698
29
21.586206
16.52066
56
false
false
0
0
0
0
0
0
0.37931
false
false
3
13a2023d4930261caf257d70592e11d500e2e2b8
26,182,120,657,788
32c32d007dfe0031dd3d0570427fa62e6e54e37b
/app/src/main/java/com/example/gj153/myapplication/Test_fragment2.java
5ca866f36f0c411bb1a517e84e6c2a07bffe268d
[]
no_license
gj1534/Football
https://github.com/gj1534/Football
357766b00448e57da79c57b35208a46c03af072f
22ca4ce394b2bdc3e042776389dd03898f8860e1
refs/heads/master
2021-01-23T02:00:05.540000
2017-06-14T19:21:25
2017-06-14T19:21:25
85,956,137
0
0
null
false
2017-03-23T16:24:10
2017-03-23T13:59:26
2017-03-23T14:01:07
2017-03-23T16:24:09
183
0
0
0
Java
null
null
package com.example.gj153.myapplication; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; /** * Created by gj153 on 2017-06-13. */ public class Test_fragment2 extends ScrollTabHolderFragment implements NotifyingScrollView.OnScrollChangedListener { private static final String ARG_POSITION = "position"; NotifyingScrollView layout; private int mPosition; public Test_fragment2() {} public static Fragment newInstance(int position) { Test_fragment2 f = new Test_fragment2(); Bundle b = new Bundle(); b.putInt(ARG_POSITION, position); f.setArguments(b); return f; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPosition = 1; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { layout = (NotifyingScrollView)inflater.inflate(R.layout.team_photo,container, false); layout.setOnScrollChangedListener(this); return layout; } @Override public void adjustScroll(int scrollHeight, int headerTranslationY) { layout.setScrollY(headerTranslationY - scrollHeight); } @Override public void onScrollChanged(ScrollView view, int l, int t, int oldl, int oldt) { if (mScrollTabHolder != null) mScrollTabHolder.onScroll(view, l, t, oldl, oldt, mPosition); } }
UTF-8
Java
1,644
java
Test_fragment2.java
Java
[ { "context": "package com.example.gj153.myapplication;\n\nimport android.os.Bundle;\nimport ", "end": 25, "score": 0.9041519165039062, "start": 20, "tag": "USERNAME", "value": "gj153" }, { "context": "port android.widget.ScrollView;\n\n/**\n * Created by gj153 on 2017-06-13.\n */\n\npublic class Test_fragment2 e", "end": 303, "score": 0.9995721578598022, "start": 298, "tag": "USERNAME", "value": "gj153" } ]
null
[]
package com.example.gj153.myapplication; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; /** * Created by gj153 on 2017-06-13. */ public class Test_fragment2 extends ScrollTabHolderFragment implements NotifyingScrollView.OnScrollChangedListener { private static final String ARG_POSITION = "position"; NotifyingScrollView layout; private int mPosition; public Test_fragment2() {} public static Fragment newInstance(int position) { Test_fragment2 f = new Test_fragment2(); Bundle b = new Bundle(); b.putInt(ARG_POSITION, position); f.setArguments(b); return f; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPosition = 1; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { layout = (NotifyingScrollView)inflater.inflate(R.layout.team_photo,container, false); layout.setOnScrollChangedListener(this); return layout; } @Override public void adjustScroll(int scrollHeight, int headerTranslationY) { layout.setScrollY(headerTranslationY - scrollHeight); } @Override public void onScrollChanged(ScrollView view, int l, int t, int oldl, int oldt) { if (mScrollTabHolder != null) mScrollTabHolder.onScroll(view, l, t, oldl, oldt, mPosition); } }
1,644
0.709246
0.69708
56
28.357143
28.545971
116
false
false
0
0
0
0
0
0
0.678571
false
false
3
2d365421402046652630c206944ecccdbc0a36d8
13,606,456,414,223
1b9ac717e7739a93aa376082b599bc8c699197ef
/AccountSystemLogic/src/main/java/za/ac/nwu/as/logic/flow/impl/FetchAccountTypeFlowImpl.java
0169bc1f989a8cc927a254492b22b48a8d46ba3d
[]
no_license
aEtheRAx/AccountingSystem
https://github.com/aEtheRAx/AccountingSystem
6d3e4152d0e36ab3de41be523f8b6604533a2ac4
39eb4acd5e679783f1c9d80c5fcc005555bf11ba
refs/heads/master
2023-08-20T17:25:14.255000
2021-10-11T17:44:11
2021-10-11T17:44:11
409,541,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package za.ac.nwu.as.logic.flow.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import za.ac.nwu.as.domain.dto.AccountTypeDto; import za.ac.nwu.as.domain.persistence.AccountType; import za.ac.nwu.as.logic.flow.FetchAccountTypeFlow; import za.ac.nwu.as.translator.AccountTypeTranslator; import javax.transaction.Transactional; import java.util.List; @Transactional @Component public class FetchAccountTypeFlowImpl implements FetchAccountTypeFlow { private final AccountTypeTranslator accountTranslator; @Autowired public FetchAccountTypeFlowImpl(AccountTypeTranslator accountTypeTranslator){ this.accountTranslator = accountTypeTranslator; } @Override public List<AccountTypeDto> getAllAccountTypes(){ return accountTranslator.getAllAccountTypes(); } @Override public AccountTypeDto getAccountTypeByMnemonic(String mnemonic) { return accountTranslator.getAccountTypeByMnemonicNativeQuery(mnemonic); } @Override public AccountType getAccountTypeDbEntityByMnemonic(String accountTypeMnemonic) { return accountTranslator.getAccountTypeDbEntityByMnemonic(accountTypeMnemonic); } public boolean methodToTest() { return true; } }
UTF-8
Java
1,302
java
FetchAccountTypeFlowImpl.java
Java
[]
null
[]
package za.ac.nwu.as.logic.flow.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import za.ac.nwu.as.domain.dto.AccountTypeDto; import za.ac.nwu.as.domain.persistence.AccountType; import za.ac.nwu.as.logic.flow.FetchAccountTypeFlow; import za.ac.nwu.as.translator.AccountTypeTranslator; import javax.transaction.Transactional; import java.util.List; @Transactional @Component public class FetchAccountTypeFlowImpl implements FetchAccountTypeFlow { private final AccountTypeTranslator accountTranslator; @Autowired public FetchAccountTypeFlowImpl(AccountTypeTranslator accountTypeTranslator){ this.accountTranslator = accountTypeTranslator; } @Override public List<AccountTypeDto> getAllAccountTypes(){ return accountTranslator.getAllAccountTypes(); } @Override public AccountTypeDto getAccountTypeByMnemonic(String mnemonic) { return accountTranslator.getAccountTypeByMnemonicNativeQuery(mnemonic); } @Override public AccountType getAccountTypeDbEntityByMnemonic(String accountTypeMnemonic) { return accountTranslator.getAccountTypeDbEntityByMnemonic(accountTypeMnemonic); } public boolean methodToTest() { return true; } }
1,302
0.78725
0.78725
41
30.756098
28.499704
87
false
false
0
0
0
0
0
0
0.365854
false
false
3
903c8bc3585b1114d4f1cd5455b74d36952bf9a1
1,984,274,925,485
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_f6dd9145dfd16bbbd2957ea9e844f74c74b38b77/EmployeeDaoImpl/2_f6dd9145dfd16bbbd2957ea9e844f74c74b38b77_EmployeeDaoImpl_t.java
d6cffb89f949a6b2a3c8d31f9e961ef7eaed8299
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/************************************************************************** * Copyright (c) 2013 2359 Media Pvt Ltd * * NOTICE: All information contained herein is, and remains the * property of 2359 Media Pvt Ltd and its suppliers, if any. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from 2359 Media Pvt Ltd ***************************************************************************/ package com.media2359.euphoria.dao.employee; /** * EmployeeDaoImpl * * TODO Write something about this class * * @author Praveen * @version 1.0 2013 **/ import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.media2359.euphoria.model.employee.Employee; @Repository @Transactional(readOnly = true) public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao { private final Logger log = Logger.getLogger(EmployeeDaoImpl.class); @Autowired public EmployeeDaoImpl(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } @SuppressWarnings("unchecked") public List<Employee> getAllEmployees() { List<Employee> employeeList = new ArrayList<Employee>(); Employee emp1 = new Employee(); emp1.setName("Alfred"); emp1.setCompanyEmail("alfred@companyemail.com"); emp1.setEmploymentType("Permenant"); emp1.setDesignation("System Architect"); emp1.setPlatForms("Rails,iOS,HTML,Android"); emp1.setMobile("99999988"); emp1.setPersonalEmail("alfred@personalemail.com"); employeeList.add(emp1); Employee emp2 = new Employee(); emp2.setName("Lung Sen"); emp2.setCompanyEmail("lungsen@companyemail.com"); emp2.setEmploymentType("Hourly"); emp2.setDesignation("Developer"); emp2.setPlatForms("HTML,Android"); emp2.setMobile("99998988"); emp2.setPersonalEmail("lungsen@personalemail.com"); employeeList.add(emp2); Employee emp3 = new Employee(); emp3.setName("May"); emp3.setCompanyEmail("may@companyemail.com"); emp3.setEmploymentType("Conntract"); emp3.setDesignation("Developer"); emp3.setPlatForms("Rails,iOS"); emp3.setMobile("99898988"); emp3.setPersonalEmail("may@personalemail.com"); employeeList.add(emp3); Employee emp4 = new Employee(); emp4.setName("TY"); emp4.setCompanyEmail("may@companyemail.com"); emp4.setEmploymentType("Permenant"); emp4.setDesignation("Developer"); emp4.setPlatForms("HTML,iOS"); emp4.setMobile("99898988"); emp4.setPersonalEmail("may@personalemail.com"); employeeList.add(emp4); Employee emp5 = new Employee(); emp5.setName("Praveen"); emp5.setCompanyEmail("praveen@companyemail.com"); emp5.setEmploymentType("Hourly"); emp5.setDesignation("Developer"); emp5.setPlatForms("HTML,iOS"); emp5.setMobile("98898988"); emp5.setPersonalEmail("praveen@personalemail.com"); employeeList.add(emp5); Employee emp6 = new Employee(); emp6.setName("Shiv"); emp6.setCompanyEmail("shiv@companyemail.com"); emp6.setEmploymentType("Permenant"); emp6.setDesignation("PM"); emp6.setPlatForms("Rails,iOS,HTML,Android"); emp6.setMobile("98888988"); emp6.setPersonalEmail("shiv@personalemail.com"); employeeList.add(emp6); return employeeList; } }
UTF-8
Java
3,727
java
2_f6dd9145dfd16bbbd2957ea9e844f74c74b38b77_EmployeeDaoImpl_t.java
Java
[ { "context": " Write something about this class\n * \n * @author Praveen\n * @version 1.0 2013\n **/\n \n import java.util.A", "end": 642, "score": 0.9998697638511658, "start": 635, "tag": "NAME", "value": "Praveen" }, { "context": "mployee emp1 = new Employee();\n \t\t emp1.setName(\"Alfred\");\n \t\t emp1.setCompanyEmail(\"alfred@companyemail.", "end": 1636, "score": 0.9998300671577454, "start": 1630, "tag": "NAME", "value": "Alfred" }, { "context": "emp1.setName(\"Alfred\");\n \t\t emp1.setCompanyEmail(\"alfred@companyemail.com\");\n \t\t emp1.setEmploymentType(\"Permenant\");\n \t\t e", "end": 1689, "score": 0.9999296069145203, "start": 1666, "tag": "EMAIL", "value": "alfred@companyemail.com" }, { "context": "setMobile(\"99999988\");\n \t\t emp1.setPersonalEmail(\"alfred@personalemail.com\");\n \t\t employeeList.add(emp1);\n \t\t \n \t\t Employee ", "end": 1911, "score": 0.9999290108680725, "start": 1887, "tag": "EMAIL", "value": "alfred@personalemail.com" }, { "context": "mployee emp2 = new Employee();\n \t\t emp2.setName(\"Lung Sen\");\n \t\t emp2.setCompanyEmail(\"lungsen@companyemail", "end": 2011, "score": 0.9991903305053711, "start": 2003, "tag": "NAME", "value": "Lung Sen" }, { "context": "p2.setName(\"Lung Sen\");\n \t\t emp2.setCompanyEmail(\"lungsen@companyemail.com\");\n \t\t emp2.setEmploymentType(\"Hourly\");\n \t\t emp2", "end": 2065, "score": 0.999927282333374, "start": 2041, "tag": "EMAIL", "value": "lungsen@companyemail.com" }, { "context": "setMobile(\"99998988\");\n \t\t emp2.setPersonalEmail(\"lungsen@personalemail.com\");\n \t\t employeeList.add(emp2);\n \t\t \n \t\t Employee ", "end": 2268, "score": 0.9999285936355591, "start": 2243, "tag": "EMAIL", "value": "lungsen@personalemail.com" }, { "context": "mployee emp3 = new Employee();\n \t\t emp3.setName(\"May\");\n \t\t emp3.setCompanyEmail(\"may@companyemail.com", "end": 2363, "score": 0.9989312887191772, "start": 2360, "tag": "NAME", "value": "May" }, { "context": "\t\t emp3.setName(\"May\");\n \t\t emp3.setCompanyEmail(\"may@companyemail.com\");\n \t\t emp3.setEmploymentType(\"Conntract\");\n \t\t e", "end": 2413, "score": 0.999927818775177, "start": 2393, "tag": "EMAIL", "value": "may@companyemail.com" }, { "context": "setMobile(\"99898988\");\n \t\t emp3.setPersonalEmail(\"may@personalemail.com\");\n \t\t employeeList.add(emp3);\n \t\t \n \t\t Employee ", "end": 2612, "score": 0.9999281764030457, "start": 2591, "tag": "EMAIL", "value": "may@personalemail.com" }, { "context": "mployee emp4 = new Employee();\n \t\t emp4.setName(\"TY\");\n \t\t emp4.setCompanyEmail(\"may@companyemail.com", "end": 2706, "score": 0.995940089225769, "start": 2704, "tag": "NAME", "value": "TY" }, { "context": " \t\t emp4.setName(\"TY\");\n \t\t emp4.setCompanyEmail(\"may@companyemail.com\");\n \t\t emp4.setEmploymentType(\"Permenant\");\n \t\t e", "end": 2756, "score": 0.9999275803565979, "start": 2736, "tag": "EMAIL", "value": "may@companyemail.com" }, { "context": "setMobile(\"99898988\");\n \t\t emp4.setPersonalEmail(\"may@personalemail.com\");\n \t\t employeeList.add(emp4);\n \t\t \n \t\t Employee ", "end": 2954, "score": 0.9999293088912964, "start": 2933, "tag": "EMAIL", "value": "may@personalemail.com" }, { "context": "mployee emp5 = new Employee();\n \t\t emp5.setName(\"Praveen\");\n \t\t emp5.setCompanyEmail(\"praveen@companyemail", "end": 3053, "score": 0.9996738433837891, "start": 3046, "tag": "NAME", "value": "Praveen" }, { "context": "mp5.setName(\"Praveen\");\n \t\t emp5.setCompanyEmail(\"praveen@companyemail.com\");\n \t\t emp5.setEmploymentType(\"Hourly\");\n \t\t emp5", "end": 3107, "score": 0.9999279975891113, "start": 3083, "tag": "EMAIL", "value": "praveen@companyemail.com" }, { "context": "setMobile(\"98898988\");\n \t\t emp5.setPersonalEmail(\"praveen@personalemail.com\");\n \t\t employeeList.add(emp5);\n \t\t \n \t\t Employee ", "end": 3306, "score": 0.9999295473098755, "start": 3281, "tag": "EMAIL", "value": "praveen@personalemail.com" }, { "context": "mployee emp6 = new Employee();\n \t\t emp6.setName(\"Shiv\");\n \t\t emp6.setCompanyEmail(\"shiv@companyemail.co", "end": 3402, "score": 0.9995076060295105, "start": 3398, "tag": "NAME", "value": "Shiv" }, { "context": "\t emp6.setName(\"Shiv\");\n \t\t emp6.setCompanyEmail(\"shiv@companyemail.com\");\n \t\t emp6.setEmploymentType(\"Permenant\");\n\t\t em", "end": 3453, "score": 0.9999284744262695, "start": 3432, "tag": "EMAIL", "value": "shiv@companyemail.com" }, { "context": "setMobile(\"98888988\");\n \t\t emp6.setPersonalEmail(\"shiv@personalemail.com\");\n \t\t employeeList.add(emp6);\n \t\t \n \t\t return em", "end": 3658, "score": 0.9999279379844666, "start": 3636, "tag": "EMAIL", "value": "shiv@personalemail.com" } ]
null
[]
/************************************************************************** * Copyright (c) 2013 2359 Media Pvt Ltd * * NOTICE: All information contained herein is, and remains the * property of 2359 Media Pvt Ltd and its suppliers, if any. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from 2359 Media Pvt Ltd ***************************************************************************/ package com.media2359.euphoria.dao.employee; /** * EmployeeDaoImpl * * TODO Write something about this class * * @author Praveen * @version 1.0 2013 **/ import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.media2359.euphoria.model.employee.Employee; @Repository @Transactional(readOnly = true) public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao { private final Logger log = Logger.getLogger(EmployeeDaoImpl.class); @Autowired public EmployeeDaoImpl(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } @SuppressWarnings("unchecked") public List<Employee> getAllEmployees() { List<Employee> employeeList = new ArrayList<Employee>(); Employee emp1 = new Employee(); emp1.setName("Alfred"); emp1.setCompanyEmail("<EMAIL>"); emp1.setEmploymentType("Permenant"); emp1.setDesignation("System Architect"); emp1.setPlatForms("Rails,iOS,HTML,Android"); emp1.setMobile("99999988"); emp1.setPersonalEmail("<EMAIL>"); employeeList.add(emp1); Employee emp2 = new Employee(); emp2.setName("<NAME>"); emp2.setCompanyEmail("<EMAIL>"); emp2.setEmploymentType("Hourly"); emp2.setDesignation("Developer"); emp2.setPlatForms("HTML,Android"); emp2.setMobile("99998988"); emp2.setPersonalEmail("<EMAIL>"); employeeList.add(emp2); Employee emp3 = new Employee(); emp3.setName("May"); emp3.setCompanyEmail("<EMAIL>"); emp3.setEmploymentType("Conntract"); emp3.setDesignation("Developer"); emp3.setPlatForms("Rails,iOS"); emp3.setMobile("99898988"); emp3.setPersonalEmail("<EMAIL>"); employeeList.add(emp3); Employee emp4 = new Employee(); emp4.setName("TY"); emp4.setCompanyEmail("<EMAIL>"); emp4.setEmploymentType("Permenant"); emp4.setDesignation("Developer"); emp4.setPlatForms("HTML,iOS"); emp4.setMobile("99898988"); emp4.setPersonalEmail("<EMAIL>"); employeeList.add(emp4); Employee emp5 = new Employee(); emp5.setName("Praveen"); emp5.setCompanyEmail("<EMAIL>"); emp5.setEmploymentType("Hourly"); emp5.setDesignation("Developer"); emp5.setPlatForms("HTML,iOS"); emp5.setMobile("98898988"); emp5.setPersonalEmail("<EMAIL>"); employeeList.add(emp5); Employee emp6 = new Employee(); emp6.setName("Shiv"); emp6.setCompanyEmail("<EMAIL>"); emp6.setEmploymentType("Permenant"); emp6.setDesignation("PM"); emp6.setPlatForms("Rails,iOS,HTML,Android"); emp6.setMobile("98888988"); emp6.setPersonalEmail("<EMAIL>"); employeeList.add(emp6); return employeeList; } }
3,539
0.687684
0.651731
109
33.183487
20.420427
82
false
false
0
0
0
0
0
0
1.990826
false
false
3
fb68352a94c51f2459abe37c01cf4de9097a9e32
27,908,697,548,004
ae2f6e708a761c322f34b9ca65e94cb6037319e2
/simu_base_common - final/simu_base_common/src/enstabretagne/base/math/MoreRandom.java
284d0f2bf774168e76f1bf3118f11d118c064f34
[]
no_license
JMK-22/simulation
https://github.com/JMK-22/simulation
72c7ad070f7b81d75d5302aab34c2883967f25d8
5b066c355c801047c007fe93d19fe46caaf46fa6
refs/heads/master
2020-12-19T19:11:02.622000
2020-01-31T11:13:38
2020-01-31T11:13:38
235,824,314
0
3
null
false
2020-01-29T15:40:45
2020-01-23T15:29:06
2020-01-29T15:40:18
2020-01-29T15:40:44
354
0
2
0
Java
false
false
/** * Classe MoreRandom.java *@author Olivier VERRON *@version 1.0. */ /** * Fournit les classes nécessaires pour effectuer * des simulations à événements discrets basiques. * @author Pascal CANTOT (cantot@wanadoo.fr] * @version 1.0 */ package enstabretagne.base.math; import java.util.Random; import java.lang.System; // TODO: Auto-generated Javadoc /** * Etend les fonctions de génération de nombre aléatoires. * Fournit notamment des générateurs suivant différentes lois. * * @author cantot@wanadoo.fr * @see java.util.Random */ public class MoreRandom extends Random { /** The Constant serialVersionUID. */ public static final long serialVersionUID = 1L; /** The global seed. */ public static long globalSeed=0; /** The initial seed. */ private static long initialSeed = 0L; /** * Constructeur par défaut. * Le générateur aléatoire sera initialisé avec un germe "aléaloire" (horloge système) */ public MoreRandom() { super(); initialSeed = globalSeed; } /** * Constructeur initialisé avec un germe aléatoire explicité. * @param seed germe. */ public MoreRandom(long seed) { super(seed); initialSeed = seed; } /** * Réinitialise le germe à la valeur indiquée. * @param seed germe. */ public void setSeed(long seed) { super.setSeed(seed); initialSeed = seed; } /** * Retourne le germe initial. * @return germe. */ public long getSeed() { return initialSeed; } /** * Initialise le germe à une valeur aléatoire, * construite à partir de l'heure système. * Fournit une valeur de germe différente du germe précédent à chaque exécution, * même lors de deux appels se succédant à moins d'une milliseconde d'écart. * @return la valeur du germe. */ public long randomize() { long newSeed; // Boucle pour éviter d'avoir un germe identique si appels trop rapprochés. // Inconvénient: prend jusqu'à 1ms maxi à s'exécuter (rarement) // Avantage: très rapide dans la plupart des cas // (donc peut-être mieux qu'un thread.sleep(1);) do { newSeed = System.currentTimeMillis(); } while (newSeed == initialSeed); setSeed(newSeed); return newSeed; } /** * Générateur pseudo-aléatoire suivant la loi uniforme sur [0,1]. * @return un nombre pseudo-aléatoire entre 0.0 et 1.0, suivant la loi uniforme */ public double nextUniform() { return super.nextDouble(); } /** * Générateur pseudo-aléatoire suivant la loi uniforme sur [a,b]. * * @param a the a * @param b the b * @return un nombre pseudo-aléatoire entre <code>a</code> et <code>b</code>, * suivant la loi uniforme */ public double nextUniform(double a, double b) { return a + (b-a)*nextDouble(); } /** * Générateur pseudo-aléatoire suivant la loi triangulaire. * @param a borne inférieure; * @param b abscisse de la densité de probabilité maximale; * @param c borne supérieure. * @return un nombre pseudo-aléatoir entre <code>a</code> et <code>c</code> * suivant une loi triangulaire(a,b,c). */ public double nextTriangle(double a, double b, double c) { double beta; double t; double u; // Méthode de la transformée inverse u = nextUniform(); beta = (b-a)/(c-a); if (u < beta) t = Math.sqrt(beta*u); else t = 1.0 - Math.sqrt((1-beta)*(1-u)); return a + (c-a)*t; } /** * Générateur pseudo-aléatoire suivant la loi exponentielle. * @param lambda paramètre de la loi * @return un nombre pseudo-aléatoir suivant la loi exponentielle. */ public double nextExp(double lambda) { return (-1.0/lambda)*Math.log(1-nextUniform()); } /** * Do test. */ private static void doTest() { int i; MoreRandom alea = new MoreRandom(); System.out.println("*** TEST CLASSE moreRandom ***"); // Teste les générateurs System.out.print("Loi uniforme [0;1]: "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Loi uniforme [-10;10]: "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform(-10.0,10.0)); System.out.println(); System.out.print("Après changement de germe: "); alea.setSeed(1234L); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Après randomize: "); alea.randomize(); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Après randomize (bis): "); alea.randomize(); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Après reprise du germe: "); alea.setSeed(1234L); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Loi triangulaire(0,5,10): "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextTriangle(0,5,10)); System.out.println(); System.out.print("Loi exponentielle(1.0/10.0): "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextExp(1.0/10.0)); System.out.println(); } /** * The main method. * * @param args the arguments */ public static void main(String[] args) { doTest(); } } // Class MoreRandom
ISO-8859-1
Java
5,782
java
MoreRandom.java
Java
[ { "context": "/**\n* Classe MoreRandom.java\n*@author Olivier VERRON\n*@version 1.0.\n*/\n/**\n * Fournit les classes néce", "end": 52, "score": 0.9998598098754883, "start": 38, "tag": "NAME", "value": "Olivier VERRON" }, { "context": "tions à événements discrets basiques.\n * @author \tPascal CANTOT (cantot@wanadoo.fr]\n * @version\t1.0\n */\npackage e", "end": 201, "score": 0.9998652338981628, "start": 188, "tag": "NAME", "value": "Pascal CANTOT" }, { "context": "nts discrets basiques.\n * @author \tPascal CANTOT (cantot@wanadoo.fr]\n * @version\t1.0\n */\npackage enstabretagne.base.m", "end": 220, "score": 0.9999078512191772, "start": 203, "tag": "EMAIL", "value": "cantot@wanadoo.fr" }, { "context": "énérateurs suivant différentes lois.\n *\n * @author cantot@wanadoo.fr\n * @see java.util.Random\n */\npublic class MoreRan", "end": 519, "score": 0.999931275844574, "start": 502, "tag": "EMAIL", "value": "cantot@wanadoo.fr" }, { "context": "la densité de probabilité maximale;\n\t\t * @param\tc\tborne supérieure.\n\t\t * @return\tun nombre pseudo-aléatoir entre <co", "end": 2990, "score": 0.9997016787528992, "start": 2974, "tag": "NAME", "value": "borne supérieure" } ]
null
[]
/** * Classe MoreRandom.java *@author <NAME> *@version 1.0. */ /** * Fournit les classes nécessaires pour effectuer * des simulations à événements discrets basiques. * @author <NAME> (<EMAIL>] * @version 1.0 */ package enstabretagne.base.math; import java.util.Random; import java.lang.System; // TODO: Auto-generated Javadoc /** * Etend les fonctions de génération de nombre aléatoires. * Fournit notamment des générateurs suivant différentes lois. * * @author <EMAIL> * @see java.util.Random */ public class MoreRandom extends Random { /** The Constant serialVersionUID. */ public static final long serialVersionUID = 1L; /** The global seed. */ public static long globalSeed=0; /** The initial seed. */ private static long initialSeed = 0L; /** * Constructeur par défaut. * Le générateur aléatoire sera initialisé avec un germe "aléaloire" (horloge système) */ public MoreRandom() { super(); initialSeed = globalSeed; } /** * Constructeur initialisé avec un germe aléatoire explicité. * @param seed germe. */ public MoreRandom(long seed) { super(seed); initialSeed = seed; } /** * Réinitialise le germe à la valeur indiquée. * @param seed germe. */ public void setSeed(long seed) { super.setSeed(seed); initialSeed = seed; } /** * Retourne le germe initial. * @return germe. */ public long getSeed() { return initialSeed; } /** * Initialise le germe à une valeur aléatoire, * construite à partir de l'heure système. * Fournit une valeur de germe différente du germe précédent à chaque exécution, * même lors de deux appels se succédant à moins d'une milliseconde d'écart. * @return la valeur du germe. */ public long randomize() { long newSeed; // Boucle pour éviter d'avoir un germe identique si appels trop rapprochés. // Inconvénient: prend jusqu'à 1ms maxi à s'exécuter (rarement) // Avantage: très rapide dans la plupart des cas // (donc peut-être mieux qu'un thread.sleep(1);) do { newSeed = System.currentTimeMillis(); } while (newSeed == initialSeed); setSeed(newSeed); return newSeed; } /** * Générateur pseudo-aléatoire suivant la loi uniforme sur [0,1]. * @return un nombre pseudo-aléatoire entre 0.0 et 1.0, suivant la loi uniforme */ public double nextUniform() { return super.nextDouble(); } /** * Générateur pseudo-aléatoire suivant la loi uniforme sur [a,b]. * * @param a the a * @param b the b * @return un nombre pseudo-aléatoire entre <code>a</code> et <code>b</code>, * suivant la loi uniforme */ public double nextUniform(double a, double b) { return a + (b-a)*nextDouble(); } /** * Générateur pseudo-aléatoire suivant la loi triangulaire. * @param a borne inférieure; * @param b abscisse de la densité de probabilité maximale; * @param c <NAME>. * @return un nombre pseudo-aléatoir entre <code>a</code> et <code>c</code> * suivant une loi triangulaire(a,b,c). */ public double nextTriangle(double a, double b, double c) { double beta; double t; double u; // Méthode de la transformée inverse u = nextUniform(); beta = (b-a)/(c-a); if (u < beta) t = Math.sqrt(beta*u); else t = 1.0 - Math.sqrt((1-beta)*(1-u)); return a + (c-a)*t; } /** * Générateur pseudo-aléatoire suivant la loi exponentielle. * @param lambda paramètre de la loi * @return un nombre pseudo-aléatoir suivant la loi exponentielle. */ public double nextExp(double lambda) { return (-1.0/lambda)*Math.log(1-nextUniform()); } /** * Do test. */ private static void doTest() { int i; MoreRandom alea = new MoreRandom(); System.out.println("*** TEST CLASSE moreRandom ***"); // Teste les générateurs System.out.print("Loi uniforme [0;1]: "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Loi uniforme [-10;10]: "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform(-10.0,10.0)); System.out.println(); System.out.print("Après changement de germe: "); alea.setSeed(1234L); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Après randomize: "); alea.randomize(); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Après randomize (bis): "); alea.randomize(); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Après reprise du germe: "); alea.setSeed(1234L); System.out.println("(germe:" + alea.getSeed()+ ")"); for (i=0; i<10; i++) System.out.print(" " + alea.nextUniform()); System.out.println(); System.out.print("Loi triangulaire(0,5,10): "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextTriangle(0,5,10)); System.out.println(); System.out.print("Loi exponentielle(1.0/10.0): "); System.out.println(); for (i=0; i<10; i++) System.out.print(" " + alea.nextExp(1.0/10.0)); System.out.println(); } /** * The main method. * * @param args the arguments */ public static void main(String[] args) { doTest(); } } // Class MoreRandom
5,736
0.628657
0.613943
234
23.380342
21.351068
88
false
false
0
0
0
0
0
0
2.58547
false
false
3
d0ed841ec4a708c9a68a626a14aea4f04dab39e0
25,168,508,413,379
24368db595f8976c44d26542c0a24d76104a52e9
/src/dk/itu/pls/ocal2gcal/LockFailedException.java
55735e5a616cc50fa8aa3e810e2293a7c3494476
[]
no_license
zhangzhichao1985/Ocal2Gcal
https://github.com/zhangzhichao1985/Ocal2Gcal
9fda29b026fb8862a7087e0e67d2abdefe05d3dc
f6d08dcb67a0eb23690bd8969b764d0f3ab2ec5b
refs/heads/master
2021-01-20T23:44:24.233000
2010-07-23T16:02:11
2010-07-23T16:02:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package dk.itu.pls.ocal2gcal; /** Exception indicating that an attempt to obtain a * lock in an SQL database failed. * @author panic * */ public class LockFailedException extends Exception { /** * */ public LockFailedException () { } /** * @param message */ public LockFailedException (String message) { super (message); } /** * @param cause */ public LockFailedException (Throwable cause) { super (cause); } /** * @param message * @param cause */ public LockFailedException (String message, Throwable cause) { super (message, cause); } }
UTF-8
Java
625
java
LockFailedException.java
Java
[ { "context": "in a\n * lock in an SQL database failed.\n * @author panic\n *\n */\npublic class LockFailedException extends E", "end": 147, "score": 0.9876054525375366, "start": 142, "tag": "USERNAME", "value": "panic" } ]
null
[]
/** * */ package dk.itu.pls.ocal2gcal; /** Exception indicating that an attempt to obtain a * lock in an SQL database failed. * @author panic * */ public class LockFailedException extends Exception { /** * */ public LockFailedException () { } /** * @param message */ public LockFailedException (String message) { super (message); } /** * @param cause */ public LockFailedException (Throwable cause) { super (cause); } /** * @param message * @param cause */ public LockFailedException (String message, Throwable cause) { super (message, cause); } }
625
0.6144
0.6128
41
14.243902
17.175962
64
false
false
0
0
0
0
0
0
0.146341
false
false
3
2c9bab060f61b6bc1016b9383e7161beb2405eec
18,253,611,011,929
eb896b8bc69062a02b433606c6c9e87bf9a81c08
/src/main/java/tv/lycam/model/StreamResponseModel.java
51488e207af7816535eb5486eaf5e37e7fe81e65
[ "MIT" ]
permissive
Cheng-Bin/lycamplus-java-sdk
https://github.com/Cheng-Bin/lycamplus-java-sdk
31a2fa7b0c77e55f9076c453c4e6378af5870d8f
42ee51534e2a1ec1f940ef2914d389b79a98ed99
refs/heads/master
2021-01-11T19:05:31.413000
2017-01-23T09:11:57
2017-01-23T09:11:57
79,215,513
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tv.lycam.model; import java.io.Serializable; import java.util.Arrays; /** * Created by lycamandroid on 17/1/19. */ public class StreamResponseModel extends StreamRequestModel implements Serializable { private String streamId; private String status; private StreamURLModel[] streamUrls; private String resourceUrl; private String streamType; private String chatUrl; private String chatChannel; private String chatToken; private String uploadUrl; private int videoWidth; private int videoHeight; private String timeStarted; private String timeFinished; public String getStreamId() { return streamId; } public void setStreamId(String streamId) { this.streamId = streamId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public StreamURLModel[] getStreamUrls() { return streamUrls; } public void setStreamUrls(StreamURLModel[] streamUrls) { this.streamUrls = streamUrls; } public String getResourceUrl() { return resourceUrl; } public void setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; } public String getStreamType() { return streamType; } public void setStreamType(String streamType) { this.streamType = streamType; } public String getChatUrl() { return chatUrl; } public void setChatUrl(String chatUrl) { this.chatUrl = chatUrl; } public String getChatChannel() { return chatChannel; } public void setChatChannel(String chatChannel) { this.chatChannel = chatChannel; } public String getChatToken() { return chatToken; } public void setChatToken(String chatToken) { this.chatToken = chatToken; } public String getUploadUrl() { return uploadUrl; } public void setUploadUrl(String uploadUrl) { this.uploadUrl = uploadUrl; } public int getVideoWidth() { return videoWidth; } public void setVideoWidth(int videoWidth) { this.videoWidth = videoWidth; } public int getVideoHeight() { return videoHeight; } public void setVideoHeight(int videoHeight) { this.videoHeight = videoHeight; } public String getTimeStarted() { return timeStarted; } public void setTimeStarted(String timeStarted) { this.timeStarted = timeStarted; } public String getTimeFinished() { return timeFinished; } public void setTimeFinished(String timeFinished) { this.timeFinished = timeFinished; } @Override public String toString() { return "StreamResponseModel{" + "streamId='" + streamId + '\'' + ", status='" + status + '\'' + ", streamUrls=" + Arrays.toString(streamUrls) + ", resourceUrl='" + resourceUrl + '\'' + ", streamType='" + streamType + '\'' + ", chatUrl='" + chatUrl + '\'' + ", chatChannel='" + chatChannel + '\'' + ", chatToken='" + chatToken + '\'' + ", uploadUrl='" + uploadUrl + '\'' + ", videoWidth=" + videoWidth + ", videoHeight=" + videoHeight + ", timeStarted='" + timeStarted + '\'' + ", timeFinished='" + timeFinished + '\'' + "} " + super.toString(); } }
UTF-8
Java
3,585
java
StreamResponseModel.java
Java
[ { "context": "zable;\nimport java.util.Arrays;\n\n/**\n * Created by lycamandroid on 17/1/19.\n */\npublic class StreamResponseModel ", "end": 110, "score": 0.9996692538261414, "start": 98, "tag": "USERNAME", "value": "lycamandroid" } ]
null
[]
package tv.lycam.model; import java.io.Serializable; import java.util.Arrays; /** * Created by lycamandroid on 17/1/19. */ public class StreamResponseModel extends StreamRequestModel implements Serializable { private String streamId; private String status; private StreamURLModel[] streamUrls; private String resourceUrl; private String streamType; private String chatUrl; private String chatChannel; private String chatToken; private String uploadUrl; private int videoWidth; private int videoHeight; private String timeStarted; private String timeFinished; public String getStreamId() { return streamId; } public void setStreamId(String streamId) { this.streamId = streamId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public StreamURLModel[] getStreamUrls() { return streamUrls; } public void setStreamUrls(StreamURLModel[] streamUrls) { this.streamUrls = streamUrls; } public String getResourceUrl() { return resourceUrl; } public void setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; } public String getStreamType() { return streamType; } public void setStreamType(String streamType) { this.streamType = streamType; } public String getChatUrl() { return chatUrl; } public void setChatUrl(String chatUrl) { this.chatUrl = chatUrl; } public String getChatChannel() { return chatChannel; } public void setChatChannel(String chatChannel) { this.chatChannel = chatChannel; } public String getChatToken() { return chatToken; } public void setChatToken(String chatToken) { this.chatToken = chatToken; } public String getUploadUrl() { return uploadUrl; } public void setUploadUrl(String uploadUrl) { this.uploadUrl = uploadUrl; } public int getVideoWidth() { return videoWidth; } public void setVideoWidth(int videoWidth) { this.videoWidth = videoWidth; } public int getVideoHeight() { return videoHeight; } public void setVideoHeight(int videoHeight) { this.videoHeight = videoHeight; } public String getTimeStarted() { return timeStarted; } public void setTimeStarted(String timeStarted) { this.timeStarted = timeStarted; } public String getTimeFinished() { return timeFinished; } public void setTimeFinished(String timeFinished) { this.timeFinished = timeFinished; } @Override public String toString() { return "StreamResponseModel{" + "streamId='" + streamId + '\'' + ", status='" + status + '\'' + ", streamUrls=" + Arrays.toString(streamUrls) + ", resourceUrl='" + resourceUrl + '\'' + ", streamType='" + streamType + '\'' + ", chatUrl='" + chatUrl + '\'' + ", chatChannel='" + chatChannel + '\'' + ", chatToken='" + chatToken + '\'' + ", uploadUrl='" + uploadUrl + '\'' + ", videoWidth=" + videoWidth + ", videoHeight=" + videoHeight + ", timeStarted='" + timeStarted + '\'' + ", timeFinished='" + timeFinished + '\'' + "} " + super.toString(); } }
3,585
0.591353
0.589958
149
23.060402
19.75597
85
false
false
0
0
0
0
0
0
0.369128
false
false
3
9e25dcca32011e8859422b06c1aa8c2653c88858
4,191,888,115,210
c9dc9ca80cbcda26a267ec77286d205b45668505
/mocks/pdl-mock/src/main/java/no/nav/pdl/hentIdenter/HentIdenterWiring.java
d1f355f016dad0bf1b0d6e6017e2c84cf57a2a47
[ "MIT" ]
permissive
navikt/vtp
https://github.com/navikt/vtp
adc79777c719418cc6ecbdc02e24d71197c18d16
4c0d7ccf5c437391c4a079bddc381b4e73dbf1ab
refs/heads/master
2023-09-04T12:27:58.370000
2023-09-04T08:29:46
2023-09-04T08:29:46
176,907,179
6
3
MIT
false
2023-09-13T03:45:38
2019-03-21T08:59:23
2022-11-22T07:53:45
2023-09-13T03:45:38
5,150
11
2
1
Java
false
false
package no.nav.pdl.hentIdenter; import static graphql.scalars.java.JavaPrimitives.GraphQLLong; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import graphql.execution.DataFetcherResult; import graphql.schema.idl.RuntimeWiring; import no.nav.pdl.Identliste; import no.nav.pdl.PdlFunctionalException; import no.nav.pdl.exceptions.ErrorCode; import no.nav.pdl.graphql.DateScalar; import no.nav.pdl.graphql.DateTimeScalar; public class HentIdenterWiring { private static final Logger LOG = LoggerFactory.getLogger(HentIdenterWiring.class); private HentIdenterWiring() { } public static RuntimeWiring lagRuntimeWiring(HentIdenterCoordinator coordinator) { return RuntimeWiring.newRuntimeWiring() .scalar(DateScalar.DATE) .scalar(DateTimeScalar.DATE_TIME) .scalar(GraphQLLong) .type( "Query", typeWiring -> typeWiring.dataFetcher("hentIdenter", environment -> { try { var ident = (String) environment.getArgument("ident"); var grupper = (List<String>) environment.getArgument("grupper"); Identliste identliste = coordinator.hentIdenter(ident, grupper); if (identliste == null) { return DataFetcherResult.newResult() .error(ErrorCode.NOT_FOUND.construct(environment, "Fant ikke person")) .build(); } LOG.info("Identer hentet fra pdl {} for ident={}", grupper, ident); return identliste; } catch (PdlFunctionalException e) { return DataFetcherResult.newResult() .data(null) .error(e) .build(); } } ) ) .build(); } }
UTF-8
Java
2,399
java
HentIdenterWiring.java
Java
[]
null
[]
package no.nav.pdl.hentIdenter; import static graphql.scalars.java.JavaPrimitives.GraphQLLong; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import graphql.execution.DataFetcherResult; import graphql.schema.idl.RuntimeWiring; import no.nav.pdl.Identliste; import no.nav.pdl.PdlFunctionalException; import no.nav.pdl.exceptions.ErrorCode; import no.nav.pdl.graphql.DateScalar; import no.nav.pdl.graphql.DateTimeScalar; public class HentIdenterWiring { private static final Logger LOG = LoggerFactory.getLogger(HentIdenterWiring.class); private HentIdenterWiring() { } public static RuntimeWiring lagRuntimeWiring(HentIdenterCoordinator coordinator) { return RuntimeWiring.newRuntimeWiring() .scalar(DateScalar.DATE) .scalar(DateTimeScalar.DATE_TIME) .scalar(GraphQLLong) .type( "Query", typeWiring -> typeWiring.dataFetcher("hentIdenter", environment -> { try { var ident = (String) environment.getArgument("ident"); var grupper = (List<String>) environment.getArgument("grupper"); Identliste identliste = coordinator.hentIdenter(ident, grupper); if (identliste == null) { return DataFetcherResult.newResult() .error(ErrorCode.NOT_FOUND.construct(environment, "Fant ikke person")) .build(); } LOG.info("Identer hentet fra pdl {} for ident={}", grupper, ident); return identliste; } catch (PdlFunctionalException e) { return DataFetcherResult.newResult() .data(null) .error(e) .build(); } } ) ) .build(); } }
2,399
0.475198
0.474364
57
41.087719
32.051647
122
false
false
0
0
0
0
0
0
0.473684
false
false
3
07b667f9401e1f0093385917199088359f8ca655
17,806,934,470,331
1233ae8a8733c4d7001932a0c53ab63ae9ce09bd
/http/src/main/java/ch/squaredesk/nova/comm/http/RpcServer.java
fba93617b8fbff33d4dfbf7624d22522f9c85908
[ "Artistic-2.0" ]
permissive
peregin/nova
https://github.com/peregin/nova
2dae4e93c0a7a070bd8bf7657524f848abb60c6e
11d2189b4564c4965fe1df0cbc1f65d07a534b27
refs/heads/master
2017-08-01T11:43:45.892000
2017-07-12T09:23:23
2017-07-12T09:32:30
95,219,858
0
0
null
true
2017-06-23T12:51:15
2017-06-23T12:51:15
2017-06-23T09:37:13
2017-06-02T16:12:13
576
0
0
0
null
null
null
package ch.squaredesk.nova.comm.http; import ch.squaredesk.nova.comm.retrieving.MessageUnmarshaller; import ch.squaredesk.nova.comm.rpc.RpcInvocation; import ch.squaredesk.nova.comm.sending.MessageMarshaller; import ch.squaredesk.nova.metrics.Metrics; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import org.glassfish.grizzly.ReadHandler; import org.glassfish.grizzly.http.Method; import org.glassfish.grizzly.http.io.NIOReader; import org.glassfish.grizzly.http.io.NIOWriter; import org.glassfish.grizzly.http.server.HttpHandler; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.Request; import org.glassfish.grizzly.http.server.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; public class RpcServer<InternalMessageType> extends ch.squaredesk.nova.comm.rpc.RpcServer<String, InternalMessageType, HttpSpecificInfo> { private static final Logger logger = LoggerFactory.getLogger(RpcServer.class); private final MessageMarshaller<InternalMessageType, String> messageMarshaller; private final MessageUnmarshaller<String, InternalMessageType> messageUnmarshaller; private final HttpServer httpServer; public RpcServer(HttpServer httpServer, MessageMarshaller<InternalMessageType, String> messageMarshaller, MessageUnmarshaller<String, InternalMessageType> messageUnmarshaller, Metrics metrics) { this(null, httpServer, messageMarshaller, messageUnmarshaller, metrics); } public RpcServer(String identifier, HttpServer httpServer, MessageMarshaller<InternalMessageType, String> messageMarshaller, MessageUnmarshaller<String, InternalMessageType> messageUnmarshaller, Metrics metrics) { super(identifier, metrics); Objects.requireNonNull(httpServer, "httpServer must not be null"); Objects.requireNonNull(messageMarshaller, "messageMarshaller must not be null"); Objects.requireNonNull(messageUnmarshaller, "messageUnmarshaller must not be null"); this.httpServer = httpServer; this.messageUnmarshaller = messageUnmarshaller; this.messageMarshaller = messageMarshaller; } @Override public <RequestType extends InternalMessageType, ReplyType extends InternalMessageType> Flowable<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> requests(String destination, BackpressureStrategy backpressureStrategy) { // FIXME: handle multiple "subscriptions" to same path Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> rawSubject = PublishSubject.create(); Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> subject = rawSubject.toSerialized(); httpServer.getServerConfiguration().addHttpHandler(new NonBlockingHttpHandler<>(subject), destination); return subject.toFlowable(backpressureStrategy); } private static HttpSpecificInfo httpSpecificInfoFrom (Request request) throws Exception { Map<String, String> parameters = new HashMap<>(); for (Map.Entry<String,String[]> entry: request.getParameterMap().entrySet()) { String[] valueList = entry.getValue(); String valueToPass = null; if (valueList != null && valueList.length>0) { valueToPass = valueList[0]; } parameters.put(entry.getKey(), valueToPass); } return new HttpSpecificInfo( convert(request.getMethod()), parameters); } private static HttpRequestMethod convert (Method method) { if (method==Method.POST) { return HttpRequestMethod.POST; } else if (method == Method.DELETE) { return HttpRequestMethod.DELETE; } else if (method == Method.PUT) { return HttpRequestMethod.PUT; } else { // TODO: do we want to add all other ones known to grizzly? return HttpRequestMethod.GET; } } private static <T> T convertRequestData (String objectAsString, MessageUnmarshaller<String,T> unmarshaller) throws Exception { return unmarshaller.unmarshal(objectAsString); } private static <T> String convertResponseData (T replyObject, MessageMarshaller<T, String> marshaller) throws Exception { return marshaller.marshal(replyObject); } /** * writes reply Object to response body. Assumes that the marshaller creates a String that is a JSON * representation of the reply object */ private static void writeResponse (String reply, NIOWriter out) throws Exception { BufferedWriter bw = new BufferedWriter(out); bw.write(reply); bw.flush(); bw.close(); } /** * Non-blockingly reads a maximum of <chunkSize> characters from the available data of passed InputReader and * concats those characters to the passed <currentBuffer>, returning a new character array */ private static char[] appendAvailableDataToBuffer(NIOReader in, int chunkSize, char currentBuffer[]) throws IOException { // we are not synchronizing here, since we assume that onDataAvailable() is called sequentially char[] readBuffer = new char[chunkSize]; int numRead = in.read(readBuffer); if (numRead<=0) { return currentBuffer; } else { char[] retVal = new char[currentBuffer.length + numRead]; System.arraycopy(currentBuffer, 0, retVal, 0, currentBuffer.length); System.arraycopy(readBuffer, 0, retVal, currentBuffer.length, numRead); return retVal; } } void start() throws IOException { httpServer.start(); } void shutdown() { try { httpServer.shutdown(2, TimeUnit.SECONDS).get(); } catch (Exception e) { logger.info("An error occurred, trying to shutdown REST HTTP server", e); } } private class NonBlockingHttpHandler<RequestType extends InternalMessageType, ReplyType extends InternalMessageType> extends HttpHandler { private static final int READ_CHUNK_SIZE = 256; private final Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> subject; private NonBlockingHttpHandler(Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> subject) { this.subject = subject; } public void service(Request request, Response response) throws Exception { response.suspend(); NIOWriter out = response.getNIOWriter(); NIOReader in = request.getNIOReader(); in.notifyAvailable(new ReadHandler() { private char[] inputBuffer = new char[0]; @Override public void onDataAvailable() throws Exception { inputBuffer = appendAvailableDataToBuffer(in, READ_CHUNK_SIZE, inputBuffer); in.notifyAvailable(this); } @Override public void onError(Throwable t) { // FIXME logger.error("Error parsing request data", t); response.resume(); } @Override public void onAllDataRead() throws Exception { inputBuffer = appendAvailableDataToBuffer(in, READ_CHUNK_SIZE, inputBuffer); RpcInvocation<RequestType, ReplyType, HttpSpecificInfo> rpci = new RpcInvocation<>( (RequestType) convertRequestData(new String(inputBuffer), messageUnmarshaller), httpSpecificInfoFrom(request), reply -> { try { String responseAsString = convertResponseData(reply, messageMarshaller); response.setContentType("application/json"); response.setContentLength(responseAsString.length()); writeResponse(responseAsString, out); } catch (Exception e) { // FIXME: write error or return Single.error() logger.error("An error occurred trying to write HTTP response", e); } finally { try { in.close(); } catch (Exception ignored) { // TODO - this is from the example. Do we want to do something here? } try { out.close(); } catch (Exception ignored) { // TODO - this is from the example. Do we want to do something here? } response.resume(); } }, error -> { // FIXME: write error or return Single.error() logger.error("An error occurred trying to process HTTP request", error); } ); subject.onNext(rpci); } }); } } }
UTF-8
Java
9,887
java
RpcServer.java
Java
[]
null
[]
package ch.squaredesk.nova.comm.http; import ch.squaredesk.nova.comm.retrieving.MessageUnmarshaller; import ch.squaredesk.nova.comm.rpc.RpcInvocation; import ch.squaredesk.nova.comm.sending.MessageMarshaller; import ch.squaredesk.nova.metrics.Metrics; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; import org.glassfish.grizzly.ReadHandler; import org.glassfish.grizzly.http.Method; import org.glassfish.grizzly.http.io.NIOReader; import org.glassfish.grizzly.http.io.NIOWriter; import org.glassfish.grizzly.http.server.HttpHandler; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.Request; import org.glassfish.grizzly.http.server.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; public class RpcServer<InternalMessageType> extends ch.squaredesk.nova.comm.rpc.RpcServer<String, InternalMessageType, HttpSpecificInfo> { private static final Logger logger = LoggerFactory.getLogger(RpcServer.class); private final MessageMarshaller<InternalMessageType, String> messageMarshaller; private final MessageUnmarshaller<String, InternalMessageType> messageUnmarshaller; private final HttpServer httpServer; public RpcServer(HttpServer httpServer, MessageMarshaller<InternalMessageType, String> messageMarshaller, MessageUnmarshaller<String, InternalMessageType> messageUnmarshaller, Metrics metrics) { this(null, httpServer, messageMarshaller, messageUnmarshaller, metrics); } public RpcServer(String identifier, HttpServer httpServer, MessageMarshaller<InternalMessageType, String> messageMarshaller, MessageUnmarshaller<String, InternalMessageType> messageUnmarshaller, Metrics metrics) { super(identifier, metrics); Objects.requireNonNull(httpServer, "httpServer must not be null"); Objects.requireNonNull(messageMarshaller, "messageMarshaller must not be null"); Objects.requireNonNull(messageUnmarshaller, "messageUnmarshaller must not be null"); this.httpServer = httpServer; this.messageUnmarshaller = messageUnmarshaller; this.messageMarshaller = messageMarshaller; } @Override public <RequestType extends InternalMessageType, ReplyType extends InternalMessageType> Flowable<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> requests(String destination, BackpressureStrategy backpressureStrategy) { // FIXME: handle multiple "subscriptions" to same path Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> rawSubject = PublishSubject.create(); Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> subject = rawSubject.toSerialized(); httpServer.getServerConfiguration().addHttpHandler(new NonBlockingHttpHandler<>(subject), destination); return subject.toFlowable(backpressureStrategy); } private static HttpSpecificInfo httpSpecificInfoFrom (Request request) throws Exception { Map<String, String> parameters = new HashMap<>(); for (Map.Entry<String,String[]> entry: request.getParameterMap().entrySet()) { String[] valueList = entry.getValue(); String valueToPass = null; if (valueList != null && valueList.length>0) { valueToPass = valueList[0]; } parameters.put(entry.getKey(), valueToPass); } return new HttpSpecificInfo( convert(request.getMethod()), parameters); } private static HttpRequestMethod convert (Method method) { if (method==Method.POST) { return HttpRequestMethod.POST; } else if (method == Method.DELETE) { return HttpRequestMethod.DELETE; } else if (method == Method.PUT) { return HttpRequestMethod.PUT; } else { // TODO: do we want to add all other ones known to grizzly? return HttpRequestMethod.GET; } } private static <T> T convertRequestData (String objectAsString, MessageUnmarshaller<String,T> unmarshaller) throws Exception { return unmarshaller.unmarshal(objectAsString); } private static <T> String convertResponseData (T replyObject, MessageMarshaller<T, String> marshaller) throws Exception { return marshaller.marshal(replyObject); } /** * writes reply Object to response body. Assumes that the marshaller creates a String that is a JSON * representation of the reply object */ private static void writeResponse (String reply, NIOWriter out) throws Exception { BufferedWriter bw = new BufferedWriter(out); bw.write(reply); bw.flush(); bw.close(); } /** * Non-blockingly reads a maximum of <chunkSize> characters from the available data of passed InputReader and * concats those characters to the passed <currentBuffer>, returning a new character array */ private static char[] appendAvailableDataToBuffer(NIOReader in, int chunkSize, char currentBuffer[]) throws IOException { // we are not synchronizing here, since we assume that onDataAvailable() is called sequentially char[] readBuffer = new char[chunkSize]; int numRead = in.read(readBuffer); if (numRead<=0) { return currentBuffer; } else { char[] retVal = new char[currentBuffer.length + numRead]; System.arraycopy(currentBuffer, 0, retVal, 0, currentBuffer.length); System.arraycopy(readBuffer, 0, retVal, currentBuffer.length, numRead); return retVal; } } void start() throws IOException { httpServer.start(); } void shutdown() { try { httpServer.shutdown(2, TimeUnit.SECONDS).get(); } catch (Exception e) { logger.info("An error occurred, trying to shutdown REST HTTP server", e); } } private class NonBlockingHttpHandler<RequestType extends InternalMessageType, ReplyType extends InternalMessageType> extends HttpHandler { private static final int READ_CHUNK_SIZE = 256; private final Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> subject; private NonBlockingHttpHandler(Subject<RpcInvocation<RequestType, ReplyType, HttpSpecificInfo>> subject) { this.subject = subject; } public void service(Request request, Response response) throws Exception { response.suspend(); NIOWriter out = response.getNIOWriter(); NIOReader in = request.getNIOReader(); in.notifyAvailable(new ReadHandler() { private char[] inputBuffer = new char[0]; @Override public void onDataAvailable() throws Exception { inputBuffer = appendAvailableDataToBuffer(in, READ_CHUNK_SIZE, inputBuffer); in.notifyAvailable(this); } @Override public void onError(Throwable t) { // FIXME logger.error("Error parsing request data", t); response.resume(); } @Override public void onAllDataRead() throws Exception { inputBuffer = appendAvailableDataToBuffer(in, READ_CHUNK_SIZE, inputBuffer); RpcInvocation<RequestType, ReplyType, HttpSpecificInfo> rpci = new RpcInvocation<>( (RequestType) convertRequestData(new String(inputBuffer), messageUnmarshaller), httpSpecificInfoFrom(request), reply -> { try { String responseAsString = convertResponseData(reply, messageMarshaller); response.setContentType("application/json"); response.setContentLength(responseAsString.length()); writeResponse(responseAsString, out); } catch (Exception e) { // FIXME: write error or return Single.error() logger.error("An error occurred trying to write HTTP response", e); } finally { try { in.close(); } catch (Exception ignored) { // TODO - this is from the example. Do we want to do something here? } try { out.close(); } catch (Exception ignored) { // TODO - this is from the example. Do we want to do something here? } response.resume(); } }, error -> { // FIXME: write error or return Single.error() logger.error("An error occurred trying to process HTTP request", error); } ); subject.onNext(rpci); } }); } } }
9,887
0.612319
0.611004
217
44.56221
35.15649
143
false
false
0
0
0
0
0
0
0.774194
false
false
3
201093157deafdce19edec0f3d65e1b617ff969d
4,956,392,328,822
5ca1552925577a1dcd9c3b8dbf7a7fe4c56ccd05
/bank-kata-application/src/test/java/fr/ing/interview/application/AccountServiceTest.java
cc2a530b2b0157cfb1114c9c383f82fea0bf738b
[]
no_license
djoulaye/bank-kata-public
https://github.com/djoulaye/bank-kata-public
dfbaae10c591d3be7179cfb48135f51f1f259112
1ffe1360d09ac8cd7d8aee146cc5061a1f097c5f
refs/heads/master
2023-04-09T06:55:57.237000
2021-01-31T07:48:56
2021-01-31T07:48:56
275,246,991
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.ing.interview.application; import fr.ing.interview.application.exception.AlreadyExistsAccountException; import fr.ing.interview.application.exception.UnknownAccountException; import fr.ing.interview.domain.Account; import fr.ing.interview.domain.AccountRepository; import fr.ing.interview.domain.Operation; import fr.ing.interview.domain.OperationDirection; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class AccountServiceTest { private static final String EXISTING_ACCOUNT_NUMBER = "123"; private static final String NOT_EXISTING_ACCOUNT_NUMBER = "124"; public static final double AMOUNT_10_00 = 10.00; @Mock private AccountRepository accountRepository; @InjectMocks private AccountService accountService; @Test void deposit_amount_on_not_existing_account_should_throw_exception() { assertThatThrownBy(() -> accountService.depositMoney(NOT_EXISTING_ACCOUNT_NUMBER, any(Operation.class))).isInstanceOf(UnknownAccountException.class); } @Test void deposit_amount_on_existing_account_should_not_throw_exception() { //Arrange Account account = new Account(EXISTING_ACCOUNT_NUMBER); when(accountRepository.findByAccountNumber(EXISTING_ACCOUNT_NUMBER)).thenReturn(Optional.of(account)); Operation depositOperation = new Operation(OperationDirection.CREDIT, AMOUNT_10_00); //Act & Assert assertThatCode(() -> accountService.depositMoney(EXISTING_ACCOUNT_NUMBER, depositOperation)).doesNotThrowAnyException(); } @Test void delete_not_existing_account_should_throw_exception() { when(accountRepository.isExists(NOT_EXISTING_ACCOUNT_NUMBER)).thenReturn(false); assertThatThrownBy(() -> accountService.deleteAccount(NOT_EXISTING_ACCOUNT_NUMBER)).isInstanceOf(UnknownAccountException.class); verify(accountRepository, times(1)).isExists(NOT_EXISTING_ACCOUNT_NUMBER); } @Test public void create_already_existing_account_should_throws_exception() { when(accountRepository.isExists(EXISTING_ACCOUNT_NUMBER)).thenReturn(true); assertThat(accountRepository.isExists(EXISTING_ACCOUNT_NUMBER)).isTrue(); assertThatThrownBy(() -> accountService.createAccount(EXISTING_ACCOUNT_NUMBER)).isInstanceOf(AlreadyExistsAccountException.class); } }
UTF-8
Java
2,623
java
AccountServiceTest.java
Java
[]
null
[]
package fr.ing.interview.application; import fr.ing.interview.application.exception.AlreadyExistsAccountException; import fr.ing.interview.application.exception.UnknownAccountException; import fr.ing.interview.domain.Account; import fr.ing.interview.domain.AccountRepository; import fr.ing.interview.domain.Operation; import fr.ing.interview.domain.OperationDirection; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class AccountServiceTest { private static final String EXISTING_ACCOUNT_NUMBER = "123"; private static final String NOT_EXISTING_ACCOUNT_NUMBER = "124"; public static final double AMOUNT_10_00 = 10.00; @Mock private AccountRepository accountRepository; @InjectMocks private AccountService accountService; @Test void deposit_amount_on_not_existing_account_should_throw_exception() { assertThatThrownBy(() -> accountService.depositMoney(NOT_EXISTING_ACCOUNT_NUMBER, any(Operation.class))).isInstanceOf(UnknownAccountException.class); } @Test void deposit_amount_on_existing_account_should_not_throw_exception() { //Arrange Account account = new Account(EXISTING_ACCOUNT_NUMBER); when(accountRepository.findByAccountNumber(EXISTING_ACCOUNT_NUMBER)).thenReturn(Optional.of(account)); Operation depositOperation = new Operation(OperationDirection.CREDIT, AMOUNT_10_00); //Act & Assert assertThatCode(() -> accountService.depositMoney(EXISTING_ACCOUNT_NUMBER, depositOperation)).doesNotThrowAnyException(); } @Test void delete_not_existing_account_should_throw_exception() { when(accountRepository.isExists(NOT_EXISTING_ACCOUNT_NUMBER)).thenReturn(false); assertThatThrownBy(() -> accountService.deleteAccount(NOT_EXISTING_ACCOUNT_NUMBER)).isInstanceOf(UnknownAccountException.class); verify(accountRepository, times(1)).isExists(NOT_EXISTING_ACCOUNT_NUMBER); } @Test public void create_already_existing_account_should_throws_exception() { when(accountRepository.isExists(EXISTING_ACCOUNT_NUMBER)).thenReturn(true); assertThat(accountRepository.isExists(EXISTING_ACCOUNT_NUMBER)).isTrue(); assertThatThrownBy(() -> accountService.createAccount(EXISTING_ACCOUNT_NUMBER)).isInstanceOf(AlreadyExistsAccountException.class); } }
2,623
0.766679
0.759436
63
40.650795
39.542686
157
false
false
0
0
0
0
0
0
0.555556
false
false
3
0fff355ee2ffad0b5caef68d7f5f50d2dc5e22d2
17,051,020,226,935
caf5e8e37a1be2e0f04b07ef19e1b568e86fa5fe
/xiaoyuan-upms/xiaoyuan-upms-admin/src/main/java/com/gospell/xiaoyuan/cloud/upms/admin/repository/SysUserRepository.java
38ea016a200841c19121a084d55d4523241abd86
[]
no_license
PayYouDont/xiaoyuan-cloud
https://github.com/PayYouDont/xiaoyuan-cloud
673edca5f6078d55bd6e67d3342213a859fbcb30
d905870a0258d92a6c27a232218905dff182ce0b
refs/heads/master
2023-03-08T07:09:50.553000
2021-02-21T02:16:54
2021-02-21T02:16:54
340,798,509
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gospell.xiaoyuan.cloud.upms.admin.repository; import com.gospell.xiaoyuan.cloud.common.data.jpa.base.BaseRepository; import com.gospell.xiaoyuan.cloud.upms.common.entity.SysUser; import java.util.Optional; /** * description: SysUserRepository <br> * date: 2020/12/31 15:11 <br> * author: pay <br> * version: 1.0 <br> */ public interface SysUserRepository extends BaseRepository<SysUser> { Optional<SysUser> findByUsername(String username); /*@Query(value = "select * from sys_user su left join sys_organ so on so.id=su.organ_id " + "where su.username like concat('%',?1,'%') " + "and so.id in (select sou.ancestor from sys_organ_user sou where sou.ancestor=?2)",nativeQuery = true) List<UserVO> findUserVOAll(String username,Long organId); @Query(value = "select * from sys_user su left join sys_organ so on so.id=su.organ_id",nativeQuery = true) List<UserVO> findUserVOAll();*/ }
UTF-8
Java
948
java
SysUserRepository.java
Java
[ { "context": "ory <br>\n * date: 2020/12/31 15:11 <br>\n * author: pay <br>\n * version: 1.0 <br>\n */\npublic interface Sy", "end": 309, "score": 0.996343195438385, "start": 306, "tag": "USERNAME", "value": "pay" } ]
null
[]
package com.gospell.xiaoyuan.cloud.upms.admin.repository; import com.gospell.xiaoyuan.cloud.common.data.jpa.base.BaseRepository; import com.gospell.xiaoyuan.cloud.upms.common.entity.SysUser; import java.util.Optional; /** * description: SysUserRepository <br> * date: 2020/12/31 15:11 <br> * author: pay <br> * version: 1.0 <br> */ public interface SysUserRepository extends BaseRepository<SysUser> { Optional<SysUser> findByUsername(String username); /*@Query(value = "select * from sys_user su left join sys_organ so on so.id=su.organ_id " + "where su.username like concat('%',?1,'%') " + "and so.id in (select sou.ancestor from sys_organ_user sou where sou.ancestor=?2)",nativeQuery = true) List<UserVO> findUserVOAll(String username,Long organId); @Query(value = "select * from sys_user su left join sys_organ so on so.id=su.organ_id",nativeQuery = true) List<UserVO> findUserVOAll();*/ }
948
0.705696
0.688819
25
36.919998
35.532429
114
false
false
0
0
0
0
0
0
0.48
false
false
3
2b9f314639236bd1c180039e837e4f5540def1fc
8,916,352,134,964
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.mm/classes.jar/kotlinx/coroutines/b/ae.java
62f7b8faab0ac5759a83568d49f40d5d5ce0b700
[]
no_license
tsuzcx/qq_apk
https://github.com/tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651000
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
false
2022-01-31T09:46:26
2022-01-31T02:43:22
2022-01-31T06:56:43
2022-01-31T09:46:26
167,304
0
1
1
Java
false
false
package kotlinx.coroutines.b; import kotlin.Metadata; import kotlin.ah; @Metadata(d1={""}, d2={"Lkotlinx/coroutines/flow/SharedFlowSlot;", "Lkotlinx/coroutines/flow/internal/AbstractSharedFlowSlot;", "Lkotlinx/coroutines/flow/SharedFlowImpl;", "()V", "cont", "Lkotlin/coroutines/Continuation;", "", "index", "", "allocateLocked", "", "flow", "freeLocked", "", "(Lkotlinx/coroutines/flow/SharedFlowImpl;)[Lkotlin/coroutines/Continuation;", "kotlinx-coroutines-core"}, k=1, mv={1, 5, 1}, xi=48) final class ae extends kotlinx.coroutines.b.a.d<ac<?>> { public long Dpr = -1L; public kotlin.d.d<? super ah> ajyZ; } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes3.jar * Qualified Name: kotlinx.coroutines.b.ae * JD-Core Version: 0.7.0.1 */
UTF-8
Java
804
java
ae.java
Java
[]
null
[]
package kotlinx.coroutines.b; import kotlin.Metadata; import kotlin.ah; @Metadata(d1={""}, d2={"Lkotlinx/coroutines/flow/SharedFlowSlot;", "Lkotlinx/coroutines/flow/internal/AbstractSharedFlowSlot;", "Lkotlinx/coroutines/flow/SharedFlowImpl;", "()V", "cont", "Lkotlin/coroutines/Continuation;", "", "index", "", "allocateLocked", "", "flow", "freeLocked", "", "(Lkotlinx/coroutines/flow/SharedFlowImpl;)[Lkotlin/coroutines/Continuation;", "kotlinx-coroutines-core"}, k=1, mv={1, 5, 1}, xi=48) final class ae extends kotlinx.coroutines.b.a.d<ac<?>> { public long Dpr = -1L; public kotlin.d.d<? super ah> ajyZ; } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes3.jar * Qualified Name: kotlinx.coroutines.b.ae * JD-Core Version: 0.7.0.1 */
804
0.676617
0.659204
22
34.81818
86.507294
420
false
false
0
0
0
0
0
0
1.454545
false
false
3
e64d6f314bcbe45dad1ae3740d4b45ad2015ef10
28,106,266,017,808
fb7eb652ca72389006675081bec922e99efb7b20
/web-ui/src/main/java/com/ai/bss/webui/customerorder/model/CustomerOrder.java
bd71f20eb6b81a18d605e92934c27bbb696f97c3
[]
no_license
konglingjuanyi/axonbss
https://github.com/konglingjuanyi/axonbss
3451a023f01d1a3740129726df604d0889aed3da
e217e36f374d6951f759d3ff6d67943ec5fbaa25
refs/heads/master
2021-01-12T07:48:21.489000
2016-12-02T09:13:49
2016-12-02T09:13:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ai.bss.webui.customerorder.model; import java.util.Set; import com.ai.bss.api.base.CharacteristicValue; import com.ai.bss.api.customer.CustomerId; import com.ai.bss.api.customerorder.CustomerOrderId; public class CustomerOrder { private CustomerId customerId; private CustomerOrderId customerOrderId; private Set<CustomerOrderItem> orderItems; private Set<CharacteristicValue> characterValues; public CustomerOrder() { // TODO Auto-generated constructor stub } public CustomerOrderId getCustomerOrderId() { return customerOrderId; } public void setCustomerOrderId(CustomerOrderId customerOrderId) { this.customerOrderId = customerOrderId; } public Set<CustomerOrderItem> getOrderItems() { return orderItems; } public void addOrderItem(CustomerOrderItem item){ if (!orderItems.contains(item)){ orderItems.add(item); } } public Set<CharacteristicValue> getCharacterValues() { return characterValues; } public void addOCharacterValue(CharacteristicValue value){ if (!characterValues.contains(value)){ characterValues.add(value); } } public CustomerId getCustomerId() { return customerId; } public void setCustomerId(CustomerId customerId) { this.customerId = customerId; } }
UTF-8
Java
1,293
java
CustomerOrder.java
Java
[]
null
[]
package com.ai.bss.webui.customerorder.model; import java.util.Set; import com.ai.bss.api.base.CharacteristicValue; import com.ai.bss.api.customer.CustomerId; import com.ai.bss.api.customerorder.CustomerOrderId; public class CustomerOrder { private CustomerId customerId; private CustomerOrderId customerOrderId; private Set<CustomerOrderItem> orderItems; private Set<CharacteristicValue> characterValues; public CustomerOrder() { // TODO Auto-generated constructor stub } public CustomerOrderId getCustomerOrderId() { return customerOrderId; } public void setCustomerOrderId(CustomerOrderId customerOrderId) { this.customerOrderId = customerOrderId; } public Set<CustomerOrderItem> getOrderItems() { return orderItems; } public void addOrderItem(CustomerOrderItem item){ if (!orderItems.contains(item)){ orderItems.add(item); } } public Set<CharacteristicValue> getCharacterValues() { return characterValues; } public void addOCharacterValue(CharacteristicValue value){ if (!characterValues.contains(value)){ characterValues.add(value); } } public CustomerId getCustomerId() { return customerId; } public void setCustomerId(CustomerId customerId) { this.customerId = customerId; } }
1,293
0.750193
0.750193
49
24.387754
20.574223
66
false
false
0
0
0
0
0
0
1.428571
false
false
3
b4382cd08fb5206b619c3d255633999230052325
14,474,039,848,346
db2ca48fffaf6689c9db439abaf9d98729548e0b
/minsu-web-report/src/main/java/com/ziroom/minsu/spider/airbnb/entity/enums/RoomTypeEnum.java
faebaf71d263ccd2e24b0365d2ac902f2d3c49e5
[]
no_license
majinwen/sojourn
https://github.com/majinwen/sojourn
46a950dbd64442e4ef333c512eb956be9faef50d
ab98247790b1951017fc7dd340e1941d5b76dc39
refs/heads/master
2020-03-22T07:07:05.299000
2018-03-18T13:45:23
2018-03-18T13:45:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @FileName: RoomTypeEnum.java * @Package com.ziroom.minsu.spider.airbnb.entity.enums * * @author zl * @created 2016年10月9日 下午9:36:43 * * Copyright 2016-2025 ziroom */ package com.ziroom.minsu.spider.airbnb.entity.enums; import java.util.HashMap; import java.util.Map; /** * 房间类型 * <p>TODO</p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author zl * @since 1.0 * @version 1.0 */ public enum RoomTypeEnum { ENTIRE("Entire home/apt","整套房子/公寓"), PRIVATE("Private room","独立房间"), SHARED("Shared room","合住房间"); RoomTypeEnum(String code,String name) { this.code = code; this.name = name; } private static Map<String,String> codeNameMap=new HashMap<String, String>(); private static Map<String,String> nameCodeMap=new HashMap<String,String>(); static{ for (RoomTypeEnum roomTypeEnum : RoomTypeEnum.values()) { codeNameMap.put(roomTypeEnum.getCode(), roomTypeEnum.getName()); nameCodeMap.put(roomTypeEnum.getName(), roomTypeEnum.getCode()); } } public static String getCodeByName(String name){ if (name==null || name.length()==0) { return null; } return nameCodeMap.get(name); } public static String geNametByCode(String code){ if (code==null) { return null; } return codeNameMap.get(code); } /** code */ private String code; /** 名称 */ private String name; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static String[] getCodes(){ String[] codes=new String[RoomTypeEnum.values().length]; for (int i=0;i<codes.length;i++) { codes[i]=RoomTypeEnum.values()[i].getCode(); } return codes; } }
UTF-8
Java
1,938
java
RoomTypeEnum.java
Java
[ { "context": "om.minsu.spider.airbnb.entity.enums\n * \n * @author zl\n * @created 2016年10月9日 下午9:36:43\n * \n * Copyright", "end": 109, "score": 0.9986433386802673, "start": 107, "tag": "USERNAME", "value": "zl" }, { "context": " * <BR>\t修改日期\t\t\t修改人\t\t\t修改内容\n * </PRE>\n * \n * @author zl\n * @since 1.0\n * @version 1.0\n */\npublic enum Roo", "end": 446, "score": 0.9985527992248535, "start": 444, "tag": "USERNAME", "value": "zl" } ]
null
[]
/** * @FileName: RoomTypeEnum.java * @Package com.ziroom.minsu.spider.airbnb.entity.enums * * @author zl * @created 2016年10月9日 下午9:36:43 * * Copyright 2016-2025 ziroom */ package com.ziroom.minsu.spider.airbnb.entity.enums; import java.util.HashMap; import java.util.Map; /** * 房间类型 * <p>TODO</p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author zl * @since 1.0 * @version 1.0 */ public enum RoomTypeEnum { ENTIRE("Entire home/apt","整套房子/公寓"), PRIVATE("Private room","独立房间"), SHARED("Shared room","合住房间"); RoomTypeEnum(String code,String name) { this.code = code; this.name = name; } private static Map<String,String> codeNameMap=new HashMap<String, String>(); private static Map<String,String> nameCodeMap=new HashMap<String,String>(); static{ for (RoomTypeEnum roomTypeEnum : RoomTypeEnum.values()) { codeNameMap.put(roomTypeEnum.getCode(), roomTypeEnum.getName()); nameCodeMap.put(roomTypeEnum.getName(), roomTypeEnum.getCode()); } } public static String getCodeByName(String name){ if (name==null || name.length()==0) { return null; } return nameCodeMap.get(name); } public static String geNametByCode(String code){ if (code==null) { return null; } return codeNameMap.get(code); } /** code */ private String code; /** 名称 */ private String name; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static String[] getCodes(){ String[] codes=new String[RoomTypeEnum.values().length]; for (int i=0;i<codes.length;i++) { codes[i]=RoomTypeEnum.values()[i].getCode(); } return codes; } }
1,938
0.634553
0.62056
99
17.767677
19.446289
77
false
false
0
0
0
0
0
0
1.393939
false
false
3
56aa922281bdb523679ebc4fa112f8865c65d73e
6,751,688,629,142
f5c2859338afedbb9b7fbc16e5cea53827c2bfbd
/30_days_of_code/day28/Solution.java
d7454ac3ffc4cc68e2a888f176e5915bedc3a3d1
[]
no_license
mandy1339/hacker-rank-solutions
https://github.com/mandy1339/hacker-rank-solutions
91f46a6d0a5e68d30470dfcbdddaeb9f0b362d9d
f28efed13c0c935e3443e283caaea803fc39566a
refs/heads/master
2020-12-30T09:15:13.590000
2018-09-30T23:12:48
2018-09-30T23:12:48
100,400,065
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import java.util.regex.*; public class Solution { public static void main(String [] args) { ArrayList<String> results = new ArrayList<String>(); // container for results String regExStr ="^.+@gmail.com$"; // regEx Scanner scan = new Scanner(System.in); // set up scanner int n = scan.nextInt(); // scan n scan.nextLine(); // advance scanner to next line Pattern p = Pattern.compile(regExStr); // create a pattern with the regex for(int i = 0; i < n; i++) { Matcher m = p.matcher(scan.nextLine()); if(m.find()) { results.add(m.group()); } } // create new arraylist ArrayList<String> names = new ArrayList<String>(); for(int i = 0; i < results.size(); i++) { String [] name = results.get(i).split(" "); names.add(name[0]); } // sort the arraylist with names Collections.sort(names); for(int i = 0; i < results.size(); i++) { System.out.println(names.get(i)); } } }
UTF-8
Java
977
java
Solution.java
Java
[ { "context": "();\t// container for results\n\t\tString regExStr =\"^.+@gmail.com$\";\t\t\t\t\t\t// regEx\n\t\t\n\t\tScanner scan = new Scanner(", "end": 227, "score": 0.9995919466018677, "start": 217, "tag": "EMAIL", "value": "@gmail.com" } ]
null
[]
import java.util.*; import java.util.regex.*; public class Solution { public static void main(String [] args) { ArrayList<String> results = new ArrayList<String>(); // container for results String regExStr ="^.+<EMAIL>$"; // regEx Scanner scan = new Scanner(System.in); // set up scanner int n = scan.nextInt(); // scan n scan.nextLine(); // advance scanner to next line Pattern p = Pattern.compile(regExStr); // create a pattern with the regex for(int i = 0; i < n; i++) { Matcher m = p.matcher(scan.nextLine()); if(m.find()) { results.add(m.group()); } } // create new arraylist ArrayList<String> names = new ArrayList<String>(); for(int i = 0; i < results.size(); i++) { String [] name = results.get(i).split(" "); names.add(name[0]); } // sort the arraylist with names Collections.sort(names); for(int i = 0; i < results.size(); i++) { System.out.println(names.get(i)); } } }
974
0.603889
0.599795
34
27.735294
22.861874
79
false
false
0
0
0
0
0
0
3.441176
false
false
3
8ba9dec1c1dd3eb355c4a504873d2e2bbd3336e1
6,751,688,630,087
250713e8ee2ec893df548024ef89d06f60b16dd5
/2.0.1/CN-Persistent-Common-2000/src/main/java/com/zmsoft/framework/persistent/system/S901060Parameter/S901060ParameterDBO.java
b95ee4f0a3692b8142ee0c2ea2a4467016b0caba
[ "BSD-3-Clause-Clear" ]
permissive
moutainhigh/cnsoft
https://github.com/moutainhigh/cnsoft
5ecda93285476041cde6711b8fa46dc7e7354a7d
b9b921d43ea9b06c881121ab5d98ce18e14df87d
refs/heads/master
2023-07-31T23:20:56.388000
2021-04-30T03:50:46
2021-04-30T03:50:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zmsoft.framework.persistent.system.S901060Parameter; import org.zmsoft.framework.beans.db.MyDataBaseObjectSupport3; /** 分类参数定义*/ public class S901060ParameterDBO extends MyDataBaseObjectSupport3 { /** * 业务分类ID */ private String configTypeId = null; /** * 键定义 */ private String configKey = null; /** * 值内容 */ private String configValue = null; /** * 数值型变量初始化<br> * 仅在插入场合默认调用 * @see #loadDefauft() */ public void prepareNumeric() { } /** * 获取业务分类ID * * @return Config_type_id 业务分类ID */ public String getConfigTypeId() { return this.configTypeId; } /** * 获取键定义 * * @return Config_key 键定义 */ public String getConfigKey() { return this.configKey; } /** * 获取值内容 * * @return Config_value 值内容 */ public String getConfigValue() { return this.configValue; } /** * 设置业务分类ID * * @param Config_type_id 业务分类ID */ public void setConfigTypeId(String configtypeid) { this.configTypeId = configtypeid; } /** * 设置键定义 * * @param Config_key 键定义 */ public void setConfigKey(String configkey) { this.configKey = configkey; } /** * 设置值内容 * * @param Config_value 值内容 */ public void setConfigValue(String configvalue) { this.configValue = configvalue; } }
UTF-8
Java
1,673
java
S901060ParameterDBO.java
Java
[]
null
[]
package com.zmsoft.framework.persistent.system.S901060Parameter; import org.zmsoft.framework.beans.db.MyDataBaseObjectSupport3; /** 分类参数定义*/ public class S901060ParameterDBO extends MyDataBaseObjectSupport3 { /** * 业务分类ID */ private String configTypeId = null; /** * 键定义 */ private String configKey = null; /** * 值内容 */ private String configValue = null; /** * 数值型变量初始化<br> * 仅在插入场合默认调用 * @see #loadDefauft() */ public void prepareNumeric() { } /** * 获取业务分类ID * * @return Config_type_id 业务分类ID */ public String getConfigTypeId() { return this.configTypeId; } /** * 获取键定义 * * @return Config_key 键定义 */ public String getConfigKey() { return this.configKey; } /** * 获取值内容 * * @return Config_value 值内容 */ public String getConfigValue() { return this.configValue; } /** * 设置业务分类ID * * @param Config_type_id 业务分类ID */ public void setConfigTypeId(String configtypeid) { this.configTypeId = configtypeid; } /** * 设置键定义 * * @param Config_key 键定义 */ public void setConfigKey(String configkey) { this.configKey = configkey; } /** * 设置值内容 * * @param Config_value 值内容 */ public void setConfigValue(String configvalue) { this.configValue = configvalue; } }
1,673
0.549634
0.540306
84
16.869047
16.643875
65
false
false
0
0
0
0
0
0
0.130952
false
false
3
daf87126fee2166c10e63a4e0e5c4aca5e2418a4
13,374,528,176,038
33b45cbfa0e5574873446fd8a0a38c51546333bd
/blog-server/src/main/java/com/bingo/blogserver/dao/SysUserRoleDao.java
8a6b31221f844a2c9eae35e1e521c44582d4ebe0
[]
no_license
bingoCoding/blog_dubbo_study
https://github.com/bingoCoding/blog_dubbo_study
c78efd65a0f8f69b0b12cdbb0ac05cd7fb78835e
d389909fef3498ddcca0522326af99fefd2dbebf
refs/heads/master
2021-04-09T11:01:07.762000
2018-03-16T09:47:18
2018-03-16T09:47:18
125,496,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bingo.blogserver.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.bingo.bloginterface.Entity.SysUserRole; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface SysUserRoleDao extends BaseMapper<SysUserRole> { @Select("select role_id from sys_user_role where user_id = #{userId}") List<Long> queryRoleIdList(@Param("userId") Long userId); }
UTF-8
Java
458
java
SysUserRoleDao.java
Java
[]
null
[]
package com.bingo.blogserver.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.bingo.bloginterface.Entity.SysUserRole; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface SysUserRoleDao extends BaseMapper<SysUserRole> { @Select("select role_id from sys_user_role where user_id = #{userId}") List<Long> queryRoleIdList(@Param("userId") Long userId); }
458
0.786026
0.786026
15
29.533333
26.705471
74
false
false
0
0
0
0
0
0
0.466667
false
false
3
88edfe0b22a0f94d3515686250f3f4515d199817
32,298,154,110,445
6418c4425986cbddd88b0d2925c4b5bd23dc294f
/trunk/SwRI_Goggles-eclipse/src/edu/ttu/swri/messenger/AppContext.java
83d85ba68fccb0292444cfb9721a2f5a36c98f62
[]
no_license
kub1x/swri-goggles
https://github.com/kub1x/swri-goggles
d2995084d16098f64eda89569a1778f7214f74c7
7dfb8a8efb3f4633e06299f50616e62cfa3c4fcb
refs/heads/master
2021-01-01T05:34:06.325000
2013-05-19T18:19:36
2013-05-19T18:19:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ttu.swri.messenger; import java.util.ArrayList; import android.app.Application; import android.content.SharedPreferences; import android.provider.Settings.Secure; import com.google.gson.Gson; import edu.ttu.swri.data.model.ElementMate; import edu.ttu.swri.data.model.ElementPoi; import edu.ttu.swri.goggles.R; import edu.ttu.swri.goggles.persistence.impl.UserPrefsDAO; public class AppContext extends Application { public static UserPrefsDAO dao; private static final String friendLocationAction = "FRIEND_UPDATE"; private static final String friendMessageAction = "FRIEND_MESSAGE"; private static final String userLocationAction = "USER_LOCATION_CHANGED"; private static final String messageBodyExtra = "MESSAGE_BODY"; private static String current_user_name; private static String currrent_user_friend; private static String projectId; private static String token; private static String poiName = "custom_poi"; public static final String swriFriendsQ = "SWRI_FRIENDS"; private static String uniqueDeviceId; private static ElementMate currentUserLatestLocation = null; private static ElementMate currentUserFriendLatestLocation = null; private static ElementPoi poi = null; private static Gson gson = new Gson(); private static SharedPreferences settings = null; @Override public void onCreate() { dao = new UserPrefsDAO(getApplicationContext()); dao.deleteAllMates(); projectId = getResources().getString(R.string.project_id); token = getResources().getString(R.string.token); settings = getSharedPreferences("prefs", 0); AppContext.current_user_name = "GogglesDemo";// settings.getString("selectedUser", // "Goggles_UI"); // AppContext.currrent_user_friend = // getResources().getString(R.string.current_user_friend); String locationString = settings .getString( AppContext.current_user_name, "{\"description\":\"\",\"name\":\"Alex\",\"longitude\":-98.311491,\"latitude\":26.23413147,\"id\":\"cb08ba625f0009c6\",\"lastUpdate\":\"May 7, 2013 4:27:40 AM\",\"type\":\"T_MATE\"}"); if (locationString != null) { AppContext.currentUserLatestLocation = gson.fromJson( locationString, ElementMate.class); } locationString = settings.getString(AppContext.currrent_user_friend, null); if (locationString != null) { AppContext.currentUserFriendLatestLocation = gson.fromJson( locationString, ElementMate.class); } locationString = settings.getString(AppContext.poiName, null); if (locationString != null) { AppContext.poi = gson.fromJson(locationString, ElementPoi.class); } uniqueDeviceId = Secure.getString(getApplicationContext() .getContentResolver(), Secure.ANDROID_ID) + "x"; dao.saveElementMates(getFriendlies()); super.onCreate(); } public static String getUniqueDeviceId() { return uniqueDeviceId; } public static String getCurrentUserName() { return current_user_name; } public static void setCurrentUserName(String username) { current_user_name = username; } public static String getCurrrentUserFriend() { return currrent_user_friend; } public static void setCurrentUserFriend(String currentFriend) { currrent_user_friend = currentFriend; } public static ElementMate getCurrentUserLatestLocation() { return currentUserLatestLocation; } public static ElementMate getCurrentUserFriendLatestLocation() { return currentUserFriendLatestLocation; } public static ElementPoi getPoi() { return AppContext.poi; } public static void setCurrentUserLatestLocation( ElementMate currentUserLatestLocation) { AppContext.currentUserLatestLocation = currentUserLatestLocation; settings.edit().putString(AppContext.current_user_name, gson.toJson(currentUserLatestLocation)); } public static void setCurrentUserFriendLatestLocation( ElementMate currentUserFriendLatestLocation) { AppContext.currentUserFriendLatestLocation = currentUserFriendLatestLocation; settings.edit().putString(AppContext.currrent_user_friend, gson.toJson(currentUserFriendLatestLocation)); } public static void setPoi(ElementPoi poi) { AppContext.poi = poi; settings.edit().putString(AppContext.poiName, gson.toJson(poi)); } public static String getProjectId() { return projectId; } public static String getToken() { return token; } public static String getFriendLocationAction() { return friendLocationAction; } public static String getFriendMessageAction() { return friendMessageAction; } public static String getUserLocationAction() { return userLocationAction; } public static String getMessageBodyExtra() { return messageBodyExtra; } private ArrayList<ElementMate> getFriendlies() { ArrayList<ElementMate> matesArray = new ArrayList<ElementMate>(); ElementMate mate = new ElementMate("Alex", ""); matesArray.add(mate); mate = new ElementMate("Jakub", ""); matesArray.add(mate); mate = new ElementMate("Sebastian", ""); matesArray.add(mate); mate = new ElementMate("Aotuo", ""); matesArray.add(mate); return matesArray; } }
UTF-8
Java
5,064
java
AppContext.java
Java
[ { "context": "es(\"prefs\", 0);\n\t\tAppContext.current_user_name = \"GogglesDemo\";// settings.getString(\"selectedUser\",\n\t\t\t\t\t\t\t\t\t\t", "end": 1622, "score": 0.9985737204551697, "start": 1611, "tag": "USERNAME", "value": "GogglesDemo" }, { "context": "ser_name,\n\t\t\t\t\t\t\"{\\\"description\\\":\\\"\\\",\\\"name\\\":\\\"Alex\\\",\\\"longitude\\\":-98.311491,\\\"latitude\\\":26.234131", "end": 1926, "score": 0.9998327493667603, "start": 1922, "tag": "NAME", "value": "Alex" }, { "context": "entMate>();\n\t\tElementMate mate = new ElementMate(\"Alex\", \"\");\n\t\tmatesArray.add(mate);\n\t\tmate = new Eleme", "end": 4813, "score": 0.9998780488967896, "start": 4809, "tag": "NAME", "value": "Alex" }, { "context": "\t\tmatesArray.add(mate);\n\t\tmate = new ElementMate(\"Jakub\", \"\");\n\t\tmatesArray.add(mate);\n\t\tmate = new Eleme", "end": 4876, "score": 0.9995809197425842, "start": 4871, "tag": "NAME", "value": "Jakub" }, { "context": "\t\tmatesArray.add(mate);\n\t\tmate = new ElementMate(\"Sebastian\", \"\");\n\t\tmatesArray.add(mate);\n\t\tmate = new Eleme", "end": 4943, "score": 0.9997161030769348, "start": 4934, "tag": "NAME", "value": "Sebastian" }, { "context": "\t\tmatesArray.add(mate);\n\t\tmate = new ElementMate(\"Aotuo\", \"\");\n\t\tmatesArray.add(mate);\n\t\treturn matesArra", "end": 5006, "score": 0.9997485280036926, "start": 5001, "tag": "NAME", "value": "Aotuo" } ]
null
[]
package edu.ttu.swri.messenger; import java.util.ArrayList; import android.app.Application; import android.content.SharedPreferences; import android.provider.Settings.Secure; import com.google.gson.Gson; import edu.ttu.swri.data.model.ElementMate; import edu.ttu.swri.data.model.ElementPoi; import edu.ttu.swri.goggles.R; import edu.ttu.swri.goggles.persistence.impl.UserPrefsDAO; public class AppContext extends Application { public static UserPrefsDAO dao; private static final String friendLocationAction = "FRIEND_UPDATE"; private static final String friendMessageAction = "FRIEND_MESSAGE"; private static final String userLocationAction = "USER_LOCATION_CHANGED"; private static final String messageBodyExtra = "MESSAGE_BODY"; private static String current_user_name; private static String currrent_user_friend; private static String projectId; private static String token; private static String poiName = "custom_poi"; public static final String swriFriendsQ = "SWRI_FRIENDS"; private static String uniqueDeviceId; private static ElementMate currentUserLatestLocation = null; private static ElementMate currentUserFriendLatestLocation = null; private static ElementPoi poi = null; private static Gson gson = new Gson(); private static SharedPreferences settings = null; @Override public void onCreate() { dao = new UserPrefsDAO(getApplicationContext()); dao.deleteAllMates(); projectId = getResources().getString(R.string.project_id); token = getResources().getString(R.string.token); settings = getSharedPreferences("prefs", 0); AppContext.current_user_name = "GogglesDemo";// settings.getString("selectedUser", // "Goggles_UI"); // AppContext.currrent_user_friend = // getResources().getString(R.string.current_user_friend); String locationString = settings .getString( AppContext.current_user_name, "{\"description\":\"\",\"name\":\"Alex\",\"longitude\":-98.311491,\"latitude\":26.23413147,\"id\":\"cb08ba625f0009c6\",\"lastUpdate\":\"May 7, 2013 4:27:40 AM\",\"type\":\"T_MATE\"}"); if (locationString != null) { AppContext.currentUserLatestLocation = gson.fromJson( locationString, ElementMate.class); } locationString = settings.getString(AppContext.currrent_user_friend, null); if (locationString != null) { AppContext.currentUserFriendLatestLocation = gson.fromJson( locationString, ElementMate.class); } locationString = settings.getString(AppContext.poiName, null); if (locationString != null) { AppContext.poi = gson.fromJson(locationString, ElementPoi.class); } uniqueDeviceId = Secure.getString(getApplicationContext() .getContentResolver(), Secure.ANDROID_ID) + "x"; dao.saveElementMates(getFriendlies()); super.onCreate(); } public static String getUniqueDeviceId() { return uniqueDeviceId; } public static String getCurrentUserName() { return current_user_name; } public static void setCurrentUserName(String username) { current_user_name = username; } public static String getCurrrentUserFriend() { return currrent_user_friend; } public static void setCurrentUserFriend(String currentFriend) { currrent_user_friend = currentFriend; } public static ElementMate getCurrentUserLatestLocation() { return currentUserLatestLocation; } public static ElementMate getCurrentUserFriendLatestLocation() { return currentUserFriendLatestLocation; } public static ElementPoi getPoi() { return AppContext.poi; } public static void setCurrentUserLatestLocation( ElementMate currentUserLatestLocation) { AppContext.currentUserLatestLocation = currentUserLatestLocation; settings.edit().putString(AppContext.current_user_name, gson.toJson(currentUserLatestLocation)); } public static void setCurrentUserFriendLatestLocation( ElementMate currentUserFriendLatestLocation) { AppContext.currentUserFriendLatestLocation = currentUserFriendLatestLocation; settings.edit().putString(AppContext.currrent_user_friend, gson.toJson(currentUserFriendLatestLocation)); } public static void setPoi(ElementPoi poi) { AppContext.poi = poi; settings.edit().putString(AppContext.poiName, gson.toJson(poi)); } public static String getProjectId() { return projectId; } public static String getToken() { return token; } public static String getFriendLocationAction() { return friendLocationAction; } public static String getFriendMessageAction() { return friendMessageAction; } public static String getUserLocationAction() { return userLocationAction; } public static String getMessageBodyExtra() { return messageBodyExtra; } private ArrayList<ElementMate> getFriendlies() { ArrayList<ElementMate> matesArray = new ArrayList<ElementMate>(); ElementMate mate = new ElementMate("Alex", ""); matesArray.add(mate); mate = new ElementMate("Jakub", ""); matesArray.add(mate); mate = new ElementMate("Sebastian", ""); matesArray.add(mate); mate = new ElementMate("Aotuo", ""); matesArray.add(mate); return matesArray; } }
5,064
0.758096
0.750395
168
29.142857
26.602964
190
false
false
0
0
0
0
0
0
1.952381
false
false
3
c52bf23df74c0ad64774c17341c5b25cb16dd7c8
23,175,643,594,622
5a9f375535b52d1e539c2489bad3a5baa2c8ca70
/DeepWorking/IUnionFind.java
df7e241e6d61a7782b37f30a107ca2a9f69936b1
[]
no_license
AbdoAhmedAbdelaleem/Data-Structures-with-Coursera
https://github.com/AbdoAhmedAbdelaleem/Data-Structures-with-Coursera
de9268b7eeb8d2e2aadcd13c7eaa27e2ecf77231
7152fb5560f1ea875c5abfe9075fd254e76d550f
refs/heads/master
2022-06-21T23:47:07.191000
2020-05-13T05:51:12
2020-05-13T05:51:12
255,009,342
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DeepWorking; /** * * @author Abdo */ public interface IUnionFind { public int find(int index); public void makeSet(int index); public void union(int i,int j); }
UTF-8
Java
378
java
IUnionFind.java
Java
[ { "context": "ditor.\n */\npackage DeepWorking;\n\n/**\n *\n * @author Abdo\n */\npublic interface IUnionFind {\n\n public int", "end": 229, "score": 0.9106711745262146, "start": 225, "tag": "USERNAME", "value": "Abdo" } ]
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 DeepWorking; /** * * @author Abdo */ public interface IUnionFind { public int find(int index); public void makeSet(int index); public void union(int i,int j); }
378
0.685185
0.685185
20
17.9
22.149267
79
false
false
0
0
0
0
0
0
0.4
false
false
3
07db035aca2c84bf157adb79771ec0453784196d
23,880,018,179,910
e128c0e988ad1d714909aff3bc1668cb29ef20a4
/src/team/avengers/gameobjects/HulkSkill.java
ee57717a84ec8e47650f2d5b0039491e785c6593
[]
no_license
fsw0422/Avengers
https://github.com/fsw0422/Avengers
c4ecb20a815e005629a853eba486eba1f771b9df
24b46af11a5e7f49cb4af505b06a5f7d4063b947
refs/heads/master
2016-08-04T16:49:36.330000
2015-02-12T05:40:27
2015-02-12T05:40:27
20,355,125
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package team.avengers.gameobjects; import com.badlogic.gdx.Gdx; public class HulkSkill extends Skill { public HulkSkill(int dur, int cool) { super(dur, cool); soundEffect = Gdx.audio.newSound(Gdx.files.internal("asset/sound/hulk.wav")); } public void changeToHulk(Player ply) { ply.transform(Player.HULK); //hulk이미지는 리스트 1번에 존재 ply.setVelocity(10); ply.setUserData(new UserData("hulk", ply)); soundEffect.play(); } }
UHC
Java
460
java
HulkSkill.java
Java
[]
null
[]
package team.avengers.gameobjects; import com.badlogic.gdx.Gdx; public class HulkSkill extends Skill { public HulkSkill(int dur, int cool) { super(dur, cool); soundEffect = Gdx.audio.newSound(Gdx.files.internal("asset/sound/hulk.wav")); } public void changeToHulk(Player ply) { ply.transform(Player.HULK); //hulk이미지는 리스트 1번에 존재 ply.setVelocity(10); ply.setUserData(new UserData("hulk", ply)); soundEffect.play(); } }
460
0.723744
0.716895
20
20.950001
22.060089
79
false
false
0
0
0
0
0
0
1.4
false
false
5
b6cc562ece79e8e92b1b85bfc9d643fbe8f37a9e
5,059,471,478,015
45335f89eabe4c2baf81d65c51afad4088832c1c
/src/com/promesa/internalFrame/planificacion/IPlanificacion.java
eee9b9c1c08be167c65773163c38aecbf77c3104
[]
no_license
danilmoreno17/proffline
https://github.com/danilmoreno17/proffline
36d00a5b511f3eb8b7216cbd5ba4f9e2628f16df
4ee16759bb6b8bd7d637796f7d4395e93ff759f3
refs/heads/master
2021-06-30T08:23:09.366000
2020-09-08T04:22:25
2020-09-08T04:22:25
134,219,808
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.promesa.internalFrame.planificacion; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.border.BevelBorder; import javax.swing.border.TitledBorder; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; //import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.SwingConstants; import com.promesa.bean.*; import com.promesa.planificacion.bean.*; import com.promesa.planificacion.sql.*; import com.promesa.planificacion.sql.impl.*; import com.promesa.sap.SPlanificacion; import com.promesa.sincronizacion.bean.BeanTareaProgramada; import com.promesa.util.*; import com.toedter.calendar.JCalendar; public class IPlanificacion extends JInternalFrame implements ActionListener, MouseListener, KeyListener { private static final long serialVersionUID = 1L; JToolBar mnuToolBar; JButton btnGuardar; JButton btnEliminar; private JLabel lblEjVen; @SuppressWarnings("rawtypes") JComboBox cmbEjVen; private JLabel lblClie; @SuppressWarnings("rawtypes") JComboBox cmbClie; private JLabel lblDiaOcu; private JLabel lblDesDO; private JLabel lblHorSug; @SuppressWarnings("rawtypes") JComboBox cmbHorSug; private JLabel lblFre; @SuppressWarnings("rawtypes") JComboBox cmbFre; private JLabel lblIdClie = new JLabel(); private JLabel lblIdHorSug = new JLabel(); private JLabel lblIdFre = new JLabel(); private JLabel lblBotonImportExcel = null; private JLabel lblBotonLeerExcel = null; private JLabel lblBotonSalir = null; private JLabel lblBotonExaminarExcel = null; private JPopupMenu popupImportaExcel = null; private JPanel pnlImportaExcel = null; private JPanel pnlPrincipalPopup = null; private JPanel pnlInterno1Popup = null; private JPanel pnlInterno2Popup = null; private JPanel pnlInterno3Popup = null; private JPanel pnlInterno4Popup = null; private JTextField txtDireccionExcel; private JProgressBar pgbInsertado = null; JSeparator separador; JPanel pnlParametros; JPanel pnlListado; JScrollPane scrListado; private JTable tblPlanificacion; DefaultTableModel modeloTabla; private JCalendar dchCalendario; static List<BeanDato> datose; private SqlEmpleado getEmpleado = null; private SqlCliente getCliente = null; private SqlHora getHora = null; private SqlFrecuencia getFrecuencia = null; private SqlPlanificacion getPlanificacion = null; @SuppressWarnings("unused") private SqlVisita getVisita = null; BeanEmpleado em = null; BeanCliente clie = null; BeanHora hor = null; BeanFrecuencia fre = null; BeanPlanificacion pla = null; BeanVisita vis = null; List<BeanEmpleado> listaEmpleado = null; List<BeanCliente> listaCliente = null; List<BeanHora> listaHora = null; List<BeanFrecuencia> listaFrecuencia = null; List<BeanPlanificacion> listaPlanificacion = null; SPlanificacion objSAP; List<BeanPlanificacion> planificacionese; private String fecAct = ""; private String fsp = ""; /* FECHA DE SELECCIÓN PARA PLANIFICACIÓN */ private String fsv = ""; /* FECHA DE SELECCIÓN PARA VISITA */ String[] fecha; private String DireccionFormato = " "; private String estado = "0"; // 0 = NUEVA PLANIFICACIÓN y 1 = ACTUALIZA private String iD = ""; /* ID DE LA PLANIFICACIÓN */ @SuppressWarnings({ "static-access", "rawtypes" }) public IPlanificacion(BeanTareaProgramada beanTareaProgramada) { super("Parámetros de Planificación", true, true, true, true); this.setFrameIcon(new ImageIcon(this.getClass().getResource("/imagenes/iplanificaciones.gif"))); this.setPreferredSize(new java.awt.Dimension(606, 640)); this.setBounds(0, 0, 606, 640); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(235, 239, 242)); mnuToolBar = new JToolBar(); getContentPane().add(mnuToolBar, BorderLayout.NORTH); mnuToolBar.setBounds(0, 0, 1366, 37); // 0, 0, 1018, 37 mnuToolBar.setBackground(new java.awt.Color(235, 239, 242)); separador = new JSeparator(); getContentPane().add(separador); separador.setBounds(0, 39, 1366, 10); // 0, 39, 1318, 10 this.datose = beanTareaProgramada.getDatose(); getEmpleado = new SqlEmpleadoImpl(); getCliente = new SqlClienteImpl(); getHora = new SqlHoraImpl(); getFrecuencia = new SqlFrecuenciaImpl(); getPlanificacion = new SqlPlanificacionImpl(); getVisita = new SqlVisitaImpl(); btnGuardar = new JButton(); mnuToolBar.add(btnGuardar); btnGuardar.setText("Guardar"); btnGuardar.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/guardar.png"))); btnGuardar.addActionListener(this); btnGuardar.setToolTipText("Guardar"); btnGuardar.setPreferredSize(new java.awt.Dimension(93, 29)); btnGuardar.setBackground(new java.awt.Color(0, 128, 64)); btnGuardar.setOpaque(false); btnGuardar.setBorder(null); btnGuardar.setFocusable(false); btnEliminar = new JButton(); mnuToolBar.add(btnEliminar); btnEliminar.setText("Eliminar"); btnEliminar.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/eliminar.gif"))); btnEliminar.addActionListener(this); btnEliminar.setToolTipText("Eliminar"); btnEliminar.setPreferredSize(new java.awt.Dimension(100, 29)); btnEliminar.setBackground(new java.awt.Color(0, 128, 64)); btnEliminar.setOpaque(false); btnEliminar.setBorder(null); btnEliminar.setFocusable(false); pnlParametros = new JPanel(); getContentPane().add(pnlParametros); pnlParametros.setBounds(0, 48, 790, 210); pnlParametros.setLayout(null); pnlParametros.setBorder(BorderFactory.createTitledBorder("Parámetros")); pnlParametros.setFocusable(false); { lblEjVen = new JLabel(); pnlParametros.add(lblEjVen); lblEjVen.setText("Ejecutivo de Ventas:"); lblEjVen.setBounds(16, 25, 119, 17); lblEjVen.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbEjVen = new JComboBox(); pnlParametros.add(cmbEjVen); cmbEjVen.setToolTipText("Ejecutivo de Ventas"); cmbEjVen.setBounds(145, 23, 220, 24); cmbEjVen.setFocusable(false); cmbEjVen.setFont(new java.awt.Font("Candara", 0, 11)); cargaInicialVendedor(); cmbEjVen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { cargaCliente(); bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } }); cmbEjVen.setBackground(new java.awt.Color(255, 255, 255)); } { lblClie = new JLabel(); pnlParametros.add(lblClie); lblClie.setText("Cliente:"); lblClie.setBounds(389, 25, 125, 17); lblClie.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbClie = new JComboBox(); pnlParametros.add(cmbClie); cmbClie.setToolTipText("Cliente"); cmbClie.setBounds(449, 23, 220, 24); cmbClie.setFocusable(false); cmbClie.setFont(new java.awt.Font("Candara", 0, 11)); cargaInicialCliente(); cmbClie.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { buscaPlanificacion(); bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } }); cmbClie.setBackground(new java.awt.Color(255, 255, 255)); } { lblDiaOcu = new JLabel(); pnlParametros.add(lblDiaOcu); lblDiaOcu.setText("Día y Ocurrencia:"); lblDiaOcu.setBounds(16, 60, 125, 17); lblDiaOcu.setFont(new java.awt.Font("Arial", 1, 11)); } { dchCalendario = new JCalendar(); pnlParametros.add(dchCalendario); dchCalendario.setBounds(335, 50, 200, 155); dchCalendario.setRequestFocusEnabled(false); dchCalendario.getDayChooser().addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { validaFecha(); } }); dchCalendario.setFocusable(false); } { lblDesDO = new JLabel(); pnlParametros.add(lblDesDO); lblDesDO.setText(capturaOrganizaFecha()); lblDesDO.setBounds(145, 60, 147, 17); lblDesDO.setFont(new java.awt.Font("Arial", 2, 12)); lblDesDO.setForeground(new java.awt.Color(0, 0, 255)); } if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { { lblBotonImportExcel = new JLabel("Importar (desde Excel)"); lblBotonImportExcel.setBackground(new Color(238, 238, 238)); lblBotonImportExcel.setFont(new Font("Arial", 1, 11)); lblBotonImportExcel.setIcon(new ImageIcon(getClass().getResource("/imagenes/exportar.gif"))); lblBotonImportExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonImportExcel.setBounds(620, 180, 160, 20); lblBotonImportExcel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonImportExcelMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonImportExcelMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonImportExcelMouseReleased(evt); } }); pnlParametros.add(lblBotonImportExcel); } { lblBotonLeerExcel = new JLabel(" Leer "); lblBotonLeerExcel.setBackground(new Color(238, 238, 238)); lblBotonLeerExcel.setFont(new Font("Arial", 1, 12)); lblBotonLeerExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonLeerExcel.setBounds(650, 50, 90, 20); lblBotonLeerExcel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonLeerExcelMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonLeerExcelMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonLeerExcelMouseReleased(evt); } }); } { lblBotonSalir = new JLabel(); lblBotonSalir.setBackground(new Color(238, 238, 238)); lblBotonSalir.setFont(new Font("Arial", 1, 12)); lblBotonSalir.setIcon(new ImageIcon(getClass().getResource("/imagenes/borrar.png"))); lblBotonSalir.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonSalir.setBounds(650, 50, 150, 20); lblBotonSalir.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonSalirMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonSalirMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonSalirMouseReleased(evt); } }); } { lblBotonExaminarExcel = new JLabel(" Examinar "); lblBotonExaminarExcel.setBackground(new Color(238, 238, 238)); lblBotonExaminarExcel.setFont(new Font("Arial", 1, 12)); lblBotonExaminarExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonExaminarExcel.setBounds(650, 50, 90, 20); lblBotonExaminarExcel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonExaminarExcelMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonExaminarExcelMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonExaminarExcelMouseReleased(evt); } }); } { pgbInsertado = new JProgressBar(0, 100); pgbInsertado.setValue(0); pgbInsertado.setStringPainted(true); } { txtDireccionExcel = new JTextField(); txtDireccionExcel.setEditable(false); txtDireccionExcel.setBackground(new java.awt.Color(255, 255,255)); } { pnlInterno1Popup = new JPanel(new BorderLayout()); pnlInterno1Popup.add(txtDireccionExcel, BorderLayout.NORTH); } { pnlInterno3Popup = new JPanel(); pnlInterno3Popup.add(lblBotonLeerExcel); lblBotonLeerExcel.setBounds(1, 100, 60, 30); } { pnlInterno4Popup = new JPanel(new BorderLayout()); pnlInterno4Popup.setLayout(new BorderLayout()); pnlInterno4Popup.add(lblBotonSalir, BorderLayout.EAST); } { pnlInterno2Popup = new JPanel(); pnlInterno2Popup.setLayout(new BorderLayout()); pnlInterno2Popup.add(pnlInterno3Popup, BorderLayout.CENTER); pnlInterno2Popup.add(lblBotonExaminarExcel, BorderLayout.NORTH); } { pnlImportaExcel = new JPanel(); pnlImportaExcel.setLayout(new BorderLayout()); pnlImportaExcel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Importar Excel", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Arial", 1, 12))); pnlImportaExcel.add(pnlInterno1Popup, BorderLayout.CENTER); pnlImportaExcel.add(pnlInterno2Popup, BorderLayout.EAST); } { pnlPrincipalPopup = new JPanel(); pnlPrincipalPopup.setLayout(new BorderLayout()); pnlPrincipalPopup.add(pnlInterno4Popup, BorderLayout.NORTH); pnlPrincipalPopup.add(pnlImportaExcel, BorderLayout.CENTER); pnlPrincipalPopup.add(pgbInsertado, BorderLayout.SOUTH); pnlPrincipalPopup.setPreferredSize(new Dimension(300, 115)); } { popupImportaExcel = new JPopupMenu(); popupImportaExcel.add(pnlPrincipalPopup); } } { lblHorSug = new JLabel(); pnlParametros.add(lblHorSug); lblHorSug.setText("Hora Sugerida:"); lblHorSug.setBounds(16, 95, 125, 17); lblHorSug.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbHorSug = new JComboBox(); pnlParametros.add(cmbHorSug); cmbHorSug.setToolTipText("Hora Sugerida"); cmbHorSug.setBounds(145, 93, 147, 24); cmbHorSug.setFocusable(false); cmbHorSug.setFont(new java.awt.Font("Candara", 0, 11)); cargaHora(); cmbHorSug.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { eventoHora(); } }); cmbHorSug.setBackground(new java.awt.Color(255, 255, 255)); } { lblFre = new JLabel(); pnlParametros.add(lblFre); lblFre.setText("Frecuencia:"); lblFre.setBounds(16, 130, 125, 17); lblFre.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbFre = new JComboBox(); pnlParametros.add(cmbFre); cmbFre.setToolTipText("Frecuencia"); cmbFre.setBounds(145, 128, 147, 24); cmbFre.setFocusable(false); cmbFre.setFont(new java.awt.Font("Candara", 0, 11)); cargaFrecuencia(); cmbFre.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { eventoFrecuencia(); } }); cmbFre.setBackground(new java.awt.Color(255, 255, 255)); } pnlListado = new JPanel(); getContentPane().add(pnlListado); pnlListado.setBounds(0, 260, 790, 145); pnlListado.setLayout(null); pnlListado.setBorder(BorderFactory.createTitledBorder("Planificaciones")); pnlListado.setFocusable(false); scrListado = new JScrollPane(); pnlListado.add(scrListado); scrListado.setBounds(50, 29, 680, 95); scrListado.setToolTipText("Relación de Planificaciones"); buscaPlanificacion(); } /* MÉTODO QUE LISTA PLANIFICACIONES */ public void buscaPlanificacion() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); planificacionese = new ArrayList<BeanPlanificacion>(); try { objSAP = new SPlanificacion(); if (be == null && bc == null) { listaPlanificacion = null; } else if (be.getStrIdEmpleado() == null && bc.getStrIdCliente() == null) { Mensaje.mostrarAviso(Constante.MENSAJE_NO_VENDEDOR_NO_CLIENTE); } else if (be.getStrIdEmpleado() != null && bc == null) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { listaPlanificacion = objSAP.listaPlanificacion(be.getStrIdEmpleado(), Constante.VACIO); } else { BeanPlanificacion planificacion = new BeanPlanificacion(); planificacion.setStrIdVendedor(be.getStrIdEmpleado()); planificacion.setStrIdCliente(Constante.VACIO); getPlanificacion.setListaPlanificacion(planificacion); listaPlanificacion = getPlanificacion.getListaPlanificacion(); } } else if (be.getStrIdEmpleado() != null && bc.getStrIdCliente() != null) { if (bc.getStrIdCliente().equals(Constante.VACIO)) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { listaPlanificacion = objSAP.listaPlanificacion(be.getStrIdEmpleado(), Constante.VACIO); } else { BeanPlanificacion planificacion = new BeanPlanificacion(); planificacion.setStrIdVendedor(be.getStrIdEmpleado()); planificacion.setStrIdCliente(Constante.VACIO); getPlanificacion.setListaPlanificacion(planificacion); listaPlanificacion = getPlanificacion.getListaPlanificacion(); } } else { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { listaPlanificacion = objSAP.listaPlanificacion(Constante.VACIO, bc.getStrIdCliente()); } else { BeanPlanificacion planificacion = new BeanPlanificacion(); planificacion.setStrIdVendedor(Constante.VACIO); planificacion.setStrIdCliente(bc.getStrIdCliente()); getPlanificacion.setListaPlanificacion(planificacion); listaPlanificacion = getPlanificacion.getListaPlanificacion(); } } } } catch (Exception e) { Util.mostrarExcepcion(e); } if (listaPlanificacion != null) { for (BeanPlanificacion p : listaPlanificacion) { pla = new BeanPlanificacion(); pla.setStrIdPlan(p.getStrIdPlan()); pla.setStrIdVendedor(p.getStrIdVendedor()); pla.setStrIdJefe(p.getStrIdJefe()); pla.setStrFechaInicio(p.getStrFechaInicio()); pla.setStrFechaFin(p.getStrFechaFin()); pla.setStrHora(p.getStrHora()); pla.setStrIdCliente(p.getStrIdCliente()); pla.setStrIdFrecuencia(p.getStrIdFrecuencia()); pla.setStrFrecuencia(p.getStrFrecuencia()); pla.setStrDia(p.getStrDia()); pla.setStrNombreCliente(p.getStrNombreCliente()); try { planificacionese.add(pla); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_BUSQUEDA_PLANIFICACION); } } } if (planificacionese == null || planificacionese.size() == 0) { tablaVacia(); btnEliminar.setEnabled(false); } else { tablaLLena(); btnEliminar.setEnabled(true); } } /* MÉTODO QUE CARGA VENDEDORES SEGÚN SUPERVISOR */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void cargaInicialVendedor() { BeanEmpleado empleado = new BeanEmpleado(); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { try { objSAP = new SPlanificacion(); listaEmpleado = objSAP.listaVendedor(((BeanDato) datose.get(0)).getStrCodigo()); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(e.getMessage()); } } else { empleado.setStrIdSupervisor(((BeanDato) datose.get(0)).getStrCodigo()); getEmpleado.setListaEmpleado(empleado); listaEmpleado = new ArrayList<BeanEmpleado>(); listaEmpleado = getEmpleado.getListaEmpleado(); } if (listaEmpleado != null && listaEmpleado.size() > 0) { cmbEjVen.setModel(new DefaultComboBoxModel(listaEmpleado.toArray())); } else { cmbEjVen.setModel(new DefaultComboBoxModel()); } } /* MÉTODO QUE CARGA CLIENTES SEGÚN VENDEDOR */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void cargaInicialCliente() { if (listaEmpleado != null && listaEmpleado.size() > 0) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { try { objSAP = new SPlanificacion(); listaCliente = objSAP.listaClientePlanificacion(listaEmpleado.get(0).getStrIdEmpleado()); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(e.getMessage()); } } else { BeanCliente cliente = new BeanCliente(); BeanClienteEmpleado clienteEmpleado = new BeanClienteEmpleado(); clienteEmpleado.setStrIdEmpleado(listaEmpleado.get(0).getStrIdEmpleado()); cliente.setClienteEmpleado(clienteEmpleado); getCliente.setListaCliente(cliente); listaCliente = new ArrayList<BeanCliente>(); listaCliente = getCliente.getListaCliente(); } } if (listaCliente != null && listaCliente.size() > 0) { cmbClie.setModel(new DefaultComboBoxModel(listaCliente.toArray())); } else { cmbClie.setModel(new DefaultComboBoxModel()); } } /* MÉTODO QUE CARGA CLIENTES SEGÚN CAMBIO DE VENDEDOR */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void cargaCliente() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { try { objSAP = new SPlanificacion(); listaCliente = objSAP.listaClientePlanificacion(be.getStrIdEmpleado()); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(e.getMessage()); } } else { BeanCliente cliente = new BeanCliente(); BeanClienteEmpleado clienteEmpleado = new BeanClienteEmpleado(); clienteEmpleado.setStrIdEmpleado(be.getStrIdEmpleado()); cliente.setClienteEmpleado(clienteEmpleado); getCliente.setListaCliente(cliente); listaCliente = new ArrayList<BeanCliente>(); listaCliente = getCliente.getListaCliente(); } if (listaCliente != null && listaCliente.size() > 0) { cmbClie.setModel(new DefaultComboBoxModel(listaCliente.toArray())); } else { cmbClie.setModel(new DefaultComboBoxModel()); } buscaPlanificacion(); } /* MÉTODO QUE PINTA UNA TABLA SIN DATOS */ public void tablaVacia() { String Columnas[] = { "Plan", "Fecha Inicio", "Día y Ocurrencia", "Hora", "Frecuencia", "ID Cliente", "Cliente" }; modeloTabla = new DefaultTableModel(null, Columnas); TableModel tblTablaModel = new DefaultTableModel( new Object[][] { { "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "" } }, Columnas) { private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { return false; } }; tblPlanificacion = new JTable(); tblPlanificacion.setModel(tblTablaModel); scrListado.setViewportView(tblPlanificacion); pnlListado.add(scrListado); } /* MÉTODO QUE PINTA UNA TABLA CON DATOS */ public void tablaLLena() { String Columnas[] = { "Plan", "Fecha Inicio", "Día y Ocurrencia", "Hora", "Frecuencia", "ID Cliente", "Cliente" }; modeloTabla = new DefaultTableModel(null, Columnas) { private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { return false; } }; if (planificacionese.size() > 4) { modeloTabla.setNumRows(planificacionese.size()); } else { modeloTabla.setNumRows(4); } for (int i = 0; i < planificacionese.size(); i++) { modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrIdPlan(), i, 0); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { modeloTabla.setValueAt(convierteFecha(((BeanPlanificacion) planificacionese.get(i)).getStrFechaInicio()), i, 1); } else { modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrFechaInicio(), i, 1); } modeloTabla.setValueAt(convierteDO(((BeanPlanificacion) planificacionese.get(i)).getStrFechaInicio()), i, 2); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrHora(),i, 3); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrFrecuencia(), i, 4); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrIdCliente(), i, 5); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrNombreCliente(), i, 6); } tblPlanificacion = new JTable(); tblPlanificacion.setModel(modeloTabla); tblPlanificacion.addKeyListener(this); tblPlanificacion.addMouseListener(this); tblPlanificacion.getColumnModel().getColumn(0).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(1).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(2).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(3).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(4).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(5).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(6).setCellRenderer(new Renderer().getCenterCell()); scrListado.setViewportView(tblPlanificacion); pnlListado.add(scrListado); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 0, 70); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 1, 80); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 2, 130); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 3, 40); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 4, 70); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 5, 89); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 6, 201); } /* MÉTODO QUE OBTIENE DÍA Y OCURRENCIA */ public String convierteDO(String fsf) { int dia, mes, anio; if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { dia = Integer.parseInt(convierteFecha(fsf).substring(0, 2)); } else { dia = Integer.parseInt(fsf.substring(0, 2)); } if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { mes = Integer.parseInt(convierteFecha(fsf).substring(3, 5)) - 1; } else { mes = Integer.parseInt(fsf.substring(3, 5)) - 1; } if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { anio = Integer.parseInt(convierteFecha(fsf).substring(6, 10)); } else { anio = Integer.parseInt(fsf.substring(6, 10)); } Calendar c = new GregorianCalendar(Locale.ROOT); c.setFirstDayOfWeek(Calendar.MONDAY); c.set(anio, mes, dia); int posicionMes = c.get(Calendar.DAY_OF_WEEK_IN_MONTH); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { return obtieneDO(String.valueOf(posicionMes), convierteFecha(fsf)); } else { return obtieneDO(String.valueOf(posicionMes), fsf); } } /* CONVERSIÓN A DD.MM.YYYY */ public String convierteFecha(String fsf) { SimpleDateFormat sdf1 = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); SimpleDateFormat sdf2 = new SimpleDateFormat("dd.MM.yyyy"); try { String StringRecogido = fsf; Date datehora = sdf1.parse(StringRecogido); return sdf2.format(datehora); } catch (Exception e) { Util.mostrarExcepcion(e); return e.getMessage(); } } /* MÉTODO QUE CAPTURA ID FRECUENCIA */ public void eventoFrecuencia() { lblIdFre.setText(listaFrecuencia.get(cmbFre.getSelectedIndex()).getStrIdFrecuencia()); } /* MÉTODO QUE CAPTURA ID HORA */ public void eventoHora() { lblIdHorSug.setText(listaHora.get(cmbHorSug.getSelectedIndex()).getStrIdHora()); } /* MÉTODO QUE CAPTURA ID CLIENTE */ public void eventoCliente() { lblIdClie.setText(listaCliente.get(cmbClie.getSelectedIndex()).getStrIdCliente()); } /* MÉTODO QUE CARGA LAS FRECUENCIAS */ @SuppressWarnings("unchecked") public void cargaFrecuencia() { BeanFrecuencia frecuencia = new BeanFrecuencia(); getFrecuencia.setListaFrecuencia(frecuencia); listaFrecuencia = new ArrayList<BeanFrecuencia>(); listaFrecuencia = getFrecuencia.getListaFrecuencia(); if (listaFrecuencia != null && listaFrecuencia.size() > 0) { lblIdFre.setText(listaFrecuencia.get(0).getStrIdFrecuencia()); for (int i = 0; i < listaFrecuencia.size(); i++) { fre = new BeanFrecuencia(); fre = listaFrecuencia.get(i); cmbFre.addItem(fre.getStrFrecuencia()); } } else { cmbFre.addItem(""); } } /* MÉTODO QUE CARGA LAS HORAS */ @SuppressWarnings("unchecked") public void cargaHora() { BeanHora hora = new BeanHora(); getHora.setListaHora(hora); listaHora = new ArrayList<BeanHora>(); listaHora = getHora.getListaHora(); if (listaHora != null && listaHora.size() > 0) { lblIdHorSug.setText(listaHora.get(0).getStrIdHora()); for (int i = 0; i < listaHora.size(); i++) { hor = new BeanHora(); hor = listaHora.get(i); cmbHorSug.addItem(hor.getStrHora()); } } else { cmbHorSug.addItem(""); } } @Override public void keyPressed(KeyEvent arg0) { } @Override public void keyReleased(KeyEvent arg0) { } @Override public void keyTyped(KeyEvent arg0) { } @Override public void mouseClicked(MouseEvent arg0) { if (arg0.getClickCount() == 2) { if (arg0.getSource() == tblPlanificacion) { int fila = tblPlanificacion.rowAtPoint(arg0.getPoint()); if ((fila > -1)) { estado = "1"; /* ESPECIFICA UNA ACTUALIZACIÓN */ iD = modeloTabla.getValueAt(fila, 0).toString(); cmbEjVen.setEnabled(false); cmbClie.setEnabled(false); btnEliminar.setEnabled(false); } else { Mensaje.mostrarError(Constante.MENSAJE_BUSQUEDA_PLANIFICACION); } } } } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } /* MÉTODO QUE PROCESA LA FECHA */ public String[] fecha() { String[] fecha = new String[3]; fecha[0] = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)); fecha[1] = Integer.toString(dchCalendario.getCalendar().get( java.util.Calendar.MONTH) + 1); if (fecha[1].equals("1") || fecha[1].equals("2") || fecha[1].equals("3") || fecha[1].equals("4") || fecha[1].equals("5") || fecha[1].equals("6") || fecha[1].equals("7") || fecha[1].equals("8") || fecha[1].equals("9")) { fecha[1] = "0" + fecha[1]; } fecha[2] = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.DATE)); if (fecha[2].equals("1") || fecha[2].equals("2") || fecha[2].equals("3") || fecha[2].equals("4") || fecha[2].equals("5") || fecha[2].equals("6") || fecha[2].equals("7") || fecha[2].equals("8") || fecha[2].equals("9")) { fecha[2] = "0" + fecha[2]; } return fecha; } /* MÉTODO QUE RECIBE Y ENVÍA LA FECHA */ public String capturaOrganizaFecha() { fecha = fecha(); fecAct = fecha[2] + "." + fecha[1] + "." + fecha[0]; return fecAct; } /* MÉTODO QUE OBTIENE LA OCURRENCIA */ public String obtieneDO(String v1, String v2) { String cadena = ""; if (v1.equals("1")) { cadena = Constante.PRIMERO; } if (v1.equals("2")) { cadena = Constante.SEGUNDO; } if (v1.equals("3")) { cadena = Constante.TERCERO; } if (v1.equals("4")) { cadena = Constante.CUARTO; } if (v1.equals("5")) { cadena = Constante.QUINTO; } return cadena + " " + FechaHora.getDia(v2) + " del mes"; } /* MÉTODO QUE ANUNCIA LOS MESES (DE REALIZACIÓN) DE LA PLANIFICACIÓN */ public String anunciaMesesPlanificacion(String mes) { String msg = ""; if (mes.equals("01")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Enero y Febrero."; } if (mes.equals("02")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Febrero y Marzo."; } if (mes.equals("03")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Marzo y Abril."; } if (mes.equals("04")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Abril y Mayo."; } if (mes.equals("05")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Mayo y Junio."; } if (mes.equals("06")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Junio y Julio."; } if (mes.equals("07")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Julio y Agosto."; } if (mes.equals("08")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Agosto y Setiembre."; } if (mes.equals("09")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Setiembre y Octubre."; } if (mes.equals("10")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Octubre y Noviembre."; } if (mes.equals("11")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Noviembre y Diciembre."; } if (mes.equals("12")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Diciembre y Enero."; } return msg; } /* MÉTODO QUE VALIDA LA FECHA */ public void validaFecha() { String año; /* AÑO */ año = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)); /* CAPTURA AÑO */ if ((FechaHora.getFecha().charAt(6) + Constante.VACIO + FechaHora.getFecha().charAt(7) + Constante.VACIO + FechaHora.getFecha().charAt(8) + Constante.VACIO + FechaHora.getFecha().charAt(9)).equals(año)) { String vD; vD = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.DAY_OF_WEEK)); if (!(vD.equals("1"))) { String mes, dia; mes = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.MONTH) + 1); if (mes.equals("1") || mes.equals("2") || mes.equals("3") || mes.equals("4") || mes.equals("5") || mes.equals("6") || mes.equals("7") || mes.equals("8") || mes.equals("9")) { mes = "0" + mes; } dia = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.DATE)); if (dia.equals("1") || dia.equals("2") || dia.equals("3") || dia.equals("4") || dia.equals("5") || dia.equals("6") || dia.equals("7") || dia.equals("8") || dia.equals("9")) { dia = "0" + dia; } fsp = año + mes + dia; fsv = dia + Constante.SEPARADOR + mes + Constante.SEPARADOR + año; lblDesDO.setText(obtieneDO(String.valueOf(dchCalendario.getCalendar().get(java.util.Calendar.DAY_OF_WEEK_IN_MONTH)), fsv)); } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_DOMINGO); } } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_AÑO_ACTUAL); } } /* MÉTODO QUE CALCULA EL MES */ public String calculaMes(String cadena) { String mes = ""; if ((cadena.charAt(4) + "" + cadena.charAt(5)).equals("12")) { mes = "01"; } else { int temp; temp = Integer.parseInt(cadena.charAt(4) + "" + cadena.charAt(5)) + 1; if (temp < 10) { mes = "0" + temp; } else { mes = String.valueOf(temp); } } return mes; } /* MÉTODO QUE CALCULA EL DÍA */ public String calculaDia(String cadena) { String dia = ""; if (calculaMes(cadena).equals("01")) { dia = "31"; } if (calculaMes(cadena).equals("02")) { GregorianCalendar calendar = new GregorianCalendar(); if (calendar.isLeapYear(Integer.parseInt(cadena.charAt(0) + "" + cadena.charAt(1) + "" + cadena.charAt(2) + "" + cadena.charAt(3)))) dia = "29"; else dia = "28"; } if (calculaMes(cadena).equals("03")) { dia = "31"; } if (calculaMes(cadena).equals("04")) { dia = "30"; } if (calculaMes(cadena).equals("05")) { dia = "31"; } if (calculaMes(cadena).equals("06")) { dia = "30"; } if (calculaMes(cadena).equals("07")) { dia = "31"; } if (calculaMes(cadena).equals("08")) { dia = "31"; } if (calculaMes(cadena).equals("09")) { dia = "30"; } if (calculaMes(cadena).equals("10")) { dia = "31"; } if (calculaMes(cadena).equals("11")) { dia = "30"; } if (calculaMes(cadena).equals("12")) { dia = "31"; } return dia; } /* MÉTODO QUE INGRESA UNA PLANIFICACIÓN */ @SuppressWarnings("static-access") public void ingresaModificaPlanificacion() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); if (be == null && bc == null) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPOS_VACIOS_VENDEDOR_CLIENTE); } else if (cmbEjVen.getSelectedItem().toString().equals("") && cmbClie.getSelectedItem().toString().equals("")) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPOS_VACIOS_VENDEDOR_CLIENTE); } else if (cmbEjVen.getSelectedItem().toString().equals("") && !cmbClie.getSelectedItem().toString().equals("")) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPO_VACIO_VENDEDOR); } else if (!cmbEjVen.getSelectedItem().toString().equals("") && cmbClie.getSelectedItem().toString().equals("")) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPO_VACIO_CLIENTE); } else if (!cmbEjVen.getSelectedItem().toString().equals("") && !cmbClie.getSelectedItem().toString().equals("")) { if (estado.equals("0")) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); String idPla; try { objSAP = new SPlanificacion(); idPla = objSAP.ingresaPlanificacion(be.getStrIdEmpleado(), ((BeanDato) datose.get(0)).getStrCodigo(), fsp, Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)) + calculaMes(fsp) + calculaDia(fsp), cmbHorSug .getSelectedItem().toString(), bc.getStrIdCliente(), "0" + lblIdFre.getText().trim()); if (idPla != null) { String msg; for (int j = 0; j < idPla.length(); j++) { if (idPla.charAt(j) != '0') { idPla = idPla.substring(j, idPla.length()); break; } } Visita objFI = new Visita(); List<String> lstFechas = objFI.siguientesVisitas(fsv, "0" + lblIdFre.getText().trim()); msg = objSAP.ingresaVisitaFueraDeRuta(be.getStrIdEmpleado(), bc.getStrIdCliente(), lstFechas, cmbHorSug.getSelectedItem().toString(), Constante.TIPO_VISITA1, idPla); if (msg != null) { Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_NUEVA_PLANIFICACION); Mensaje.mostrarAviso(anunciaMesesPlanificacion(fsp.substring(4, 6))); buscaPlanificacion(); } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); } } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); } bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } else { Mensaje.mostrarWarning(Constante.MENSAJE_VALIDA_NUEVA_PLANIFICACION); } } else { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); String msg1; try { objSAP = new SPlanificacion(); msg1 = objSAP.actualizaPlanificacion(iD, bc.getStrIdCliente(), fsp, cmbHorSug.getSelectedItem().toString(), "0" + lblIdFre.getText().trim()); if (msg1 != null) { String msg2; Visita objFI = new Visita(); List<String> lstFechas = objFI.siguientesVisitas(fsv, "0"+ lblIdFre.getText().trim()); msg2 = objSAP.ingresaVisitaFueraDeRuta(be.getStrIdEmpleado(), bc.getStrIdCliente(), lstFechas, cmbHorSug.getSelectedItem().toString(), Constante.TIPO_VISITA1, iD); if (msg2 != null) { Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_MODIFICA_PLANIFICACION); Mensaje.mostrarAviso(anunciaMesesPlanificacion(fsp.substring(4, 6))); buscaPlanificacion(); } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_MODIFICA_PLANIFICACION); } cmbEjVen.setEnabled(true); cmbClie.setEnabled(true); btnEliminar.setEnabled(true); estado = "0"; } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_MODIFICA_PLANIFICACION); } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_MODIFICA_PLANIFICACION); } bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } else { Mensaje.mostrarWarning(Constante.MENSAJE_VALIDA_MODIFICA_PLANIFICACION); } } } } public void eliminaPlanificacion() { if (!cmbEjVen.getSelectedItem().toString().equals("")&& !cmbClie.getSelectedItem().toString().equals("")) { if (tblPlanificacion.getSelectedRow() > -1) { if (Mensaje.preguntar(Constante.MENSAJE_PREGUNTA_ELIMINA_PLANIFICACION)) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); try { objSAP = new SPlanificacion(); DefaultTableModel dtm = (DefaultTableModel) tblPlanificacion.getModel(); int fila = tblPlanificacion.getSelectedRow(); objSAP.eliminaPlanificacion(modeloTabla.getValueAt(fila, 0).toString(), be.getStrIdEmpleado(), bc.getStrIdCliente()); Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_ELIMINA_PLANIFICACION); dtm.removeRow(fila); if (modeloTabla.getRowCount() == 3) { dtm.insertRow(3, new Object[] { "", "", "", "", "" }); } else { dtm.insertRow(planificacionese.size() - 1, new Object[] { "", "", "", "", "" }); } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_ELIMINA_PLANIFICACION); } bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } else { Mensaje.mostrarWarning(Constante.MENSAJE_VALIDA_ELIMINA_PLANIFICACION); } } } else { Mensaje.mostrarAviso(Constante.MENSAJE_SELECCION_ELIMINA_PLANIFICACION); } } } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() == btnGuardar) { /* IMPLEMEMTA FUNCIONALIDAD GUARDAR */ ingresaModificaPlanificacion(); } if (arg0.getSource() == btnEliminar) { /* IMPLEMEMTA FUNCIONALIDAD ELIMINAR */ eliminaPlanificacion(); } } private void lblBotonImportExcelMouseClicked(MouseEvent evt) { lblBotonImportExcel.add(popupImportaExcel); popupImportaExcel.show(lblBotonImportExcel, -150, 0); popupImportaExcel.setVisible(true); } private void lblBotonImportExcelMousePressed(MouseEvent evt) { if (lblBotonImportExcel.isEnabled() == true) { lblBotonImportExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonImportExcel.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonImportExcelMouseReleased(MouseEvent evt) { lblBotonImportExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonImportExcel.setVerticalAlignment(SwingConstants.CENTER); } private void lblBotonLeerExcelMouseClicked(MouseEvent evt) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { pgbInsertado.setValue(0); insertaPlanificado(); bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } /* MÉTODO QUE RETORNA EL ID FRECUENCIA SEGÚN DESCRIPCIÓN */ public String idFrecuencia(String frecuencia) { String idFre = ""; if (frecuencia.equalsIgnoreCase("7")) { idFre = "01"; } if (frecuencia.equalsIgnoreCase("14")) { idFre = "02"; } if (frecuencia.equalsIgnoreCase("28")) { idFre = "03"; } return idFre; } /* MÉTODO QUE COMPLETA CEROS */ public String completaCeros(String codigo) { int i = codigo.length(); while (i < 10) { codigo = "0" + codigo; i++; } return codigo; } /* MÉTODO QUE VALIDA UN VENDEDOR */ public boolean validaVendedor(String codigo) { boolean resultado = false; String temp = completaCeros(codigo); for (int i = 0; i < listaEmpleado.size(); i++) { if (listaEmpleado.get(i).getStrIdEmpleado().equals(temp)) { resultado = true; break; } } return resultado; } /* MÉTODO QUE VALIDA HORA */ public boolean validaHora(String hora) { boolean resultado = false; if (hora.length() == 5) { if (hora.equals("08:00") || hora.equals("08:30") || hora.equals("09:00") || hora.equals("09:30") || hora.equals("10:00") || hora.equals("10:30") || hora.equals("11:00") || hora.equals("11:30") || hora.equals("12:00") || hora.equals("12:30") || hora.equals("13:00") || hora.equals("13:30") || hora.equals("14:00") || hora.equals("14:30") || hora.equals("15:00") || hora.equals("15:30") || hora.equals("16:00") || hora.equals("16:30") || hora.equals("17:00") || hora.equals("17:30") || hora.equals("18:00") || hora.equals("18:30")) resultado = true; } return resultado; } /* MÉTODO QUE VALIDA UN CLIENTE */ public boolean validaCliente(String codigo) { boolean resultado = false; String temp = completaCeros(codigo); for (int i = 0; i < listaCliente.size(); i++) { if (listaCliente.get(i).getStrIdCliente().equals(temp)) { resultado = true; break; } } return resultado; } /* MÉTODO QUE VALIDA UNA FECHA */ public boolean validaFecha(String fecha) { boolean resultado = false; String anio = "" + fecha.charAt(0) + fecha.charAt(1) + fecha.charAt(2) + fecha.charAt(3); String mes = "" + fecha.charAt(4) + fecha.charAt(5); String dia = "" + fecha.charAt(6) + fecha.charAt(7); if (fecha.length() == 8) { if (anio.equals(Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)))) { if (mes.charAt(0) == '0') { if (mes.charAt(1) == '1' || mes.charAt(1) == '2' || mes.charAt(1) == '3' || mes.charAt(1) == '4' || mes.charAt(1) == '5' || mes.charAt(1) == '6' || mes.charAt(1) == '7' || mes.charAt(1) == '8' || mes.charAt(1) == '9') { if (dia.charAt(0) == '0') { if (dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '1') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '2') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '3') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1') { resultado = true; } } } } if (mes.charAt(0) == '1') { if (mes.charAt(1) == '0' || mes.charAt(1) == '1' || mes.charAt(1) == '2') { if (dia.charAt(0) == '0') { if (dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '1') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '2') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '3') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1') { resultado = true; } } } } } } return resultado; } /* MÉTODO QUE VALIDA FRECUENCIA */ public boolean validaFrecuencia(String frecuencia) { boolean resultado = false; if (frecuencia.equals("7") || frecuencia.equals("14") || frecuencia.equals("28")) resultado = true; return resultado; } @SuppressWarnings({ "unused", "static-access" }) public void insertaPlanificado() { boolean estado = false; /* VALOR INICIAL */ LeerHojaExcel leerHojaExcel = new LeerHojaExcel(); List<HashMap<String, String>> listaPlanificacion = null; HashMap<String, String> dataSet = null; SqlPlanificacion getPlanificacion = new SqlPlanificacionImpl(); ThreadSocketProgressBar thrProgreso = null; String idPla; String msg; String diaVisita; int filas = 0; int contarFilas = 0; SqlVisita sqlVisita = new SqlVisitaImpl(); BeanVisita visita = null; BeanPlanificacion planificacion = null; pgbInsertado.setValue(0); HashMap<Integer, String> lblColumna_Planificacion = new HashMap<Integer, String>(); lblColumna_Planificacion.put(0, Id_Vendedor_Planificacion); lblColumna_Planificacion.put(1, Id_Cliente_Planificacion); lblColumna_Planificacion.put(2, FechaInicio_Planificacion); lblColumna_Planificacion.put(3, Hora_Planificacion); lblColumna_Planificacion.put(4, Frecuencia_Planificacion); leerHojaExcel.LeerHojaExcel1(txtDireccionExcel.getText(), 1, 6, lblColumna_Planificacion); listaPlanificacion = leerHojaExcel.getListaDataSet(); filas = listaPlanificacion.size(); for (HashMap<String, String> map : listaPlanificacion) { if (map.get(Id_Vendedor_Planificacion) != null && map.get(FechaInicio_Planificacion) != null && map.get(Hora_Planificacion) != null && map.get(Id_Cliente_Planificacion) != null && map.get(Frecuencia_Planificacion) != null) { if (validaVendedor(map.get(Id_Vendedor_Planificacion)) == true && validaFecha(map.get(FechaInicio_Planificacion)) == true && validaHora(map.get(Hora_Planificacion)) == true && validaCliente(map.get(Id_Cliente_Planificacion)) == true && validaFrecuencia(map.get(Frecuencia_Planificacion)) == true) { try { objSAP = new SPlanificacion(); idPla = objSAP.ingresaPlanificacion(completaCeros(map.get(Id_Vendedor_Planificacion)), ((BeanDato) datose.get(0)).getStrCodigo(), map.get(FechaInicio_Planificacion), Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)) + calculaMes(map.get(FechaInicio_Planificacion)) + calculaDia(map.get(FechaInicio_Planificacion)), map.get(Hora_Planificacion), completaCeros(map.get(Id_Cliente_Planificacion)), idFrecuencia(map.get(Frecuencia_Planificacion))); if (idPla != null) { for (int j = 0; j < idPla.length(); j++) { if (idPla.charAt(j) != '0') { idPla = idPla.substring(j, idPla.length()); break; } } Visita objFI = new Visita(); List<String> lstFechas = objFI .siguientesVisitas("" + map.get(FechaInicio_Planificacion).charAt(6) + map.get(FechaInicio_Planificacion).charAt(7) + Constante.SEPARADOR + map.get(FechaInicio_Planificacion).charAt(4) + map.get(FechaInicio_Planificacion).charAt(5) + Constante.SEPARADOR + map.get(FechaInicio_Planificacion).charAt(0) + map.get(FechaInicio_Planificacion).charAt(1) + map.get(FechaInicio_Planificacion).charAt(2) + map.get(FechaInicio_Planificacion).charAt(3), idFrecuencia(map.get(Frecuencia_Planificacion))); msg = objSAP.ingresaVisitaFueraDeRuta(completaCeros(map.get(Id_Vendedor_Planificacion)), completaCeros(map.get(Id_Cliente_Planificacion)), lstFechas, map.get(Hora_Planificacion), Constante.TIPO_VISITA1, idPla); if (msg != null) { contarFilas++; pgbInsertado.setValue((int) ((100 * contarFilas) / filas)); pgbInsertado.repaint(); estado = true; } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_IMPORTA_PLANIFICACION); break; } } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_IMPORTA_PLANIFICACION); break; } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); break; } } } } if (estado) { Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_IMPORTA_PLANIFICACION); buscaPlanificacion(); } } private void lblBotonLeerExcelMousePressed(MouseEvent evt) { if (lblBotonLeerExcel.isEnabled() == true) { lblBotonLeerExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonLeerExcel.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonLeerExcelMouseReleased(MouseEvent evt) { lblBotonLeerExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonLeerExcel.setVerticalAlignment(SwingConstants.CENTER); } private void lblBotonSalirMouseClicked(MouseEvent evt) { popupImportaExcel.setVisible(false); pgbInsertado.setValue(0); } private void lblBotonSalirMousePressed(MouseEvent evt) { if (lblBotonSalir.isEnabled() == true) { lblBotonSalir.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonSalir.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonSalirMouseReleased(MouseEvent evt) { lblBotonSalir.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonSalir.setVerticalAlignment(SwingConstants.CENTER); } private void lblBotonExaminarExcelMouseClicked(MouseEvent evt) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(IPlanificacion.this); if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); DireccionFormato = String.valueOf(file.getAbsoluteFile()); DireccionFormato = DireccionFormato.trim(); txtDireccionExcel.setText(DireccionFormato); popupImportaExcel.setVisible(true); } pgbInsertado.setValue(0); } private void lblBotonExaminarExcelMousePressed(MouseEvent evt) { if (lblBotonExaminarExcel.isEnabled() == true) { lblBotonExaminarExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonExaminarExcel.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonExaminarExcelMouseReleased(MouseEvent evt) { lblBotonExaminarExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonExaminarExcel.setVerticalAlignment(SwingConstants.CENTER); } private class ThreadSocketProgressBar extends Thread { int progreso; @SuppressWarnings("unused") public ThreadSocketProgressBar(int progreso) { this.progreso = progreso; } public void run() { pgbInsertado.setValue(progreso); Rectangle progressRect = pgbInsertado.getBounds(); progressRect.x = 0; progressRect.y = 0; pgbInsertado.paintImmediately(progressRect); } } private String Id_Vendedor_Planificacion = "IdVendedor"; private String Id_Cliente_Planificacion = "IdCliente"; private String FechaInicio_Planificacion = "FechaInicio"; private String Hora_Planificacion = "Hora"; private String Frecuencia_Planificacion = "Frecuencia"; }
ISO-8859-1
Java
56,741
java
IPlanificacion.java
Java
[]
null
[]
package com.promesa.internalFrame.planificacion; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.border.BevelBorder; import javax.swing.border.TitledBorder; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; //import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.SwingConstants; import com.promesa.bean.*; import com.promesa.planificacion.bean.*; import com.promesa.planificacion.sql.*; import com.promesa.planificacion.sql.impl.*; import com.promesa.sap.SPlanificacion; import com.promesa.sincronizacion.bean.BeanTareaProgramada; import com.promesa.util.*; import com.toedter.calendar.JCalendar; public class IPlanificacion extends JInternalFrame implements ActionListener, MouseListener, KeyListener { private static final long serialVersionUID = 1L; JToolBar mnuToolBar; JButton btnGuardar; JButton btnEliminar; private JLabel lblEjVen; @SuppressWarnings("rawtypes") JComboBox cmbEjVen; private JLabel lblClie; @SuppressWarnings("rawtypes") JComboBox cmbClie; private JLabel lblDiaOcu; private JLabel lblDesDO; private JLabel lblHorSug; @SuppressWarnings("rawtypes") JComboBox cmbHorSug; private JLabel lblFre; @SuppressWarnings("rawtypes") JComboBox cmbFre; private JLabel lblIdClie = new JLabel(); private JLabel lblIdHorSug = new JLabel(); private JLabel lblIdFre = new JLabel(); private JLabel lblBotonImportExcel = null; private JLabel lblBotonLeerExcel = null; private JLabel lblBotonSalir = null; private JLabel lblBotonExaminarExcel = null; private JPopupMenu popupImportaExcel = null; private JPanel pnlImportaExcel = null; private JPanel pnlPrincipalPopup = null; private JPanel pnlInterno1Popup = null; private JPanel pnlInterno2Popup = null; private JPanel pnlInterno3Popup = null; private JPanel pnlInterno4Popup = null; private JTextField txtDireccionExcel; private JProgressBar pgbInsertado = null; JSeparator separador; JPanel pnlParametros; JPanel pnlListado; JScrollPane scrListado; private JTable tblPlanificacion; DefaultTableModel modeloTabla; private JCalendar dchCalendario; static List<BeanDato> datose; private SqlEmpleado getEmpleado = null; private SqlCliente getCliente = null; private SqlHora getHora = null; private SqlFrecuencia getFrecuencia = null; private SqlPlanificacion getPlanificacion = null; @SuppressWarnings("unused") private SqlVisita getVisita = null; BeanEmpleado em = null; BeanCliente clie = null; BeanHora hor = null; BeanFrecuencia fre = null; BeanPlanificacion pla = null; BeanVisita vis = null; List<BeanEmpleado> listaEmpleado = null; List<BeanCliente> listaCliente = null; List<BeanHora> listaHora = null; List<BeanFrecuencia> listaFrecuencia = null; List<BeanPlanificacion> listaPlanificacion = null; SPlanificacion objSAP; List<BeanPlanificacion> planificacionese; private String fecAct = ""; private String fsp = ""; /* FECHA DE SELECCIÓN PARA PLANIFICACIÓN */ private String fsv = ""; /* FECHA DE SELECCIÓN PARA VISITA */ String[] fecha; private String DireccionFormato = " "; private String estado = "0"; // 0 = NUEVA PLANIFICACIÓN y 1 = ACTUALIZA private String iD = ""; /* ID DE LA PLANIFICACIÓN */ @SuppressWarnings({ "static-access", "rawtypes" }) public IPlanificacion(BeanTareaProgramada beanTareaProgramada) { super("Parámetros de Planificación", true, true, true, true); this.setFrameIcon(new ImageIcon(this.getClass().getResource("/imagenes/iplanificaciones.gif"))); this.setPreferredSize(new java.awt.Dimension(606, 640)); this.setBounds(0, 0, 606, 640); getContentPane().setLayout(null); getContentPane().setBackground(new java.awt.Color(235, 239, 242)); mnuToolBar = new JToolBar(); getContentPane().add(mnuToolBar, BorderLayout.NORTH); mnuToolBar.setBounds(0, 0, 1366, 37); // 0, 0, 1018, 37 mnuToolBar.setBackground(new java.awt.Color(235, 239, 242)); separador = new JSeparator(); getContentPane().add(separador); separador.setBounds(0, 39, 1366, 10); // 0, 39, 1318, 10 this.datose = beanTareaProgramada.getDatose(); getEmpleado = new SqlEmpleadoImpl(); getCliente = new SqlClienteImpl(); getHora = new SqlHoraImpl(); getFrecuencia = new SqlFrecuenciaImpl(); getPlanificacion = new SqlPlanificacionImpl(); getVisita = new SqlVisitaImpl(); btnGuardar = new JButton(); mnuToolBar.add(btnGuardar); btnGuardar.setText("Guardar"); btnGuardar.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/guardar.png"))); btnGuardar.addActionListener(this); btnGuardar.setToolTipText("Guardar"); btnGuardar.setPreferredSize(new java.awt.Dimension(93, 29)); btnGuardar.setBackground(new java.awt.Color(0, 128, 64)); btnGuardar.setOpaque(false); btnGuardar.setBorder(null); btnGuardar.setFocusable(false); btnEliminar = new JButton(); mnuToolBar.add(btnEliminar); btnEliminar.setText("Eliminar"); btnEliminar.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/eliminar.gif"))); btnEliminar.addActionListener(this); btnEliminar.setToolTipText("Eliminar"); btnEliminar.setPreferredSize(new java.awt.Dimension(100, 29)); btnEliminar.setBackground(new java.awt.Color(0, 128, 64)); btnEliminar.setOpaque(false); btnEliminar.setBorder(null); btnEliminar.setFocusable(false); pnlParametros = new JPanel(); getContentPane().add(pnlParametros); pnlParametros.setBounds(0, 48, 790, 210); pnlParametros.setLayout(null); pnlParametros.setBorder(BorderFactory.createTitledBorder("Parámetros")); pnlParametros.setFocusable(false); { lblEjVen = new JLabel(); pnlParametros.add(lblEjVen); lblEjVen.setText("Ejecutivo de Ventas:"); lblEjVen.setBounds(16, 25, 119, 17); lblEjVen.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbEjVen = new JComboBox(); pnlParametros.add(cmbEjVen); cmbEjVen.setToolTipText("Ejecutivo de Ventas"); cmbEjVen.setBounds(145, 23, 220, 24); cmbEjVen.setFocusable(false); cmbEjVen.setFont(new java.awt.Font("Candara", 0, 11)); cargaInicialVendedor(); cmbEjVen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { cargaCliente(); bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } }); cmbEjVen.setBackground(new java.awt.Color(255, 255, 255)); } { lblClie = new JLabel(); pnlParametros.add(lblClie); lblClie.setText("Cliente:"); lblClie.setBounds(389, 25, 125, 17); lblClie.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbClie = new JComboBox(); pnlParametros.add(cmbClie); cmbClie.setToolTipText("Cliente"); cmbClie.setBounds(449, 23, 220, 24); cmbClie.setFocusable(false); cmbClie.setFont(new java.awt.Font("Candara", 0, 11)); cargaInicialCliente(); cmbClie.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { buscaPlanificacion(); bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } }); cmbClie.setBackground(new java.awt.Color(255, 255, 255)); } { lblDiaOcu = new JLabel(); pnlParametros.add(lblDiaOcu); lblDiaOcu.setText("Día y Ocurrencia:"); lblDiaOcu.setBounds(16, 60, 125, 17); lblDiaOcu.setFont(new java.awt.Font("Arial", 1, 11)); } { dchCalendario = new JCalendar(); pnlParametros.add(dchCalendario); dchCalendario.setBounds(335, 50, 200, 155); dchCalendario.setRequestFocusEnabled(false); dchCalendario.getDayChooser().addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { validaFecha(); } }); dchCalendario.setFocusable(false); } { lblDesDO = new JLabel(); pnlParametros.add(lblDesDO); lblDesDO.setText(capturaOrganizaFecha()); lblDesDO.setBounds(145, 60, 147, 17); lblDesDO.setFont(new java.awt.Font("Arial", 2, 12)); lblDesDO.setForeground(new java.awt.Color(0, 0, 255)); } if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { { lblBotonImportExcel = new JLabel("Importar (desde Excel)"); lblBotonImportExcel.setBackground(new Color(238, 238, 238)); lblBotonImportExcel.setFont(new Font("Arial", 1, 11)); lblBotonImportExcel.setIcon(new ImageIcon(getClass().getResource("/imagenes/exportar.gif"))); lblBotonImportExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonImportExcel.setBounds(620, 180, 160, 20); lblBotonImportExcel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonImportExcelMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonImportExcelMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonImportExcelMouseReleased(evt); } }); pnlParametros.add(lblBotonImportExcel); } { lblBotonLeerExcel = new JLabel(" Leer "); lblBotonLeerExcel.setBackground(new Color(238, 238, 238)); lblBotonLeerExcel.setFont(new Font("Arial", 1, 12)); lblBotonLeerExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonLeerExcel.setBounds(650, 50, 90, 20); lblBotonLeerExcel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonLeerExcelMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonLeerExcelMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonLeerExcelMouseReleased(evt); } }); } { lblBotonSalir = new JLabel(); lblBotonSalir.setBackground(new Color(238, 238, 238)); lblBotonSalir.setFont(new Font("Arial", 1, 12)); lblBotonSalir.setIcon(new ImageIcon(getClass().getResource("/imagenes/borrar.png"))); lblBotonSalir.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonSalir.setBounds(650, 50, 150, 20); lblBotonSalir.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonSalirMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonSalirMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonSalirMouseReleased(evt); } }); } { lblBotonExaminarExcel = new JLabel(" Examinar "); lblBotonExaminarExcel.setBackground(new Color(238, 238, 238)); lblBotonExaminarExcel.setFont(new Font("Arial", 1, 12)); lblBotonExaminarExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonExaminarExcel.setBounds(650, 50, 90, 20); lblBotonExaminarExcel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { lblBotonExaminarExcelMouseClicked(evt); } public void mousePressed(MouseEvent evt) { lblBotonExaminarExcelMousePressed(evt); } public void mouseReleased(MouseEvent evt) { lblBotonExaminarExcelMouseReleased(evt); } }); } { pgbInsertado = new JProgressBar(0, 100); pgbInsertado.setValue(0); pgbInsertado.setStringPainted(true); } { txtDireccionExcel = new JTextField(); txtDireccionExcel.setEditable(false); txtDireccionExcel.setBackground(new java.awt.Color(255, 255,255)); } { pnlInterno1Popup = new JPanel(new BorderLayout()); pnlInterno1Popup.add(txtDireccionExcel, BorderLayout.NORTH); } { pnlInterno3Popup = new JPanel(); pnlInterno3Popup.add(lblBotonLeerExcel); lblBotonLeerExcel.setBounds(1, 100, 60, 30); } { pnlInterno4Popup = new JPanel(new BorderLayout()); pnlInterno4Popup.setLayout(new BorderLayout()); pnlInterno4Popup.add(lblBotonSalir, BorderLayout.EAST); } { pnlInterno2Popup = new JPanel(); pnlInterno2Popup.setLayout(new BorderLayout()); pnlInterno2Popup.add(pnlInterno3Popup, BorderLayout.CENTER); pnlInterno2Popup.add(lblBotonExaminarExcel, BorderLayout.NORTH); } { pnlImportaExcel = new JPanel(); pnlImportaExcel.setLayout(new BorderLayout()); pnlImportaExcel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Importar Excel", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Arial", 1, 12))); pnlImportaExcel.add(pnlInterno1Popup, BorderLayout.CENTER); pnlImportaExcel.add(pnlInterno2Popup, BorderLayout.EAST); } { pnlPrincipalPopup = new JPanel(); pnlPrincipalPopup.setLayout(new BorderLayout()); pnlPrincipalPopup.add(pnlInterno4Popup, BorderLayout.NORTH); pnlPrincipalPopup.add(pnlImportaExcel, BorderLayout.CENTER); pnlPrincipalPopup.add(pgbInsertado, BorderLayout.SOUTH); pnlPrincipalPopup.setPreferredSize(new Dimension(300, 115)); } { popupImportaExcel = new JPopupMenu(); popupImportaExcel.add(pnlPrincipalPopup); } } { lblHorSug = new JLabel(); pnlParametros.add(lblHorSug); lblHorSug.setText("Hora Sugerida:"); lblHorSug.setBounds(16, 95, 125, 17); lblHorSug.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbHorSug = new JComboBox(); pnlParametros.add(cmbHorSug); cmbHorSug.setToolTipText("Hora Sugerida"); cmbHorSug.setBounds(145, 93, 147, 24); cmbHorSug.setFocusable(false); cmbHorSug.setFont(new java.awt.Font("Candara", 0, 11)); cargaHora(); cmbHorSug.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { eventoHora(); } }); cmbHorSug.setBackground(new java.awt.Color(255, 255, 255)); } { lblFre = new JLabel(); pnlParametros.add(lblFre); lblFre.setText("Frecuencia:"); lblFre.setBounds(16, 130, 125, 17); lblFre.setFont(new java.awt.Font("Arial", 1, 11)); } { cmbFre = new JComboBox(); pnlParametros.add(cmbFre); cmbFre.setToolTipText("Frecuencia"); cmbFre.setBounds(145, 128, 147, 24); cmbFre.setFocusable(false); cmbFre.setFont(new java.awt.Font("Candara", 0, 11)); cargaFrecuencia(); cmbFre.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { eventoFrecuencia(); } }); cmbFre.setBackground(new java.awt.Color(255, 255, 255)); } pnlListado = new JPanel(); getContentPane().add(pnlListado); pnlListado.setBounds(0, 260, 790, 145); pnlListado.setLayout(null); pnlListado.setBorder(BorderFactory.createTitledBorder("Planificaciones")); pnlListado.setFocusable(false); scrListado = new JScrollPane(); pnlListado.add(scrListado); scrListado.setBounds(50, 29, 680, 95); scrListado.setToolTipText("Relación de Planificaciones"); buscaPlanificacion(); } /* MÉTODO QUE LISTA PLANIFICACIONES */ public void buscaPlanificacion() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); planificacionese = new ArrayList<BeanPlanificacion>(); try { objSAP = new SPlanificacion(); if (be == null && bc == null) { listaPlanificacion = null; } else if (be.getStrIdEmpleado() == null && bc.getStrIdCliente() == null) { Mensaje.mostrarAviso(Constante.MENSAJE_NO_VENDEDOR_NO_CLIENTE); } else if (be.getStrIdEmpleado() != null && bc == null) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { listaPlanificacion = objSAP.listaPlanificacion(be.getStrIdEmpleado(), Constante.VACIO); } else { BeanPlanificacion planificacion = new BeanPlanificacion(); planificacion.setStrIdVendedor(be.getStrIdEmpleado()); planificacion.setStrIdCliente(Constante.VACIO); getPlanificacion.setListaPlanificacion(planificacion); listaPlanificacion = getPlanificacion.getListaPlanificacion(); } } else if (be.getStrIdEmpleado() != null && bc.getStrIdCliente() != null) { if (bc.getStrIdCliente().equals(Constante.VACIO)) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { listaPlanificacion = objSAP.listaPlanificacion(be.getStrIdEmpleado(), Constante.VACIO); } else { BeanPlanificacion planificacion = new BeanPlanificacion(); planificacion.setStrIdVendedor(be.getStrIdEmpleado()); planificacion.setStrIdCliente(Constante.VACIO); getPlanificacion.setListaPlanificacion(planificacion); listaPlanificacion = getPlanificacion.getListaPlanificacion(); } } else { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { listaPlanificacion = objSAP.listaPlanificacion(Constante.VACIO, bc.getStrIdCliente()); } else { BeanPlanificacion planificacion = new BeanPlanificacion(); planificacion.setStrIdVendedor(Constante.VACIO); planificacion.setStrIdCliente(bc.getStrIdCliente()); getPlanificacion.setListaPlanificacion(planificacion); listaPlanificacion = getPlanificacion.getListaPlanificacion(); } } } } catch (Exception e) { Util.mostrarExcepcion(e); } if (listaPlanificacion != null) { for (BeanPlanificacion p : listaPlanificacion) { pla = new BeanPlanificacion(); pla.setStrIdPlan(p.getStrIdPlan()); pla.setStrIdVendedor(p.getStrIdVendedor()); pla.setStrIdJefe(p.getStrIdJefe()); pla.setStrFechaInicio(p.getStrFechaInicio()); pla.setStrFechaFin(p.getStrFechaFin()); pla.setStrHora(p.getStrHora()); pla.setStrIdCliente(p.getStrIdCliente()); pla.setStrIdFrecuencia(p.getStrIdFrecuencia()); pla.setStrFrecuencia(p.getStrFrecuencia()); pla.setStrDia(p.getStrDia()); pla.setStrNombreCliente(p.getStrNombreCliente()); try { planificacionese.add(pla); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_BUSQUEDA_PLANIFICACION); } } } if (planificacionese == null || planificacionese.size() == 0) { tablaVacia(); btnEliminar.setEnabled(false); } else { tablaLLena(); btnEliminar.setEnabled(true); } } /* MÉTODO QUE CARGA VENDEDORES SEGÚN SUPERVISOR */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void cargaInicialVendedor() { BeanEmpleado empleado = new BeanEmpleado(); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { try { objSAP = new SPlanificacion(); listaEmpleado = objSAP.listaVendedor(((BeanDato) datose.get(0)).getStrCodigo()); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(e.getMessage()); } } else { empleado.setStrIdSupervisor(((BeanDato) datose.get(0)).getStrCodigo()); getEmpleado.setListaEmpleado(empleado); listaEmpleado = new ArrayList<BeanEmpleado>(); listaEmpleado = getEmpleado.getListaEmpleado(); } if (listaEmpleado != null && listaEmpleado.size() > 0) { cmbEjVen.setModel(new DefaultComboBoxModel(listaEmpleado.toArray())); } else { cmbEjVen.setModel(new DefaultComboBoxModel()); } } /* MÉTODO QUE CARGA CLIENTES SEGÚN VENDEDOR */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void cargaInicialCliente() { if (listaEmpleado != null && listaEmpleado.size() > 0) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { try { objSAP = new SPlanificacion(); listaCliente = objSAP.listaClientePlanificacion(listaEmpleado.get(0).getStrIdEmpleado()); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(e.getMessage()); } } else { BeanCliente cliente = new BeanCliente(); BeanClienteEmpleado clienteEmpleado = new BeanClienteEmpleado(); clienteEmpleado.setStrIdEmpleado(listaEmpleado.get(0).getStrIdEmpleado()); cliente.setClienteEmpleado(clienteEmpleado); getCliente.setListaCliente(cliente); listaCliente = new ArrayList<BeanCliente>(); listaCliente = getCliente.getListaCliente(); } } if (listaCliente != null && listaCliente.size() > 0) { cmbClie.setModel(new DefaultComboBoxModel(listaCliente.toArray())); } else { cmbClie.setModel(new DefaultComboBoxModel()); } } /* MÉTODO QUE CARGA CLIENTES SEGÚN CAMBIO DE VENDEDOR */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void cargaCliente() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { try { objSAP = new SPlanificacion(); listaCliente = objSAP.listaClientePlanificacion(be.getStrIdEmpleado()); } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(e.getMessage()); } } else { BeanCliente cliente = new BeanCliente(); BeanClienteEmpleado clienteEmpleado = new BeanClienteEmpleado(); clienteEmpleado.setStrIdEmpleado(be.getStrIdEmpleado()); cliente.setClienteEmpleado(clienteEmpleado); getCliente.setListaCliente(cliente); listaCliente = new ArrayList<BeanCliente>(); listaCliente = getCliente.getListaCliente(); } if (listaCliente != null && listaCliente.size() > 0) { cmbClie.setModel(new DefaultComboBoxModel(listaCliente.toArray())); } else { cmbClie.setModel(new DefaultComboBoxModel()); } buscaPlanificacion(); } /* MÉTODO QUE PINTA UNA TABLA SIN DATOS */ public void tablaVacia() { String Columnas[] = { "Plan", "Fecha Inicio", "Día y Ocurrencia", "Hora", "Frecuencia", "ID Cliente", "Cliente" }; modeloTabla = new DefaultTableModel(null, Columnas); TableModel tblTablaModel = new DefaultTableModel( new Object[][] { { "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "" } }, Columnas) { private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { return false; } }; tblPlanificacion = new JTable(); tblPlanificacion.setModel(tblTablaModel); scrListado.setViewportView(tblPlanificacion); pnlListado.add(scrListado); } /* MÉTODO QUE PINTA UNA TABLA CON DATOS */ public void tablaLLena() { String Columnas[] = { "Plan", "Fecha Inicio", "Día y Ocurrencia", "Hora", "Frecuencia", "ID Cliente", "Cliente" }; modeloTabla = new DefaultTableModel(null, Columnas) { private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { return false; } }; if (planificacionese.size() > 4) { modeloTabla.setNumRows(planificacionese.size()); } else { modeloTabla.setNumRows(4); } for (int i = 0; i < planificacionese.size(); i++) { modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrIdPlan(), i, 0); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { modeloTabla.setValueAt(convierteFecha(((BeanPlanificacion) planificacionese.get(i)).getStrFechaInicio()), i, 1); } else { modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrFechaInicio(), i, 1); } modeloTabla.setValueAt(convierteDO(((BeanPlanificacion) planificacionese.get(i)).getStrFechaInicio()), i, 2); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrHora(),i, 3); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrFrecuencia(), i, 4); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrIdCliente(), i, 5); modeloTabla.setValueAt(((BeanPlanificacion) planificacionese.get(i)).getStrNombreCliente(), i, 6); } tblPlanificacion = new JTable(); tblPlanificacion.setModel(modeloTabla); tblPlanificacion.addKeyListener(this); tblPlanificacion.addMouseListener(this); tblPlanificacion.getColumnModel().getColumn(0).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(1).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(2).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(3).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(4).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(5).setCellRenderer(new Renderer().getCenterCell()); tblPlanificacion.getColumnModel().getColumn(6).setCellRenderer(new Renderer().getCenterCell()); scrListado.setViewportView(tblPlanificacion); pnlListado.add(scrListado); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 0, 70); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 1, 80); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 2, 130); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 3, 40); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 4, 70); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 5, 89); new Renderer().setSizeColumn(tblPlanificacion.getColumnModel(), 6, 201); } /* MÉTODO QUE OBTIENE DÍA Y OCURRENCIA */ public String convierteDO(String fsf) { int dia, mes, anio; if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { dia = Integer.parseInt(convierteFecha(fsf).substring(0, 2)); } else { dia = Integer.parseInt(fsf.substring(0, 2)); } if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { mes = Integer.parseInt(convierteFecha(fsf).substring(3, 5)) - 1; } else { mes = Integer.parseInt(fsf.substring(3, 5)) - 1; } if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { anio = Integer.parseInt(convierteFecha(fsf).substring(6, 10)); } else { anio = Integer.parseInt(fsf.substring(6, 10)); } Calendar c = new GregorianCalendar(Locale.ROOT); c.setFirstDayOfWeek(Calendar.MONDAY); c.set(anio, mes, dia); int posicionMes = c.get(Calendar.DAY_OF_WEEK_IN_MONTH); if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { return obtieneDO(String.valueOf(posicionMes), convierteFecha(fsf)); } else { return obtieneDO(String.valueOf(posicionMes), fsf); } } /* CONVERSIÓN A DD.MM.YYYY */ public String convierteFecha(String fsf) { SimpleDateFormat sdf1 = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); SimpleDateFormat sdf2 = new SimpleDateFormat("dd.MM.yyyy"); try { String StringRecogido = fsf; Date datehora = sdf1.parse(StringRecogido); return sdf2.format(datehora); } catch (Exception e) { Util.mostrarExcepcion(e); return e.getMessage(); } } /* MÉTODO QUE CAPTURA ID FRECUENCIA */ public void eventoFrecuencia() { lblIdFre.setText(listaFrecuencia.get(cmbFre.getSelectedIndex()).getStrIdFrecuencia()); } /* MÉTODO QUE CAPTURA ID HORA */ public void eventoHora() { lblIdHorSug.setText(listaHora.get(cmbHorSug.getSelectedIndex()).getStrIdHora()); } /* MÉTODO QUE CAPTURA ID CLIENTE */ public void eventoCliente() { lblIdClie.setText(listaCliente.get(cmbClie.getSelectedIndex()).getStrIdCliente()); } /* MÉTODO QUE CARGA LAS FRECUENCIAS */ @SuppressWarnings("unchecked") public void cargaFrecuencia() { BeanFrecuencia frecuencia = new BeanFrecuencia(); getFrecuencia.setListaFrecuencia(frecuencia); listaFrecuencia = new ArrayList<BeanFrecuencia>(); listaFrecuencia = getFrecuencia.getListaFrecuencia(); if (listaFrecuencia != null && listaFrecuencia.size() > 0) { lblIdFre.setText(listaFrecuencia.get(0).getStrIdFrecuencia()); for (int i = 0; i < listaFrecuencia.size(); i++) { fre = new BeanFrecuencia(); fre = listaFrecuencia.get(i); cmbFre.addItem(fre.getStrFrecuencia()); } } else { cmbFre.addItem(""); } } /* MÉTODO QUE CARGA LAS HORAS */ @SuppressWarnings("unchecked") public void cargaHora() { BeanHora hora = new BeanHora(); getHora.setListaHora(hora); listaHora = new ArrayList<BeanHora>(); listaHora = getHora.getListaHora(); if (listaHora != null && listaHora.size() > 0) { lblIdHorSug.setText(listaHora.get(0).getStrIdHora()); for (int i = 0; i < listaHora.size(); i++) { hor = new BeanHora(); hor = listaHora.get(i); cmbHorSug.addItem(hor.getStrHora()); } } else { cmbHorSug.addItem(""); } } @Override public void keyPressed(KeyEvent arg0) { } @Override public void keyReleased(KeyEvent arg0) { } @Override public void keyTyped(KeyEvent arg0) { } @Override public void mouseClicked(MouseEvent arg0) { if (arg0.getClickCount() == 2) { if (arg0.getSource() == tblPlanificacion) { int fila = tblPlanificacion.rowAtPoint(arg0.getPoint()); if ((fila > -1)) { estado = "1"; /* ESPECIFICA UNA ACTUALIZACIÓN */ iD = modeloTabla.getValueAt(fila, 0).toString(); cmbEjVen.setEnabled(false); cmbClie.setEnabled(false); btnEliminar.setEnabled(false); } else { Mensaje.mostrarError(Constante.MENSAJE_BUSQUEDA_PLANIFICACION); } } } } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } /* MÉTODO QUE PROCESA LA FECHA */ public String[] fecha() { String[] fecha = new String[3]; fecha[0] = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)); fecha[1] = Integer.toString(dchCalendario.getCalendar().get( java.util.Calendar.MONTH) + 1); if (fecha[1].equals("1") || fecha[1].equals("2") || fecha[1].equals("3") || fecha[1].equals("4") || fecha[1].equals("5") || fecha[1].equals("6") || fecha[1].equals("7") || fecha[1].equals("8") || fecha[1].equals("9")) { fecha[1] = "0" + fecha[1]; } fecha[2] = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.DATE)); if (fecha[2].equals("1") || fecha[2].equals("2") || fecha[2].equals("3") || fecha[2].equals("4") || fecha[2].equals("5") || fecha[2].equals("6") || fecha[2].equals("7") || fecha[2].equals("8") || fecha[2].equals("9")) { fecha[2] = "0" + fecha[2]; } return fecha; } /* MÉTODO QUE RECIBE Y ENVÍA LA FECHA */ public String capturaOrganizaFecha() { fecha = fecha(); fecAct = fecha[2] + "." + fecha[1] + "." + fecha[0]; return fecAct; } /* MÉTODO QUE OBTIENE LA OCURRENCIA */ public String obtieneDO(String v1, String v2) { String cadena = ""; if (v1.equals("1")) { cadena = Constante.PRIMERO; } if (v1.equals("2")) { cadena = Constante.SEGUNDO; } if (v1.equals("3")) { cadena = Constante.TERCERO; } if (v1.equals("4")) { cadena = Constante.CUARTO; } if (v1.equals("5")) { cadena = Constante.QUINTO; } return cadena + " " + FechaHora.getDia(v2) + " del mes"; } /* MÉTODO QUE ANUNCIA LOS MESES (DE REALIZACIÓN) DE LA PLANIFICACIÓN */ public String anunciaMesesPlanificacion(String mes) { String msg = ""; if (mes.equals("01")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Enero y Febrero."; } if (mes.equals("02")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Febrero y Marzo."; } if (mes.equals("03")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Marzo y Abril."; } if (mes.equals("04")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Abril y Mayo."; } if (mes.equals("05")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Mayo y Junio."; } if (mes.equals("06")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Junio y Julio."; } if (mes.equals("07")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Julio y Agosto."; } if (mes.equals("08")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Agosto y Setiembre."; } if (mes.equals("09")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Setiembre y Octubre."; } if (mes.equals("10")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Octubre y Noviembre."; } if (mes.equals("11")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Noviembre y Diciembre."; } if (mes.equals("12")) { msg = "Tener en cuenta que la planificación (generada) es para los meses de Diciembre y Enero."; } return msg; } /* MÉTODO QUE VALIDA LA FECHA */ public void validaFecha() { String año; /* AÑO */ año = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)); /* CAPTURA AÑO */ if ((FechaHora.getFecha().charAt(6) + Constante.VACIO + FechaHora.getFecha().charAt(7) + Constante.VACIO + FechaHora.getFecha().charAt(8) + Constante.VACIO + FechaHora.getFecha().charAt(9)).equals(año)) { String vD; vD = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.DAY_OF_WEEK)); if (!(vD.equals("1"))) { String mes, dia; mes = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.MONTH) + 1); if (mes.equals("1") || mes.equals("2") || mes.equals("3") || mes.equals("4") || mes.equals("5") || mes.equals("6") || mes.equals("7") || mes.equals("8") || mes.equals("9")) { mes = "0" + mes; } dia = Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.DATE)); if (dia.equals("1") || dia.equals("2") || dia.equals("3") || dia.equals("4") || dia.equals("5") || dia.equals("6") || dia.equals("7") || dia.equals("8") || dia.equals("9")) { dia = "0" + dia; } fsp = año + mes + dia; fsv = dia + Constante.SEPARADOR + mes + Constante.SEPARADOR + año; lblDesDO.setText(obtieneDO(String.valueOf(dchCalendario.getCalendar().get(java.util.Calendar.DAY_OF_WEEK_IN_MONTH)), fsv)); } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_DOMINGO); } } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_AÑO_ACTUAL); } } /* MÉTODO QUE CALCULA EL MES */ public String calculaMes(String cadena) { String mes = ""; if ((cadena.charAt(4) + "" + cadena.charAt(5)).equals("12")) { mes = "01"; } else { int temp; temp = Integer.parseInt(cadena.charAt(4) + "" + cadena.charAt(5)) + 1; if (temp < 10) { mes = "0" + temp; } else { mes = String.valueOf(temp); } } return mes; } /* MÉTODO QUE CALCULA EL DÍA */ public String calculaDia(String cadena) { String dia = ""; if (calculaMes(cadena).equals("01")) { dia = "31"; } if (calculaMes(cadena).equals("02")) { GregorianCalendar calendar = new GregorianCalendar(); if (calendar.isLeapYear(Integer.parseInt(cadena.charAt(0) + "" + cadena.charAt(1) + "" + cadena.charAt(2) + "" + cadena.charAt(3)))) dia = "29"; else dia = "28"; } if (calculaMes(cadena).equals("03")) { dia = "31"; } if (calculaMes(cadena).equals("04")) { dia = "30"; } if (calculaMes(cadena).equals("05")) { dia = "31"; } if (calculaMes(cadena).equals("06")) { dia = "30"; } if (calculaMes(cadena).equals("07")) { dia = "31"; } if (calculaMes(cadena).equals("08")) { dia = "31"; } if (calculaMes(cadena).equals("09")) { dia = "30"; } if (calculaMes(cadena).equals("10")) { dia = "31"; } if (calculaMes(cadena).equals("11")) { dia = "30"; } if (calculaMes(cadena).equals("12")) { dia = "31"; } return dia; } /* MÉTODO QUE INGRESA UNA PLANIFICACIÓN */ @SuppressWarnings("static-access") public void ingresaModificaPlanificacion() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); if (be == null && bc == null) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPOS_VACIOS_VENDEDOR_CLIENTE); } else if (cmbEjVen.getSelectedItem().toString().equals("") && cmbClie.getSelectedItem().toString().equals("")) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPOS_VACIOS_VENDEDOR_CLIENTE); } else if (cmbEjVen.getSelectedItem().toString().equals("") && !cmbClie.getSelectedItem().toString().equals("")) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPO_VACIO_VENDEDOR); } else if (!cmbEjVen.getSelectedItem().toString().equals("") && cmbClie.getSelectedItem().toString().equals("")) { Mensaje.mostrarError(Constante.MENSAJE_ERROR_CAMPO_VACIO_CLIENTE); } else if (!cmbEjVen.getSelectedItem().toString().equals("") && !cmbClie.getSelectedItem().toString().equals("")) { if (estado.equals("0")) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); String idPla; try { objSAP = new SPlanificacion(); idPla = objSAP.ingresaPlanificacion(be.getStrIdEmpleado(), ((BeanDato) datose.get(0)).getStrCodigo(), fsp, Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)) + calculaMes(fsp) + calculaDia(fsp), cmbHorSug .getSelectedItem().toString(), bc.getStrIdCliente(), "0" + lblIdFre.getText().trim()); if (idPla != null) { String msg; for (int j = 0; j < idPla.length(); j++) { if (idPla.charAt(j) != '0') { idPla = idPla.substring(j, idPla.length()); break; } } Visita objFI = new Visita(); List<String> lstFechas = objFI.siguientesVisitas(fsv, "0" + lblIdFre.getText().trim()); msg = objSAP.ingresaVisitaFueraDeRuta(be.getStrIdEmpleado(), bc.getStrIdCliente(), lstFechas, cmbHorSug.getSelectedItem().toString(), Constante.TIPO_VISITA1, idPla); if (msg != null) { Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_NUEVA_PLANIFICACION); Mensaje.mostrarAviso(anunciaMesesPlanificacion(fsp.substring(4, 6))); buscaPlanificacion(); } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); } } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); } bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } else { Mensaje.mostrarWarning(Constante.MENSAJE_VALIDA_NUEVA_PLANIFICACION); } } else { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); String msg1; try { objSAP = new SPlanificacion(); msg1 = objSAP.actualizaPlanificacion(iD, bc.getStrIdCliente(), fsp, cmbHorSug.getSelectedItem().toString(), "0" + lblIdFre.getText().trim()); if (msg1 != null) { String msg2; Visita objFI = new Visita(); List<String> lstFechas = objFI.siguientesVisitas(fsv, "0"+ lblIdFre.getText().trim()); msg2 = objSAP.ingresaVisitaFueraDeRuta(be.getStrIdEmpleado(), bc.getStrIdCliente(), lstFechas, cmbHorSug.getSelectedItem().toString(), Constante.TIPO_VISITA1, iD); if (msg2 != null) { Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_MODIFICA_PLANIFICACION); Mensaje.mostrarAviso(anunciaMesesPlanificacion(fsp.substring(4, 6))); buscaPlanificacion(); } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_MODIFICA_PLANIFICACION); } cmbEjVen.setEnabled(true); cmbClie.setEnabled(true); btnEliminar.setEnabled(true); estado = "0"; } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_MODIFICA_PLANIFICACION); } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_MODIFICA_PLANIFICACION); } bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } else { Mensaje.mostrarWarning(Constante.MENSAJE_VALIDA_MODIFICA_PLANIFICACION); } } } } public void eliminaPlanificacion() { if (!cmbEjVen.getSelectedItem().toString().equals("")&& !cmbClie.getSelectedItem().toString().equals("")) { if (tblPlanificacion.getSelectedRow() > -1) { if (Mensaje.preguntar(Constante.MENSAJE_PREGUNTA_ELIMINA_PLANIFICACION)) { if (((BeanDato) datose.get(0)).getStrModo().equals(Constante.MODO_ONLINE)) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { BeanEmpleado be = (BeanEmpleado) cmbEjVen.getSelectedItem(); BeanCliente bc = (BeanCliente) cmbClie.getSelectedItem(); try { objSAP = new SPlanificacion(); DefaultTableModel dtm = (DefaultTableModel) tblPlanificacion.getModel(); int fila = tblPlanificacion.getSelectedRow(); objSAP.eliminaPlanificacion(modeloTabla.getValueAt(fila, 0).toString(), be.getStrIdEmpleado(), bc.getStrIdCliente()); Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_ELIMINA_PLANIFICACION); dtm.removeRow(fila); if (modeloTabla.getRowCount() == 3) { dtm.insertRow(3, new Object[] { "", "", "", "", "" }); } else { dtm.insertRow(planificacionese.size() - 1, new Object[] { "", "", "", "", "" }); } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_ELIMINA_PLANIFICACION); } bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } else { Mensaje.mostrarWarning(Constante.MENSAJE_VALIDA_ELIMINA_PLANIFICACION); } } } else { Mensaje.mostrarAviso(Constante.MENSAJE_SELECCION_ELIMINA_PLANIFICACION); } } } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() == btnGuardar) { /* IMPLEMEMTA FUNCIONALIDAD GUARDAR */ ingresaModificaPlanificacion(); } if (arg0.getSource() == btnEliminar) { /* IMPLEMEMTA FUNCIONALIDAD ELIMINAR */ eliminaPlanificacion(); } } private void lblBotonImportExcelMouseClicked(MouseEvent evt) { lblBotonImportExcel.add(popupImportaExcel); popupImportaExcel.show(lblBotonImportExcel, -150, 0); popupImportaExcel.setVisible(true); } private void lblBotonImportExcelMousePressed(MouseEvent evt) { if (lblBotonImportExcel.isEnabled() == true) { lblBotonImportExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonImportExcel.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonImportExcelMouseReleased(MouseEvent evt) { lblBotonImportExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonImportExcel.setVerticalAlignment(SwingConstants.CENTER); } private void lblBotonLeerExcelMouseClicked(MouseEvent evt) { final DLocker bloqueador = new DLocker(); Thread hilo = new Thread() { public void run() { pgbInsertado.setValue(0); insertaPlanificado(); bloqueador.dispose(); } }; hilo.start(); bloqueador.setVisible(true); } /* MÉTODO QUE RETORNA EL ID FRECUENCIA SEGÚN DESCRIPCIÓN */ public String idFrecuencia(String frecuencia) { String idFre = ""; if (frecuencia.equalsIgnoreCase("7")) { idFre = "01"; } if (frecuencia.equalsIgnoreCase("14")) { idFre = "02"; } if (frecuencia.equalsIgnoreCase("28")) { idFre = "03"; } return idFre; } /* MÉTODO QUE COMPLETA CEROS */ public String completaCeros(String codigo) { int i = codigo.length(); while (i < 10) { codigo = "0" + codigo; i++; } return codigo; } /* MÉTODO QUE VALIDA UN VENDEDOR */ public boolean validaVendedor(String codigo) { boolean resultado = false; String temp = completaCeros(codigo); for (int i = 0; i < listaEmpleado.size(); i++) { if (listaEmpleado.get(i).getStrIdEmpleado().equals(temp)) { resultado = true; break; } } return resultado; } /* MÉTODO QUE VALIDA HORA */ public boolean validaHora(String hora) { boolean resultado = false; if (hora.length() == 5) { if (hora.equals("08:00") || hora.equals("08:30") || hora.equals("09:00") || hora.equals("09:30") || hora.equals("10:00") || hora.equals("10:30") || hora.equals("11:00") || hora.equals("11:30") || hora.equals("12:00") || hora.equals("12:30") || hora.equals("13:00") || hora.equals("13:30") || hora.equals("14:00") || hora.equals("14:30") || hora.equals("15:00") || hora.equals("15:30") || hora.equals("16:00") || hora.equals("16:30") || hora.equals("17:00") || hora.equals("17:30") || hora.equals("18:00") || hora.equals("18:30")) resultado = true; } return resultado; } /* MÉTODO QUE VALIDA UN CLIENTE */ public boolean validaCliente(String codigo) { boolean resultado = false; String temp = completaCeros(codigo); for (int i = 0; i < listaCliente.size(); i++) { if (listaCliente.get(i).getStrIdCliente().equals(temp)) { resultado = true; break; } } return resultado; } /* MÉTODO QUE VALIDA UNA FECHA */ public boolean validaFecha(String fecha) { boolean resultado = false; String anio = "" + fecha.charAt(0) + fecha.charAt(1) + fecha.charAt(2) + fecha.charAt(3); String mes = "" + fecha.charAt(4) + fecha.charAt(5); String dia = "" + fecha.charAt(6) + fecha.charAt(7); if (fecha.length() == 8) { if (anio.equals(Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)))) { if (mes.charAt(0) == '0') { if (mes.charAt(1) == '1' || mes.charAt(1) == '2' || mes.charAt(1) == '3' || mes.charAt(1) == '4' || mes.charAt(1) == '5' || mes.charAt(1) == '6' || mes.charAt(1) == '7' || mes.charAt(1) == '8' || mes.charAt(1) == '9') { if (dia.charAt(0) == '0') { if (dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '1') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '2') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '3') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1') { resultado = true; } } } } if (mes.charAt(0) == '1') { if (mes.charAt(1) == '0' || mes.charAt(1) == '1' || mes.charAt(1) == '2') { if (dia.charAt(0) == '0') { if (dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '1') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '2') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1' || dia.charAt(1) == '2' || dia.charAt(1) == '3' || dia.charAt(1) == '4' || dia.charAt(1) == '5' || dia.charAt(1) == '6' || dia.charAt(1) == '7' || dia.charAt(1) == '8' || dia.charAt(1) == '9') { resultado = true; } } if (dia.charAt(0) == '3') { if (dia.charAt(1) == '0' || dia.charAt(1) == '1') { resultado = true; } } } } } } return resultado; } /* MÉTODO QUE VALIDA FRECUENCIA */ public boolean validaFrecuencia(String frecuencia) { boolean resultado = false; if (frecuencia.equals("7") || frecuencia.equals("14") || frecuencia.equals("28")) resultado = true; return resultado; } @SuppressWarnings({ "unused", "static-access" }) public void insertaPlanificado() { boolean estado = false; /* VALOR INICIAL */ LeerHojaExcel leerHojaExcel = new LeerHojaExcel(); List<HashMap<String, String>> listaPlanificacion = null; HashMap<String, String> dataSet = null; SqlPlanificacion getPlanificacion = new SqlPlanificacionImpl(); ThreadSocketProgressBar thrProgreso = null; String idPla; String msg; String diaVisita; int filas = 0; int contarFilas = 0; SqlVisita sqlVisita = new SqlVisitaImpl(); BeanVisita visita = null; BeanPlanificacion planificacion = null; pgbInsertado.setValue(0); HashMap<Integer, String> lblColumna_Planificacion = new HashMap<Integer, String>(); lblColumna_Planificacion.put(0, Id_Vendedor_Planificacion); lblColumna_Planificacion.put(1, Id_Cliente_Planificacion); lblColumna_Planificacion.put(2, FechaInicio_Planificacion); lblColumna_Planificacion.put(3, Hora_Planificacion); lblColumna_Planificacion.put(4, Frecuencia_Planificacion); leerHojaExcel.LeerHojaExcel1(txtDireccionExcel.getText(), 1, 6, lblColumna_Planificacion); listaPlanificacion = leerHojaExcel.getListaDataSet(); filas = listaPlanificacion.size(); for (HashMap<String, String> map : listaPlanificacion) { if (map.get(Id_Vendedor_Planificacion) != null && map.get(FechaInicio_Planificacion) != null && map.get(Hora_Planificacion) != null && map.get(Id_Cliente_Planificacion) != null && map.get(Frecuencia_Planificacion) != null) { if (validaVendedor(map.get(Id_Vendedor_Planificacion)) == true && validaFecha(map.get(FechaInicio_Planificacion)) == true && validaHora(map.get(Hora_Planificacion)) == true && validaCliente(map.get(Id_Cliente_Planificacion)) == true && validaFrecuencia(map.get(Frecuencia_Planificacion)) == true) { try { objSAP = new SPlanificacion(); idPla = objSAP.ingresaPlanificacion(completaCeros(map.get(Id_Vendedor_Planificacion)), ((BeanDato) datose.get(0)).getStrCodigo(), map.get(FechaInicio_Planificacion), Integer.toString(dchCalendario.getCalendar().get(java.util.Calendar.YEAR)) + calculaMes(map.get(FechaInicio_Planificacion)) + calculaDia(map.get(FechaInicio_Planificacion)), map.get(Hora_Planificacion), completaCeros(map.get(Id_Cliente_Planificacion)), idFrecuencia(map.get(Frecuencia_Planificacion))); if (idPla != null) { for (int j = 0; j < idPla.length(); j++) { if (idPla.charAt(j) != '0') { idPla = idPla.substring(j, idPla.length()); break; } } Visita objFI = new Visita(); List<String> lstFechas = objFI .siguientesVisitas("" + map.get(FechaInicio_Planificacion).charAt(6) + map.get(FechaInicio_Planificacion).charAt(7) + Constante.SEPARADOR + map.get(FechaInicio_Planificacion).charAt(4) + map.get(FechaInicio_Planificacion).charAt(5) + Constante.SEPARADOR + map.get(FechaInicio_Planificacion).charAt(0) + map.get(FechaInicio_Planificacion).charAt(1) + map.get(FechaInicio_Planificacion).charAt(2) + map.get(FechaInicio_Planificacion).charAt(3), idFrecuencia(map.get(Frecuencia_Planificacion))); msg = objSAP.ingresaVisitaFueraDeRuta(completaCeros(map.get(Id_Vendedor_Planificacion)), completaCeros(map.get(Id_Cliente_Planificacion)), lstFechas, map.get(Hora_Planificacion), Constante.TIPO_VISITA1, idPla); if (msg != null) { contarFilas++; pgbInsertado.setValue((int) ((100 * contarFilas) / filas)); pgbInsertado.repaint(); estado = true; } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_IMPORTA_PLANIFICACION); break; } } else { Mensaje.mostrarError(Constante.MENSAJE_ERROR_IMPORTA_PLANIFICACION); break; } } catch (Exception e) { Util.mostrarExcepcion(e); Mensaje.mostrarError(Constante.MENSAJE_ERROR_NUEVA_PLANIFICACION); break; } } } } if (estado) { Mensaje.mostrarAviso(Constante.MENSAJE_EXITO_IMPORTA_PLANIFICACION); buscaPlanificacion(); } } private void lblBotonLeerExcelMousePressed(MouseEvent evt) { if (lblBotonLeerExcel.isEnabled() == true) { lblBotonLeerExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonLeerExcel.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonLeerExcelMouseReleased(MouseEvent evt) { lblBotonLeerExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonLeerExcel.setVerticalAlignment(SwingConstants.CENTER); } private void lblBotonSalirMouseClicked(MouseEvent evt) { popupImportaExcel.setVisible(false); pgbInsertado.setValue(0); } private void lblBotonSalirMousePressed(MouseEvent evt) { if (lblBotonSalir.isEnabled() == true) { lblBotonSalir.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonSalir.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonSalirMouseReleased(MouseEvent evt) { lblBotonSalir.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonSalir.setVerticalAlignment(SwingConstants.CENTER); } private void lblBotonExaminarExcelMouseClicked(MouseEvent evt) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(IPlanificacion.this); if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); DireccionFormato = String.valueOf(file.getAbsoluteFile()); DireccionFormato = DireccionFormato.trim(); txtDireccionExcel.setText(DireccionFormato); popupImportaExcel.setVisible(true); } pgbInsertado.setValue(0); } private void lblBotonExaminarExcelMousePressed(MouseEvent evt) { if (lblBotonExaminarExcel.isEnabled() == true) { lblBotonExaminarExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); lblBotonExaminarExcel.setVerticalAlignment(SwingConstants.BOTTOM); } } private void lblBotonExaminarExcelMouseReleased(MouseEvent evt) { lblBotonExaminarExcel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); lblBotonExaminarExcel.setVerticalAlignment(SwingConstants.CENTER); } private class ThreadSocketProgressBar extends Thread { int progreso; @SuppressWarnings("unused") public ThreadSocketProgressBar(int progreso) { this.progreso = progreso; } public void run() { pgbInsertado.setValue(progreso); Rectangle progressRect = pgbInsertado.getBounds(); progressRect.x = 0; progressRect.y = 0; pgbInsertado.paintImmediately(progressRect); } } private String Id_Vendedor_Planificacion = "IdVendedor"; private String Id_Cliente_Planificacion = "IdCliente"; private String FechaInicio_Planificacion = "FechaInicio"; private String Hora_Planificacion = "Hora"; private String Frecuencia_Planificacion = "Frecuencia"; }
56,741
0.684095
0.665143
1,504
36.67952
34.925697
474
false
false
0
0
0
0
0
0
3.964096
false
false
5
ac11b2adad97913415f3d1c23a98e6e253400cbc
68,719,479,942
d40e5031834bec90872d8460f38d0c220dceb140
/src/main/java/com/github/ydydwang/rtsp/client/channel/RtspWriter.java
db79cdcf1ddf1ac1e0858a3ff962780ddf460268
[]
no_license
YDYDWang/rtsp-client
https://github.com/YDYDWang/rtsp-client
91151f6565ee8d59539a2b9542166c80581ca312
fbe458a0e85e2670db53900f097f0fc0a493fe06
refs/heads/master
2021-04-15T03:50:29.219000
2018-03-23T10:12:27
2018-03-23T10:12:27
126,314,037
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.ydydwang.rtsp.client.channel; import java.io.OutputStream; public class RtspWriter extends ProxyWriter { public RtspWriter(OutputStream outputStream) { super(outputStream); } }
UTF-8
Java
213
java
RtspWriter.java
Java
[ { "context": "package com.github.ydydwang.rtsp.client.channel;\r\n\r\nimport java.io.OutputStre", "end": 27, "score": 0.9672021865844727, "start": 19, "tag": "USERNAME", "value": "ydydwang" } ]
null
[]
package com.github.ydydwang.rtsp.client.channel; import java.io.OutputStream; public class RtspWriter extends ProxyWriter { public RtspWriter(OutputStream outputStream) { super(outputStream); } }
213
0.755869
0.755869
10
19.299999
20.214104
48
false
false
0
0
0
0
0
0
0.7
false
false
5
63fadd0197772b284fb591ef6869000091e9f332
8,615,704,402,370
33b51cc267c7c9e23cef34a78dba09de47c32585
/MySql/src/mysql/clauses/RequiredClause.java
a7df37629dfaad4b470f1d0351f3de107b7bbca8
[]
no_license
Nuno-Rafael-Figueiredo/nuno-rafael-figueiredo-java-dev
https://github.com/Nuno-Rafael-Figueiredo/nuno-rafael-figueiredo-java-dev
818b0696214107602230db9a976df9abddee5fab
efb8eb87e8baf9231602655d8a9e8cf06f65ba9b
refs/heads/master
2016-09-05T20:55:34.551000
2013-09-05T19:51:34
2013-09-05T19:51:34
33,076,599
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mysql.clauses; import mysql.statements.Statement; /** * User: Nuno * Date: 21-08-2013 * Time: 16:40 */ public class RequiredClause<E extends Statement> extends Clause<E> { protected RequiredClause(String name, E statement) { super(name, statement, true); } public RequiredClause(E statement) { super(statement, true); } }
UTF-8
Java
387
java
RequiredClause.java
Java
[ { "context": "mport mysql.statements.Statement;\r\n\r\n/**\r\n * User: Nuno\r\n * Date: 21-08-2013\r\n * Time: 16:40\r\n */\r\npublic", "end": 82, "score": 0.9977315664291382, "start": 78, "tag": "USERNAME", "value": "Nuno" } ]
null
[]
package mysql.clauses; import mysql.statements.Statement; /** * User: Nuno * Date: 21-08-2013 * Time: 16:40 */ public class RequiredClause<E extends Statement> extends Clause<E> { protected RequiredClause(String name, E statement) { super(name, statement, true); } public RequiredClause(E statement) { super(statement, true); } }
387
0.635659
0.604651
18
19.5
20.111494
68
false
false
0
0
0
0
0
0
0.444444
false
false
5
1272a55002734c3837dbe4c63d019d8e0680ac4c
9,844,065,047,455
b0d6f5c3fdecf0d2a2a38b97c35ca9ffa5fc1112
/panoramapublic/src/org/labkey/panoramapublic/PanoramaPublicFileListener.java
4a63b6506ed10ad41e0a7242b54f698e7bf5c066
[]
no_license
LabKey/MacCossLabModules
https://github.com/LabKey/MacCossLabModules
15a3ee7bcabe3cb19e87e6dc907e09c81b5f2635
142c022b1b7001dcd57e57c959189f015daa4684
refs/heads/develop
2023-08-30T05:26:01.897000
2023-08-29T23:58:09
2023-08-29T23:58:09
186,678,156
2
2
null
false
2023-09-06T20:58:01
2019-05-14T18:28:02
2023-07-18T09:09:57
2023-09-06T20:57:58
59,153
1
2
0
Java
false
false
package org.labkey.panoramapublic; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.data.Container; import org.labkey.api.data.SQLFragment; import org.labkey.api.exp.api.ExpData; import org.labkey.api.exp.api.ExperimentService; import org.labkey.api.files.FileListener; import org.labkey.api.security.User; import java.io.File; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; public class PanoramaPublicFileListener implements FileListener { @Override public String getSourceName() { return null; } @Override public void fileCreated(@NotNull File created, @Nullable User user, @Nullable Container container) { } @Override public int fileMoved(@NotNull File src, @NotNull File dest, @Nullable User user, @Nullable Container container) { // Update any symlinks targeting the file PanoramaPublicSymlinkManager.get().fireSymlinkUpdate(src.toPath(), dest.toPath(), container, user); ExpData data = ExperimentService.get().getExpDataByURL(src, null); if (null != data) data.setDataFileURI(dest.toURI()); return 0; } @Override public void fileDeleted(@NotNull Path deleted, @Nullable User user, @Nullable Container container) { ExpData data = ExperimentService.get().getExpDataByURL(deleted, container); if (null != data) data.delete(user); } @Override public Collection<File> listFiles(@Nullable Container container) { return Collections.emptyList(); } @Override public SQLFragment listFilesQuery() { throw new UnsupportedOperationException("Not implemented"); } }
UTF-8
Java
1,768
java
PanoramaPublicFileListener.java
Java
[]
null
[]
package org.labkey.panoramapublic; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.data.Container; import org.labkey.api.data.SQLFragment; import org.labkey.api.exp.api.ExpData; import org.labkey.api.exp.api.ExperimentService; import org.labkey.api.files.FileListener; import org.labkey.api.security.User; import java.io.File; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; public class PanoramaPublicFileListener implements FileListener { @Override public String getSourceName() { return null; } @Override public void fileCreated(@NotNull File created, @Nullable User user, @Nullable Container container) { } @Override public int fileMoved(@NotNull File src, @NotNull File dest, @Nullable User user, @Nullable Container container) { // Update any symlinks targeting the file PanoramaPublicSymlinkManager.get().fireSymlinkUpdate(src.toPath(), dest.toPath(), container, user); ExpData data = ExperimentService.get().getExpDataByURL(src, null); if (null != data) data.setDataFileURI(dest.toURI()); return 0; } @Override public void fileDeleted(@NotNull Path deleted, @Nullable User user, @Nullable Container container) { ExpData data = ExperimentService.get().getExpDataByURL(deleted, container); if (null != data) data.delete(user); } @Override public Collection<File> listFiles(@Nullable Container container) { return Collections.emptyList(); } @Override public SQLFragment listFilesQuery() { throw new UnsupportedOperationException("Not implemented"); } }
1,768
0.702489
0.701923
65
26.200001
29.359941
115
false
false
0
0
0
0
0
0
0.523077
false
false
5
4842419fddfde7a968c1680b2ebea044659d3c7d
18,021,682,780,014
2e47d3688bba44b38f5c5631d9c028a2500df9c9
/src/main/java/com/hgyllensvard/geofencemanager/geofence/playIntegration/GeofenceTransitionsIntentService.java
94bc06d55d5d50875d7f5e776d8f0741e9f9434d
[ "Apache-2.0" ]
permissive
HGyllensvard/geofence-manager
https://github.com/HGyllensvard/geofence-manager
0c397c7cb8a36295bef069edfd597a5003af7f6a
5cbe46ff891b4e4a248fdf0d5b2858c9a088bdf8
refs/heads/master
2020-12-26T03:12:49.789000
2017-04-11T21:22:18
2017-04-11T21:22:18
68,647,964
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hgyllensvard.geofencemanager.geofence.playIntegration; import android.app.IntentService; import android.content.Intent; import com.google.android.gms.location.GeofencingEvent; import com.hgyllensvard.geofencemanager.di.GeofenceModuleManager; import javax.inject.Inject; import timber.log.Timber; public class GeofenceTransitionsIntentService extends IntentService { @Inject GeofenceTriggeredManager geofenceEventTriggerManager; public GeofenceTransitionsIntentService() { super(GeofenceTransitionsIntentService.class.getSimpleName()); GeofenceModuleManager.geofenceManagerComponent(getApplicationContext()) .inject(this); } /** * Handles incoming intents. * * @param intent The Intent sent by Location Services. This Intent is provided to Location * Services (inside a PendingIntent) when addGeofences() is called. */ @Override protected void onHandleIntent(Intent intent) { GeofencingEvent geofenceEvent = GeofencingEvent.fromIntent(intent); if (geofenceEvent.hasError()) { int errorCode = geofenceEvent.getErrorCode(); Timber.e("Location Services error: " + errorCode); return; } geofenceEventTriggerManager.geofencesTriggered(geofenceEvent); } }
UTF-8
Java
1,341
java
GeofenceTransitionsIntentService.java
Java
[]
null
[]
package com.hgyllensvard.geofencemanager.geofence.playIntegration; import android.app.IntentService; import android.content.Intent; import com.google.android.gms.location.GeofencingEvent; import com.hgyllensvard.geofencemanager.di.GeofenceModuleManager; import javax.inject.Inject; import timber.log.Timber; public class GeofenceTransitionsIntentService extends IntentService { @Inject GeofenceTriggeredManager geofenceEventTriggerManager; public GeofenceTransitionsIntentService() { super(GeofenceTransitionsIntentService.class.getSimpleName()); GeofenceModuleManager.geofenceManagerComponent(getApplicationContext()) .inject(this); } /** * Handles incoming intents. * * @param intent The Intent sent by Location Services. This Intent is provided to Location * Services (inside a PendingIntent) when addGeofences() is called. */ @Override protected void onHandleIntent(Intent intent) { GeofencingEvent geofenceEvent = GeofencingEvent.fromIntent(intent); if (geofenceEvent.hasError()) { int errorCode = geofenceEvent.getErrorCode(); Timber.e("Location Services error: " + errorCode); return; } geofenceEventTriggerManager.geofencesTriggered(geofenceEvent); } }
1,341
0.721849
0.721849
42
30.952381
29.524769
94
false
false
0
0
0
0
0
0
0.357143
false
false
5
a090414a2417eb10b4fc0b2d4ab4ee13f8efc384
1,151,051,247,735
b652cfafe68f947979f04596b7cb5f9a0bfa4d2f
/app/src/main/java/com/leocardz/url/unshortener/About.java
26628d243b464b0490173c95477748f634b8cd93
[ "Apache-2.0" ]
permissive
LeonardoCardoso/Unshorten-It
https://github.com/LeonardoCardoso/Unshorten-It
7ec3755eda972b7a2b37b71b8e953daef154ab3a
fc8028eac02b98ae5dfaeeb7511c32314cca7511
refs/heads/master
2021-01-18T21:22:49.622000
2016-09-13T14:09:53
2016-09-13T14:09:53
30,667,778
9
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leocardz.url.unshortener; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Toast; import java.util.ArrayList; public class About extends ActionBarActivity { Activity context; Button button; Button rateIt, shareIt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); context = this; getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); shareIt = (Button) findViewById(R.id.share_us_button); shareIt.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { shareUs(); } }); rateIt = (Button) findViewById(R.id.rate_us_button); rateIt.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { rateUs(); } }); } private void shareUs() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.spread_subject)); intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.spread_text)); startActivity(Intent.createChooser(intent, getString(R.string.share_via))); } private void rateUs() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri .parse("market://details?id=com.leocardz.url.unshortener")); startActivity(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; default: break; } return super.onOptionsItemSelected(item); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out); } }
UTF-8
Java
2,549
java
About.java
Java
[]
null
[]
package com.leocardz.url.unshortener; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Toast; import java.util.ArrayList; public class About extends ActionBarActivity { Activity context; Button button; Button rateIt, shareIt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); context = this; getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); shareIt = (Button) findViewById(R.id.share_us_button); shareIt.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { shareUs(); } }); rateIt = (Button) findViewById(R.id.rate_us_button); rateIt.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { rateUs(); } }); } private void shareUs() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.spread_subject)); intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.spread_text)); startActivity(Intent.createChooser(intent, getString(R.string.share_via))); } private void rateUs() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri .parse("market://details?id=com.leocardz.url.unshortener")); startActivity(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; default: break; } return super.onOptionsItemSelected(item); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out); } }
2,549
0.631228
0.630051
93
26.408602
20.199137
76
false
false
0
0
0
0
0
0
0.526882
false
false
5
584136a3a9b0405abffe343d9605ebdd05a80eff
27,058,293,975,620
2eff4d30d80873003d26c07480cc6a5c994fd39c
/src/main/java/leetcode/character/MaximumRepeatingSubstring.java
811f4ed59237635ce7b7bf84fed7ad7c492ef0d6
[]
no_license
jorksz/CS-Algorithm
https://github.com/jorksz/CS-Algorithm
9cbc6fc2e3b31ece96784fdd91c7e4ebb9b483b2
9ffd6aa4d133001747c83be5f413a1d2711effc1
refs/heads/master
2023-07-25T18:37:38.351000
2023-07-12T14:48:15
2023-07-12T14:48:15
201,883,338
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode.character; public class MaximumRepeatingSubstring { public int maxRepeating(String sequence, String word) { int res = 0; StringBuilder words = new StringBuilder(); words.append(word); while (sequence.length() >= words.toString().length()) { if (sequence.contains(words.toString())) { res ++; } words.append(word); } return res; } public static void main(String[] args) { String sequence = "ababc", word = "ab"; MaximumRepeatingSubstring maximumRepeatingSubstring = new MaximumRepeatingSubstring(); System.out.println(maximumRepeatingSubstring.maxRepeating(sequence, word)); } }
UTF-8
Java
742
java
MaximumRepeatingSubstring.java
Java
[]
null
[]
package leetcode.character; public class MaximumRepeatingSubstring { public int maxRepeating(String sequence, String word) { int res = 0; StringBuilder words = new StringBuilder(); words.append(word); while (sequence.length() >= words.toString().length()) { if (sequence.contains(words.toString())) { res ++; } words.append(word); } return res; } public static void main(String[] args) { String sequence = "ababc", word = "ab"; MaximumRepeatingSubstring maximumRepeatingSubstring = new MaximumRepeatingSubstring(); System.out.println(maximumRepeatingSubstring.maxRepeating(sequence, word)); } }
742
0.613208
0.61186
27
26.481482
26.900875
94
false
false
0
0
0
0
0
0
0.481481
false
false
5
0fc3423380ed7d269444bc11dc1d12917f663fb3
29,102,698,407,365
9ece1790ee2f86ff651448f1da652db681671cd7
/src/test/java/com/deloitte/automation/testcase/functionalTests/UT/IF_Test624/Test624_TC01.java
55bd68ce2b79128c02c52e410a7577d5ef874a1a
[]
no_license
hemantojhaa/AAA_Framework
https://github.com/hemantojhaa/AAA_Framework
b5fabbfe7681327388e870de38762c107716ab61
db723b292b38b017114667ac4595ca53b234fa1f
refs/heads/master
2016-05-05T11:23:05.609000
2015-09-28T14:52:43
2015-09-28T14:52:43
43,306,922
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.deloitte.automation.testcase.functionalTests.UT.IF_Test624; import org.testng.annotations.Test; import com.exigen.automation.common.CommonActionFunctions; import com.exigen.automation.common.CommonDataFilling; import com.exigen.automation.constant.element.autoss.AssBindTabUiIds; import com.exigen.automation.constant.element.autoss.AssQuoteConsViewUiIds; import com.exigen.automation.constant.key.PropertiesKeyConstants; import com.exigen.automation.dataFilling.AccountDataFilling; import com.exigen.automation.dataFilling.autoss.AssBindPurchaseTabFilling; import com.exigen.automation.dataFilling.autoss.AssDocumentsTabFilling; import com.exigen.automation.dataFilling.autoss.AssDriverTabFilling; import com.exigen.automation.dataFilling.autoss.AssFormsTabFilling; import com.exigen.automation.dataFilling.autoss.AssGeneralTabFilling; import com.exigen.automation.dataFilling.autoss.AssPrefillTabFilling; import com.exigen.automation.dataFilling.autoss.AssPremiumTabFilling; import com.exigen.automation.dataFilling.autoss.AssReportsTabFilling; import com.exigen.automation.dataFilling.autoss.AssVehicleTabFilling; import com.exigen.automation.infrastructure.AppBaseClass; /** * @author eis */ public class Test624_TC01 extends AppBaseClass { @Test public void Test624_Tc01() { CommonActionFunctions func = new CommonActionFunctions(getSelenium()); AccountDataFilling accountDataFilling = new AccountDataFilling(getSelenium()); CommonActionFunctions commonFunc = new CommonActionFunctions(getSelenium()); AssPrefillTabFilling assPrefillTabFilling = new AssPrefillTabFilling(getSelenium()); AssGeneralTabFilling assGeneralTabFilling = new AssGeneralTabFilling(getSelenium()); AssDriverTabFilling assDriverTabFilling = new AssDriverTabFilling(getSelenium()); AssReportsTabFilling assReportsTabFilling = new AssReportsTabFilling(getSelenium()); AssVehicleTabFilling assVehicleTabFilling = new AssVehicleTabFilling(getSelenium()); AssPremiumTabFilling assPremiumTabFilling = new AssPremiumTabFilling(getSelenium()); AssDocumentsTabFilling assDocumentsTabFilling = new AssDocumentsTabFilling(getSelenium()); AssBindPurchaseTabFilling assBindPurchaseTabFilling = new AssBindPurchaseTabFilling(getSelenium()); CommonDataFilling commonDataFilling = new CommonDataFilling(getSelenium()); AssFormsTabFilling assFormsTabFilling = new AssFormsTabFilling(getSelenium()); // create new quote // Create account func.goToSearchWindow(); accountDataFilling.accountFilling(getDataSet(), "SCN_264_AccountFillData1", "BrokerFillData1"); func.goToSearchWindow(); commonFunc.createASSQuote(); // prefill assPrefillTabFilling.prefillFillingSmoke(getDataSet(), "PrefillFillSmoke", "PrefillValidateSmoke"); assPrefillTabFilling.setPrefillAddressType("Prior"); assPrefillTabFilling.validateAddress(); assPrefillTabFilling.continueButton(); // general assGeneralTabFilling.generalFullTabFilling(getDataSet(), "InsuredFillData4", "GeneralFillSmoke"); assGeneralTabFilling.setProductsOwnerRentersYes(); assGeneralTabFilling.setProductsOwnerRentersPolicy("123456"); //PAS04 Change //assGeneralTabFilling.setCurrentCarrierExpirationDate(addDaysToCurrentDate(+1)); assGeneralTabFilling.setAgentEnteredCarrierExpirationDate(addDaysToCurrentDate(+1)); // assGeneralTabFilling.setInsuredPriorAddressYes(); assGeneralTabFilling.validateAddress(); assGeneralTabFilling.continueButton(); // driver tab assDriverTabFilling.driverFilling(getDataSet(), "DriverFillData3"); assDriverTabFilling.setAgeFirstLicensed("15"); assDriverTabFilling.driverFillingAdd(getDataSet(), "DriverCheckData1"); assDriverTabFilling.setDriverType("Not Available for Rating"); assDriverTabFilling.setDriverReason("Other"); assDriverTabFilling.setOccupation("Military"); assDriverTabFilling.addIncident("Minor Violation", "Door Open Lane", addDaysToCurrentDate(-2)); assDriverTabFilling.continueButton(); // order reports tab assReportsTabFilling.reportsFillingSmoke(); assReportsTabFilling.continueButton(); // vehicle tab assVehicleTabFilling.vehicleFilling(getDataSet(), "SCN_264_Vehicle1"); assVehicleTabFilling.vehicleFillingAdd(getDataSet(), "VehicleCheckData1"); assVehicleTabFilling.continueButton(); // form assFormsTabFilling.formsTabFillingSmoke(); assFormsTabFilling.continueButton(); // Premium Coverages tab assPremiumTabFilling.setPaymentPlan("Semi-Annual"); // Payment Method- AutoPay disabled assPremiumTabFilling.setTotCovUnderinsuredMBI_AZ("$50,000/$100,000"); assPremiumTabFilling.calculatePremiumButton(); // continue to the next tab assPremiumTabFilling.continueButton(); // documents tab assDocumentsTabFilling.documentsFillingSmoke(); assDocumentsTabFilling.continueButton(); commonDataFilling.overrideAllRules(); assDocumentsTabFilling.continueButton(); // bind tab assBindPurchaseTabFilling.bindTabFillingSmoke(); commonDataFilling.addCreditCard("4024007124493254"); assBindPurchaseTabFilling.setRecurring(); Double amount = CommonActionFunctions.currencyToDouble(getTextOfElement(AssBindTabUiIds.REQUIRED_AMOUNT)); inputText(AssBindTabUiIds.PAYMENT_AMOUNT_RECCURING, CommonActionFunctions.doubleToCurrency(amount)); waitForAjax(getAjaxWaitTime()); waitForElementEditable(AssBindTabUiIds.APPLY_PAYMENT, getMiddleWaitTime()); // click Apply Payment button click(AssBindTabUiIds.APPLY_PAYMENT); waitForElementVisible(AssBindTabUiIds.BIND_YES, getMiddleWaitTime()); clickAndWait(AssBindTabUiIds.BIND_YES, getMiddleWaitTime()); checkTextOfElementEquals(AssQuoteConsViewUiIds.POLICY_STATUS, "Policy Active"); String policyNo = getTextOfElement(AssQuoteConsViewUiIds.HEADER_POLICY_NUMBER); if(policyNo != null) { addKeyValueIntoPropertiesFile(PropertiesKeyConstants.DC_POLICY_NUMBERS_FILE, "Test28" + PropertiesKeyConstants.ASS_POLICY_NUMBER, policyNo); printToConsole("============================================="); printToConsole("Test28" + PropertiesKeyConstants.ASS_POLICY_NUMBER + " created with number: " + policyNo); printToConsole("============================================="); } clickAndWait(AssQuoteConsViewUiIds.ACTIVE_TASK, getMiddleWaitTime()); verifyTextOfElementContains(idConversion(AssQuoteConsViewUiIds.TASK_$_NAME, 1), "If Underinsured coverage is rejected or lower limits"); printToConsole(getTextOfElement(idConversion(AssQuoteConsViewUiIds.TASK_$_NAME, 1))); printToConsole("If Underinsured coverage is rejected or lower limits"); verifyTrue(getTextOfElement(idConversion(AssQuoteConsViewUiIds.TASK_$_NAME, 1)).contains("Underinsured coverage is rejected or lower limits"), "Task doesn't exits - Underinsured coverage is rejected or lower limits"); checkForVerificationErrors(); } }
UTF-8
Java
6,992
java
Test624_TC01.java
Java
[ { "context": "on.infrastructure.AppBaseClass;\r\n\r\n/**\r\n * @author eis\r\n */\r\npublic class Test624_TC01 extends AppBaseCl", "end": 1245, "score": 0.8711079359054565, "start": 1242, "tag": "USERNAME", "value": "eis" }, { "context": "nfrastructure.AppBaseClass;\r\n\r\n/**\r\n * @author eis\r\n */\r\npublic class Test624_TC01 extends AppBaseClas", "end": 1245, "score": 0.44930052757263184, "start": 1245, "tag": "NAME", "value": "" } ]
null
[]
/** * */ package com.deloitte.automation.testcase.functionalTests.UT.IF_Test624; import org.testng.annotations.Test; import com.exigen.automation.common.CommonActionFunctions; import com.exigen.automation.common.CommonDataFilling; import com.exigen.automation.constant.element.autoss.AssBindTabUiIds; import com.exigen.automation.constant.element.autoss.AssQuoteConsViewUiIds; import com.exigen.automation.constant.key.PropertiesKeyConstants; import com.exigen.automation.dataFilling.AccountDataFilling; import com.exigen.automation.dataFilling.autoss.AssBindPurchaseTabFilling; import com.exigen.automation.dataFilling.autoss.AssDocumentsTabFilling; import com.exigen.automation.dataFilling.autoss.AssDriverTabFilling; import com.exigen.automation.dataFilling.autoss.AssFormsTabFilling; import com.exigen.automation.dataFilling.autoss.AssGeneralTabFilling; import com.exigen.automation.dataFilling.autoss.AssPrefillTabFilling; import com.exigen.automation.dataFilling.autoss.AssPremiumTabFilling; import com.exigen.automation.dataFilling.autoss.AssReportsTabFilling; import com.exigen.automation.dataFilling.autoss.AssVehicleTabFilling; import com.exigen.automation.infrastructure.AppBaseClass; /** * @author eis */ public class Test624_TC01 extends AppBaseClass { @Test public void Test624_Tc01() { CommonActionFunctions func = new CommonActionFunctions(getSelenium()); AccountDataFilling accountDataFilling = new AccountDataFilling(getSelenium()); CommonActionFunctions commonFunc = new CommonActionFunctions(getSelenium()); AssPrefillTabFilling assPrefillTabFilling = new AssPrefillTabFilling(getSelenium()); AssGeneralTabFilling assGeneralTabFilling = new AssGeneralTabFilling(getSelenium()); AssDriverTabFilling assDriverTabFilling = new AssDriverTabFilling(getSelenium()); AssReportsTabFilling assReportsTabFilling = new AssReportsTabFilling(getSelenium()); AssVehicleTabFilling assVehicleTabFilling = new AssVehicleTabFilling(getSelenium()); AssPremiumTabFilling assPremiumTabFilling = new AssPremiumTabFilling(getSelenium()); AssDocumentsTabFilling assDocumentsTabFilling = new AssDocumentsTabFilling(getSelenium()); AssBindPurchaseTabFilling assBindPurchaseTabFilling = new AssBindPurchaseTabFilling(getSelenium()); CommonDataFilling commonDataFilling = new CommonDataFilling(getSelenium()); AssFormsTabFilling assFormsTabFilling = new AssFormsTabFilling(getSelenium()); // create new quote // Create account func.goToSearchWindow(); accountDataFilling.accountFilling(getDataSet(), "SCN_264_AccountFillData1", "BrokerFillData1"); func.goToSearchWindow(); commonFunc.createASSQuote(); // prefill assPrefillTabFilling.prefillFillingSmoke(getDataSet(), "PrefillFillSmoke", "PrefillValidateSmoke"); assPrefillTabFilling.setPrefillAddressType("Prior"); assPrefillTabFilling.validateAddress(); assPrefillTabFilling.continueButton(); // general assGeneralTabFilling.generalFullTabFilling(getDataSet(), "InsuredFillData4", "GeneralFillSmoke"); assGeneralTabFilling.setProductsOwnerRentersYes(); assGeneralTabFilling.setProductsOwnerRentersPolicy("123456"); //PAS04 Change //assGeneralTabFilling.setCurrentCarrierExpirationDate(addDaysToCurrentDate(+1)); assGeneralTabFilling.setAgentEnteredCarrierExpirationDate(addDaysToCurrentDate(+1)); // assGeneralTabFilling.setInsuredPriorAddressYes(); assGeneralTabFilling.validateAddress(); assGeneralTabFilling.continueButton(); // driver tab assDriverTabFilling.driverFilling(getDataSet(), "DriverFillData3"); assDriverTabFilling.setAgeFirstLicensed("15"); assDriverTabFilling.driverFillingAdd(getDataSet(), "DriverCheckData1"); assDriverTabFilling.setDriverType("Not Available for Rating"); assDriverTabFilling.setDriverReason("Other"); assDriverTabFilling.setOccupation("Military"); assDriverTabFilling.addIncident("Minor Violation", "Door Open Lane", addDaysToCurrentDate(-2)); assDriverTabFilling.continueButton(); // order reports tab assReportsTabFilling.reportsFillingSmoke(); assReportsTabFilling.continueButton(); // vehicle tab assVehicleTabFilling.vehicleFilling(getDataSet(), "SCN_264_Vehicle1"); assVehicleTabFilling.vehicleFillingAdd(getDataSet(), "VehicleCheckData1"); assVehicleTabFilling.continueButton(); // form assFormsTabFilling.formsTabFillingSmoke(); assFormsTabFilling.continueButton(); // Premium Coverages tab assPremiumTabFilling.setPaymentPlan("Semi-Annual"); // Payment Method- AutoPay disabled assPremiumTabFilling.setTotCovUnderinsuredMBI_AZ("$50,000/$100,000"); assPremiumTabFilling.calculatePremiumButton(); // continue to the next tab assPremiumTabFilling.continueButton(); // documents tab assDocumentsTabFilling.documentsFillingSmoke(); assDocumentsTabFilling.continueButton(); commonDataFilling.overrideAllRules(); assDocumentsTabFilling.continueButton(); // bind tab assBindPurchaseTabFilling.bindTabFillingSmoke(); commonDataFilling.addCreditCard("4024007124493254"); assBindPurchaseTabFilling.setRecurring(); Double amount = CommonActionFunctions.currencyToDouble(getTextOfElement(AssBindTabUiIds.REQUIRED_AMOUNT)); inputText(AssBindTabUiIds.PAYMENT_AMOUNT_RECCURING, CommonActionFunctions.doubleToCurrency(amount)); waitForAjax(getAjaxWaitTime()); waitForElementEditable(AssBindTabUiIds.APPLY_PAYMENT, getMiddleWaitTime()); // click Apply Payment button click(AssBindTabUiIds.APPLY_PAYMENT); waitForElementVisible(AssBindTabUiIds.BIND_YES, getMiddleWaitTime()); clickAndWait(AssBindTabUiIds.BIND_YES, getMiddleWaitTime()); checkTextOfElementEquals(AssQuoteConsViewUiIds.POLICY_STATUS, "Policy Active"); String policyNo = getTextOfElement(AssQuoteConsViewUiIds.HEADER_POLICY_NUMBER); if(policyNo != null) { addKeyValueIntoPropertiesFile(PropertiesKeyConstants.DC_POLICY_NUMBERS_FILE, "Test28" + PropertiesKeyConstants.ASS_POLICY_NUMBER, policyNo); printToConsole("============================================="); printToConsole("Test28" + PropertiesKeyConstants.ASS_POLICY_NUMBER + " created with number: " + policyNo); printToConsole("============================================="); } clickAndWait(AssQuoteConsViewUiIds.ACTIVE_TASK, getMiddleWaitTime()); verifyTextOfElementContains(idConversion(AssQuoteConsViewUiIds.TASK_$_NAME, 1), "If Underinsured coverage is rejected or lower limits"); printToConsole(getTextOfElement(idConversion(AssQuoteConsViewUiIds.TASK_$_NAME, 1))); printToConsole("If Underinsured coverage is rejected or lower limits"); verifyTrue(getTextOfElement(idConversion(AssQuoteConsViewUiIds.TASK_$_NAME, 1)).contains("Underinsured coverage is rejected or lower limits"), "Task doesn't exits - Underinsured coverage is rejected or lower limits"); checkForVerificationErrors(); } }
6,992
0.787471
0.777031
156
42.820515
37.366257
219
false
false
0
0
0
0
0
0
2.083333
false
false
5
69eaa3ed1e32c83b67024270e59773d61e00ac3a
6,339,371,740,311
fd1c8a4d830f99291365886c85c43680f62df312
/example/src/main/java/com/catyee/mybatis/example/model/ClassGrade.java
44f59c271aa1bdebf745f47d00aa664cd1a81adc
[ "Apache-2.0" ]
permissive
Wwwwan/mybatis-ds-generator
https://github.com/Wwwwan/mybatis-ds-generator
de36a0d30a526a575b4eec8958cfff1116d6ea40
de6757d9855feee2c217d85f2b223fcc778efc35
refs/heads/main
2023-04-16T07:53:21.681000
2021-04-18T09:09:01
2021-04-18T09:09:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.catyee.mybatis.example.model; import com.catyee.mybatis.example.custom.entity.GradeType; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class ClassGrade implements Serializable { private Long id; private String name; private String description; private GradeType gradeType; private Long regulatorId; private LocalDateTime createTime; private LocalDateTime lastUpdateTime; private List<Student> students; private Teacher regulator; private static final long serialVersionUID = 1L; }
UTF-8
Java
752
java
ClassGrade.java
Java
[]
null
[]
package com.catyee.mybatis.example.model; import com.catyee.mybatis.example.custom.entity.GradeType; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class ClassGrade implements Serializable { private Long id; private String name; private String description; private GradeType gradeType; private Long regulatorId; private LocalDateTime createTime; private LocalDateTime lastUpdateTime; private List<Student> students; private Teacher regulator; private static final long serialVersionUID = 1L; }
752
0.785904
0.784574
36
19.916666
17.327522
58
false
false
0
0
0
0
0
0
0.527778
false
false
5
eadc8ac04bf1bb73e2f663ba5caff706d00bcbb7
14,594,298,885,375
72d87cc90f4ff7933e716cf765af0b5435e5bc04
/src/main/java/br/net/gvt/efika/efikaServiceAPI/model/service/validator/TelecomServicesDistribution.java
d97ae0d206a18c6cf9b319d3ce352c57af686dee
[]
no_license
pjefika/efikaServiceAPI
https://github.com/pjefika/efikaServiceAPI
c1c2d1f8f5f7dfece5b40c4d187f8701636448a2
dc863c4d240ae3f204ad177dc9e2095ccbcdfb1f
refs/heads/master
2020-03-09T02:55:56.045000
2018-08-13T12:45:59
2018-08-13T12:45:59
128,552,567
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.net.gvt.efika.efikaServiceAPI.model.service.validator; import br.net.gvt.efika.efikaServiceAPI.model.ExecDetailedRequest; import br.net.gvt.efika.efikaServiceAPI.model.validador.AcaoValidadora; import br.net.gvt.efika.efikaServiceAPI.model.validador.AcaoRequest; import br.net.gvt.efika.efikaServiceAPI.model.validador.ExecucaoDetalhada; /** * * @author G0041775 ainda a ser renomeada - sugestões aceitas... */ public interface TelecomServicesDistribution { public AcaoValidadora validacao(AcaoRequest acao) throws Exception; public ExecucaoDetalhada execucaoDetalhada(ExecDetailedRequest req) throws Exception; }
UTF-8
Java
848
java
TelecomServicesDistribution.java
Java
[ { "context": "alidador.ExecucaoDetalhada;\r\n\r\n/**\r\n *\r\n * @author G0041775 ainda a ser renomeada - sugestões aceitas...\r\n */", "end": 576, "score": 0.9996277093887329, "start": 568, "tag": "USERNAME", "value": "G0041775" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.net.gvt.efika.efikaServiceAPI.model.service.validator; import br.net.gvt.efika.efikaServiceAPI.model.ExecDetailedRequest; import br.net.gvt.efika.efikaServiceAPI.model.validador.AcaoValidadora; import br.net.gvt.efika.efikaServiceAPI.model.validador.AcaoRequest; import br.net.gvt.efika.efikaServiceAPI.model.validador.ExecucaoDetalhada; /** * * @author G0041775 ainda a ser renomeada - sugestões aceitas... */ public interface TelecomServicesDistribution { public AcaoValidadora validacao(AcaoRequest acao) throws Exception; public ExecucaoDetalhada execucaoDetalhada(ExecDetailedRequest req) throws Exception; }
848
0.782763
0.774498
22
36.5
33.461987
89
false
false
0
0
0
0
0
0
0.454545
false
false
5
5b7b0d4ecab089bd193185edb828c0ba59bd5600
28,415,503,631,988
ab8b1a13411e9f81f9b126c3ceba74e4b5df4f74
/src/main/java/com/kwetter/JMS/TweetMessagePublisher.java
2e0f3eb355c31af99cbacfbd856ee7180d940e04
[]
no_license
HDauven/TwitterClone
https://github.com/HDauven/TwitterClone
7797141de0c57d899238d20046e0a91c2a4d3964
e1da2bc0c261f1598756e95cdb7e2a8f8a1385fb
refs/heads/master
2021-07-13T16:14:15.963000
2017-10-17T10:56:00
2017-10-17T10:56:00
84,760,217
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kwetter.JMS; import com.kwetter.model.Hashtag; import com.kwetter.model.Tweet; import org.apache.activemq.ActiveMQConnectionFactory; import javax.annotation.Resource; import javax.enterprise.event.Observes; import javax.jms.*; import javax.json.JsonObject; import javax.json.spi.JsonProvider; import java.util.List; /** * Created by hein on 5/26/17. */ public class TweetMessagePublisher { public TweetMessagePublisher() { } public void sendTweet(@Observes Tweet tweet) { Connection connection = null; try { ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic("tweetTopic"); MessageProducer producer = session.createProducer(topic); List<Hashtag> hashtags = tweet.getHashtags(); for (Hashtag hashtag: hashtags) { if (hashtag.getTag().equalsIgnoreCase("sports")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "sports"); producer.send(message); } if (hashtag.getTag().equalsIgnoreCase("politics")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "politics"); producer.send(message); } if (hashtag.getTag().equalsIgnoreCase("computers")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "computers"); producer.send(message); } if (hashtag.getTag().equalsIgnoreCase("games")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "games"); producer.send(message); } if (hashtag.getTag() != null) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", hashtag.getTag()); System.out.println(message.getStringProperty("typeMessage")); System.out.println(message); producer.send(message); } } } catch (JMSException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } private String tweetToJson(Tweet tweet) { JsonProvider provider = JsonProvider.provider(); JsonObject addMessage = provider.createObjectBuilder() .add("id", tweet.getId()) .add("tweeter", tweet.getTweeter().getUsername()) .add("message", tweet.getDescription()) .add("createdOn", tweet.getCreatedAt().toString()) .build(); return addMessage.toString(); } }
UTF-8
Java
3,410
java
TweetMessagePublisher.java
Java
[ { "context": "rovider;\nimport java.util.List;\n\n/**\n * Created by hein on 5/26/17.\n */\npublic class TweetMessagePublishe", "end": 353, "score": 0.9994488954544067, "start": 349, "tag": "USERNAME", "value": "hein" } ]
null
[]
package com.kwetter.JMS; import com.kwetter.model.Hashtag; import com.kwetter.model.Tweet; import org.apache.activemq.ActiveMQConnectionFactory; import javax.annotation.Resource; import javax.enterprise.event.Observes; import javax.jms.*; import javax.json.JsonObject; import javax.json.spi.JsonProvider; import java.util.List; /** * Created by hein on 5/26/17. */ public class TweetMessagePublisher { public TweetMessagePublisher() { } public void sendTweet(@Observes Tweet tweet) { Connection connection = null; try { ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic("tweetTopic"); MessageProducer producer = session.createProducer(topic); List<Hashtag> hashtags = tweet.getHashtags(); for (Hashtag hashtag: hashtags) { if (hashtag.getTag().equalsIgnoreCase("sports")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "sports"); producer.send(message); } if (hashtag.getTag().equalsIgnoreCase("politics")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "politics"); producer.send(message); } if (hashtag.getTag().equalsIgnoreCase("computers")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "computers"); producer.send(message); } if (hashtag.getTag().equalsIgnoreCase("games")) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", "games"); producer.send(message); } if (hashtag.getTag() != null) { TextMessage message = session.createTextMessage(tweetToJson(tweet)); message.setStringProperty("typeMessage", hashtag.getTag()); System.out.println(message.getStringProperty("typeMessage")); System.out.println(message); producer.send(message); } } } catch (JMSException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } private String tweetToJson(Tweet tweet) { JsonProvider provider = JsonProvider.provider(); JsonObject addMessage = provider.createObjectBuilder() .add("id", tweet.getId()) .add("tweeter", tweet.getTweeter().getUsername()) .add("message", tweet.getDescription()) .add("createdOn", tweet.getCreatedAt().toString()) .build(); return addMessage.toString(); } }
3,410
0.571847
0.568915
83
40.084339
26.43346
95
false
false
0
0
0
0
0
0
0.60241
false
false
5
9e385d55be1c8d64baea232f48b6eebfd4992221
5,171,140,689,257
3cd4ffe8c4cb05018878c5299c6ef8829a2ff1b1
/src/Coffe.java
f8fa5dbb7f2e26f959a1bd65febcdca0ffe2d820
[]
no_license
sahanahmadjit/DesignPattren
https://github.com/sahanahmadjit/DesignPattren
14b563803dee4126a667bbbabbc86d94dedfa0f6
68efe1936d856ef60e9ab1fcb3a7b483a3041e1d
refs/heads/master
2020-12-31T07:55:36.165000
2015-05-29T20:15:38
2015-05-29T20:15:38
36,396,050
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Created by Administrator on 5/30/2015. */ public class Coffe extends TemplatePattern{ @Override void pour() { System.out.println("Pour Coffie into Water"); } @Override void addEditionalCommodities() { System.out.println("Add Extrea Commodities"); } }
UTF-8
Java
303
java
Coffe.java
Java
[ { "context": "/**\n * Created by Administrator on 5/30/2015.\n */\npublic class Coffe extends Te", "end": 31, "score": 0.6621725559234619, "start": 18, "tag": "NAME", "value": "Administrator" } ]
null
[]
/** * Created by Administrator on 5/30/2015. */ public class Coffe extends TemplatePattern{ @Override void pour() { System.out.println("Pour Coffie into Water"); } @Override void addEditionalCommodities() { System.out.println("Add Extrea Commodities"); } }
303
0.630363
0.607261
15
19.200001
19.640774
53
false
false
0
0
0
0
0
0
0.133333
false
false
5
1d2d6e52773952acd3d75b4b3b9ba3599d407a39
15,350,213,158,065
b43551fa90461726083354025009c8000d4edaf6
/src/main/java/com/zl/wxgzh/httpsManage/CertificateManage.java
aa0708715c83ac319ca642c01f8370addd2c80c0
[]
no_license
zhang-love/wxgzh
https://github.com/zhang-love/wxgzh
23587c8e712857328b6582e57df3703c7518cac2
38e36268eaaabaf8917b00b867b3df71497a790f
refs/heads/master
2022-06-21T21:08:41.654000
2019-09-03T03:09:42
2019-09-03T03:09:42
200,953,669
0
0
null
false
2022-06-17T02:21:36
2019-08-07T02:04:03
2019-09-03T03:10:12
2022-06-17T02:21:33
86
0
0
1
Java
false
false
package com.zl.wxgzh.httpsManage; import org.springframework.web.bind.annotation.RequestMapping; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * https请求需要一个证书信任管理器 */ @RequestMapping public class CertificateManage implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
UTF-8
Java
772
java
CertificateManage.java
Java
[]
null
[]
package com.zl.wxgzh.httpsManage; import org.springframework.web.bind.annotation.RequestMapping; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * https请求需要一个证书信任管理器 */ @RequestMapping public class CertificateManage implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
772
0.741287
0.703753
29
23.724138
30.591745
110
false
false
0
0
0
0
0
0
0.275862
false
false
5
18927b5be455b88e7901c5b40637e8579c5c9e16
32,006,096,323,680
728ca881966d7b7881ac4458d79a4693177dad71
/app/src/main/java/id/edutech/baso/mapsproject/TrendingFragment.java
043fefb008465d09cb9d7fa7788999a82cc6c654
[]
no_license
ahmadmuflih/Hispot
https://github.com/ahmadmuflih/Hispot
14926326493322806b8b85f65a5efc2bf9de6f8d
96ff67b44b7929d402f787d4adfe864690f7db6a
refs/heads/master
2021-01-19T20:30:18.636000
2017-04-17T13:51:58
2017-04-17T13:51:58
88,512,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package id.edutech.baso.mapsproject; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import id.edutech.baso.mapsproject.R; import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener; import com.google.vr.sdk.widgets.pano.VrPanoramaView; import java.util.ArrayList; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmModel; import io.realm.RealmResults; import models.APIService; import models.Location; import models.Post; import models.PostResults; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Baso on 10/8/2016. */ public class TrendingFragment extends Fragment{ View view; ImageView imageVR, imageProfil; ProgressBar progressVR; private ImageAdapter imageAdapter; TextView txtNama; String locationVR; int locationID; // private static final String TAG = SimpleVrPanoramaActivity.class.getSimpleName(); private VrPanoramaView panoWidgetView; public boolean loadImageSuccessful; private Uri fileUri; private VrPanoramaView.Options panoOptions = new VrPanoramaView.Options(); private ImageLoaderTask backgroundImageLoaderTask; public TrendingFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initTrending(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_trending, container, false); imageProfil=(ImageView) view.findViewById(R.id.imageProfil); //imageVR=(ImageView) view.findViewById(R.id.vr_image); txtNama = (TextView)view.findViewById(R.id.location_name); progressVR=(ProgressBar)view.findViewById(R.id.progress_vr); panoWidgetView = (VrPanoramaView) view.findViewById(R.id.pano_view); panoWidgetView.setEventListener(new ActivityEventListener()); // Initial launch of the app or an Activity recreation due to rotation. return view; } public void initTrending(){ final Realm realm = Realm.getDefaultInstance(); String api_key = Preferences.getStringPreferences("api_key",getActivity()); /*---- Offline Mode */ RealmResults<Post> capture = realm.where(Post.class).equalTo("statusTrending","1").findAll(); /* RealmList<Post> results = new RealmList<>(); results.addAll(capture.subList(0, capture.size())); */ final ArrayList<Post> posts = new ArrayList<>(capture); Log.d("POST", "read : "+posts.size()); imageAdapter = new ImageAdapter(getActivity().getApplicationContext(),posts,1); imageAdapter.setOnPostSelectedListener(new ImageAdapter.OnPostSelectedListener() { @Override public void onSelected(Post post) { Intent intent = new Intent(getActivity(), PhotoActivity.class); intent.putExtra("post_id", post.getIdPost()); intent.putExtra("url_gambar", post.getUrlGambar()); intent.putExtra("waktu",post.getWaktu()); intent.putExtra("review",post.getReview()); intent.putExtra("location_id",post.getLocationID()); intent.putExtra("location_name", post.getLocationName()); intent.putExtra("id_user",post.getIdUser()); intent.putExtra("nama_user",post.getNamaUser()); intent.putExtra("rating", post.getRating()); intent.putExtra("jumlahLike",post.getJumlahLike()); intent.putExtra("foto_user",post.getFoto_user()); startActivity(intent); } }); final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3)); recyclerView.setAdapter(imageAdapter); recyclerView.setFocusable(false); // Call<PostResults> postResultsCall = APIService.service.getTrending("","",api_key); postResultsCall.enqueue(new Callback<PostResults>() { @Override public void onResponse(Call<PostResults> call, Response<PostResults> response) { if(response.isSuccessful()){ /* Update Status Trending */ realm.beginTransaction(); for(Post post: posts){ post.setStatusTrending(""); realm.copyToRealmOrUpdate(post); } realm.commitTransaction(); // ArrayList<Post>newPosts = response.body().getPosts(); for(Post post : newPosts){ post.setStatusTrending("1"); } realm.beginTransaction(); realm.copyToRealmOrUpdate(newPosts); realm.commitTransaction(); RealmResults<Post> results = realm.where(Post.class).findAll(); Log.d("Post", "Saved to realm. size : "+results.size()); Location location = response.body().getLocation(); locationVR = location.getVr(); locationID = location.getLocationId(); Preferences.setIntPreferences("vrtrendingid",locationID,getActivity()); Preferences.setStringPreferences("vrtrendingurl",locationVR,getActivity()); handleIntent(getActivity().getIntent()); txtNama.setText(location.getLocationName()); imageAdapter.setPosts(newPosts); recyclerView.setAdapter(imageAdapter); } else{ Toast.makeText(getActivity(), "Please check your internet connection!", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<PostResults> call, Throwable t) { //Toast.makeText(getActivity(), "Oops!", Toast.LENGTH_SHORT).show(); locationVR = Preferences.getStringPreferences("vrtrendingurl",getActivity()); locationID = Preferences.getIntPreferences("vrtrendingid",getActivity()); handleIntent(getActivity().getIntent()); } }); } protected void onNewIntent(Intent intent) { Log.i(TAG, this.hashCode() + ".onNewIntent()"); // Save the intent. This allows the getIntent() call in onCreate() to use this new Intent during // future invocations. getActivity().setIntent(intent); // Load the new image. handleIntent(intent); } private void handleIntent(Intent intent) { // Determine if the Intent contains a file to load. if (Intent.ACTION_VIEW.equals(intent.getAction())) { Log.i(TAG, "ACTION_VIEW Intent recieved"); fileUri = intent.getData(); if (fileUri == null) { Log.w(TAG, "No data uri specified. Use \"-d /path/filename\"."); } else { Log.i(TAG, "Using file " + fileUri.toString()); } panoOptions.inputType = intent.getIntExtra("inputType", VrPanoramaView.Options.TYPE_MONO); Log.i(TAG, "Options.inputType = " + panoOptions.inputType); } else { Log.i(TAG, "Intent is not ACTION_VIEW. Using default pano image."); fileUri = null; panoOptions.inputType = VrPanoramaView.Options.TYPE_MONO; } // Load the bitmap in a background thread to avoid blocking the UI thread. This operation can // take 100s of milliseconds. if (backgroundImageLoaderTask != null) { // Cancel any task from a previous intent sent to this activity. backgroundImageLoaderTask.cancel(true); } backgroundImageLoaderTask = new ImageLoaderTask(); backgroundImageLoaderTask.execute(Pair.create(fileUri, panoOptions)); } @Override public void onPause() { panoWidgetView.pauseRendering(); super.onPause(); } @Override public void onResume() { super.onResume(); panoWidgetView.resumeRendering(); } @Override public void onDestroy() { // Destroy the widget and free memory. panoWidgetView.shutdown(); // The background task has a 5 second timeout so it can potentially stay alive for 5 seconds // after the activity is destroyed unless it is explicitly cancelled. if (backgroundImageLoaderTask != null) { backgroundImageLoaderTask.cancel(true); } super.onDestroy(); } class ImageLoaderTask extends AsyncTask<Pair<Uri, VrPanoramaView.Options>, Void, Boolean> { /** * Reads the bitmap from disk in the background and waits until it's loaded by pano widget. */ @Override protected Boolean doInBackground(Pair<Uri, VrPanoramaView.Options>... fileInformation) { final VrPanoramaView.Options panoOptions = new VrPanoramaView.Options(); panoOptions.inputType = VrPanoramaView.Options.TYPE_STEREO_OVER_UNDER; // It's safe to use null VrPanoramaView.Options. final String simpanFoto ="vr"+locationID+".png"; Bitmap fotoS = ImageUtil.getImage(simpanFoto, getActivity()); if(fotoS==null) { ImageDownloader imageDownloader = new ImageDownloader(locationVR); imageDownloader.setDownloadImageListener(new ImageDownloader.DownloadImageListener() { @Override public void onFinish(Bitmap bitmap) { SaveBitmap saveBitmap = new SaveBitmap(bitmap, simpanFoto, getActivity()); saveBitmap.commit(); panoWidgetView.loadImageFromBitmap(bitmap, panoOptions); } @Override public void onError() { //Toast.makeText(getContext(), "Gagal membuka gambar!", Toast.LENGTH_SHORT).show(); } }); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) imageDownloader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else imageDownloader.execute(); } else{ panoWidgetView.loadImageFromBitmap(fotoS, panoOptions); } /* try { istr.close(); } catch (IOException e) { Log.e(TAG, "Could not close input stream: " + e); } */ return true; } } /** * Listen to the important events from widget. */ private class ActivityEventListener extends VrPanoramaEventListener { /** * Called by pano widget on the UI thread when it's done loading the image. */ @Override public void onLoadSuccess() { loadImageSuccessful = true; } /** * Called by pano widget on the UI thread on any asynchronous error. */ @Override public void onLoadError(String errorMessage) { loadImageSuccessful = false; Toast.makeText( getActivity(), "Error loading pano: " + errorMessage, Toast.LENGTH_LONG) .show(); Log.e(TAG, "Error loading pano: " + errorMessage); } } }
UTF-8
Java
12,473
java
TrendingFragment.java
Java
[]
null
[]
package id.edutech.baso.mapsproject; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import id.edutech.baso.mapsproject.R; import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener; import com.google.vr.sdk.widgets.pano.VrPanoramaView; import java.util.ArrayList; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmModel; import io.realm.RealmResults; import models.APIService; import models.Location; import models.Post; import models.PostResults; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Baso on 10/8/2016. */ public class TrendingFragment extends Fragment{ View view; ImageView imageVR, imageProfil; ProgressBar progressVR; private ImageAdapter imageAdapter; TextView txtNama; String locationVR; int locationID; // private static final String TAG = SimpleVrPanoramaActivity.class.getSimpleName(); private VrPanoramaView panoWidgetView; public boolean loadImageSuccessful; private Uri fileUri; private VrPanoramaView.Options panoOptions = new VrPanoramaView.Options(); private ImageLoaderTask backgroundImageLoaderTask; public TrendingFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initTrending(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_trending, container, false); imageProfil=(ImageView) view.findViewById(R.id.imageProfil); //imageVR=(ImageView) view.findViewById(R.id.vr_image); txtNama = (TextView)view.findViewById(R.id.location_name); progressVR=(ProgressBar)view.findViewById(R.id.progress_vr); panoWidgetView = (VrPanoramaView) view.findViewById(R.id.pano_view); panoWidgetView.setEventListener(new ActivityEventListener()); // Initial launch of the app or an Activity recreation due to rotation. return view; } public void initTrending(){ final Realm realm = Realm.getDefaultInstance(); String api_key = Preferences.getStringPreferences("api_key",getActivity()); /*---- Offline Mode */ RealmResults<Post> capture = realm.where(Post.class).equalTo("statusTrending","1").findAll(); /* RealmList<Post> results = new RealmList<>(); results.addAll(capture.subList(0, capture.size())); */ final ArrayList<Post> posts = new ArrayList<>(capture); Log.d("POST", "read : "+posts.size()); imageAdapter = new ImageAdapter(getActivity().getApplicationContext(),posts,1); imageAdapter.setOnPostSelectedListener(new ImageAdapter.OnPostSelectedListener() { @Override public void onSelected(Post post) { Intent intent = new Intent(getActivity(), PhotoActivity.class); intent.putExtra("post_id", post.getIdPost()); intent.putExtra("url_gambar", post.getUrlGambar()); intent.putExtra("waktu",post.getWaktu()); intent.putExtra("review",post.getReview()); intent.putExtra("location_id",post.getLocationID()); intent.putExtra("location_name", post.getLocationName()); intent.putExtra("id_user",post.getIdUser()); intent.putExtra("nama_user",post.getNamaUser()); intent.putExtra("rating", post.getRating()); intent.putExtra("jumlahLike",post.getJumlahLike()); intent.putExtra("foto_user",post.getFoto_user()); startActivity(intent); } }); final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3)); recyclerView.setAdapter(imageAdapter); recyclerView.setFocusable(false); // Call<PostResults> postResultsCall = APIService.service.getTrending("","",api_key); postResultsCall.enqueue(new Callback<PostResults>() { @Override public void onResponse(Call<PostResults> call, Response<PostResults> response) { if(response.isSuccessful()){ /* Update Status Trending */ realm.beginTransaction(); for(Post post: posts){ post.setStatusTrending(""); realm.copyToRealmOrUpdate(post); } realm.commitTransaction(); // ArrayList<Post>newPosts = response.body().getPosts(); for(Post post : newPosts){ post.setStatusTrending("1"); } realm.beginTransaction(); realm.copyToRealmOrUpdate(newPosts); realm.commitTransaction(); RealmResults<Post> results = realm.where(Post.class).findAll(); Log.d("Post", "Saved to realm. size : "+results.size()); Location location = response.body().getLocation(); locationVR = location.getVr(); locationID = location.getLocationId(); Preferences.setIntPreferences("vrtrendingid",locationID,getActivity()); Preferences.setStringPreferences("vrtrendingurl",locationVR,getActivity()); handleIntent(getActivity().getIntent()); txtNama.setText(location.getLocationName()); imageAdapter.setPosts(newPosts); recyclerView.setAdapter(imageAdapter); } else{ Toast.makeText(getActivity(), "Please check your internet connection!", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<PostResults> call, Throwable t) { //Toast.makeText(getActivity(), "Oops!", Toast.LENGTH_SHORT).show(); locationVR = Preferences.getStringPreferences("vrtrendingurl",getActivity()); locationID = Preferences.getIntPreferences("vrtrendingid",getActivity()); handleIntent(getActivity().getIntent()); } }); } protected void onNewIntent(Intent intent) { Log.i(TAG, this.hashCode() + ".onNewIntent()"); // Save the intent. This allows the getIntent() call in onCreate() to use this new Intent during // future invocations. getActivity().setIntent(intent); // Load the new image. handleIntent(intent); } private void handleIntent(Intent intent) { // Determine if the Intent contains a file to load. if (Intent.ACTION_VIEW.equals(intent.getAction())) { Log.i(TAG, "ACTION_VIEW Intent recieved"); fileUri = intent.getData(); if (fileUri == null) { Log.w(TAG, "No data uri specified. Use \"-d /path/filename\"."); } else { Log.i(TAG, "Using file " + fileUri.toString()); } panoOptions.inputType = intent.getIntExtra("inputType", VrPanoramaView.Options.TYPE_MONO); Log.i(TAG, "Options.inputType = " + panoOptions.inputType); } else { Log.i(TAG, "Intent is not ACTION_VIEW. Using default pano image."); fileUri = null; panoOptions.inputType = VrPanoramaView.Options.TYPE_MONO; } // Load the bitmap in a background thread to avoid blocking the UI thread. This operation can // take 100s of milliseconds. if (backgroundImageLoaderTask != null) { // Cancel any task from a previous intent sent to this activity. backgroundImageLoaderTask.cancel(true); } backgroundImageLoaderTask = new ImageLoaderTask(); backgroundImageLoaderTask.execute(Pair.create(fileUri, panoOptions)); } @Override public void onPause() { panoWidgetView.pauseRendering(); super.onPause(); } @Override public void onResume() { super.onResume(); panoWidgetView.resumeRendering(); } @Override public void onDestroy() { // Destroy the widget and free memory. panoWidgetView.shutdown(); // The background task has a 5 second timeout so it can potentially stay alive for 5 seconds // after the activity is destroyed unless it is explicitly cancelled. if (backgroundImageLoaderTask != null) { backgroundImageLoaderTask.cancel(true); } super.onDestroy(); } class ImageLoaderTask extends AsyncTask<Pair<Uri, VrPanoramaView.Options>, Void, Boolean> { /** * Reads the bitmap from disk in the background and waits until it's loaded by pano widget. */ @Override protected Boolean doInBackground(Pair<Uri, VrPanoramaView.Options>... fileInformation) { final VrPanoramaView.Options panoOptions = new VrPanoramaView.Options(); panoOptions.inputType = VrPanoramaView.Options.TYPE_STEREO_OVER_UNDER; // It's safe to use null VrPanoramaView.Options. final String simpanFoto ="vr"+locationID+".png"; Bitmap fotoS = ImageUtil.getImage(simpanFoto, getActivity()); if(fotoS==null) { ImageDownloader imageDownloader = new ImageDownloader(locationVR); imageDownloader.setDownloadImageListener(new ImageDownloader.DownloadImageListener() { @Override public void onFinish(Bitmap bitmap) { SaveBitmap saveBitmap = new SaveBitmap(bitmap, simpanFoto, getActivity()); saveBitmap.commit(); panoWidgetView.loadImageFromBitmap(bitmap, panoOptions); } @Override public void onError() { //Toast.makeText(getContext(), "Gagal membuka gambar!", Toast.LENGTH_SHORT).show(); } }); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) imageDownloader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else imageDownloader.execute(); } else{ panoWidgetView.loadImageFromBitmap(fotoS, panoOptions); } /* try { istr.close(); } catch (IOException e) { Log.e(TAG, "Could not close input stream: " + e); } */ return true; } } /** * Listen to the important events from widget. */ private class ActivityEventListener extends VrPanoramaEventListener { /** * Called by pano widget on the UI thread when it's done loading the image. */ @Override public void onLoadSuccess() { loadImageSuccessful = true; } /** * Called by pano widget on the UI thread on any asynchronous error. */ @Override public void onLoadError(String errorMessage) { loadImageSuccessful = false; Toast.makeText( getActivity(), "Error loading pano: " + errorMessage, Toast.LENGTH_LONG) .show(); Log.e(TAG, "Error loading pano: " + errorMessage); } } }
12,473
0.609877
0.608033
333
36.456455
30.04994
132
false
false
0
0
0
0
0
0
0.654655
false
false
5
e8cfd35288b34b0c3f4eae13334c952253a83421
32,006,096,327,515
a12279aaa7fd828c6ed4895c3128347482245ee0
/src/main/java/com/emosist/pagessante/utils/PostgresOperation.java
da48dcf1df35aaae460fb48a3f89a6ba0b862f9d
[]
no_license
ProjetLicenceGCS/PagesSante_Referentiel
https://github.com/ProjetLicenceGCS/PagesSante_Referentiel
b06480cff44cc2ca46c85978a65981b39bdb0f89
09478db2155d39bb6b14abb6813b32a751dd274d
refs/heads/master
2020-04-21T18:04:28.276000
2014-02-18T19:52:44
2014-02-18T19:52:44
15,135,205
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.emosist.pagessante.utils; public class PostgresOperation { }
UTF-8
Java
80
java
PostgresOperation.java
Java
[]
null
[]
package com.emosist.pagessante.utils; public class PostgresOperation { }
80
0.75
0.75
5
14
16.816658
37
false
false
0
0
0
0
0
0
0.2
false
false
5
6517f241f5bc0278760304e7af9c528d4511e6f6
4,930,622,497,079
c81c2080c90a18aa7d7d71d0aedf15fa2808d0ab
/src/main/java/com/unionpay/unionpay_test/base/BaseController.java
0c4a783e966198570cc905cc397517b5c27837a6
[]
no_license
VingKing/unionpay_test
https://github.com/VingKing/unionpay_test
2c1f3eb31055fd7c17f3f45c19e69314893a9c6f
cf201c72399d902a1cc9610a5a4968687cf567c5
refs/heads/master
2018-07-10T17:16:15.981000
2018-07-06T02:16:40
2018-07-06T02:16:40
135,260,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.unionpay.unionpay_test.base; import java.util.HashMap; import java.util.Map; public abstract class BaseController { /** * closeCurrent自动判断 * * @param statusCode * 状态码 * @param tabid * 待刷新navid * @return */ public Map<String, Object> jsonReturn(int statusCode, String tabid) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("message", ""); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("message", "操作失败,请重试"); jsonObj.put("closeCurrent", false); } jsonObj.put("tabid", tabid); return jsonObj; } /** * * @param statusCode * 状态码 * @param closeCurrent * 是否关闭当前窗口 * @param msg * 提示信息 * @return */ public Map<String, Object> jsonReturn(int statusCode, boolean closeCurrent, String msg) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); } jsonObj.put("message", msg); jsonObj.put("closeCurrent", closeCurrent); return jsonObj; } /** * closeCurrent自动判断 * * @param statusCode * 状态码 * @param msg * 提示 * @param tabid * 待刷新navid * @return */ public Map<String, Object> jsonReturn(int statusCode, String msg, String tabid) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("closeCurrent", false); } jsonObj.put("message", msg); jsonObj.put("tabid", tabid); return jsonObj; } /** * * @param statusCode * 状态码 * @param msg * 提示 * @param closeCurrent * 是否关闭窗口 * @param tabid * 待刷新navid * @return */ public Map<String, Object> jsonReturn(int statusCode, String msg, boolean closeCurrent, String tabid) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); } else { jsonObj.put("statusCode", statusCode); } jsonObj.put("message", msg); jsonObj.put("tabid", tabid); jsonObj.put("closeCurrent", closeCurrent); return jsonObj; } /** * * @Description: B-JUI上传组件成功返回 * @author: huangShengJie * @param statusCode * @param msg * @param tabid * @return Map<String,Object> * @date 2018年1月4日 上午10:09:38 */ public Map<String, Object> jsonReturnBJUI(int statusCode, String message, String filename) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("closeCurrent", false); } jsonObj.put("message", message); jsonObj.put("filename", filename); return jsonObj; } /** * * @Description: B-JUI上传组件失败返回 * @author: huangShengJie * @param statusCode * @param msg * @param tabid * @return Map<String,Object> * @date 2018年1月4日 上午10:09:38 */ public Map<String, Object> jsonReturnBJUI(int statusCode, String message) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("closeCurrent", false); } jsonObj.put("message", message); return jsonObj; } }
UTF-8
Java
4,127
java
BaseController.java
Java
[ { "context": " * \r\n\t * @Description: B-JUI上传组件成功返回\r\n\t * @author: huangShengJie\r\n\t * @param statusCode\r\n\t * @param msg\r\n\t * @para", "end": 2724, "score": 0.9996405243873596, "start": 2711, "tag": "NAME", "value": "huangShengJie" }, { "context": " * \r\n\t * @Description: B-JUI上传组件失败返回\r\n\t * @author: huangShengJie\r\n\t * @param statusCode\r\n\t * @param msg\r\n\t * @para", "end": 3403, "score": 0.9998447299003601, "start": 3390, "tag": "NAME", "value": "huangShengJie" } ]
null
[]
package com.unionpay.unionpay_test.base; import java.util.HashMap; import java.util.Map; public abstract class BaseController { /** * closeCurrent自动判断 * * @param statusCode * 状态码 * @param tabid * 待刷新navid * @return */ public Map<String, Object> jsonReturn(int statusCode, String tabid) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("message", ""); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("message", "操作失败,请重试"); jsonObj.put("closeCurrent", false); } jsonObj.put("tabid", tabid); return jsonObj; } /** * * @param statusCode * 状态码 * @param closeCurrent * 是否关闭当前窗口 * @param msg * 提示信息 * @return */ public Map<String, Object> jsonReturn(int statusCode, boolean closeCurrent, String msg) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); } jsonObj.put("message", msg); jsonObj.put("closeCurrent", closeCurrent); return jsonObj; } /** * closeCurrent自动判断 * * @param statusCode * 状态码 * @param msg * 提示 * @param tabid * 待刷新navid * @return */ public Map<String, Object> jsonReturn(int statusCode, String msg, String tabid) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("closeCurrent", false); } jsonObj.put("message", msg); jsonObj.put("tabid", tabid); return jsonObj; } /** * * @param statusCode * 状态码 * @param msg * 提示 * @param closeCurrent * 是否关闭窗口 * @param tabid * 待刷新navid * @return */ public Map<String, Object> jsonReturn(int statusCode, String msg, boolean closeCurrent, String tabid) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); } else { jsonObj.put("statusCode", statusCode); } jsonObj.put("message", msg); jsonObj.put("tabid", tabid); jsonObj.put("closeCurrent", closeCurrent); return jsonObj; } /** * * @Description: B-JUI上传组件成功返回 * @author: huangShengJie * @param statusCode * @param msg * @param tabid * @return Map<String,Object> * @date 2018年1月4日 上午10:09:38 */ public Map<String, Object> jsonReturnBJUI(int statusCode, String message, String filename) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("closeCurrent", false); } jsonObj.put("message", message); jsonObj.put("filename", filename); return jsonObj; } /** * * @Description: B-JUI上传组件失败返回 * @author: huangShengJie * @param statusCode * @param msg * @param tabid * @return Map<String,Object> * @date 2018年1月4日 上午10:09:38 */ public Map<String, Object> jsonReturnBJUI(int statusCode, String message) { Map<String, Object> jsonObj = new HashMap<String, Object>(); if (statusCode == 200) { jsonObj.put("statusCode", 200); jsonObj.put("closeCurrent", true); } else if (statusCode == 300) { jsonObj.put("statusCode", 300); jsonObj.put("closeCurrent", false); } jsonObj.put("message", message); return jsonObj; } }
4,127
0.601971
0.57771
155
23.529032
19.68504
104
false
false
0
0
0
0
0
0
2.2
false
false
5
e1e31a828cdac7b3e0a84dfd9b0c655a16f39b69
11,338,713,722,655
950ad02850d365a4de859562a276cd5ce31d2ccb
/app/src/main/java/com/zakhulhaq/filmku/ui/tv/TvAdapter.java
70487bc0119af23284f138ad5088ac0efed25daf
[]
no_license
DafaZakhulhaq27/FilmKu
https://github.com/DafaZakhulhaq27/FilmKu
4d94c053c25c1dfbcd105acd53d9e6fe25367908
d4a38471cf47285515a86e91a745de3edea008d4
refs/heads/master
2020-07-30T14:33:36.280000
2019-10-04T04:32:34
2019-10-04T04:32:34
210,265,034
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zakhulhaq.filmku.ui.tv; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.zakhulhaq.filmku.DetailTv; import com.zakhulhaq.filmku.R; import java.util.ArrayList; public class TvAdapter extends RecyclerView.Adapter<TvAdapter.TvViewHolder> { private ArrayList<TvItem> mData = new ArrayList<>(); public void setData(ArrayList<TvItem> items) { mData.clear(); mData.addAll(items); notifyDataSetChanged(); } @NonNull @Override public TvAdapter.TvViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tv_item, parent, false); return new TvAdapter.TvViewHolder(mView); } @Override public void onBindViewHolder(@NonNull TvAdapter.TvViewHolder holder, int position) { holder.bind(mData.get(position)); } @Override public int getItemCount() { return mData.size(); } public class TvViewHolder extends RecyclerView.ViewHolder { TextView title, overview, tvrating, date; ImageView poster; RatingBar ratingbar; public TvViewHolder(@NonNull View itemView) { super(itemView); title = itemView.findViewById(R.id.tv_title); overview = itemView.findViewById(R.id.tv_overview); date = itemView.findViewById(R.id.tv_year); poster = itemView.findViewById(R.id.movie_poster); } public void bind(final TvItem tvItem) { title.setText(tvItem.getName()); overview.setText(tvItem.getOverview()); date.setText(tvItem.getFirst_air_date()); Glide.with(itemView.getContext()) .load("https://image.tmdb.org/t/p/w185/" + tvItem.getPoster_path()) .apply(new RequestOptions().override(600, 200)) .into(poster); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent DetailTvc = new Intent(v.getContext(), DetailTv.class); DetailTvc.putExtra(DetailTv.EXTRA_TV, tvItem); v.getContext().startActivity(DetailTvc); } }); } } }
UTF-8
Java
2,673
java
TvAdapter.java
Java
[]
null
[]
package com.zakhulhaq.filmku.ui.tv; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.zakhulhaq.filmku.DetailTv; import com.zakhulhaq.filmku.R; import java.util.ArrayList; public class TvAdapter extends RecyclerView.Adapter<TvAdapter.TvViewHolder> { private ArrayList<TvItem> mData = new ArrayList<>(); public void setData(ArrayList<TvItem> items) { mData.clear(); mData.addAll(items); notifyDataSetChanged(); } @NonNull @Override public TvAdapter.TvViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tv_item, parent, false); return new TvAdapter.TvViewHolder(mView); } @Override public void onBindViewHolder(@NonNull TvAdapter.TvViewHolder holder, int position) { holder.bind(mData.get(position)); } @Override public int getItemCount() { return mData.size(); } public class TvViewHolder extends RecyclerView.ViewHolder { TextView title, overview, tvrating, date; ImageView poster; RatingBar ratingbar; public TvViewHolder(@NonNull View itemView) { super(itemView); title = itemView.findViewById(R.id.tv_title); overview = itemView.findViewById(R.id.tv_overview); date = itemView.findViewById(R.id.tv_year); poster = itemView.findViewById(R.id.movie_poster); } public void bind(final TvItem tvItem) { title.setText(tvItem.getName()); overview.setText(tvItem.getOverview()); date.setText(tvItem.getFirst_air_date()); Glide.with(itemView.getContext()) .load("https://image.tmdb.org/t/p/w185/" + tvItem.getPoster_path()) .apply(new RequestOptions().override(600, 200)) .into(poster); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent DetailTvc = new Intent(v.getContext(), DetailTv.class); DetailTvc.putExtra(DetailTv.EXTRA_TV, tvItem); v.getContext().startActivity(DetailTvc); } }); } } }
2,673
0.648709
0.645342
81
32
26.21092
103
false
false
0
0
0
0
0
0
0.604938
false
false
5
ac383142909f7f5cc64bc4ff62cfc4f5eb6658f1
22,213,570,890,577
0095fefdd7af95192834254ca6feb766747fba0a
/iplanner-api/src/main/java/ibox/iplanner/api/lambda/GetEntityDefinitionHandlerWrapper.java
01f2bb114c31b82cce4af752b56987c4a0b9df50
[]
no_license
coder-weiru/ibox
https://github.com/coder-weiru/ibox
0f31aa73738657cff6937ab7fea22d7967298b33
7c40bcedcca5c58a6416e79e9a220c4e8e4029e2
refs/heads/master
2022-12-22T00:35:48.415000
2019-11-15T16:26:13
2019-11-15T16:26:13
187,427,299
0
0
null
false
2022-12-12T21:41:51
2019-05-19T02:57:00
2019-11-15T16:26:19
2022-12-12T21:41:51
4,784
0
0
10
Java
false
false
package ibox.iplanner.api.lambda; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import ibox.iplanner.api.config.DaggerIPlannerComponent; import ibox.iplanner.api.config.IPlannerComponent; import ibox.iplanner.api.lambda.handler.GetEntityDefinitionHandler; public class GetEntityDefinitionHandlerWrapper implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { private GetEntityDefinitionHandler getEntityDefinitionHandler = new GetEntityDefinitionHandler(); public GetEntityDefinitionHandlerWrapper() { IPlannerComponent iPlannerComponent = DaggerIPlannerComponent.builder().build(); iPlannerComponent.inject(getEntityDefinitionHandler); } @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent requestEvent, Context context) { return getEntityDefinitionHandler.handleRequest(requestEvent, context); } }
UTF-8
Java
1,152
java
GetEntityDefinitionHandlerWrapper.java
Java
[]
null
[]
package ibox.iplanner.api.lambda; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import ibox.iplanner.api.config.DaggerIPlannerComponent; import ibox.iplanner.api.config.IPlannerComponent; import ibox.iplanner.api.lambda.handler.GetEntityDefinitionHandler; public class GetEntityDefinitionHandlerWrapper implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { private GetEntityDefinitionHandler getEntityDefinitionHandler = new GetEntityDefinitionHandler(); public GetEntityDefinitionHandlerWrapper() { IPlannerComponent iPlannerComponent = DaggerIPlannerComponent.builder().build(); iPlannerComponent.inject(getEntityDefinitionHandler); } @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent requestEvent, Context context) { return getEntityDefinitionHandler.handleRequest(requestEvent, context); } }
1,152
0.838542
0.838542
24
47
40.147644
133
false
false
0
0
0
0
0
0
0.625
false
false
5
0d6e80b4ffc4fce8304e1a10c66b92f27b0dcd4a
22,213,570,887,623
ec4de1e06c8ef59e87f87b07932e1e9f28d37aac
/src/application/VerticalProgressBar.java
19654473e37de8d5ec589016b26b27e91a0d51bf
[]
no_license
daixiaoxiao/Java_basketballShoot-
https://github.com/daixiaoxiao/Java_basketballShoot-
571fb8da90f7d804a277411a1e3e1071bf7c4436
fb5ddbac4d71ebde322e44837363089c684c5f50
refs/heads/master
2021-01-19T13:49:41.588000
2017-02-18T23:25:03
2017-02-18T23:25:03
82,421,291
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package application; import javafx.scene.control.ProgressBar; import javafx.scene.layout.StackPane; import javafx.scene.transform.Rotate; import javafx.scene.transform.Translate; public class VerticalProgressBar { private ProgressBar progressBar = new ProgressBar(); public VerticalProgressBar(double width, double height) { progressBar.setMinSize(StackPane.USE_PREF_SIZE, StackPane.USE_PREF_SIZE); progressBar.setPrefSize(height, width); progressBar.setMaxSize(StackPane.USE_PREF_SIZE, StackPane.USE_PREF_SIZE); progressBar.getTransforms().setAll( new Translate(0, height), new Rotate(-90, 0, 0) ); } public ProgressBar getProgressBar() { return progressBar; } }
UTF-8
Java
771
java
VerticalProgressBar.java
Java
[]
null
[]
package application; import javafx.scene.control.ProgressBar; import javafx.scene.layout.StackPane; import javafx.scene.transform.Rotate; import javafx.scene.transform.Translate; public class VerticalProgressBar { private ProgressBar progressBar = new ProgressBar(); public VerticalProgressBar(double width, double height) { progressBar.setMinSize(StackPane.USE_PREF_SIZE, StackPane.USE_PREF_SIZE); progressBar.setPrefSize(height, width); progressBar.setMaxSize(StackPane.USE_PREF_SIZE, StackPane.USE_PREF_SIZE); progressBar.getTransforms().setAll( new Translate(0, height), new Rotate(-90, 0, 0) ); } public ProgressBar getProgressBar() { return progressBar; } }
771
0.697795
0.69131
24
31.125
24.355547
81
false
false
0
0
0
0
0
0
0.791667
false
false
5
3a062548556b37789428e4da71e584095bb3f3e6
5,351,529,275,487
27ffe207a31b91ea15a00792ec7e36a2386882fe
/CCChargedMinersLauncher/src/com/chargedminers/launcher/ServerJoinInfo.java
c86769fe9b49dc3001a072abdf90881e95930e7b
[ "BSD-3-Clause" ]
permissive
Charged/CCChargedMinersLauncher
https://github.com/Charged/CCChargedMinersLauncher
2ed6587b8e3eaa4c1f6dd55c33fa082597ddbc51
90bb249a789ebb3ad5de199885635b86dfab63cf
refs/heads/master
2020-05-15T14:34:22.998000
2014-07-16T16:34:30
2014-07-16T16:34:30
17,154,210
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chargedminers.launcher; import java.net.InetAddress; public class ServerJoinInfo { public String playerName; public String hash; public InetAddress address; public int port; public String pass; public boolean override; public boolean signInNeeded; public boolean passNeeded; }
UTF-8
Java
324
java
ServerJoinInfo.java
Java
[]
null
[]
package com.chargedminers.launcher; import java.net.InetAddress; public class ServerJoinInfo { public String playerName; public String hash; public InetAddress address; public int port; public String pass; public boolean override; public boolean signInNeeded; public boolean passNeeded; }
324
0.740741
0.740741
15
20.6
12.789579
35
false
false
0
0
0
0
0
0
0.666667
false
false
5
b30035ef52796b6fdad429d977aa338616abc77a
6,150,393,171,613
3289d6a8c3f5f57e34aab1edd0fd6a9c16216610
/oops/lingkaran/Lingkaran.java
cf4c8a92215e4e07ea8ed67e30770ee7bb7e4549
[ "MIT" ]
permissive
aammiit2002/Hacktoberfest2021-5
https://github.com/aammiit2002/Hacktoberfest2021-5
3a2c334132129466cfa060fadaeefa7759e4ce50
6702bc97cacc2ed3219436db74eabc2a62bb627c
refs/heads/main
2023-09-03T15:03:44.859000
2021-10-31T17:47:44
2021-10-31T17:47:44
423,219,418
0
0
MIT
true
2021-10-31T17:46:54
2021-10-31T17:46:54
2021-10-31T17:46:53
2021-10-31T17:05:41
380
0
0
0
null
false
false
package Minggu2_Objek; public class Lingkaran { double PHI = 3.14; double r; double hitungLuas(){ double luas = PHI * r *r; return luas; } double hitungKeliling(){ double keliling = 2*PHI*r; return keliling; } }
UTF-8
Java
274
java
Lingkaran.java
Java
[]
null
[]
package Minggu2_Objek; public class Lingkaran { double PHI = 3.14; double r; double hitungLuas(){ double luas = PHI * r *r; return luas; } double hitungKeliling(){ double keliling = 2*PHI*r; return keliling; } }
274
0.554745
0.536496
19
13.421053
12.402529
34
false
false
0
0
0
0
0
0
0.368421
false
false
5
d99d220996c3b7fa78e06a8597f886b5dfbc938e
10,436,770,537,182
4a0f932f1f1b6e47662b8993377cce1d122cd7b8
/src/main/java/com/cn/template/repository/experiment/InspectionRecordDao.java
cc40f507147d02a34140f742da1cea618501c48c
[]
no_license
rong1005/template
https://github.com/rong1005/template
244934af4f6848d42f2aaf7c1d7f6d278f404684
66ccedbcdf074a93186c2d38ae7838c026b57de0
refs/heads/master
2016-09-06T21:24:23.123000
2014-09-22T13:02:39
2014-09-22T13:02:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cn.template.repository.experiment; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import com.cn.template.entity.experiment.InspectionRecord; /** * 巡检记录的数据访问接口. * @author Libra * */ public interface InspectionRecordDao extends PagingAndSortingRepository<InspectionRecord, Long>, JpaSpecificationExecutor<InspectionRecord> { }
UTF-8
Java
464
java
InspectionRecordDao.java
Java
[ { "context": ".InspectionRecord;\n\n/**\n * 巡检记录的数据访问接口.\n * @author Libra\n *\n */\npublic interface InspectionRecordDao exten", "end": 289, "score": 0.8014289140701294, "start": 284, "tag": "NAME", "value": "Libra" } ]
null
[]
package com.cn.template.repository.experiment; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import com.cn.template.entity.experiment.InspectionRecord; /** * 巡检记录的数据访问接口. * @author Libra * */ public interface InspectionRecordDao extends PagingAndSortingRepository<InspectionRecord, Long>, JpaSpecificationExecutor<InspectionRecord> { }
464
0.834842
0.834842
15
28.466667
39.82774
141
false
false
0
0
0
0
0
0
0.4
false
false
5
5f1f5f4f58f4e114186f257d6d7715f897ef2491
11,484,742,565,968
94117ab57c41757ce0986be484162bc6be92720e
/day09/src/day09/PersonStudentMain.java
cdd03f2fee5fa7e7978001824f3d6fb2db3436d1
[]
no_license
gkdyddl33/java1_workspace
https://github.com/gkdyddl33/java1_workspace
33ca67000849f27ebf865b99f49721d59d183247
32059d079029e6dcd00266eb64fa6709c1af4ba8
refs/heads/master
2023-01-05T08:09:41.839000
2020-11-02T13:45:53
2020-11-02T13:45:53
308,164,254
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day09; public class PersonStudentMain { public static void main(String[] args) { Student student1 = new Student("홍길동",20,175,70,"20170101",1,4.5); Student student2 = new Student("이순신",30,170,80,"20090505",4,3.0); student1.show(); student2.show(); Teacher teacher1 = new Teacher("John Doe",25,180,120,"ABC201",3000000,5); teacher1.show(); } }
UHC
Java
387
java
PersonStudentMain.java
Java
[ { "context": "ng[] args) {\n\t\t\n\t\tStudent student1 = new Student(\"홍길동\",20,175,70,\"20170101\",1,4.5);\n\t\tStudent student2 ", "end": 131, "score": 0.8762639760971069, "start": 128, "tag": "NAME", "value": "홍길동" }, { "context": "170101\",1,4.5);\n\t\tStudent student2 = new Student(\"이순신\",30,170,80,\"20090505\",4,3.0);\n\t\t\n\t\tstudent1.show(", "end": 199, "score": 0.9869266748428345, "start": 196, "tag": "NAME", "value": "이순신" }, { "context": "ent2.show();\n\t\t\n\t\tTeacher teacher1 = new Teacher(\"John Doe\",25,180,120,\"ABC201\",3000000,5);\n\t\tteacher1.show(", "end": 316, "score": 0.9998570680618286, "start": 308, "tag": "NAME", "value": "John Doe" } ]
null
[]
package day09; public class PersonStudentMain { public static void main(String[] args) { Student student1 = new Student("홍길동",20,175,70,"20170101",1,4.5); Student student2 = new Student("이순신",30,170,80,"20090505",4,3.0); student1.show(); student2.show(); Teacher teacher1 = new Teacher("<NAME>",25,180,120,"ABC201",3000000,5); teacher1.show(); } }
385
0.672
0.504
16
22.4375
25.541555
75
false
false
0
0
0
0
0
0
2.8125
false
false
5
57e128b2e0c6508afd011ec85ce9993926b87b97
10,264,971,872,763
79e2c4bbae6774b3b83769b792b0a13851f75b08
/eco-app/src/test/java/easycare/alc/cuke/pageObjects/HstPageUrls.java
07e12daf999386e97c4a84dc211bac63ff4f78ca
[]
no_license
mikessun/reports-repo
https://github.com/mikessun/reports-repo
782916378ec3753c7c42db8a85c2313e588d41e0
b2f44c22547ef777402716393debb58039b39b5c
refs/heads/master
2019-01-19T20:11:40.844000
2016-04-15T23:08:32
2016-04-15T23:08:32
56,277,427
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package easycare.alc.cuke.pageObjects; import static easycare.cuke.pageObjects.PageUrls.EASYCARE_NUMBER; import static easycare.cuke.pageObjects.PageUrls.OPTIONAL_QUERY_STRING; public final class HstPageUrls { private HstPageUrls() { } /** matches one or more digits */ public static final String DIGITS = "\\d+"; public static final String HST_PATIENT_NOTES_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/notes" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_NEW_NOTE_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/notes/new/?(\\?.+)?"; public static final String HST_PATIENT_LIST_URL = "/hst/patients" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_EVENT_LOGS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/eventlogs" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_ACCESS_LOGS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/accesslogs" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_EDIT_CONTACT_INFO_URL = "/hst/patients/" + EASYCARE_NUMBER + "/contactdetails/edit"; public static final String HST_PATIENT_EDIT_BASIC_INFO_URL = "/hst/patients/" + EASYCARE_NUMBER + "/basicdetails/edit/?$"; public static final String HST_PATIENT_DIAGNOSTIC_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/diagnostic/?$"; public static final String HST_PATIENT_SIGNALS_VIEW_ERROR_URL = "/hst/patients/" + EASYCARE_NUMBER + "/error"; public static final String HST_PATIENT_DETAILS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/basicdetails/?$"; public static final String HST_PATIENT_CONTACT_DETAILS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/contactdetails/?$"; public static final String HST_PATIENT_ADDITIONAL_DETAILS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/additionaldetails/?$"; public static final String HST_PATIENT_ADDITIONAL_DETAILS_EDIT_URL = "/hst/patients/" + EASYCARE_NUMBER + "/additionaldetails/edit/?$"; public static final String HST_DEVICE_DOWNLOAD_URL = "/hst/device/download" + OPTIONAL_QUERY_STRING; public static final String HST_DEVICE_ASSOCIATION_URL = "/hst/patients/" + EASYCARE_NUMBER + "/associate" + OPTIONAL_QUERY_STRING; public static final String HST_DATA_SIGNALS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/diagnostic/signals" + OPTIONAL_QUERY_STRING; public static final String CREATE_HST_PATIENT_URL = "/hst/patients/new" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_PRESCRIPTION_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/prescription/?$"; public static final String HST_PATIENT_PRESCRIPTION_REPORT_URL = "/hst/patients/" + EASYCARE_NUMBER + "/report/prescription/foo.pdf$"; public static final String HST_PATIENT_INSURANCE_URL = "/hst/patients/" + EASYCARE_NUMBER + "/insurance" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_INSURANCE_ADD_URL = "/hst/patients/" + EASYCARE_NUMBER + "/insurance/add"; public static final String HST_PATIENT_INSURANCE_EDIT_URL = "/hst/patients/" + EASYCARE_NUMBER + "/insurance/edit"; public static final String HST_PATIENT_SEND_RESULTS_READY_URL = "/hst/patients/" + EASYCARE_NUMBER + "/hme-push-send-ready$"; }
UTF-8
Java
3,231
java
HstPageUrls.java
Java
[]
null
[]
package easycare.alc.cuke.pageObjects; import static easycare.cuke.pageObjects.PageUrls.EASYCARE_NUMBER; import static easycare.cuke.pageObjects.PageUrls.OPTIONAL_QUERY_STRING; public final class HstPageUrls { private HstPageUrls() { } /** matches one or more digits */ public static final String DIGITS = "\\d+"; public static final String HST_PATIENT_NOTES_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/notes" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_NEW_NOTE_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/notes/new/?(\\?.+)?"; public static final String HST_PATIENT_LIST_URL = "/hst/patients" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_EVENT_LOGS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/eventlogs" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_ACCESS_LOGS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/accesslogs" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_EDIT_CONTACT_INFO_URL = "/hst/patients/" + EASYCARE_NUMBER + "/contactdetails/edit"; public static final String HST_PATIENT_EDIT_BASIC_INFO_URL = "/hst/patients/" + EASYCARE_NUMBER + "/basicdetails/edit/?$"; public static final String HST_PATIENT_DIAGNOSTIC_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/diagnostic/?$"; public static final String HST_PATIENT_SIGNALS_VIEW_ERROR_URL = "/hst/patients/" + EASYCARE_NUMBER + "/error"; public static final String HST_PATIENT_DETAILS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/basicdetails/?$"; public static final String HST_PATIENT_CONTACT_DETAILS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/contactdetails/?$"; public static final String HST_PATIENT_ADDITIONAL_DETAILS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/additionaldetails/?$"; public static final String HST_PATIENT_ADDITIONAL_DETAILS_EDIT_URL = "/hst/patients/" + EASYCARE_NUMBER + "/additionaldetails/edit/?$"; public static final String HST_DEVICE_DOWNLOAD_URL = "/hst/device/download" + OPTIONAL_QUERY_STRING; public static final String HST_DEVICE_ASSOCIATION_URL = "/hst/patients/" + EASYCARE_NUMBER + "/associate" + OPTIONAL_QUERY_STRING; public static final String HST_DATA_SIGNALS_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/diagnostic/signals" + OPTIONAL_QUERY_STRING; public static final String CREATE_HST_PATIENT_URL = "/hst/patients/new" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_PRESCRIPTION_VIEW_URL = "/hst/patients/" + EASYCARE_NUMBER + "/prescription/?$"; public static final String HST_PATIENT_PRESCRIPTION_REPORT_URL = "/hst/patients/" + EASYCARE_NUMBER + "/report/prescription/foo.pdf$"; public static final String HST_PATIENT_INSURANCE_URL = "/hst/patients/" + EASYCARE_NUMBER + "/insurance" + OPTIONAL_QUERY_STRING; public static final String HST_PATIENT_INSURANCE_ADD_URL = "/hst/patients/" + EASYCARE_NUMBER + "/insurance/add"; public static final String HST_PATIENT_INSURANCE_EDIT_URL = "/hst/patients/" + EASYCARE_NUMBER + "/insurance/edit"; public static final String HST_PATIENT_SEND_RESULTS_READY_URL = "/hst/patients/" + EASYCARE_NUMBER + "/hme-push-send-ready$"; }
3,231
0.724853
0.724853
37
86.324326
52.620544
142
false
false
0
0
0
0
0
0
0.72973
false
false
5
1a4e151456f062e2cfd1ae17ea378d6c6c94ec66
30,176,440,243,581
003a6ee01d39c3d5e7d3e57f0bac56bc411d2bd5
/TigerGolf004/TGolfer/src/main/java/com/boha/golfpractice/player/adapters/BagListAdapter.java
45f602bedbfd71e59bbe2d7353c196a6d67e732f
[]
no_license
malengatiger/TigerGolf004
https://github.com/malengatiger/TigerGolf004
e9ee4c7b88f384907670971b7e21d5f66a22e096
16c7e5afa26711bf2aab70fc9685cca983d9a2c7
refs/heads/master
2021-01-18T23:43:35.285000
2016-06-08T13:07:47
2016-06-08T13:07:47
54,854,472
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boha.golfpractice.player.adapters; import android.content.Context; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import android.widget.TextView; import com.boha.golfpractice.player.R; import com.boha.golfpractice.player.dto.BagDTO; import com.boha.golfpractice.player.dto.PracticeSessionDTO; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; /** * Created by aubreyM on 14/12/17. */ public class BagListAdapter extends RecyclerView.Adapter<BagListAdapter.BagViewHolder> { public interface BagListener { void onSummaryClicked(BagDTO bag); void onRefreshRequired(BagDTO bag, int days); } private BagListener mListener; private List<BagDTO> bagList; private Context ctx; private int days; public BagListAdapter(List<BagDTO> bagList, Context context, int days, BagListener listener) { this.bagList = bagList; this.ctx = context; this.mListener = listener; this.days = days; } @Override public BagViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.coach_session_summary, parent, false); return new BagViewHolder(v); } @Override public void onBindViewHolder(final BagViewHolder h, final int position) { final BagDTO bag = bagList.get(position); final List<PracticeSessionDTO> practiceSessionList = bag.getPracticeSessionList(); h.count.setText(df.format(practiceSessionList.size())); h.golfCourse.setText(bag.getDescription()); h.seekBar.setProgress(days); h.days.setText("" + days); int totalStrokes = 0, totalPar = 0, totalUnderPar = 0, totalOverPar = 0, totalHoles = 0, totalMistakes = 0; for (PracticeSessionDTO p : practiceSessionList) { totalHoles += p.getNumberOfHoles(); totalStrokes += p.getTotalStrokes(); totalPar += p.getPar(); totalUnderPar += p.getUnderPar(); totalOverPar += p.getOverPar(); totalMistakes += p.getTotalMistakes(); } h.numHoles.setText(df.format(totalHoles)); h.numStrokes.setText(df.format(totalStrokes)); h.numUnder.setText(df.format(totalUnderPar)); h.numOver.setText(df.format(totalOverPar)); h.par.setText(df.format(totalPar)); h.numMistakes.setText(df.format(totalMistakes)); if (totalHoles == 0) { h.numHolesAvg.setText("0.0"); h.numStrokesAvg.setText("0.0"); h.numUnderAvg.setText("0.0%"); h.parAvg.setText("0.0%"); h.numOverAvg.setText("0.0%"); h.numMistakesAvg.setText("0.0%"); } else { Double hAvg = Double.parseDouble("" + totalHoles) / Double.parseDouble("" + practiceSessionList.size()); h.numHolesAvg.setText(dfAvg.format(hAvg)); Double strokeAvg = Double.parseDouble("" + totalStrokes) / Double.parseDouble("" + totalHoles); h.numStrokesAvg.setText(dfAvg.format(strokeAvg)); Double underAvg = Double.parseDouble("" + totalUnderPar) / Double.parseDouble("" + totalHoles) * 100; h.numUnderAvg.setText(dfAvg.format(underAvg) + "%"); Double overAvg = Double.parseDouble("" + totalOverPar) / Double.parseDouble("" + totalHoles) * 100; h.numOverAvg.setText(dfAvg.format(overAvg) + "%"); Double pAvg = Double.parseDouble("" + totalPar) / Double.parseDouble("" + totalHoles) * 100; h.parAvg.setText(dfAvg.format(pAvg) + "%"); Double misAvg = Double.parseDouble("" + totalMistakes) / Double.parseDouble("" + totalHoles) * 100; h.numMistakesAvg.setText(dfAvg.format(misAvg) + "%"); } h.fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int days = h.seekBar.getProgress(); if (days == 0) { days = 90; } mListener.onRefreshRequired(bag, days); } }); h.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { h.days.setText("" + progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } @Override public int getItemCount() { return bagList == null ? 0 : bagList.size(); } static final Locale loc = Locale.getDefault(); static final SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMMM yyyy HH:mm", loc); static final DecimalFormat df = new DecimalFormat("###,###,###,###"); static final DecimalFormat dfAvg = new DecimalFormat("###,###,##0.00"); public class BagViewHolder extends RecyclerView.ViewHolder { protected TextView golfCourse, sessionDate, count, days; protected TextView numHoles, numStrokes, numUnder, numOver, par, numMistakes; protected TextView numHolesAvg, numStrokesAvg, numUnderAvg, numOverAvg, parAvg, numMistakesAvg; SeekBar seekBar; FloatingActionButton fab; public BagViewHolder(View itemView) { super(itemView); days = (TextView) itemView .findViewById(R.id.days); golfCourse = (TextView) itemView .findViewById(R.id.golfCourse); sessionDate = (TextView) itemView .findViewById(R.id.days); numHoles = (TextView) itemView .findViewById(R.id.holeCount); numStrokes = (TextView) itemView .findViewById(R.id.strokes); numUnder = (TextView) itemView .findViewById(R.id.underPar); numOver = (TextView) itemView .findViewById(R.id.overpar); par = (TextView) itemView .findViewById(R.id.par); numMistakes = (TextView) itemView .findViewById(R.id.mistakes); count = (TextView) itemView .findViewById(R.id.count); numHolesAvg = (TextView) itemView .findViewById(R.id.holeAverage); numStrokesAvg = (TextView) itemView .findViewById(R.id.strokeAverage); numUnderAvg = (TextView) itemView .findViewById(R.id.underParAverage); numOverAvg = (TextView) itemView .findViewById(R.id.overParAverage); parAvg = (TextView) itemView .findViewById(R.id.parAverage); numMistakesAvg = (TextView) itemView .findViewById(R.id.mistakeAverage); seekBar = (SeekBar) itemView.findViewById(R.id.seekBar); fab = (FloatingActionButton) itemView.findViewById(R.id.fab); } } static final String LOG = BagListAdapter.class.getSimpleName(); }
UTF-8
Java
7,564
java
BagListAdapter.java
Java
[ { "context": ".List;\nimport java.util.Locale;\n\n/**\n * Created by aubreyM on 14/12/17.\n */\npublic class BagListAdapter exte", "end": 632, "score": 0.9996629953384399, "start": 625, "tag": "USERNAME", "value": "aubreyM" } ]
null
[]
package com.boha.golfpractice.player.adapters; import android.content.Context; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import android.widget.TextView; import com.boha.golfpractice.player.R; import com.boha.golfpractice.player.dto.BagDTO; import com.boha.golfpractice.player.dto.PracticeSessionDTO; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; /** * Created by aubreyM on 14/12/17. */ public class BagListAdapter extends RecyclerView.Adapter<BagListAdapter.BagViewHolder> { public interface BagListener { void onSummaryClicked(BagDTO bag); void onRefreshRequired(BagDTO bag, int days); } private BagListener mListener; private List<BagDTO> bagList; private Context ctx; private int days; public BagListAdapter(List<BagDTO> bagList, Context context, int days, BagListener listener) { this.bagList = bagList; this.ctx = context; this.mListener = listener; this.days = days; } @Override public BagViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.coach_session_summary, parent, false); return new BagViewHolder(v); } @Override public void onBindViewHolder(final BagViewHolder h, final int position) { final BagDTO bag = bagList.get(position); final List<PracticeSessionDTO> practiceSessionList = bag.getPracticeSessionList(); h.count.setText(df.format(practiceSessionList.size())); h.golfCourse.setText(bag.getDescription()); h.seekBar.setProgress(days); h.days.setText("" + days); int totalStrokes = 0, totalPar = 0, totalUnderPar = 0, totalOverPar = 0, totalHoles = 0, totalMistakes = 0; for (PracticeSessionDTO p : practiceSessionList) { totalHoles += p.getNumberOfHoles(); totalStrokes += p.getTotalStrokes(); totalPar += p.getPar(); totalUnderPar += p.getUnderPar(); totalOverPar += p.getOverPar(); totalMistakes += p.getTotalMistakes(); } h.numHoles.setText(df.format(totalHoles)); h.numStrokes.setText(df.format(totalStrokes)); h.numUnder.setText(df.format(totalUnderPar)); h.numOver.setText(df.format(totalOverPar)); h.par.setText(df.format(totalPar)); h.numMistakes.setText(df.format(totalMistakes)); if (totalHoles == 0) { h.numHolesAvg.setText("0.0"); h.numStrokesAvg.setText("0.0"); h.numUnderAvg.setText("0.0%"); h.parAvg.setText("0.0%"); h.numOverAvg.setText("0.0%"); h.numMistakesAvg.setText("0.0%"); } else { Double hAvg = Double.parseDouble("" + totalHoles) / Double.parseDouble("" + practiceSessionList.size()); h.numHolesAvg.setText(dfAvg.format(hAvg)); Double strokeAvg = Double.parseDouble("" + totalStrokes) / Double.parseDouble("" + totalHoles); h.numStrokesAvg.setText(dfAvg.format(strokeAvg)); Double underAvg = Double.parseDouble("" + totalUnderPar) / Double.parseDouble("" + totalHoles) * 100; h.numUnderAvg.setText(dfAvg.format(underAvg) + "%"); Double overAvg = Double.parseDouble("" + totalOverPar) / Double.parseDouble("" + totalHoles) * 100; h.numOverAvg.setText(dfAvg.format(overAvg) + "%"); Double pAvg = Double.parseDouble("" + totalPar) / Double.parseDouble("" + totalHoles) * 100; h.parAvg.setText(dfAvg.format(pAvg) + "%"); Double misAvg = Double.parseDouble("" + totalMistakes) / Double.parseDouble("" + totalHoles) * 100; h.numMistakesAvg.setText(dfAvg.format(misAvg) + "%"); } h.fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int days = h.seekBar.getProgress(); if (days == 0) { days = 90; } mListener.onRefreshRequired(bag, days); } }); h.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { h.days.setText("" + progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } @Override public int getItemCount() { return bagList == null ? 0 : bagList.size(); } static final Locale loc = Locale.getDefault(); static final SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMMM yyyy HH:mm", loc); static final DecimalFormat df = new DecimalFormat("###,###,###,###"); static final DecimalFormat dfAvg = new DecimalFormat("###,###,##0.00"); public class BagViewHolder extends RecyclerView.ViewHolder { protected TextView golfCourse, sessionDate, count, days; protected TextView numHoles, numStrokes, numUnder, numOver, par, numMistakes; protected TextView numHolesAvg, numStrokesAvg, numUnderAvg, numOverAvg, parAvg, numMistakesAvg; SeekBar seekBar; FloatingActionButton fab; public BagViewHolder(View itemView) { super(itemView); days = (TextView) itemView .findViewById(R.id.days); golfCourse = (TextView) itemView .findViewById(R.id.golfCourse); sessionDate = (TextView) itemView .findViewById(R.id.days); numHoles = (TextView) itemView .findViewById(R.id.holeCount); numStrokes = (TextView) itemView .findViewById(R.id.strokes); numUnder = (TextView) itemView .findViewById(R.id.underPar); numOver = (TextView) itemView .findViewById(R.id.overpar); par = (TextView) itemView .findViewById(R.id.par); numMistakes = (TextView) itemView .findViewById(R.id.mistakes); count = (TextView) itemView .findViewById(R.id.count); numHolesAvg = (TextView) itemView .findViewById(R.id.holeAverage); numStrokesAvg = (TextView) itemView .findViewById(R.id.strokeAverage); numUnderAvg = (TextView) itemView .findViewById(R.id.underParAverage); numOverAvg = (TextView) itemView .findViewById(R.id.overParAverage); parAvg = (TextView) itemView .findViewById(R.id.parAverage); numMistakesAvg = (TextView) itemView .findViewById(R.id.mistakeAverage); seekBar = (SeekBar) itemView.findViewById(R.id.seekBar); fab = (FloatingActionButton) itemView.findViewById(R.id.fab); } } static final String LOG = BagListAdapter.class.getSimpleName(); }
7,564
0.605235
0.599286
200
36.82
27.706453
116
false
false
0
0
0
0
0
0
0.68
false
false
5
7d6bf5600a6e830b8aef64c807bd290d34467568
223,338,332,229
d2af70eedab94df6fda54a44437579907cef4d94
/src/main/java/com/isolutions/usermanagement/service/EmploymentHistoryService.java
b409a9b6050238723b3b1ad2c81e7f60651e6035
[]
no_license
alkettarko/User-Management
https://github.com/alkettarko/User-Management
3dda820af9564be46959b6bcacf7f6bb735d7fd4
e200e198ef33cd7f6d70fb841c55cdde0d61cdbf
refs/heads/master
2022-03-24T06:28:21.243000
2019-12-10T01:06:43
2019-12-10T01:06:43
224,932,455
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.isolutions.usermanagement.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.isolutions.usermanagement.dto.EmploymentHistoryDto; import com.isolutions.usermanagement.model.Employee; import com.isolutions.usermanagement.model.EmploymentHistory; import com.isolutions.usermanagement.repository.EmploymentHistoryRepository; @Service public class EmploymentHistoryService { @Autowired private EmploymentHistoryRepository employmentHistoryRepository; public List<EmploymentHistory> getEmploymentHistory() { return employmentHistoryRepository.findAll(); } public List<EmploymentHistoryDto> getHistoryByEmployee(Employee employee) { List<EmploymentHistory> employmentList = employmentHistoryRepository.findByEmployee(employee); return convertToDto(employmentList); } private List<EmploymentHistoryDto> convertToDto(List<EmploymentHistory> employmentList) { List<EmploymentHistoryDto> employmentHistoryDtoList = new ArrayList<EmploymentHistoryDto>(); employmentList.forEach(em -> { EmploymentHistoryDto employmentHistoryDto = new EmploymentHistoryDto(); employmentHistoryDto.setId(em.getId()); employmentHistoryDto.setCurrentDepartment(em.getCurrentDepartment().getName()); employmentHistoryDto.setPreviousDepartment(em.getPreviousDepartment().getName()); employmentHistoryDto.setDate(em.getDepartmentJoinDate()); employmentHistoryDto.setEmployeeName(em.getEmployee().getFirstName()); employmentHistoryDtoList.add(employmentHistoryDto); }); return employmentHistoryDtoList; } }
UTF-8
Java
1,670
java
EmploymentHistoryService.java
Java
[]
null
[]
package com.isolutions.usermanagement.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.isolutions.usermanagement.dto.EmploymentHistoryDto; import com.isolutions.usermanagement.model.Employee; import com.isolutions.usermanagement.model.EmploymentHistory; import com.isolutions.usermanagement.repository.EmploymentHistoryRepository; @Service public class EmploymentHistoryService { @Autowired private EmploymentHistoryRepository employmentHistoryRepository; public List<EmploymentHistory> getEmploymentHistory() { return employmentHistoryRepository.findAll(); } public List<EmploymentHistoryDto> getHistoryByEmployee(Employee employee) { List<EmploymentHistory> employmentList = employmentHistoryRepository.findByEmployee(employee); return convertToDto(employmentList); } private List<EmploymentHistoryDto> convertToDto(List<EmploymentHistory> employmentList) { List<EmploymentHistoryDto> employmentHistoryDtoList = new ArrayList<EmploymentHistoryDto>(); employmentList.forEach(em -> { EmploymentHistoryDto employmentHistoryDto = new EmploymentHistoryDto(); employmentHistoryDto.setId(em.getId()); employmentHistoryDto.setCurrentDepartment(em.getCurrentDepartment().getName()); employmentHistoryDto.setPreviousDepartment(em.getPreviousDepartment().getName()); employmentHistoryDto.setDate(em.getDepartmentJoinDate()); employmentHistoryDto.setEmployeeName(em.getEmployee().getFirstName()); employmentHistoryDtoList.add(employmentHistoryDto); }); return employmentHistoryDtoList; } }
1,670
0.831737
0.831737
49
33.081635
32.400452
96
false
false
0
0
0
0
0
0
1.346939
false
false
5
8d89a18614d3613156b26d7075bcba96ce750fc9
23,398,981,840,990
f1707897c314e588deb265120ec17d63c5546862
/app/src/main/java/com/androidfizz/viewpagerparallaxtransformer/MainActivity.java
36a305ab13aa7818b1e3e188366f13716cc1021d
[]
no_license
androidfizz/ViewPager-Parallax-Transformer
https://github.com/androidfizz/ViewPager-Parallax-Transformer
fe1c711dce56550b633899ded7c836fe3b434c05
2a56c2b6dc9534caa232895e35f791f74747299e
refs/heads/master
2021-04-15T04:46:55.593000
2018-03-26T17:24:59
2018-03-26T17:24:59
126,864,165
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.androidfizz.viewpagerparallaxtransformer; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import com.androidfizz.viewpagerparallaxtransformer.adapter.PagerAdapter; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = findViewById(R.id.viewPager); ArrayList<String> list = new ArrayList<>(); list.add("http://naturewallpapers.biz/wp-content/uploads/2012/05/kitten.jpg"); list.add("http://www.themountainpulse.com/wp-content/images/2011/09/IMG_0145-Copy.jpg"); list.add("https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/eclipse_full_res_0.png"); PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), list); viewPager.setAdapter(adapter); ParallaxPageTransformer pageTransformer = new ParallaxPageTransformer(); ParallaxPageTransformer.ParallaxTransformInformation transformInformation1 = new ParallaxPageTransformer .ParallaxTransformInformation(R.id.imageView, 2, 2); pageTransformer.addViewToParallax(transformInformation1); /* adding parallax to another view inside view pager */ /*ParallaxPageTransformer.ParallaxTransformInformation transformInformation2 = new ParallaxPageTransformer .ParallaxTransformInformation(R.id.layoutContent, -1.95f, ParallaxPageTransformer.ParallaxTransformInformation.PARALLAX_EFFECT_DEFAULT); pageTransformer.addViewToParallax(transformInformation2);*/ viewPager.setPageTransformer(true, pageTransformer); } }
UTF-8
Java
1,936
java
MainActivity.java
Java
[]
null
[]
package com.androidfizz.viewpagerparallaxtransformer; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import com.androidfizz.viewpagerparallaxtransformer.adapter.PagerAdapter; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = findViewById(R.id.viewPager); ArrayList<String> list = new ArrayList<>(); list.add("http://naturewallpapers.biz/wp-content/uploads/2012/05/kitten.jpg"); list.add("http://www.themountainpulse.com/wp-content/images/2011/09/IMG_0145-Copy.jpg"); list.add("https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/eclipse_full_res_0.png"); PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), list); viewPager.setAdapter(adapter); ParallaxPageTransformer pageTransformer = new ParallaxPageTransformer(); ParallaxPageTransformer.ParallaxTransformInformation transformInformation1 = new ParallaxPageTransformer .ParallaxTransformInformation(R.id.imageView, 2, 2); pageTransformer.addViewToParallax(transformInformation1); /* adding parallax to another view inside view pager */ /*ParallaxPageTransformer.ParallaxTransformInformation transformInformation2 = new ParallaxPageTransformer .ParallaxTransformInformation(R.id.layoutContent, -1.95f, ParallaxPageTransformer.ParallaxTransformInformation.PARALLAX_EFFECT_DEFAULT); pageTransformer.addViewToParallax(transformInformation2);*/ viewPager.setPageTransformer(true, pageTransformer); } }
1,936
0.727273
0.71281
48
39.333332
36.548103
134
false
false
0
0
0
0
0
0
0.5625
false
false
5
5ec83eb1ad8a93ccd384f05db4d569640bd46ec7
30,674,656,481,745
7cc46f38676ce131c5a3896651b5cff6edb2aba5
/src/jeuDesPetitsCheveaux/JeuDesPetitsCheveaux.java
e83139551404053f2bd732ff67c551697d002817
[]
no_license
Corrun/groupe-10
https://github.com/Corrun/groupe-10
14691b54fe290fb53467fbb701b6f28fbf944ab8
17100422468eee3b8f002079527f8ef25e786a40
refs/heads/main
2023-07-18T23:32:32.431000
2021-09-02T20:29:17
2021-09-02T20:29:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * This file is licensed to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package jeuDesPetitsCheveaux; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Set; /** * * Cette classe sert à ......... * * @author <a href="mailto:adnan.kouakoua@univ-lille1.fr">Adnân KOUAKOUA</a> * IUT-A Informatique, Universite de Lille. * @date 2 sept. 2021 */ public class JeuDesPetitsCheveaux { protected Scanner scanner = new Scanner(System.in); private List<Utilisateur> utilisateurs= new ArrayList<>(); private static final int NOMBREMAXJOUEUR=4; public JeuDesPetitsCheveaux(List<Joueur> joueurs) { if(joueurs.size()>4) { for(int i=0; i<4;i++) { addUtilisateur(utilisateurs.get(i)); } } else { for(int i=0; i<joueurs.size();i++) { addUtilisateur(utilisateurs.get(i)); } } } public static void main(String[] args) { //Actions.affichCouleur(Couleur.ROUGE,"NAPS GOAT"); System.out.println("NAPS GOAT"); } private void attributionDesJoueurs() { System.out.println(""); System.out.println(); } public Utilisateur aGagner () { for(int i=0; i< utilisateurs.size();i++) { Utilisateur joueur =this.utilisateurs.get(i); if(joueur.nbPionsEnReserve==0) { for(int j=0;j<4;j++) { if(joueur.getEcurie()[j] == null) return null; } return joueur; } } return null; } private void ajouterJoueur() { int nombreBot=0; String entree=""; if(utilisateurs.size()<4) { System.out.println("Ajouter un utilisateur :"); System.out.println("Souhaitez-vous qu'il soit un joueur ou une IA ?"); entree=scanner.next(); while(!entree.toLowerCase().equals("ia") || !entree.toLowerCase().equals("joueur")) { entree=scanner.next(); } if(entree.toLowerCase().equals("IA")) { nombreBot++; addUtilisateur(new Ia("bot n°"+nombreBot)); } if(entree.toLowerCase().equals("joueur")) { System.out.println("choissisez un pseudo :"); entree=scanner.next(); addUtilisateur(new Joueur(entree)); } } } private boolean addUtilisateur(Utilisateur u) { if(utilisateurs.size()<=NOMBREMAXJOUEUR) { utilisateurs.add(u); return true; } return false; } public Set<Integer> coupsPossibles(){ return null; } //public List<>coupsPossibles() { }
UTF-8
Java
2,889
java
JeuDesPetitsCheveaux.java
Java
[ { "context": "se sert à .........\n *\n * @author <a href=\"mailto:adnan.kouakoua@univ-lille1.fr\">Adnân KOUAKOUA</a>\n * IUT-A Informatique, Univer", "end": 815, "score": 0.9998810291290283, "start": 786, "tag": "EMAIL", "value": "adnan.kouakoua@univ-lille1.fr" }, { "context": "or <a href=\"mailto:adnan.kouakoua@univ-lille1.fr\">Adnân KOUAKOUA</a>\n * IUT-A Informatique, Universite de Lille.\n ", "end": 831, "score": 0.9998828768730164, "start": 817, "tag": "NAME", "value": "Adnân KOUAKOUA" } ]
null
[]
/* * This file is licensed to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package jeuDesPetitsCheveaux; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Set; /** * * Cette classe sert à ......... * * @author <a href="mailto:<EMAIL>"><NAME></a> * IUT-A Informatique, Universite de Lille. * @date 2 sept. 2021 */ public class JeuDesPetitsCheveaux { protected Scanner scanner = new Scanner(System.in); private List<Utilisateur> utilisateurs= new ArrayList<>(); private static final int NOMBREMAXJOUEUR=4; public JeuDesPetitsCheveaux(List<Joueur> joueurs) { if(joueurs.size()>4) { for(int i=0; i<4;i++) { addUtilisateur(utilisateurs.get(i)); } } else { for(int i=0; i<joueurs.size();i++) { addUtilisateur(utilisateurs.get(i)); } } } public static void main(String[] args) { //Actions.affichCouleur(Couleur.ROUGE,"NAPS GOAT"); System.out.println("NAPS GOAT"); } private void attributionDesJoueurs() { System.out.println(""); System.out.println(); } public Utilisateur aGagner () { for(int i=0; i< utilisateurs.size();i++) { Utilisateur joueur =this.utilisateurs.get(i); if(joueur.nbPionsEnReserve==0) { for(int j=0;j<4;j++) { if(joueur.getEcurie()[j] == null) return null; } return joueur; } } return null; } private void ajouterJoueur() { int nombreBot=0; String entree=""; if(utilisateurs.size()<4) { System.out.println("Ajouter un utilisateur :"); System.out.println("Souhaitez-vous qu'il soit un joueur ou une IA ?"); entree=scanner.next(); while(!entree.toLowerCase().equals("ia") || !entree.toLowerCase().equals("joueur")) { entree=scanner.next(); } if(entree.toLowerCase().equals("IA")) { nombreBot++; addUtilisateur(new Ia("bot n°"+nombreBot)); } if(entree.toLowerCase().equals("joueur")) { System.out.println("choissisez un pseudo :"); entree=scanner.next(); addUtilisateur(new Joueur(entree)); } } } private boolean addUtilisateur(Utilisateur u) { if(utilisateurs.size()<=NOMBREMAXJOUEUR) { utilisateurs.add(u); return true; } return false; } public Set<Integer> coupsPossibles(){ return null; } //public List<>coupsPossibles() { }
2,858
0.660083
0.651767
129
21.372093
22.072844
88
false
false
0
0
0
0
0
0
2.031008
false
false
5
9557d54d526eb14046c78a373909e534af7b12e3
18,794,776,937,552
0579649dd15c99472685b1e9b22c24742b85525c
/app/src/main/java/com/example/oud/api/Playlist.java
e0f20218a4d34d0f0eb4a6c6a048a5719340bec5
[ "MIT" ]
permissive
youssefEdrees/Oud-1
https://github.com/youssefEdrees/Oud-1
62445fe7475af009424078bcc06ffdff28bae8bf
fc013e81a16f140b90ca6d7a00f7174328223ac9
refs/heads/master
2023-06-26T02:57:18.686000
2021-07-31T16:36:09
2021-07-31T16:36:09
272,238,327
0
0
MIT
true
2021-07-31T16:36:10
2020-06-14T16:15:22
2020-06-16T18:46:58
2021-07-31T16:36:09
66,055
0
0
0
Java
false
false
package com.example.oud.api; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class Playlist { @SerializedName("_id") private String id; private String name; private String owner; private boolean collaborative; private String description; private int followersCount; private ArrayList<Track> tracks; private String image; @SerializedName("public") private boolean publicPlaylist; private String type; public Playlist(String id, String name, String owner, boolean collaborative, String description, int followersCount, ArrayList<Track> tracks, String image, boolean publicPlaylist, String type) { this.id = id; this.name = name; this.owner = owner; this.collaborative = collaborative; this.description = description; this.followersCount = followersCount; this.tracks = tracks; this.image = image; this.publicPlaylist = publicPlaylist; this.type = type; } public String getId() { return id; } public String getName() { return name; } public String getOwner() { return owner; } public boolean isCollaborative() { return collaborative; } public String getDescription() { return description; } public int getFollowersCount() { return followersCount; } public ArrayList<Track> getTracks() { return tracks; } public String getImage() { return image; } public boolean isPublicPlaylist() { return publicPlaylist; } public String getType() { return type; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setOwner(String owner) { this.owner = owner; } public void setCollaborative(boolean collaborative) { this.collaborative = collaborative; } public void setDescription(String description) { this.description = description; } public void setFollowersCount(int followersCount) { this.followersCount = followersCount; } public void setTracks(ArrayList<Track> tracks) { this.tracks = tracks; } public void setImage(String image) { this.image = image; } public void setPublicPlaylist(boolean publicPlaylist) { this.publicPlaylist = publicPlaylist; } public void setType(String type) { this.type = type; } }
UTF-8
Java
2,747
java
Playlist.java
Java
[]
null
[]
package com.example.oud.api; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class Playlist { @SerializedName("_id") private String id; private String name; private String owner; private boolean collaborative; private String description; private int followersCount; private ArrayList<Track> tracks; private String image; @SerializedName("public") private boolean publicPlaylist; private String type; public Playlist(String id, String name, String owner, boolean collaborative, String description, int followersCount, ArrayList<Track> tracks, String image, boolean publicPlaylist, String type) { this.id = id; this.name = name; this.owner = owner; this.collaborative = collaborative; this.description = description; this.followersCount = followersCount; this.tracks = tracks; this.image = image; this.publicPlaylist = publicPlaylist; this.type = type; } public String getId() { return id; } public String getName() { return name; } public String getOwner() { return owner; } public boolean isCollaborative() { return collaborative; } public String getDescription() { return description; } public int getFollowersCount() { return followersCount; } public ArrayList<Track> getTracks() { return tracks; } public String getImage() { return image; } public boolean isPublicPlaylist() { return publicPlaylist; } public String getType() { return type; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setOwner(String owner) { this.owner = owner; } public void setCollaborative(boolean collaborative) { this.collaborative = collaborative; } public void setDescription(String description) { this.description = description; } public void setFollowersCount(int followersCount) { this.followersCount = followersCount; } public void setTracks(ArrayList<Track> tracks) { this.tracks = tracks; } public void setImage(String image) { this.image = image; } public void setPublicPlaylist(boolean publicPlaylist) { this.publicPlaylist = publicPlaylist; } public void setType(String type) { this.type = type; } }
2,747
0.595195
0.595195
131
19.969465
17.380756
59
false
false
0
0
0
0
0
0
0.396947
false
false
5
5767af0d362a48dc93fe3f4c9574fe3006e31629
32,925,219,294,554
80afe5d514471b5c570d918562f1c7c7d3488cf6
/lesson7/src/Bai6/Rectangle.java
b9abb37faf98cc348e0b4083b695eb6bbf83ac82
[]
no_license
DuyToi140299/JavaWeb-Programimng
https://github.com/DuyToi140299/JavaWeb-Programimng
2129d6dc4acb5b7de072ce0266ba768f8dda6b1b
34fa17b840c32c305efa21a6dc451c8379ec2a71
refs/heads/master
2023-06-10T01:53:27.765000
2023-05-31T09:09:11
2023-05-31T09:09:11
171,900,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Bai6; import java.util.Scanner; /** * * @author Admin */ public class Rectangle { Scanner sc = new Scanner(System.in); private int length; private int width; public Rectangle() { } public Rectangle(int length, int width) { this.length = length; this.width = width; } protected void input() { System.out.print("Length = "); this.length = sc.nextInt(); System.out.print("Width = "); this.width = sc.nextInt(); } public int perimeter() { int chuVi = (this.length + this.width) * 2; return chuVi; } public int acreage() { int dienTich = length * width; return dienTich; } }
UTF-8
Java
910
java
Rectangle.java
Java
[ { "context": "ai6;\n\nimport java.util.Scanner;\n\n/**\n *\n * @author Admin\n */\npublic class Rectangle {\n\n Scanner sc = ne", "end": 250, "score": 0.6706902980804443, "start": 245, "tag": "USERNAME", "value": "Admin" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Bai6; import java.util.Scanner; /** * * @author Admin */ public class Rectangle { Scanner sc = new Scanner(System.in); private int length; private int width; public Rectangle() { } public Rectangle(int length, int width) { this.length = length; this.width = width; } protected void input() { System.out.print("Length = "); this.length = sc.nextInt(); System.out.print("Width = "); this.width = sc.nextInt(); } public int perimeter() { int chuVi = (this.length + this.width) * 2; return chuVi; } public int acreage() { int dienTich = length * width; return dienTich; } }
910
0.591209
0.589011
48
17.958334
18.597668
79
false
false
0
0
0
0
0
0
0.395833
false
false
5
69235f49d4df0e711a64d2ffe31172786e8a4b63
5,531,917,931,806
8ebad51a3c26aef7420bbf805277ab34db8e333b
/app/src/main/java/com/ulsu/marat/valuter/utils/DialogUtils.java
e4bfab56c6b6e69350fc7d47da474a056a2c8385
[]
no_license
zloyDemon/CourseWork
https://github.com/zloyDemon/CourseWork
dd6fd97f36799c6820ce18a284ef314856b5c361
a688820fc56292727dce0171351aa929cee9623e
refs/heads/master
2021-01-20T05:36:27.063000
2017-06-30T18:46:09
2017-06-30T18:46:09
89,795,737
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ulsu.marat.valuter.utils; import android.app.AlertDialog; import android.content.Context; /** * Created by Marat on 09.05.2017. */ public class DialogUtils { public static void DialogMessage(Context context, int title, int message){ AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(context.getString(title)) .setMessage(context.getString(message)) .setPositiveButton("OK",null) .create(); dialog.show(); } }
UTF-8
Java
528
java
DialogUtils.java
Java
[ { "context": "import android.content.Context;\n\n/**\n * Created by Marat on 09.05.2017.\n */\n\npublic class DialogUtils {\n ", "end": 127, "score": 0.9993139505386353, "start": 122, "tag": "NAME", "value": "Marat" } ]
null
[]
package com.ulsu.marat.valuter.utils; import android.app.AlertDialog; import android.content.Context; /** * Created by Marat on 09.05.2017. */ public class DialogUtils { public static void DialogMessage(Context context, int title, int message){ AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(context.getString(title)) .setMessage(context.getString(message)) .setPositiveButton("OK",null) .create(); dialog.show(); } }
528
0.640152
0.625
19
26.789474
23.109758
78
false
false
0
0
0
0
0
0
0.421053
false
false
5
3450759e6584edc81b36ea728ad0a5ea4f3194bc
5,531,917,930,849
fb6f8f24289185859a30dd50da02a42d16466bb2
/src/coen359/vendingmachine/admin/userfeedback/UserFeedbackController.java
ce6f8f955d5d4a16d8c97ba1a7914ca6e28dd0b2
[]
no_license
farzas/smartcal-vending-machine
https://github.com/farzas/smartcal-vending-machine
3cc8d93ae383f1e0b5fad478da5052a4435f4fa5
a3853285b1605a4b720e252d96ff2bf2282d22a5
refs/heads/master
2021-01-11T14:14:47.372000
2017-02-07T19:41:30
2017-02-07T19:41:30
81,242,911
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coen359.vendingmachine.admin.userfeedback; import java.text.ParseException; import javax.swing.table.TableModel; import javax.swing.event.*; /** * Glue between the view and the model . * No database specific code here. Contains a reference to both the TableModel and the graphical user interface. **/ public class UserFeedbackController implements TableModelListener { private UserFeedbackModel feedbackModel; private UserFeedbackView feedbackView; public UserFeedbackController(UserFeedbackView feedbackView) { this.feedbackView = feedbackView; // create the tableModel using the data in the cachedRowSet feedbackModel = new UserFeedbackModel(); feedbackModel.addTableModelListener(this); } public TableModel getTableModel() { return feedbackModel; } public void tableChanged(TableModelEvent e) { feedbackView.updateTable(); } /*public void valueChanged(ListSelectionEvent e) { ListSelectionModel selectModel = (ListSelectionModel) e.getSource(); int firstIndex = selectModel.getMinSelectionIndex(); if (firstIndex >= 0) { feedbackView.setIdTextField(feedbackModel.getProductList().get(firstIndex).getId()); feedbackView.setNameTextField(feedbackModel.getProductList().get(firstIndex).getName()); feedbackView.setPriceTextField(Double.toString(productModel.getProductList().get(firstIndex).getPrice())); productView.setExpiryDateTextField(productModel.getProductList().get(firstIndex).getExpiryDate().toString()); productView.setQuantityTextField(String.valueOf(productModel.getProductList().get(firstIndex).getQuantity())); productView.setImageLinkTextField(productModel.getProductList().get(firstIndex).getImageLink()); productView.setCalorieTextField(String.valueOf(productModel.getProductList().get(firstIndex).getNutritionalInfo().getCalorie())); productView.setFatTextField(String.valueOf(productModel.getProductList().get(firstIndex).getNutritionalInfo().getFat())); productView.setSugarTextField(String.valueOf(productModel.getProductList().get(firstIndex).getNutritionalInfo().getSugar())); } }*/ public void addRow(String[] array) throws NumberFormatException, ParseException { feedbackModel.addRow(array); } }
UTF-8
Java
2,346
java
UserFeedbackController.java
Java
[]
null
[]
package coen359.vendingmachine.admin.userfeedback; import java.text.ParseException; import javax.swing.table.TableModel; import javax.swing.event.*; /** * Glue between the view and the model . * No database specific code here. Contains a reference to both the TableModel and the graphical user interface. **/ public class UserFeedbackController implements TableModelListener { private UserFeedbackModel feedbackModel; private UserFeedbackView feedbackView; public UserFeedbackController(UserFeedbackView feedbackView) { this.feedbackView = feedbackView; // create the tableModel using the data in the cachedRowSet feedbackModel = new UserFeedbackModel(); feedbackModel.addTableModelListener(this); } public TableModel getTableModel() { return feedbackModel; } public void tableChanged(TableModelEvent e) { feedbackView.updateTable(); } /*public void valueChanged(ListSelectionEvent e) { ListSelectionModel selectModel = (ListSelectionModel) e.getSource(); int firstIndex = selectModel.getMinSelectionIndex(); if (firstIndex >= 0) { feedbackView.setIdTextField(feedbackModel.getProductList().get(firstIndex).getId()); feedbackView.setNameTextField(feedbackModel.getProductList().get(firstIndex).getName()); feedbackView.setPriceTextField(Double.toString(productModel.getProductList().get(firstIndex).getPrice())); productView.setExpiryDateTextField(productModel.getProductList().get(firstIndex).getExpiryDate().toString()); productView.setQuantityTextField(String.valueOf(productModel.getProductList().get(firstIndex).getQuantity())); productView.setImageLinkTextField(productModel.getProductList().get(firstIndex).getImageLink()); productView.setCalorieTextField(String.valueOf(productModel.getProductList().get(firstIndex).getNutritionalInfo().getCalorie())); productView.setFatTextField(String.valueOf(productModel.getProductList().get(firstIndex).getNutritionalInfo().getFat())); productView.setSugarTextField(String.valueOf(productModel.getProductList().get(firstIndex).getNutritionalInfo().getSugar())); } }*/ public void addRow(String[] array) throws NumberFormatException, ParseException { feedbackModel.addRow(array); } }
2,346
0.750639
0.748934
60
37.099998
40.39542
133
false
false
0
0
0
0
0
0
2.55
false
false
5
3ef8024b61f6b87944347e26fc0210a35399e333
23,948,737,662,798
381dd7a53b5ac890b3b64e442a574da49bbe995f
/SQL/SQL/Reports/src/pl/javastrt/first/Pracownik.java
f48a08681b07a43a3d09afe175308ab0eb19c5af
[]
no_license
leon230/UTMSReporting
https://github.com/leon230/UTMSReporting
9dfcf84ee5d961a94286284b9f8dc6b79838f44d
9a38de2857255d98d76570b2afbf618a3c4c2b16
refs/heads/master
2020-05-21T20:04:03.030000
2017-03-22T12:01:58
2017-03-22T12:01:58
64,285,301
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.javastrt.first; public class Pracownik { String imie; String nazwisko; int wiek; void ustawImie(String name, String surname, int age){ imie = name; nazwisko = surname; wiek = age; } String outImie(){ return imie; } String outNazwisko(){ return nazwisko; } int outWiek(){ return wiek; } }
UTF-8
Java
335
java
Pracownik.java
Java
[]
null
[]
package pl.javastrt.first; public class Pracownik { String imie; String nazwisko; int wiek; void ustawImie(String name, String surname, int age){ imie = name; nazwisko = surname; wiek = age; } String outImie(){ return imie; } String outNazwisko(){ return nazwisko; } int outWiek(){ return wiek; } }
335
0.653731
0.653731
27
11.407408
11.848611
54
false
false
0
0
0
0
0
0
1.518519
false
false
5
0c11a8951e6e20446e5a964015aef24fec641c89
12,859,132,116,979
87f0a0383169ab9e7df545684954702beed7b3f0
/src/main/java/org/simple/countstat/dao/BaseDao.java
7cb670c8aaebb022ab9dd94aadb7d71fb820d491
[ "Apache-2.0" ]
permissive
qibaoguang/simple.countstat
https://github.com/qibaoguang/simple.countstat
8a765ee51ecc87da5611618386f436bac4526376
6c38085876992f05c5db39f1ba1007aa7e915d25
refs/heads/master
2015-08-18T02:40:39.628000
2014-12-30T10:42:40
2014-12-30T10:42:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.simple.countstat.dao; import java.util.List; import org.apache.ibatis.session.SqlSessionFactory; public interface BaseDao { SqlSessionFactory getReadSessionFactory(); SqlSessionFactory getWriteSessionFactory(); int save(String statement, Object obj); int update(String statement); int update(String statement, Object obj); <T> T selectOne(String statement); <T> T selectOne(String statement, Object obj); <E> List<E> selectList(String statement); <E> List<E> selectList(String statement, Object obj); <T> T selectWithCallback(SessionCallback<T> callback); int saveOrUpdateWithCallback(WriteSessionCallback callback); int batchSaveOrUpdateWithCallback(WriteSessionCallback callback); }
UTF-8
Java
794
java
BaseDao.java
Java
[]
null
[]
package org.simple.countstat.dao; import java.util.List; import org.apache.ibatis.session.SqlSessionFactory; public interface BaseDao { SqlSessionFactory getReadSessionFactory(); SqlSessionFactory getWriteSessionFactory(); int save(String statement, Object obj); int update(String statement); int update(String statement, Object obj); <T> T selectOne(String statement); <T> T selectOne(String statement, Object obj); <E> List<E> selectList(String statement); <E> List<E> selectList(String statement, Object obj); <T> T selectWithCallback(SessionCallback<T> callback); int saveOrUpdateWithCallback(WriteSessionCallback callback); int batchSaveOrUpdateWithCallback(WriteSessionCallback callback); }
794
0.716625
0.716625
33
22.060606
24.319763
69
false
false
0
0
0
0
0
0
0.575758
false
false
5
f2198334f0373167106a49c591f55004bd0d7874
10,668,698,815,778
ce95830c0a0db6a5df5806b67ac91ce9ca555f10
/src/com/ulatina/clasesDiarioFacil/ClienteNormalHandler.java
9897b2f2789a0dd0a3394ab203558a7360e00c5a
[]
no_license
Anthony3064/DiarioFacil
https://github.com/Anthony3064/DiarioFacil
bd5369431caa398c97d217fb4b126888ffad5ca5
6e088c75c8c406514ef489f7012dca0972b3d4c7
refs/heads/master
2020-06-03T06:09:47.837000
2019-08-22T23:20:05
2019-08-22T23:20:05
191,473,946
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ulatina.clasesDiarioFacil; /** * * @author Kainthel */ public class ClienteNormalHandler extends AbstractHandler { @Override public void handleRequest(Cliente cliente) { if(cliente.getTipoCliente() != "VIP"){ double promo = 1.00; } else { System.out.println("Ese tipo de cliente no existe"); } } }
UTF-8
Java
594
java
ClienteNormalHandler.java
Java
[ { "context": ".ulatina.clasesDiarioFacil;\r\n\r\n/**\r\n *\r\n * @author Kainthel\r\n */\r\npublic class ClienteNormalHandler extends Abs", "end": 260, "score": 0.9667333960533142, "start": 252, "tag": "NAME", "value": "Kainthel" } ]
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 com.ulatina.clasesDiarioFacil; /** * * @author Kainthel */ public class ClienteNormalHandler extends AbstractHandler { @Override public void handleRequest(Cliente cliente) { if(cliente.getTipoCliente() != "VIP"){ double promo = 1.00; } else { System.out.println("Ese tipo de cliente no existe"); } } }
594
0.617845
0.612795
25
21.76
23.698574
79
false
false
0
0
0
0
0
0
0.24
false
false
5
6caf5bf5bda7e26c31444bda738c216d404c1a4b
30,270,929,561,305
8638fd326bf37198d86ae2b94b1d3529e7b1fadd
/de.uni_stuttgart.iste.cowolf.model.lqn.emf.edit/src/de/uni_stuttgart/iste/cowolf/model/LqnCore/emf/provider/TaskTypeItemProvider.java
9850d440742c3b98e3037a8951ac7097998a9fc1
[]
no_license
timsanwald/CoWolf
https://github.com/timsanwald/CoWolf
774c22d8e1f097a87093498f09524eeece1be4ad
706b12b6170cb7369d82c6840b93e3854122e6b8
refs/heads/master
2021-01-21T16:11:11.770000
2014-12-02T21:31:17
2014-12-02T21:31:17
25,541,447
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** */ package de.uni_stuttgart.iste.cowolf.model.LqnCore.emf.provider; import de.uni_stuttgart.iste.cowolf.model.LqnCore.LQNFactory; import de.uni_stuttgart.iste.cowolf.model.LqnCore.LQNPackage; import de.uni_stuttgart.iste.cowolf.model.LqnCore.TaskType; import de.uni_stuttgart.iste.cowolf.model.commonBase.emf.provider.IDBaseItemProvider; import de.uni_stuttgart.iste.cowolf.model.lqn.emf.provider.LQNEditPlugin; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; /** * This is the item provider adapter for a {@link de.uni_stuttgart.iste.cowolf.model.LqnCore.TaskType} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class TaskTypeItemProvider extends IDBaseItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TaskTypeItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addActivityGraphPropertyDescriptor(object); addMultiplicityPropertyDescriptor(object); addNamePropertyDescriptor(object); addPriorityPropertyDescriptor(object); addQueueLengthPropertyDescriptor(object); addReplicationPropertyDescriptor(object); addSchedulingPropertyDescriptor(object); addThinkTimePropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Activity Graph feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addActivityGraphPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_activityGraph_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_activityGraph_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__ACTIVITY_GRAPH, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Multiplicity feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addMultiplicityPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_multiplicity_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_multiplicity_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__MULTIPLICITY, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Name feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addNamePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_name_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_name_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__NAME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Priority feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addPriorityPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_priority_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_priority_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__PRIORITY, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Queue Length feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addQueueLengthPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_queueLength_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_queueLength_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__QUEUE_LENGTH, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Replication feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addReplicationPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_replication_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_replication_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__REPLICATION, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Scheduling feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addSchedulingPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_scheduling_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_scheduling_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__SCHEDULING, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Think Time feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addThinkTimePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_thinkTime_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_thinkTime_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__THINK_TIME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__RESULT_TASK); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__ENTRY); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__SERVICE); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__TASK_ACTIVITIES); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns TaskType.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/TaskType")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((TaskType)object).getName(); return label == null || label.length() == 0 ? getString("_UI_TaskType_type") : getString("_UI_TaskType_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(TaskType.class)) { case LQNPackage.TASK_TYPE__ACTIVITY_GRAPH: case LQNPackage.TASK_TYPE__MULTIPLICITY: case LQNPackage.TASK_TYPE__NAME: case LQNPackage.TASK_TYPE__PRIORITY: case LQNPackage.TASK_TYPE__QUEUE_LENGTH: case LQNPackage.TASK_TYPE__REPLICATION: case LQNPackage.TASK_TYPE__SCHEDULING: case LQNPackage.TASK_TYPE__THINK_TIME: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case LQNPackage.TASK_TYPE__RESULT_TASK: case LQNPackage.TASK_TYPE__ENTRY: case LQNPackage.TASK_TYPE__SERVICE: case LQNPackage.TASK_TYPE__TASK_ACTIVITIES: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__RESULT_TASK, LQNFactory.eINSTANCE.createOutputResultType())); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__ENTRY, LQNFactory.eINSTANCE.createEntryType())); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__SERVICE, LQNFactory.eINSTANCE.createServiceType())); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__TASK_ACTIVITIES, LQNFactory.eINSTANCE.createTaskActivityGraph())); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() { return LQNEditPlugin.INSTANCE; } }
UTF-8
Java
11,934
java
TaskTypeItemProvider.java
Java
[]
null
[]
/** */ package de.uni_stuttgart.iste.cowolf.model.LqnCore.emf.provider; import de.uni_stuttgart.iste.cowolf.model.LqnCore.LQNFactory; import de.uni_stuttgart.iste.cowolf.model.LqnCore.LQNPackage; import de.uni_stuttgart.iste.cowolf.model.LqnCore.TaskType; import de.uni_stuttgart.iste.cowolf.model.commonBase.emf.provider.IDBaseItemProvider; import de.uni_stuttgart.iste.cowolf.model.lqn.emf.provider.LQNEditPlugin; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; /** * This is the item provider adapter for a {@link de.uni_stuttgart.iste.cowolf.model.LqnCore.TaskType} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class TaskTypeItemProvider extends IDBaseItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TaskTypeItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addActivityGraphPropertyDescriptor(object); addMultiplicityPropertyDescriptor(object); addNamePropertyDescriptor(object); addPriorityPropertyDescriptor(object); addQueueLengthPropertyDescriptor(object); addReplicationPropertyDescriptor(object); addSchedulingPropertyDescriptor(object); addThinkTimePropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Activity Graph feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addActivityGraphPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_activityGraph_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_activityGraph_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__ACTIVITY_GRAPH, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Multiplicity feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addMultiplicityPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_multiplicity_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_multiplicity_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__MULTIPLICITY, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Name feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addNamePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_name_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_name_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__NAME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Priority feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addPriorityPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_priority_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_priority_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__PRIORITY, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Queue Length feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addQueueLengthPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_queueLength_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_queueLength_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__QUEUE_LENGTH, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Replication feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addReplicationPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_replication_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_replication_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__REPLICATION, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Scheduling feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addSchedulingPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_scheduling_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_scheduling_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__SCHEDULING, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Think Time feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addThinkTimePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_TaskType_thinkTime_feature"), getString("_UI_PropertyDescriptor_description", "_UI_TaskType_thinkTime_feature", "_UI_TaskType_type"), LQNPackage.Literals.TASK_TYPE__THINK_TIME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__RESULT_TASK); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__ENTRY); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__SERVICE); childrenFeatures.add(LQNPackage.Literals.TASK_TYPE__TASK_ACTIVITIES); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns TaskType.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/TaskType")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((TaskType)object).getName(); return label == null || label.length() == 0 ? getString("_UI_TaskType_type") : getString("_UI_TaskType_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(TaskType.class)) { case LQNPackage.TASK_TYPE__ACTIVITY_GRAPH: case LQNPackage.TASK_TYPE__MULTIPLICITY: case LQNPackage.TASK_TYPE__NAME: case LQNPackage.TASK_TYPE__PRIORITY: case LQNPackage.TASK_TYPE__QUEUE_LENGTH: case LQNPackage.TASK_TYPE__REPLICATION: case LQNPackage.TASK_TYPE__SCHEDULING: case LQNPackage.TASK_TYPE__THINK_TIME: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case LQNPackage.TASK_TYPE__RESULT_TASK: case LQNPackage.TASK_TYPE__ENTRY: case LQNPackage.TASK_TYPE__SERVICE: case LQNPackage.TASK_TYPE__TASK_ACTIVITIES: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__RESULT_TASK, LQNFactory.eINSTANCE.createOutputResultType())); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__ENTRY, LQNFactory.eINSTANCE.createEntryType())); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__SERVICE, LQNFactory.eINSTANCE.createServiceType())); newChildDescriptors.add (createChildParameter (LQNPackage.Literals.TASK_TYPE__TASK_ACTIVITIES, LQNFactory.eINSTANCE.createTaskActivityGraph())); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() { return LQNEditPlugin.INSTANCE; } }
11,934
0.715183
0.714932
379
30.488127
27.498079
112
false
false
0
0
0
0
0
0
2.379947
false
false
5
0b25d6feb31f9170d46ad010dddb3a9fb41ca1b7
7,086,696,041,887
442ee6d56a2b12cbd04ce2005f68a61c078bd04e
/Day 7 - Symbol_Tables/A1__Symbol_Table_API/BinarySearchST.java
4e78cee0f8764f05ba77183f202d041ab0b4fcbd
[]
no_license
muralimandula/PC_ADS_1
https://github.com/muralimandula/PC_ADS_1
6994632e08fd2ecafd47d58dd614fad7d96d896a
8998763d608d555146063179e600f8406e4ce960
refs/heads/master
2020-08-29T08:43:30.956000
2019-11-11T09:03:37
2019-11-11T09:03:37
217,984,986
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; class BinarySearchST<Key extends Comparable<Key>, Value> { Key[] keys; Value[] values; int capacity; int size; BinarySearchST() { this.size = 0; this.capacity = 10; this.keys = (Key[]) new Comparable[10]; this.values = (Value[]) new Object[10]; } // inserts key and a value at appropriate position in the arrays. public void put(Key k, Value v) { int keyIndex = rank(k); // key already exists in the symbol table if (keyIndex < size && keys[keyIndex].compareTo(k) == 0) { values[keyIndex] = v; return; } // inserting new key-value pair, at keyIndex/right index (since it's rank) for (int j = size; j > keyIndex; j--) { // copying value at previous to next keys[j] = keys[j-1]; values[j] = values[j-1]; } // Now we are at right index to insert keyIndex. keys[keyIndex] = k; values[keyIndex] = v; this.size++; if(this.size == this.capacity) { resize(); } } public int size() { return this.size; } public void resize() { this.keys = Arrays.copyOf(keys, capacity * 2); this.values = Arrays.copyOf(values, capacity * 2); this.capacity = capacity * 2; } // return true if the given key is in the symboltable. public boolean contains(Key k){ return get(k) != null; } // return value paired with Key. public Value get(Key k) { if (k == null) { return null; } int keyIndex = rank(k); // Finds possible position of k from rank(). // Checking it's existence in key[] using compareTo() == 0. if (keyIndex < size && keys[keyIndex].compareTo(k) == 0) { return values[keyIndex]; } return null; // Not FOUND } // return largest key at size - 1, since Ordered public Key max() { if(this.size == 0) { return null; } return this.keys[size - 1]; } public Key min() { if(this.size == 0) { return null; } return this.keys[0]; } // return largest key less than or equal to key public Key floor(Key k) { if((this.size == 0) || (k == null)) { return null; } // finding possible key position/rank in our symbol table. int keyIndex = rank(k); if (keyIndex < size && k.compareTo(keys[keyIndex]) == 0) { // finds exact return keys[keyIndex]; } else { return keys[keyIndex -1]; // if not found, just below/floor of it } } // return number of keys less than key. (i.e., index of it's own) // public int rank(Key key) { int lo = 0; int hi = size - 1; while (lo <= hi) { // A similar one of a binary Search int mid = lo + (hi - lo) / 2; int find = key.compareTo(keys[mid]); if(find == 0) { // found at mid return mid; } else if (find < 0) { // can find at left of mid. hi = mid - 1; } else { // can find at right of mid. lo = mid + 1; } } return lo; } // delete smallest key public void deleteMin() { Key minKey = this.min(); if (minKey != null) { int keyIndex = rank(minKey); if (keyIndex == size || keys[keyIndex].compareTo(minKey) != 0) { return; } // copying each next value to it's previous. for (int j = keyIndex; j < size - 1; j++) { keys[j] = keys[j+1]; values[j] = values[j+1]; } this.size--; keys[size] = null; // to avoid loitering values[size] = null; } } // public Iterable<Key> keys() { // To ignore null values // since resize to minimize not implemented int count = 0; for (int i = 0; i < keys.length; i++) { if(keys[i] == null) { break; } else { count++; } } this.keys = Arrays.copyOf(keys, count); Iterable<Key> iterable = Arrays.asList(keys); return iterable; } }
UTF-8
Java
4,557
java
BinarySearchST.java
Java
[]
null
[]
import java.util.Arrays; class BinarySearchST<Key extends Comparable<Key>, Value> { Key[] keys; Value[] values; int capacity; int size; BinarySearchST() { this.size = 0; this.capacity = 10; this.keys = (Key[]) new Comparable[10]; this.values = (Value[]) new Object[10]; } // inserts key and a value at appropriate position in the arrays. public void put(Key k, Value v) { int keyIndex = rank(k); // key already exists in the symbol table if (keyIndex < size && keys[keyIndex].compareTo(k) == 0) { values[keyIndex] = v; return; } // inserting new key-value pair, at keyIndex/right index (since it's rank) for (int j = size; j > keyIndex; j--) { // copying value at previous to next keys[j] = keys[j-1]; values[j] = values[j-1]; } // Now we are at right index to insert keyIndex. keys[keyIndex] = k; values[keyIndex] = v; this.size++; if(this.size == this.capacity) { resize(); } } public int size() { return this.size; } public void resize() { this.keys = Arrays.copyOf(keys, capacity * 2); this.values = Arrays.copyOf(values, capacity * 2); this.capacity = capacity * 2; } // return true if the given key is in the symboltable. public boolean contains(Key k){ return get(k) != null; } // return value paired with Key. public Value get(Key k) { if (k == null) { return null; } int keyIndex = rank(k); // Finds possible position of k from rank(). // Checking it's existence in key[] using compareTo() == 0. if (keyIndex < size && keys[keyIndex].compareTo(k) == 0) { return values[keyIndex]; } return null; // Not FOUND } // return largest key at size - 1, since Ordered public Key max() { if(this.size == 0) { return null; } return this.keys[size - 1]; } public Key min() { if(this.size == 0) { return null; } return this.keys[0]; } // return largest key less than or equal to key public Key floor(Key k) { if((this.size == 0) || (k == null)) { return null; } // finding possible key position/rank in our symbol table. int keyIndex = rank(k); if (keyIndex < size && k.compareTo(keys[keyIndex]) == 0) { // finds exact return keys[keyIndex]; } else { return keys[keyIndex -1]; // if not found, just below/floor of it } } // return number of keys less than key. (i.e., index of it's own) // public int rank(Key key) { int lo = 0; int hi = size - 1; while (lo <= hi) { // A similar one of a binary Search int mid = lo + (hi - lo) / 2; int find = key.compareTo(keys[mid]); if(find == 0) { // found at mid return mid; } else if (find < 0) { // can find at left of mid. hi = mid - 1; } else { // can find at right of mid. lo = mid + 1; } } return lo; } // delete smallest key public void deleteMin() { Key minKey = this.min(); if (minKey != null) { int keyIndex = rank(minKey); if (keyIndex == size || keys[keyIndex].compareTo(minKey) != 0) { return; } // copying each next value to it's previous. for (int j = keyIndex; j < size - 1; j++) { keys[j] = keys[j+1]; values[j] = values[j+1]; } this.size--; keys[size] = null; // to avoid loitering values[size] = null; } } // public Iterable<Key> keys() { // To ignore null values // since resize to minimize not implemented int count = 0; for (int i = 0; i < keys.length; i++) { if(keys[i] == null) { break; } else { count++; } } this.keys = Arrays.copyOf(keys, count); Iterable<Key> iterable = Arrays.asList(keys); return iterable; } }
4,557
0.47246
0.46456
189
23.116402
20.691414
82
false
false
0
0
0
0
0
0
0.444444
false
false
5
851f1e1c0295c02f8c95617324669337f516fabe
32,418,413,158,105
cf5e04a8d42329745786bc7c68ed9fa0a114cd5c
/io/PrintDemo.java
3b13a538c40de66ceae792a05ee77cc9aafc67dc
[]
no_license
praneethreddybilakanti/corejava
https://github.com/praneethreddybilakanti/corejava
59863c38646da40efbe9a9acc3ebfed92870f1fe
9162114041397bc98bb6787ea758948b5d2e4b19
refs/heads/master
2022-11-25T17:44:06.653000
2020-07-14T09:16:06
2020-07-14T09:16:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; class PrintDemo { public static void main(String[] args)throws IOException { PrintStream ps=new PrintStream(System.out); ps.println(20); System.out.println("Hello World!"); ps.println("praneeth"); System.err.println("Hello World!"); System.out.println("chandrika!"); int i=System.in.read();//returns ASCII code of 1st character System.out.println((char)i);//will print the character } }
UTF-8
Java
422
java
PrintDemo.java
Java
[ { "context": "ystem.out.println(\"Hello World!\");\n\t\n\tps.println(\"praneeth\");\n\t\tSystem.err.println(\"Hello World!\");\n\t\tSystem", "end": 222, "score": 0.9997532367706299, "start": 214, "tag": "NAME", "value": "praneeth" }, { "context": "rr.println(\"Hello World!\");\n\t\tSystem.out.println(\"chandrika!\");\nint i=System.in.read();//returns ASCII code o", "end": 295, "score": 0.9977524280548096, "start": 286, "tag": "NAME", "value": "chandrika" } ]
null
[]
import java.io.*; class PrintDemo { public static void main(String[] args)throws IOException { PrintStream ps=new PrintStream(System.out); ps.println(20); System.out.println("Hello World!"); ps.println("praneeth"); System.err.println("Hello World!"); System.out.println("chandrika!"); int i=System.in.read();//returns ASCII code of 1st character System.out.println((char)i);//will print the character } }
422
0.71564
0.708531
16
25.375
21.073902
62
false
false
0
0
0
0
0
0
1.3125
false
false
5
6af807699fb2f3b603c870ab7fac16a7cd57e10b
28,363,964,082,243
625b406c53b95ab5c273374384fc5a5d7ab9b164
/src/test/Lc010.java
c1278651eeb77e3533c3ab4f441fd9e51eb6ed14
[]
no_license
GLOxxxxi/Itsource
https://github.com/GLOxxxxi/Itsource
ce36391e21214702921ab4432761e93d9e601feb
0164b82fed6c2f01c3f5d5ee896b5397163623db
refs/heads/master
2023-08-03T13:16:17.996000
2021-09-23T05:11:06
2021-09-23T05:11:06
409,409,406
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import java.util.HashMap; import java.util.Map; /** * * 对于字符串 S 和 T,只有在 S = T + ... + T(T 自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。 * * 返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。 * *   * * 示例 1: * * 输入:str1 = "ABCABC", str2 = "ABC" * 输出:"ABC" * 示例 2: * * 输入:str1 = "ABABAB", str2 = "ABAB" * 输出:"AB" * 示例 3: * * 输入:str1 = "LEET", str2 = "CODE" * 输出:"" * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Lc010 { public String gcdOfStrings(String str1, String str2) { Map<Character, Integer> map = new HashMap(); Map<Character, Integer> mapTemp = new HashMap(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str1.length(); i++) { map.put(str1.charAt(i), map.getOrDefault(str1.charAt(i), 0) + 1); } for (int i = 0; i < str2.length(); i++) { if (map.containsKey(str2.charAt(i))) { mapTemp.put(str2.charAt(i), i); } } if (mapTemp.size() == 1) { return ""; } for (Map.Entry entry : mapTemp.entrySet()) { sb.append(entry.getKey()); } return sb.toString(); } public static void main(String[] args) { String str = "ABABABC"; String str1 = "ABAB"; Lc010 lc = new Lc010(); System.out.println(lc.gcdOfStrings(str, str1)); } }
UTF-8
Java
1,725
java
Lc010.java
Java
[]
null
[]
package test; import java.util.HashMap; import java.util.Map; /** * * 对于字符串 S 和 T,只有在 S = T + ... + T(T 自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。 * * 返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。 * *   * * 示例 1: * * 输入:str1 = "ABCABC", str2 = "ABC" * 输出:"ABC" * 示例 2: * * 输入:str1 = "ABABAB", str2 = "ABAB" * 输出:"AB" * 示例 3: * * 输入:str1 = "LEET", str2 = "CODE" * 输出:"" * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Lc010 { public String gcdOfStrings(String str1, String str2) { Map<Character, Integer> map = new HashMap(); Map<Character, Integer> mapTemp = new HashMap(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str1.length(); i++) { map.put(str1.charAt(i), map.getOrDefault(str1.charAt(i), 0) + 1); } for (int i = 0; i < str2.length(); i++) { if (map.containsKey(str2.charAt(i))) { mapTemp.put(str2.charAt(i), i); } } if (mapTemp.size() == 1) { return ""; } for (Map.Entry entry : mapTemp.entrySet()) { sb.append(entry.getKey()); } return sb.toString(); } public static void main(String[] args) { String str = "ABABABC"; String str1 = "ABAB"; Lc010 lc = new Lc010(); System.out.println(lc.gcdOfStrings(str, str1)); } }
1,725
0.531973
0.507483
60
23.5
21.503876
77
false
false
0
0
0
0
0
0
0.483333
false
false
5
65e19e0373a1f928814f81b96673bf65b54c7b34
24,610,162,640,599
f083997ae67b3d64cbc09f1965f4d693c712a4c6
/sda-commons-server-auth/src/test/java/org/sdase/commons/server/auth/key/RsaPublicKeyLoaderTest.java
5223da3f0e0d133ada7eee4b45dfd99e5f49d8c7
[ "MIT" ]
permissive
cawado/sda-dropwizard-commons
https://github.com/cawado/sda-dropwizard-commons
d5b69ea1577605b66479394e3aff07145fb8579d
0d71bbcfe27efd95eee128c83017709aaf0b5942
refs/heads/master
2022-04-10T21:57:52.411000
2020-03-25T14:17:47
2020-03-25T17:00:22
250,183,709
0
0
MIT
true
2020-03-26T06:57:06
2020-03-26T06:57:05
2020-03-25T17:00:27
2020-03-26T06:35:10
2,401
0
0
0
null
false
false
package org.sdase.commons.server.auth.key; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import java.security.interfaces.RSAPublicKey; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.mockito.Mockito; public class RsaPublicKeyLoaderTest { private RsaPublicKeyLoader keyLoader = new RsaPublicKeyLoader(); @Test public void shouldAddKeyWithoutKid() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return singletonList(new LoadedPublicKey(null, mockKey, this)); } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKeysWithoutId()).containsExactly(mockKey); assertThat(keyLoader.getKey(null)).isNull(); } @Test public void shouldAddKeyWithKid() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKeysWithoutId()).isEmpty(); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); } @Test public void shouldReloadIfKeyIsNotFoundAndRemoveOutdatedKeys() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); RSAPublicKey newMockKey = Mockito.mock(RSAPublicKey.class); AtomicInteger numberOfCalls = new AtomicInteger(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (numberOfCalls.getAndIncrement() < 1) { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } else { return singletonList(new LoadedPublicKey("newKid", newMockKey, this)); } } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); // no reload for known key assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("newKid")).isSameAs(newMockKey); assertThat(numberOfCalls.get()).isEqualTo(2); assertThat(keyLoader.getKey("exampleKid")).isNull(); assertThat(numberOfCalls.get()).isEqualTo(3); } @Test public void shouldReloadIfKeyIsNotFound() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); RSAPublicKey newMockKey = Mockito.mock(RSAPublicKey.class); AtomicInteger numberOfCalls = new AtomicInteger(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (numberOfCalls.getAndIncrement() < 1) { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } else { return Arrays.asList( new LoadedPublicKey("exampleKid", mockKey, this), new LoadedPublicKey("newKid", newMockKey, this)); } } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); // no reload for known key assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("newKid")).isSameAs(newMockKey); assertThat(numberOfCalls.get()).isEqualTo(2); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(2); } @Test public void shouldNotRemoveIfReloadFails() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); AtomicInteger numberOfCalls = new AtomicInteger(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (numberOfCalls.getAndIncrement() < 1) { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } else { throw new KeyLoadFailedException("Test error"); } } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); // no reload for known key assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("newKid")).isNull(); assertThat(numberOfCalls.get()).isEqualTo(2); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(2); } @Test public void shouldCountSources() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return singletonList(new LoadedPublicKey(null, mockKey, this)); } }; assertThat(keyLoader.getTotalNumberOfKeySources()).isEqualTo(0); keyLoader.addKeySource(keySource); keyLoader.getKeysWithoutId(); keyLoader.getKey("exampleKid"); assertThat(keyLoader.getTotalNumberOfKeySources()).isEqualTo(1); } @Test public void shouldCountAllKeys() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return Arrays.asList( new LoadedPublicKey(null, mockKey, this), new LoadedPublicKey("exampleKid", mockKey, this)); } }; assertThat(keyLoader.getTotalNumberOfKeys()).isEqualTo(0); keyLoader.addKeySource(keySource); keyLoader.getKeysWithoutId(); keyLoader.getKey("exampleKid"); assertThat(keyLoader.getTotalNumberOfKeys()).isEqualTo(2); } @Test public void shouldNotRemoveKeysIfReloadingFailed() { AtomicBoolean loaded = new AtomicBoolean(); AtomicBoolean thrown = new AtomicBoolean(); RsaPublicKeyLoader rsaPublicKeyLoader = new RsaPublicKeyLoader(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (loaded.getAndSet(true)) { thrown.set(true); throw new KeyLoadFailedException(); } return singletonList( new LoadedPublicKey("the-kid", Mockito.mock(RSAPublicKey.class), this)); } }; rsaPublicKeyLoader.addKeySource(keySource); assertThat(rsaPublicKeyLoader.getKey("the-kid")).isNotNull(); assertThat(loaded).isTrue(); assertThat(rsaPublicKeyLoader.getTotalNumberOfKeys()).isEqualTo(1); rsaPublicKeyLoader.getKey("unknown-key-id"); assertThat(rsaPublicKeyLoader.getTotalNumberOfKeys()).isEqualTo(1); assertThat(thrown).isTrue(); } }
UTF-8
Java
7,647
java
RsaPublicKeyLoaderTest.java
Java
[]
null
[]
package org.sdase.commons.server.auth.key; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import java.security.interfaces.RSAPublicKey; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.mockito.Mockito; public class RsaPublicKeyLoaderTest { private RsaPublicKeyLoader keyLoader = new RsaPublicKeyLoader(); @Test public void shouldAddKeyWithoutKid() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return singletonList(new LoadedPublicKey(null, mockKey, this)); } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKeysWithoutId()).containsExactly(mockKey); assertThat(keyLoader.getKey(null)).isNull(); } @Test public void shouldAddKeyWithKid() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKeysWithoutId()).isEmpty(); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); } @Test public void shouldReloadIfKeyIsNotFoundAndRemoveOutdatedKeys() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); RSAPublicKey newMockKey = Mockito.mock(RSAPublicKey.class); AtomicInteger numberOfCalls = new AtomicInteger(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (numberOfCalls.getAndIncrement() < 1) { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } else { return singletonList(new LoadedPublicKey("newKid", newMockKey, this)); } } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); // no reload for known key assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("newKid")).isSameAs(newMockKey); assertThat(numberOfCalls.get()).isEqualTo(2); assertThat(keyLoader.getKey("exampleKid")).isNull(); assertThat(numberOfCalls.get()).isEqualTo(3); } @Test public void shouldReloadIfKeyIsNotFound() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); RSAPublicKey newMockKey = Mockito.mock(RSAPublicKey.class); AtomicInteger numberOfCalls = new AtomicInteger(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (numberOfCalls.getAndIncrement() < 1) { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } else { return Arrays.asList( new LoadedPublicKey("exampleKid", mockKey, this), new LoadedPublicKey("newKid", newMockKey, this)); } } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); // no reload for known key assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("newKid")).isSameAs(newMockKey); assertThat(numberOfCalls.get()).isEqualTo(2); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(2); } @Test public void shouldNotRemoveIfReloadFails() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); AtomicInteger numberOfCalls = new AtomicInteger(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (numberOfCalls.getAndIncrement() < 1) { return singletonList(new LoadedPublicKey("exampleKid", mockKey, this)); } else { throw new KeyLoadFailedException("Test error"); } } }; keyLoader.addKeySource(keySource); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); // no reload for known key assertThat(numberOfCalls.get()).isEqualTo(1); assertThat(keyLoader.getKey("newKid")).isNull(); assertThat(numberOfCalls.get()).isEqualTo(2); assertThat(keyLoader.getKey("exampleKid")).isSameAs(mockKey); assertThat(numberOfCalls.get()).isEqualTo(2); } @Test public void shouldCountSources() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return singletonList(new LoadedPublicKey(null, mockKey, this)); } }; assertThat(keyLoader.getTotalNumberOfKeySources()).isEqualTo(0); keyLoader.addKeySource(keySource); keyLoader.getKeysWithoutId(); keyLoader.getKey("exampleKid"); assertThat(keyLoader.getTotalNumberOfKeySources()).isEqualTo(1); } @Test public void shouldCountAllKeys() { RSAPublicKey mockKey = Mockito.mock(RSAPublicKey.class); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { return Arrays.asList( new LoadedPublicKey(null, mockKey, this), new LoadedPublicKey("exampleKid", mockKey, this)); } }; assertThat(keyLoader.getTotalNumberOfKeys()).isEqualTo(0); keyLoader.addKeySource(keySource); keyLoader.getKeysWithoutId(); keyLoader.getKey("exampleKid"); assertThat(keyLoader.getTotalNumberOfKeys()).isEqualTo(2); } @Test public void shouldNotRemoveKeysIfReloadingFailed() { AtomicBoolean loaded = new AtomicBoolean(); AtomicBoolean thrown = new AtomicBoolean(); RsaPublicKeyLoader rsaPublicKeyLoader = new RsaPublicKeyLoader(); KeySource keySource = new KeySource() { @Override public List<LoadedPublicKey> loadKeysFromSource() throws KeyLoadFailedException { if (loaded.getAndSet(true)) { thrown.set(true); throw new KeyLoadFailedException(); } return singletonList( new LoadedPublicKey("the-kid", Mockito.mock(RSAPublicKey.class), this)); } }; rsaPublicKeyLoader.addKeySource(keySource); assertThat(rsaPublicKeyLoader.getKey("the-kid")).isNotNull(); assertThat(loaded).isTrue(); assertThat(rsaPublicKeyLoader.getTotalNumberOfKeys()).isEqualTo(1); rsaPublicKeyLoader.getKey("unknown-key-id"); assertThat(rsaPublicKeyLoader.getTotalNumberOfKeys()).isEqualTo(1); assertThat(thrown).isTrue(); } }
7,647
0.681967
0.679221
223
33.291481
27.194372
91
false
false
0
0
0
0
0
0
0.55157
false
false
5
d7aed81bdc5953bbb8003f6d45a91a43c870d5ae
26,018,911,898,925
19de1c1438d9def7cdcc61a4a58c65bbcb143642
/project_folder/src/SWEA/SWEA_5987.java
432e0797b3dbe211c2b8b93cff4f9cff45f90e3d
[ "MIT" ]
permissive
stevejhkang/algorithm-quiz
https://github.com/stevejhkang/algorithm-quiz
aa977586796976492e312ee68b7e2a79147065fc
066f528f3993ab8ad956774b0216712fee4b124d
refs/heads/master
2021-07-16T06:08:44.732000
2020-06-06T03:51:04
2020-06-06T03:51:04
168,269,370
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package SWEA; /** * @author steve.jh.kang@gmail.com * @time 2020. 3. 19. 오후 5:56:53 * @category * @problem_description 두사람끼리 누가 먼저 들어왔는지에 대한 정보 m개만 남아있다. * n명의 사람이 들어오는 순서로 가능한 모든 경우의 수를 구하는 프로그램 작성하라 * x y 라 할때 x가 먼저 완주했음 * @solving_description * */ public class SWEA_5987 { public static void main(String[] args) { } }
UTF-8
Java
475
java
SWEA_5987.java
Java
[ { "context": "package SWEA;\n\n/**\n * @author steve.jh.kang@gmail.com\n * @time 2020. 3. 19. 오후 5:56:53\n * @category \n* ", "end": 53, "score": 0.9998378753662109, "start": 30, "tag": "EMAIL", "value": "steve.jh.kang@gmail.com" } ]
null
[]
package SWEA; /** * @author <EMAIL> * @time 2020. 3. 19. 오후 5:56:53 * @category * @problem_description 두사람끼리 누가 먼저 들어왔는지에 대한 정보 m개만 남아있다. * n명의 사람이 들어오는 순서로 가능한 모든 경우의 수를 구하는 프로그램 작성하라 * x y 라 할때 x가 먼저 완주했음 * @solving_description * */ public class SWEA_5987 { public static void main(String[] args) { } }
459
0.656716
0.608955
18
17.611111
17.711073
57
false
false
0
0
0
0
0
0
0.277778
false
false
5
79ef07ccee563e7176ed86b6a416bcb379bdef3e
24,541,443,174,241
69006e4e166dfb3605dc2f2cea05898d6e90bdfa
/IntermediateRepresentation/src/org/shinar/neutral/representation/CodeGroup.java
667a563223f9136c718c32fe1aa61cb8a2a8a8ae
[]
no_license
marcoapintoo/ShinarProject
https://github.com/marcoapintoo/ShinarProject
493fcc36638562b9c4ba4eb798e31998b62bb8da
9303233713519b4207c776349a1a9e0d4e613670
refs/heads/master
2021-01-22T07:32:27.474000
2014-06-25T05:06:24
2014-06-25T05:06:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.shinar.neutral.representation; import lombok.AccessLevel; import lombok.Data; import lombok.Setter; import java.util.ArrayList; import java.util.List; /** * Created by marco on 24/06/14. */ @Data public class CodeGroup { @Setter(AccessLevel.PROTECTED) List<NeutralCodeUnit> units = new ArrayList<NeutralCodeUnit>(); }
UTF-8
Java
343
java
CodeGroup.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by marco on 24/06/14.\n */\n@Data\npublic class CodeGroup {\n ", "end": 189, "score": 0.9094635844230652, "start": 184, "tag": "USERNAME", "value": "marco" } ]
null
[]
package org.shinar.neutral.representation; import lombok.AccessLevel; import lombok.Data; import lombok.Setter; import java.util.ArrayList; import java.util.List; /** * Created by marco on 24/06/14. */ @Data public class CodeGroup { @Setter(AccessLevel.PROTECTED) List<NeutralCodeUnit> units = new ArrayList<NeutralCodeUnit>(); }
343
0.752187
0.734694
17
19.17647
17.974607
67
false
false
0
0
0
0
0
0
0.411765
false
false
5
cf162d422e64bd1b1bdfbdc6e0d8450be164535c
3,985,729,673,395
04cc91e3dc9c5f0583b2987c4b8393c8ddd81b6f
/BDD-Lumens-Test1/src/test/java/utilities/ScreenshotHelper.java
5dbb45d70ba9171d05f7a41b1821896737330fa4
[]
no_license
sailajagottipati29/selenium
https://github.com/sailajagottipati29/selenium
97dbd10058b9ab78a7c15efce671f2a3508d8c43
f0209906168812f29371fa5d8a1f3715b8862378
refs/heads/master
2023-04-04T10:20:18.373000
2021-04-12T10:54:04
2021-04-12T10:54:04
357,156,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utilities; public class ScreenshotHelper { }
UTF-8
Java
60
java
ScreenshotHelper.java
Java
[]
null
[]
package utilities; public class ScreenshotHelper { }
60
0.716667
0.716667
5
10
12.537943
31
false
false
0
0
0
0
0
0
0.2
false
false
5
89c1e422c32aeb746d1f610c5817e26493d0381b
21,354,577,426,080
347198779d39b9c9ef6c29e2a3b911146c5d9add
/src/main/java/com/cjm721/overloaded/block/basic/BlockTeamLoader.java
530c5bd6d4601e9a7a078fa270b1e01a78351011
[ "BSD-3-Clause" ]
permissive
CJ-MC-Mods/Overloaded
https://github.com/CJ-MC-Mods/Overloaded
bfa56d95e44cd44b64a027b2381637a02478f79b
917b0bdcd206461cd0f232baed5917d71129e76b
refs/heads/1.16
2023-04-06T02:54:06.038000
2023-03-27T05:09:28
2023-03-27T05:09:28
87,017,167
20
10
NOASSERTION
false
2021-05-31T23:37:05
2017-04-02T21:25:04
2021-05-31T23:35:00
2021-05-31T23:34:57
1,893
16
5
7
Java
false
false
package com.cjm721.overloaded.block.basic; import com.cjm721.overloaded.block.ModBlock; import com.cjm721.overloaded.tile.functional.TileTeamLoader; import net.minecraft.block.BlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockReader; import javax.annotation.Nullable; public class BlockTeamLoader extends ModBlock { public BlockTeamLoader() { super(getDefaultProperties()); setRegistryName("team_loader"); } @Override public void registerModel() { } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) { return new TileTeamLoader(); } }
UTF-8
Java
679
java
BlockTeamLoader.java
Java
[ { "context": "package com.cjm721.overloaded.block.basic;\n\nimport com.cjm721.overlo", "end": 18, "score": 0.693222165107727, "start": 14, "tag": "USERNAME", "value": "m721" }, { "context": " com.cjm721.overloaded.block.basic;\n\nimport com.cjm721.overloaded.block.ModBlock;\nimport com.cjm721.over", "end": 61, "score": 0.7753313779830933, "start": 57, "tag": "USERNAME", "value": "m721" }, { "context": "om.cjm721.overloaded.block.ModBlock;\nimport com.cjm721.overloaded.tile.functional.TileTeamLoader;\nimport", "end": 106, "score": 0.7880498170852661, "start": 102, "tag": "USERNAME", "value": "m721" } ]
null
[]
package com.cjm721.overloaded.block.basic; import com.cjm721.overloaded.block.ModBlock; import com.cjm721.overloaded.tile.functional.TileTeamLoader; import net.minecraft.block.BlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockReader; import javax.annotation.Nullable; public class BlockTeamLoader extends ModBlock { public BlockTeamLoader() { super(getDefaultProperties()); setRegistryName("team_loader"); } @Override public void registerModel() { } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) { return new TileTeamLoader(); } }
679
0.748159
0.734904
26
25.115385
21.589397
78
false
false
0
0
0
0
0
0
0.423077
false
false
5
eb8f2ebc2528c8a4cc9fcbf1473fed2f529ee4c7
35,021,163,386,878
3ea47c184c8e67b6dd11c122c781a67320be81c2
/test/AtomApp.java
7812d82a168835ee62f259338963cbd9a34873ff
[]
no_license
c21lzwastaken/DataStructuresAlgorithms
https://github.com/c21lzwastaken/DataStructuresAlgorithms
af8a25e3e1122ad4922de2a09bdd26a70ccce89d
96a76f6e0b37c6ce9df58949c298431c7df80df1
refs/heads/master
2023-05-29T07:20:37.490000
2021-06-18T15:16:04
2021-06-18T15:16:04
267,396,747
0
0
null
true
2020-05-27T18:30:27
2020-05-27T18:30:26
2019-09-04T15:27:30
2019-09-04T15:27:28
1
0
0
0
null
false
false
public class AtomApp { public static void main(String[] args) { Atom Carbon1 = new Atom("C", 4); Atom Carbon2 = new Atom("C", 4); Atom Hydrogen1 = new Atom("H", 1); Atom Hydrogen2 = new Atom("H", 1); Atom Hydrogen3 = new Atom("H", 1); Atom Helium = new Atom("H", 2); Carbon1.bondWith(Hydrogen1); Carbon1.bondWith(Hydrogen2); Carbon1.bondWith(Hydrogen3); Carbon1.bondWith(Carbon2); Carbon1.bondWith(Helium); for (int i = -1; i < Carbon1.getBondsSize(); i++) { if(i==-1){ System.out.print(Carbon1.getSymbol()); } else{ System.out.print("-" + Carbon1.getBonds(i)); } } System.out.println(); System.out.println(Atom.showBonds(Carbon1)); } }
UTF-8
Java
848
java
AtomApp.java
Java
[]
null
[]
public class AtomApp { public static void main(String[] args) { Atom Carbon1 = new Atom("C", 4); Atom Carbon2 = new Atom("C", 4); Atom Hydrogen1 = new Atom("H", 1); Atom Hydrogen2 = new Atom("H", 1); Atom Hydrogen3 = new Atom("H", 1); Atom Helium = new Atom("H", 2); Carbon1.bondWith(Hydrogen1); Carbon1.bondWith(Hydrogen2); Carbon1.bondWith(Hydrogen3); Carbon1.bondWith(Carbon2); Carbon1.bondWith(Helium); for (int i = -1; i < Carbon1.getBondsSize(); i++) { if(i==-1){ System.out.print(Carbon1.getSymbol()); } else{ System.out.print("-" + Carbon1.getBonds(i)); } } System.out.println(); System.out.println(Atom.showBonds(Carbon1)); } }
848
0.51533
0.48467
28
29.285715
18.236261
60
false
false
0
0
0
0
0
0
0.821429
false
false
5
a19d7b62ce11d1a84be8ac081c6fb7a267daa849
34,368,328,360,820
8ae880c7a72d7564f2ecf0d498ca6a08cf5f5a7c
/app/src/main/java/sse/tongji/hair/activity/SelectPicPopUpWindow.java
54e36a637786f5b3ca8d5f14e4d9c3f3fa34081c
[]
no_license
since2014/hair1
https://github.com/since2014/hair1
c75ca0b7d62d65970d37d9f3408864f3862c5f6e
03337e01cfd29347276389d32ff1421c690c9c9e
refs/heads/master
2019-07-09T21:31:59.968000
2015-09-20T04:10:40
2015-09-20T04:10:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sse.tongji.hair.activity; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.PopupWindow; import sse.tongji.hair.R; /** * Created by LLLLLyj on 2015/9/20. */ public class SelectPicPopUpWindow extends PopupWindow { private Button pic_camera; private Button pic_gallery; private Button cancel_btn; private View menuView; public SelectPicPopUpWindow(Activity context, View.OnClickListener itemOnClick){ super(context); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); menuView = inflater.inflate(R.layout.bottom_popup, null); pic_camera = (Button)menuView.findViewById(R.id.popup_pick_from_photo); pic_gallery = (Button)menuView.findViewById(R.id.popup_pick_from_gallery); cancel_btn = (Button)menuView.findViewById(R.id.popup_pick_dismiss); cancel_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); pic_gallery.setOnClickListener(itemOnClick); pic_camera.setOnClickListener(itemOnClick); this.setContentView(menuView); this.setAnimationStyle(R.style.Animation_AppCompat_DropDownUp); this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT); this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); ColorDrawable dw = new ColorDrawable(0xb0000000); this.setBackgroundDrawable(dw); menuView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { int height = menuView.findViewById(R.id.popup_window).getTop(); int y = (int) motionEvent.getY(); if(motionEvent.getAction() == MotionEvent.ACTION_UP){ if(y < height) dismiss(); } return false; } }); } }
UTF-8
Java
2,307
java
SelectPicPopUpWindow.java
Java
[ { "context": "dow;\n\nimport sse.tongji.hair.R;\n\n/**\n * Created by LLLLLyj on 2015/9/20.\n */\npublic class SelectPicPopUpWind", "end": 428, "score": 0.9994178414344788, "start": 421, "tag": "USERNAME", "value": "LLLLLyj" } ]
null
[]
package sse.tongji.hair.activity; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.PopupWindow; import sse.tongji.hair.R; /** * Created by LLLLLyj on 2015/9/20. */ public class SelectPicPopUpWindow extends PopupWindow { private Button pic_camera; private Button pic_gallery; private Button cancel_btn; private View menuView; public SelectPicPopUpWindow(Activity context, View.OnClickListener itemOnClick){ super(context); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); menuView = inflater.inflate(R.layout.bottom_popup, null); pic_camera = (Button)menuView.findViewById(R.id.popup_pick_from_photo); pic_gallery = (Button)menuView.findViewById(R.id.popup_pick_from_gallery); cancel_btn = (Button)menuView.findViewById(R.id.popup_pick_dismiss); cancel_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); pic_gallery.setOnClickListener(itemOnClick); pic_camera.setOnClickListener(itemOnClick); this.setContentView(menuView); this.setAnimationStyle(R.style.Animation_AppCompat_DropDownUp); this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT); this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); ColorDrawable dw = new ColorDrawable(0xb0000000); this.setBackgroundDrawable(dw); menuView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { int height = menuView.findViewById(R.id.popup_window).getTop(); int y = (int) motionEvent.getY(); if(motionEvent.getAction() == MotionEvent.ACTION_UP){ if(y < height) dismiss(); } return false; } }); } }
2,307
0.663199
0.656697
66
33.954544
24.984499
84
false
false
0
0
0
0
0
0
0.606061
false
false
5
c5b5f1d5b966bd0c7d81ae8b5f715951264b2c92
37,615,323,614,809
104b421e536d1667a70f234ec61864f9278137c4
/code/com/radiusnetworks/ibeacon/service/RegionData.java
2893168bfb1aa1fd448b27aecc8ecfce57623170
[]
no_license
AshwiniVijayaKumar/Chrome-Cars
https://github.com/AshwiniVijayaKumar/Chrome-Cars
f2e61347c7416d37dae228dfeaa58c3845c66090
6a5e824ad5889f0e29d1aa31f7a35b1f6894f089
refs/heads/master
2021-01-15T11:07:57.050000
2016-05-13T05:01:09
2016-05-13T05:01:09
58,521,050
1
0
null
true
2016-05-11T06:51:56
2016-05-11T06:51:56
2016-05-06T14:21:56
2016-05-11T06:20:45
45,786
0
0
0
null
null
null
package com.radiusnetworks.ibeacon.service; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import com.radiusnetworks.ibeacon.Region; public class RegionData extends Region implements Parcelable { public static final Parcelable.Creator<RegionData> CREATOR = new Parcelable.Creator() { public RegionData createFromParcel(Parcel paramAnonymousParcel) { return new RegionData(paramAnonymousParcel, null); } public RegionData[] newArray(int paramAnonymousInt) { return new RegionData[paramAnonymousInt]; } }; private RegionData(Parcel paramParcel) { this.major = Integer.valueOf(paramParcel.readInt()); if (this.major.intValue() == -1) { this.major = null; } this.minor = Integer.valueOf(paramParcel.readInt()); if (this.minor.intValue() == -1) { this.minor = null; } this.proximityUuid = paramParcel.readString(); this.uniqueId = paramParcel.readString(); } public RegionData(Region paramRegion) { super(paramRegion); } public RegionData(String paramString1, String paramString2, Integer paramInteger1, Integer paramInteger2) { super(paramString1, paramString2, paramInteger1, paramInteger2); } public int describeContents() { return 0; } public void writeToParcel(Parcel paramParcel, int paramInt) { int i = -1; if (this.major == null) { paramInt = -1; paramParcel.writeInt(paramInt); if (this.minor != null) { break label58; } } label58: for (paramInt = i;; paramInt = this.minor.intValue()) { paramParcel.writeInt(paramInt); paramParcel.writeString(this.proximityUuid); paramParcel.writeString(this.uniqueId); return; paramInt = this.major.intValue(); break; } } } /* Location: C:\Users\ADMIN\Desktop\foss\dex2jar-2.0\classes-dex2jar.jar!\com\radiusnetworks\ibeacon\service\RegionData.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
2,076
java
RegionData.java
Java
[]
null
[]
package com.radiusnetworks.ibeacon.service; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import com.radiusnetworks.ibeacon.Region; public class RegionData extends Region implements Parcelable { public static final Parcelable.Creator<RegionData> CREATOR = new Parcelable.Creator() { public RegionData createFromParcel(Parcel paramAnonymousParcel) { return new RegionData(paramAnonymousParcel, null); } public RegionData[] newArray(int paramAnonymousInt) { return new RegionData[paramAnonymousInt]; } }; private RegionData(Parcel paramParcel) { this.major = Integer.valueOf(paramParcel.readInt()); if (this.major.intValue() == -1) { this.major = null; } this.minor = Integer.valueOf(paramParcel.readInt()); if (this.minor.intValue() == -1) { this.minor = null; } this.proximityUuid = paramParcel.readString(); this.uniqueId = paramParcel.readString(); } public RegionData(Region paramRegion) { super(paramRegion); } public RegionData(String paramString1, String paramString2, Integer paramInteger1, Integer paramInteger2) { super(paramString1, paramString2, paramInteger1, paramInteger2); } public int describeContents() { return 0; } public void writeToParcel(Parcel paramParcel, int paramInt) { int i = -1; if (this.major == null) { paramInt = -1; paramParcel.writeInt(paramInt); if (this.minor != null) { break label58; } } label58: for (paramInt = i;; paramInt = this.minor.intValue()) { paramParcel.writeInt(paramInt); paramParcel.writeString(this.proximityUuid); paramParcel.writeString(this.uniqueId); return; paramInt = this.major.intValue(); break; } } } /* Location: C:\Users\ADMIN\Desktop\foss\dex2jar-2.0\classes-dex2jar.jar!\com\radiusnetworks\ibeacon\service\RegionData.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
2,076
0.671484
0.657996
82
24.329268
26.107683
138
false
false
0
0
0
0
0
0
0.451219
false
false
5
4c4fd4e60184949e0b28d47de4d6f7ed9f624b0a
39,539,468,953,004
8f95082ec9d3a78f0799202462f84d05a167f292
/app/src/main/java/com/peoit/android/online/pschool/ui/activity/FeatureActivity.java
89276649f3b36fd0b613d570f37138f886832782
[]
no_license
l612714/pSchool
https://github.com/l612714/pSchool
98b296f5ea50d272b3c28290731bee833bf8ceda
2d5efa39dafc18baa3ccdb89aed9bae6d12b7ebf
refs/heads/master
2021-01-24T16:09:36.170000
2015-11-19T03:23:31
2015-11-19T03:23:31
38,604,310
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.peoit.android.online.pschool.ui.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.peoit.android.online.pschool.R; import com.peoit.android.online.pschool.ui.Base.BaseActivity; import com.peoit.android.online.pschool.ui.Presenter.FeaturePersenter; import com.peoit.android.online.pschool.ui.adapter.FeatureAdapter; /** * 专栏界面...学校专栏 * <p/> * <p/> * author:libo * time:2015/7/14 * E-mail:boli_android@163.com * last: ... */ public class FeatureActivity extends BaseActivity implements View.OnClickListener { private ListView list; private TextView tvItem1; private TextView tvItem2; private TextView tvItem3; private TextView tvItem4; private View pullList_header; private FeaturePersenter featurePersenter; private FeatureAdapter featureAdapter; public static void startThisActivity(Activity mAc) { Intent intent = new Intent(mAc, FeatureActivity.class); mAc.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_list_layout_nopadding); } @Override public void initData() { featureAdapter = new FeatureAdapter(mContext, R.layout.act_feature_item, null); featurePersenter = new FeaturePersenter(this, featureAdapter); } @Override public void initView() { getPsActionBar().settitle("网校专栏"); list = (ListView) findViewById(R.id.list); addHeaderView(); list.setAdapter(featureAdapter); featurePersenter.loadData(); } /** * 添加listViewHeader */ private void addHeaderView() { pullList_header = getLayoutInflater().inflate(R.layout.act_feature_header, null); tvItem1 = (TextView) pullList_header.findViewById(R.id.tv_item1); tvItem2 = (TextView) pullList_header.findViewById(R.id.tv_item2); tvItem3 = (TextView) pullList_header.findViewById(R.id.tv_item3); tvItem4 = (TextView) pullList_header.findViewById(R.id.tv_item4); list.addHeaderView(pullList_header, null, true); list.setHeaderDividersEnabled(false); } @Override public void initListener() { tvItem1.setOnClickListener(this); tvItem2.setOnClickListener(this); tvItem3.setOnClickListener(this); tvItem4.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_item1: //家长课堂 // ParentsClassroomActivity.startThisActivity(mContext); ParentClassActivity.startThisActivity(mContext); break; case R.id.tv_item2: //健康顾问 HealthEducationActivity.startThisActivity(mContext); break; case R.id.tv_item3: //亲子活动 // FamilyActivitiy.startThisActivity(mContext); ParentChildAreaActivity.startThisActivity(mContext); break; case R.id.tv_item4: //专家在线 // ExpertsOnlineActivity.startThisActivity(mContext); QuizActivity.startThisActivity(mContext); break; } } }
UTF-8
Java
3,484
java
FeatureActivity.java
Java
[ { "context": "er;\n\n/**\n * 专栏界面...学校专栏\n * <p/>\n * <p/>\n * author:libo\n * time:2015/7/14\n * E-mail:boli_android@163.com\n", "end": 525, "score": 0.9989809989929199, "start": 521, "tag": "USERNAME", "value": "libo" }, { "context": "* <p/>\n * author:libo\n * time:2015/7/14\n * E-mail:boli_android@163.com\n * last: ...\n */\npublic class FeatureActivity ext", "end": 574, "score": 0.9999173879623413, "start": 554, "tag": "EMAIL", "value": "boli_android@163.com" } ]
null
[]
package com.peoit.android.online.pschool.ui.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.peoit.android.online.pschool.R; import com.peoit.android.online.pschool.ui.Base.BaseActivity; import com.peoit.android.online.pschool.ui.Presenter.FeaturePersenter; import com.peoit.android.online.pschool.ui.adapter.FeatureAdapter; /** * 专栏界面...学校专栏 * <p/> * <p/> * author:libo * time:2015/7/14 * E-mail:<EMAIL> * last: ... */ public class FeatureActivity extends BaseActivity implements View.OnClickListener { private ListView list; private TextView tvItem1; private TextView tvItem2; private TextView tvItem3; private TextView tvItem4; private View pullList_header; private FeaturePersenter featurePersenter; private FeatureAdapter featureAdapter; public static void startThisActivity(Activity mAc) { Intent intent = new Intent(mAc, FeatureActivity.class); mAc.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_list_layout_nopadding); } @Override public void initData() { featureAdapter = new FeatureAdapter(mContext, R.layout.act_feature_item, null); featurePersenter = new FeaturePersenter(this, featureAdapter); } @Override public void initView() { getPsActionBar().settitle("网校专栏"); list = (ListView) findViewById(R.id.list); addHeaderView(); list.setAdapter(featureAdapter); featurePersenter.loadData(); } /** * 添加listViewHeader */ private void addHeaderView() { pullList_header = getLayoutInflater().inflate(R.layout.act_feature_header, null); tvItem1 = (TextView) pullList_header.findViewById(R.id.tv_item1); tvItem2 = (TextView) pullList_header.findViewById(R.id.tv_item2); tvItem3 = (TextView) pullList_header.findViewById(R.id.tv_item3); tvItem4 = (TextView) pullList_header.findViewById(R.id.tv_item4); list.addHeaderView(pullList_header, null, true); list.setHeaderDividersEnabled(false); } @Override public void initListener() { tvItem1.setOnClickListener(this); tvItem2.setOnClickListener(this); tvItem3.setOnClickListener(this); tvItem4.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_item1: //家长课堂 // ParentsClassroomActivity.startThisActivity(mContext); ParentClassActivity.startThisActivity(mContext); break; case R.id.tv_item2: //健康顾问 HealthEducationActivity.startThisActivity(mContext); break; case R.id.tv_item3: //亲子活动 // FamilyActivitiy.startThisActivity(mContext); ParentChildAreaActivity.startThisActivity(mContext); break; case R.id.tv_item4: //专家在线 // ExpertsOnlineActivity.startThisActivity(mContext); QuizActivity.startThisActivity(mContext); break; } } }
3,471
0.652453
0.643692
115
28.773912
24.344292
89
false
false
0
0
0
0
0
0
0.513043
false
false
5
0e48d2c750c2d62c1eb5deb50b9676a6cf2c90c3
39,256,001,097,746
1231807ea69532ec98e44a091c576a64998c2be5
/Basic/test1054.java
db7f33db020c318278264bf727ac7e55f0065a87
[]
no_license
MubaiLi/PAT
https://github.com/MubaiLi/PAT
6fec8ed0912a17ff4a7a89de3319fa26ab5338dd
78453e56e21bc38848a90bfea07a423701f428ac
refs/heads/master
2021-07-10T20:16:15.261000
2017-10-12T14:14:51
2017-10-12T14:14:51
103,738,421
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Basic; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class test1054 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String N_str = br.readLine(); int N = Integer.parseInt(N_str); String[] str = (br.readLine()).split(" "); int cnt = 0; double sum = 0.0; for (int i = 0; i < N; i ++) { double n; try { n = Double.parseDouble(str[i]); double tmp = Double.parseDouble(String.format("%.2f", n)); if (n < -1000 || n > 1000 || Math.abs(n - tmp) != 0) { throw new NumberFormatException(); } cnt ++; sum += n; } catch (NumberFormatException e) { System.out.println("ERROR: " + str[i] + " is not a legal number"); } } if (cnt == 0) { System.out.println("The average of 0 numbers is Undefined"); } else if (cnt == 1) { System.out.printf("The average of 1 number is %.2f", sum); } else { System.out.printf("The average of %d numbers is %.2f", cnt, sum / cnt); } } }
UTF-8
Java
1,093
java
test1054.java
Java
[]
null
[]
package Basic; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class test1054 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String N_str = br.readLine(); int N = Integer.parseInt(N_str); String[] str = (br.readLine()).split(" "); int cnt = 0; double sum = 0.0; for (int i = 0; i < N; i ++) { double n; try { n = Double.parseDouble(str[i]); double tmp = Double.parseDouble(String.format("%.2f", n)); if (n < -1000 || n > 1000 || Math.abs(n - tmp) != 0) { throw new NumberFormatException(); } cnt ++; sum += n; } catch (NumberFormatException e) { System.out.println("ERROR: " + str[i] + " is not a legal number"); } } if (cnt == 0) { System.out.println("The average of 0 numbers is Undefined"); } else if (cnt == 1) { System.out.printf("The average of 1 number is %.2f", sum); } else { System.out.printf("The average of %d numbers is %.2f", cnt, sum / cnt); } } }
1,093
0.613907
0.591949
40
26.325001
23.360638
75
false
false
0
0
0
0
0
0
2.8
false
false
5
38a761ee098cf30e32bc78bf703d45c47cb01611
26,594,437,562,374
b22a2fea51744921487b4ddb4d16cf43d9fb2429
/src/layer/InputLayer.java
441371f245d65842acad91bbf0f7f1ac56b01405
[]
no_license
DerPauli/DFFNetwork
https://github.com/DerPauli/DFFNetwork
c9418a5a96089bd3897339fdc9f0256746ac8ade
0573ce2eba84013a4690f6f09f988723f72578a2
refs/heads/master
2021-07-17T17:45:36.583000
2020-05-06T17:46:05
2020-05-06T17:46:05
148,501,351
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package layer; import core.InputNeuron; /** * * @author Paul Merker * @version 1.0.1 * Input Layer extends Layer class and provides implementations for first Layer in NN. * */ public class InputLayer extends Layer { private InputNeuron[] input; public InputLayer(int neuronCount) { super(neuronCount); this.input = new InputNeuron[neuronCount]; this.initialize(); } private void initialize() { for (int i = 0; i < this.input.length-1; ++i) { this.input[i] = new InputNeuron(); } this.input[this.input.length-1] = new InputNeuron(1); } public InputNeuron[] getInputs() { return this.input; } }
UTF-8
Java
647
java
InputLayer.java
Java
[ { "context": "ayer;\n\nimport core.InputNeuron;\n/**\n * \n * @author Paul Merker\n * @version 1.0.1\n * Input Layer extends Layer cl", "end": 71, "score": 0.9996675848960876, "start": 60, "tag": "NAME", "value": "Paul Merker" } ]
null
[]
package layer; import core.InputNeuron; /** * * @author <NAME> * @version 1.0.1 * Input Layer extends Layer class and provides implementations for first Layer in NN. * */ public class InputLayer extends Layer { private InputNeuron[] input; public InputLayer(int neuronCount) { super(neuronCount); this.input = new InputNeuron[neuronCount]; this.initialize(); } private void initialize() { for (int i = 0; i < this.input.length-1; ++i) { this.input[i] = new InputNeuron(); } this.input[this.input.length-1] = new InputNeuron(1); } public InputNeuron[] getInputs() { return this.input; } }
642
0.666151
0.655332
31
19.870968
20.703346
86
false
false
0
0
0
0
0
0
1.064516
false
false
5
79d3a6100fa53bf489b903fa5d55158305929e69
25,640,954,809,271
97dc780d83f05719fb4a6fbe99218d387cb056cc
/services/src/main/java/com/routefinder/service/common/impl/GenericServiceImpl.java
34082cc1e1a6d9b0306b1128817ffd621664518c
[]
no_license
karpukdm/routefinder
https://github.com/karpukdm/routefinder
728608c479f75959fcaa017527af8f1d8614987a
3ad48472cb88378a3ce7445c9cc6a85022b2496a
refs/heads/master
2022-07-21T14:20:46.263000
2016-05-13T17:42:50
2016-05-13T17:42:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.routefinder.service.common.impl; import com.routefinder.service.common.GenericService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Persistable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.List; /** * Created by karpukdm on 29.03.16. */ @Service @Transactional public abstract class GenericServiceImpl<T extends Persistable<ID>, ID extends Serializable, Repository extends JpaRepository<T, ID>> implements GenericService<T, ID> { @Autowired protected Repository repository; @Override public long count() { return repository.count(); } @Override public void delete(ID id) { repository.delete(id); } @Override public void delete(Iterable<? extends T> entities) { repository.delete(entities); } @Override public void delete(T entity) { repository.delete(entity); } @Override public void deleteAll() { repository.deleteAll(); } @Override public void deleteAllInBatch() { repository.deleteAllInBatch(); } @Override public void deleteInBatch(Iterable<T> entities) { repository.deleteInBatch(entities); } @Override public boolean exists(ID id) { return repository.exists(id); } @Override public List<T> findAll() { return repository.findAll(); } @Override public Iterable<T> findAll(Iterable<ID> ids) { return repository.findAll(); } @Override public Page<T> findAll(Pageable pageable) { return repository.findAll(pageable); } @Override public List<T> findAll(Sort sort) { return repository.findAll(sort); } @Override public T findOne(ID id) { return repository.findOne(id); } @Override public void flush() { repository.flush(); } @Override public <S extends T> List<S> save(Iterable<S> entities) { return repository.save(entities); } @Override public <S extends T> S save(S entity) { return repository.save(entity); } @Override public T saveAndFlush(T entity) { return repository.saveAndFlush(entity); } }
UTF-8
Java
2,565
java
GenericServiceImpl.java
Java
[ { "context": "lizable;\nimport java.util.List;\n\n/**\n * Created by karpukdm on 29.03.16.\n */\n@Service\n@Transactional\npublic a", "end": 608, "score": 0.9996654391288757, "start": 600, "tag": "USERNAME", "value": "karpukdm" } ]
null
[]
package com.routefinder.service.common.impl; import com.routefinder.service.common.GenericService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Persistable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.List; /** * Created by karpukdm on 29.03.16. */ @Service @Transactional public abstract class GenericServiceImpl<T extends Persistable<ID>, ID extends Serializable, Repository extends JpaRepository<T, ID>> implements GenericService<T, ID> { @Autowired protected Repository repository; @Override public long count() { return repository.count(); } @Override public void delete(ID id) { repository.delete(id); } @Override public void delete(Iterable<? extends T> entities) { repository.delete(entities); } @Override public void delete(T entity) { repository.delete(entity); } @Override public void deleteAll() { repository.deleteAll(); } @Override public void deleteAllInBatch() { repository.deleteAllInBatch(); } @Override public void deleteInBatch(Iterable<T> entities) { repository.deleteInBatch(entities); } @Override public boolean exists(ID id) { return repository.exists(id); } @Override public List<T> findAll() { return repository.findAll(); } @Override public Iterable<T> findAll(Iterable<ID> ids) { return repository.findAll(); } @Override public Page<T> findAll(Pageable pageable) { return repository.findAll(pageable); } @Override public List<T> findAll(Sort sort) { return repository.findAll(sort); } @Override public T findOne(ID id) { return repository.findOne(id); } @Override public void flush() { repository.flush(); } @Override public <S extends T> List<S> save(Iterable<S> entities) { return repository.save(entities); } @Override public <S extends T> S save(S entity) { return repository.save(entity); } @Override public T saveAndFlush(T entity) { return repository.saveAndFlush(entity); } }
2,565
0.670175
0.667836
113
21.699116
20.68854
92
false
false
0
0
0
0
0
0
0.300885
false
false
5
c4f80b7a6ad993f4cd74cd1d1c340ed7b3e8a3c2
9,981,504,041,159
b95513258625bba3460ea0f7a7ca1ad7641d961d
/Desenvolvimento de Software para Web/Atividade05/server/src/main/java/br/ufc/server/repository/CarRepository.java
265e180cad049fdc63e726daf0a58cb9ccd19a97
[]
no_license
FcAlex/ufc
https://github.com/FcAlex/ufc
1086104868ee2c0514ab5c378039f50788236285
ebd21e8be9e1c093302e1c3926d9cfcb13b1aba6
refs/heads/main
2023-04-25T03:09:10.933000
2021-05-11T12:11:39
2021-05-11T12:11:39
358,370,678
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ufc.server.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import br.ufc.server.model.Car; public interface CarRepository extends JpaRepository<Car, Integer>{ @Query(value = "SELECT * FROM cars LIMIT ?1", nativeQuery = true) List<Car> findCarsList(Integer qtd); @Query(value = "SELECT * FROM cars where cars.marca = ?1", nativeQuery = true) List<Car> findByMarca(String marca); }
UTF-8
Java
504
java
CarRepository.java
Java
[]
null
[]
package br.ufc.server.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import br.ufc.server.model.Car; public interface CarRepository extends JpaRepository<Car, Integer>{ @Query(value = "SELECT * FROM cars LIMIT ?1", nativeQuery = true) List<Car> findCarsList(Integer qtd); @Query(value = "SELECT * FROM cars where cars.marca = ?1", nativeQuery = true) List<Car> findByMarca(String marca); }
504
0.765873
0.761905
16
30.5
27.392973
79
false
false
0
0
0
0
0
0
0.9375
false
false
5
6fbd6975a6718d9b3c932163bb56ab9def7f671a
26,474,178,459,245
8d8f1e477306448f3d010d1222a414f5c6923e08
/app/src/main/java/com/example/nemi/vaangasapdalam1/hotel2.java
f8e9f6a960a41080527c3d7c79d742f6e69731da
[]
no_license
nemishnk/hotel
https://github.com/nemishnk/hotel
39df256c47c201a9af97c65a1a81b91741e69db5
1636edef6833b1bc953d83e5ba8d92790ac0fc68
refs/heads/master
2020-12-24T18:55:13.584000
2016-04-16T14:44:48
2016-04-16T14:44:48
56,388,924
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.nemi.vaangasapdalam1; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; public class hotel2 extends AppCompatActivity { ViewPager viewPager; customswipeadapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hotel2); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager= (ViewPager) findViewById(R.id.view_pager); adapter=new customswipeadapter(this); viewPager.setAdapter(adapter); } }
UTF-8
Java
867
java
hotel2.java
Java
[ { "context": "package com.example.nemi.vaangasapdalam1;\n\nimport android.os.Bundle;\nimpor", "end": 24, "score": 0.7999142408370972, "start": 20, "tag": "USERNAME", "value": "nemi" } ]
null
[]
package com.example.nemi.vaangasapdalam1; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; public class hotel2 extends AppCompatActivity { ViewPager viewPager; customswipeadapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hotel2); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPager= (ViewPager) findViewById(R.id.view_pager); adapter=new customswipeadapter(this); viewPager.setAdapter(adapter); } }
867
0.754325
0.747405
29
28.896551
21.748318
63
false
false
0
0
0
0
0
0
0.586207
false
false
5
959cea94c38195e7ce7df9c4c9843796e8f73804
34,230,889,361,828
4df9b81cc9b44d7cf1643af3c5cd9970857061f5
/Foody/app/src/main/java/com/example/quan/foody/MeoVat.java
465c06ced4f2afcc0987fdcf8caf030ec19ba16b
[]
no_license
quanduy2505/android-app-demo
https://github.com/quanduy2505/android-app-demo
22a647f8340f06ec7e67ff52edf18e60a14a9a9f
85e2aa2175b50a9f7c0d8fce0c9a11b4a31992ae
refs/heads/master
2020-03-30T03:12:48.436000
2018-09-28T04:01:30
2018-09-28T04:01:30
150,675,989
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.quan.foody; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MeoVat extends AppCompatActivity { ListView listView; Customadater customadater; ArrayList<DocTin> mangdocbao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mon_an); listView=(ListView) findViewById(R.id.listView); mangdocbao=new ArrayList<DocTin>(); runOnUiThread(new Runnable() { @Override public void run() { new Readdata().execute("http://vnexpress.net/rss/gia-dinh.rss"); } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MeoVat.this,WebView1.class); intent.putExtra("link",mangdocbao.get(position).link); startActivity(intent); } }); } class Readdata extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... params) { return docNoiDung_Tu_URL(params[0]); } @Override protected void onPostExecute(String s) { XMLDOMParser parser = new XMLDOMParser(); Document document = parser.getDocument(s); NodeList nodeList = document.getElementsByTagName("item"); NodeList nodeListdescription =document.getElementsByTagName("description"); String hinhanh = ""; String title = ""; String link = ""; for(int i=0; i<nodeList.getLength();i++){ String cdata=nodeListdescription.item(i + 1).getTextContent(); Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"); Matcher matcher = p.matcher(cdata); if(matcher.find()){ hinhanh = matcher.group(1); Log.d("hinhanh",hinhanh + "........." + i); } Element element = (Element) nodeList.item(i); title +=parser.getValue(element,"title"); link=parser.getValue(element,"link"); mangdocbao.add(new DocTin(title,link,hinhanh)); } customadater = new Customadater(MeoVat.this,android.R.layout.simple_list_item_1,mangdocbao); listView.setAdapter(customadater); super.onPostExecute(s); } } private String docNoiDung_Tu_URL(String theUrl){ StringBuilder content = new StringBuilder(); try { // create a url object URL url = new URL(theUrl); // create a urlconnection object URLConnection urlConnection = url.openConnection(); // wrap the urlconnection in a bufferedreader BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; // read from the urlconnection via the bufferedreader while ((line = bufferedReader.readLine()) != null){ content.append(line + "\n"); } bufferedReader.close(); } catch(Exception e) { e.printStackTrace(); } return content.toString(); } }
UTF-8
Java
3,995
java
MeoVat.java
Java
[]
null
[]
package com.example.quan.foody; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MeoVat extends AppCompatActivity { ListView listView; Customadater customadater; ArrayList<DocTin> mangdocbao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mon_an); listView=(ListView) findViewById(R.id.listView); mangdocbao=new ArrayList<DocTin>(); runOnUiThread(new Runnable() { @Override public void run() { new Readdata().execute("http://vnexpress.net/rss/gia-dinh.rss"); } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MeoVat.this,WebView1.class); intent.putExtra("link",mangdocbao.get(position).link); startActivity(intent); } }); } class Readdata extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... params) { return docNoiDung_Tu_URL(params[0]); } @Override protected void onPostExecute(String s) { XMLDOMParser parser = new XMLDOMParser(); Document document = parser.getDocument(s); NodeList nodeList = document.getElementsByTagName("item"); NodeList nodeListdescription =document.getElementsByTagName("description"); String hinhanh = ""; String title = ""; String link = ""; for(int i=0; i<nodeList.getLength();i++){ String cdata=nodeListdescription.item(i + 1).getTextContent(); Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"); Matcher matcher = p.matcher(cdata); if(matcher.find()){ hinhanh = matcher.group(1); Log.d("hinhanh",hinhanh + "........." + i); } Element element = (Element) nodeList.item(i); title +=parser.getValue(element,"title"); link=parser.getValue(element,"link"); mangdocbao.add(new DocTin(title,link,hinhanh)); } customadater = new Customadater(MeoVat.this,android.R.layout.simple_list_item_1,mangdocbao); listView.setAdapter(customadater); super.onPostExecute(s); } } private String docNoiDung_Tu_URL(String theUrl){ StringBuilder content = new StringBuilder(); try { // create a url object URL url = new URL(theUrl); // create a urlconnection object URLConnection urlConnection = url.openConnection(); // wrap the urlconnection in a bufferedreader BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; // read from the urlconnection via the bufferedreader while ((line = bufferedReader.readLine()) != null){ content.append(line + "\n"); } bufferedReader.close(); } catch(Exception e) { e.printStackTrace(); } return content.toString(); } }
3,995
0.604005
0.601502
112
34.669643
25.503286
118
false
false
0
0
0
0
0
0
0.6875
false
false
5
2da086dd3d2a2cdcdd65463707d39c0ea80a4436
5,609,227,314,672
14e2f68d73537c0a9446ccec1d662bb730f10832
/src/tienda/Usuarios.java
ab9b534b5018bc3958365aee5f493220c0ef4274
[]
no_license
Rosa22/tiendita
https://github.com/Rosa22/tiendita
309e15eccc8a97f2d7b9fca6636d52571a8f18a0
d2a0944be2ff3cc6260d0f0a608cfb3d3663090c
refs/heads/master
2021-04-12T03:25:44.407000
2018-03-19T03:56:41
2018-03-19T03:56:41
125,796,799
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tienda; /** * * @author rosac */ public class Usuarios { private String nombreu; private String passu; public Usuarios(String nombreu, String passu){ this.nombreu = nombreu; this.passu = passu; } public void setNombre(String nombreu){ this.nombreu = nombreu; } public String getNombre(){ return nombreu; } public void setPass(String passu){ this.passu = passu; } public String getPass(){ return passu; } }//class
UTF-8
Java
764
java
Usuarios.java
Java
[ { "context": "the editor.\n */\npackage tienda;\n\n/**\n *\n * @author rosac\n */\npublic class Usuarios {\n private String no", "end": 225, "score": 0.9995691776275635, "start": 220, "tag": "USERNAME", "value": "rosac" } ]
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 tienda; /** * * @author rosac */ public class Usuarios { private String nombreu; private String passu; public Usuarios(String nombreu, String passu){ this.nombreu = nombreu; this.passu = passu; } public void setNombre(String nombreu){ this.nombreu = nombreu; } public String getNombre(){ return nombreu; } public void setPass(String passu){ this.passu = passu; } public String getPass(){ return passu; } }//class
764
0.587696
0.587696
43
16.767443
17.606602
79
false
false
0
0
0
0
0
0
0.302326
false
false
5
3ad257bd1a206c736c231a2f1cd2c734b43a5201
26,680,336,896,463
e01454c675daf38a5ea0b19560b4c31386894326
/src/view/Main.java
1f01add775ed89034ba58c0a561f6577375061e0
[]
no_license
assis009/AulaThread04
https://github.com/assis009/AulaThread04
f41bf56774d7cf3ccea47702ba046cc0a15c2ce8
7e55a38d1831b1d317dc70d1142b4062783f57fa
refs/heads/master
2022-12-18T05:37:40.338000
2020-09-15T00:11:29
2020-09-15T00:11:29
295,568,158
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package view; import controller.ThreadSapo; // OBJETIVO: corrida de sapo public class Main { public static void main (String args[]){ for(int i=0; i<5; i++){// chama as threads que controlam os sapos da corrida Thread sapo = new ThreadSapo(i+1); sapo.start(); } } }
UTF-8
Java
312
java
Main.java
Java
[]
null
[]
package view; import controller.ThreadSapo; // OBJETIVO: corrida de sapo public class Main { public static void main (String args[]){ for(int i=0; i<5; i++){// chama as threads que controlam os sapos da corrida Thread sapo = new ThreadSapo(i+1); sapo.start(); } } }
312
0.608974
0.599359
19
14.421053
19.969229
78
false
false
0
0
0
0
0
0
1.263158
false
false
5
795858373cc3020c7e3f8d4636498c19941aaf68
15,702,400,477,319
684092ddea8fa0f46e2adf4a2c1bd7d2fad386d7
/biz/src/main/java/com/tqmall/athena/bussiness/center/goods/CenterGoodsAttrManagerImpl.java
6c68b8624d2cb588403a28a56a233ffe885610e4
[]
no_license
xie-summer/athena-1
https://github.com/xie-summer/athena-1
1b90ff3d41feef88f3f0c0009c742e71994dde4b
3c1e8244142a69f7b4a127ca936d8b68425f586e
refs/heads/master
2021-06-16T04:20:20.861000
2017-05-11T07:57:18
2017-05-11T07:57:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tqmall.athena.bussiness.center.goods; import com.tqmall.athena.bean.entity.center.goods.CenterGoodsAttrDO; import com.tqmall.athena.common.bean.DataError; import com.tqmall.athena.common.utils.ResultUtil; import com.tqmall.athena.redisBiz.center.goods.CenterGoodsAttrRedisManager; import com.tqmall.core.common.entity.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by zxg on 16/11/2. * 14:54 * no bug,以后改代码的哥们,祝你好运~!! */ @Service public class CenterGoodsAttrManagerImpl implements CenterGoodsAttrManager { @Autowired private CenterGoodsAttrRedisManager attrRedisManager; @Override public Result<List<CenterGoodsAttrDO>> getGoodsAttrByGoodsId(Integer goodsId) { if(goodsId == null || goodsId < 1){ return ResultUtil.errorResult(DataError.ARG_ERROR); } List<CenterGoodsAttrDO> attrDOList = attrRedisManager.getGoodsAttrByGoodsId(goodsId); return Result.wrapSuccessfulResult(attrDOList); } }
UTF-8
Java
1,110
java
CenterGoodsAttrManagerImpl.java
Java
[ { "context": "ervice;\n\nimport java.util.List;\n\n/**\n * Created by zxg on 16/11/2.\n * 14:54\n * no bug,以后改代码的哥们,祝你好运~!!\n ", "end": 495, "score": 0.9996452331542969, "start": 492, "tag": "USERNAME", "value": "zxg" } ]
null
[]
package com.tqmall.athena.bussiness.center.goods; import com.tqmall.athena.bean.entity.center.goods.CenterGoodsAttrDO; import com.tqmall.athena.common.bean.DataError; import com.tqmall.athena.common.utils.ResultUtil; import com.tqmall.athena.redisBiz.center.goods.CenterGoodsAttrRedisManager; import com.tqmall.core.common.entity.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by zxg on 16/11/2. * 14:54 * no bug,以后改代码的哥们,祝你好运~!! */ @Service public class CenterGoodsAttrManagerImpl implements CenterGoodsAttrManager { @Autowired private CenterGoodsAttrRedisManager attrRedisManager; @Override public Result<List<CenterGoodsAttrDO>> getGoodsAttrByGoodsId(Integer goodsId) { if(goodsId == null || goodsId < 1){ return ResultUtil.errorResult(DataError.ARG_ERROR); } List<CenterGoodsAttrDO> attrDOList = attrRedisManager.getGoodsAttrByGoodsId(goodsId); return Result.wrapSuccessfulResult(attrDOList); } }
1,110
0.772222
0.762963
30
35
28.448784
93
false
false
0
0
0
0
0
0
0.533333
false
false
5
bf0c3e18d9349f36f0eaedb0b27147397179ed98
14,809,047,278,288
01020528028a03b397dc4ae8ba2f09bdcfa8fd5a
/stockSense/src/main/java/com/infigent/stocksense/PortView.java
280d89f16bf8f35a0f33f45322464c5fcfeffd7b
[]
no_license
aedahh/StockSense
https://github.com/aedahh/StockSense
57a2e8f10898eb168039078f0f0b92ac67f60e4a
595322e8fcb77d0f0e3340ee3c0649c25050e0b4
refs/heads/master
2020-04-04T08:33:29.863000
2018-11-01T23:02:55
2018-11-01T23:02:55
155,785,812
0
0
null
true
2018-11-01T22:56:51
2018-11-01T22:56:51
2017-06-06T20:17:36
2017-02-10T15:57:37
51,830
0
0
0
null
false
null
package com.infigent.stocksense; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import adapters.DatabaseHandler; import adapters.port; public class PortView extends Fragment { View view; int PORTFOLIO_ID; final int CONTEXT_MENU_EDIT =1; final int CONTEXT_MENU_DELETE =2; String DELETE_CODE, DELETE_TYPE; ImageButton refresh; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.portfolio_view, null); Bundle extras = getArguments(); final int id = extras.getInt("id"); PORTFOLIO_ID = id; final String name = extras.getString("name"); refresh = (ImageButton) view.findViewById(R.id.refresh); ImageButton add = (ImageButton) view.findViewById(R.id.addfromport); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Add a = new Add(); Bundle ex = new Bundle(); ex.putString("id", id+""); ex.putString("name", name); a.setArguments(ex); switchFragment(a); } }); final ListView lv = (ListView) view.findViewById(R.id.portfolio_view_list); registerForContextMenu(lv); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setup s = new setup(); s.execute(id); } }); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) { TextView cd = (TextView) v.findViewById(R.id.stock_code); String type = cd.getText().toString().substring(0, cd.getText().toString().indexOf(":")); String code = cd.getText().toString().substring(cd.getText().toString().indexOf(":")+1, cd.getText().toString().length()); DatabaseHandler db = new DatabaseHandler(getActivity()); List<port> trans = db.getAllTrans(PORTFOLIO_ID, code, type); ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); for(int j=0;j<trans.size();++j){ HashMap<String, String> map = new HashMap<String, String>(); port p = trans.get(j); map.put("q", String.valueOf(p.getQty())); map.put("p", String.valueOf(p.getPrice())); map.put("c", String.valueOf(p.getCom())); map.put("t", p.getBS().startsWith("B")?"Buy":"Sell"); list.add(map); } SimpleAdapter ad = new SimpleAdapter(getActivity(), list, R.layout.trans, new String[]{"t", "q", "p", "c"}, new int[]{R.id.tt, R.id.tq, R.id.tp, R.id.tc}); Dialog d = new Dialog(getActivity()); d.getWindow().setBackgroundDrawableResource(R.drawable.dialog_box); d.setTitle(cd.getText()+" Transactions"); d.setContentView(R.layout.transview); ListView lView = (ListView) d.findViewById(R.id.transList); lView.setAdapter(ad); d.show(); } }); TextView nameView = (TextView) view.findViewById(R.id.fName); nameView.setText(name); Log.d("NEW", name+id); setup s = new setup(); s.execute(id); return view; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; RelativeLayout s = (RelativeLayout) info.targetView; TextView codeView = (TextView) s.findViewById(R.id.stock_code); DELETE_TYPE = codeView.getText().toString().substring(0, codeView.getText().toString().indexOf(":")); DELETE_CODE = codeView.getText().toString().substring(codeView.getText().toString().indexOf(":")+1, codeView.getText().length()); //menu.add(Menu.NONE, CONTEXT_MENU_EDIT, Menu.NONE, "Edit"); menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete"); MenuItem.OnMenuItemClickListener listener = new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { onContextItemSelected(item); return true; } }; for (int i = 0, n = menu.size(); i < n; i++) menu.getItem(i).setOnMenuItemClickListener(listener); } @Override public boolean onContextItemSelected(MenuItem item) { Log.d("Clicked", "Menu"); switch(item.getItemId()){ case CONTEXT_MENU_EDIT: break; case CONTEXT_MENU_DELETE: AlertDialog.Builder alert = new AlertDialog.Builder( getActivity()); alert.setTitle("Delete"); alert.setMessage("Do you want delete this transaction?"); alert.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DatabaseHandler db = new DatabaseHandler(getActivity()); Log.d("VALS", String.valueOf(PORTFOLIO_ID)+ DELETE_CODE+ DELETE_TYPE); db.deleteTrans(String.valueOf(PORTFOLIO_ID), DELETE_CODE, DELETE_TYPE); setup s = new setup(); s.execute(PORTFOLIO_ID); } }); alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); break; } return super.onContextItemSelected(item); } private void switchFragment(Fragment fragment) { if (getActivity() == null) return; if (getActivity() instanceof MainActivity) { MainActivity fca = (MainActivity) getActivity(); fca.switchContent(fragment); } } public class setup extends AsyncTask<Integer, Integer, String[]> { ArrayList<HashMap<String, String>> pAdd = new ArrayList<HashMap<String, String>>(); ArrayList<HashMap<String, String>> listAdd = new ArrayList<HashMap<String, String>>(); DecimalFormat nf = new DecimalFormat("#.00"); ProgressBar fvp = (ProgressBar) view.findViewById(R.id.fvp); int errEx = 0; /* 0: okay 1: error 2: no transactions */ @Override protected void onPreExecute() { super.onPreExecute(); fvp.setVisibility(View.VISIBLE); refresh.setEnabled(false); } @Override protected String[] doInBackground(Integer... ints) { String a[] = new String[5]; int id = ints[0]; DatabaseHandler port = new DatabaseHandler(getActivity()); try { List<port> p = port.getAllPort(id); Log.d("ID HERE", ""+p.size()); JSONObject jObj = new JSONObject(); JSONArray arr = new JSONArray(); for(int i=0;i<p.size();++i){ port po = p.get(i); JSONObject jArr = new JSONObject(); jArr.put("name", po.getName()); jArr.put("code", po.getCode()); jArr.put("type", po.getType()); arr.put(jArr); } jObj.put("portfolio", arr); if(p.size()>0) { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(getResources().getString(R.string.website) + "port.php?j=" + URLEncoder.encode(jObj.toString(), "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpGet); InputStream inputStream = httpResponse.getEntity() .getContent(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream); BufferedReader bufferedReader = new BufferedReader( inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk; while ((bufferedStrChunk = bufferedReader.readLine()) != null) { stringBuilder.append(bufferedStrChunk); } Log.d("here", "DATA: "+stringBuilder.toString()); JSONObject jsonObj = new JSONObject(stringBuilder.toString()); double mktVal = 0, gl = 0, pl, orig = 0, dp=0, day = 0; ArrayList<String> stocks = new ArrayList<String>(); boolean err = false, derr=true; for (int j = 0; j < p.size(); ++j) { HashMap<String, String> m = new HashMap<String, String>(); port po = p.get(j); boolean eq = false; for(int l =0;l<stocks.size();++l) if (stocks.get(l).equals(po.getCode() + "_" + po.getType())) eq = true; if(!eq) { stocks.add(po.getCode() + "_" + po.getType()); JSONObject JO = jsonObj.getJSONObject(po.getCode() + "_" + po.getType()); if (JO.getString("3").equals("N/A")) { Log.d("Error", "N/A error trueee!!!!"); err = true; derr=true; //break; } if (!err) { NumberFormat format = NumberFormat.getInstance(Locale.US); Number number = format.parse(JO.getString("2").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0")); Double cVal = number.doubleValue(); Number oVal = format.parse(JO.getString("4").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0"). replace("\n", "")); Number dll = format.parse(JO.getString("3"). replace("+", "").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0")); Double ol = oVal.doubleValue(); double spl = 0, dpl = 0; int shares = 0; double den = 0; day = 0; double smtVal = 0; for (int l = j; l < p.size(); ++l) { port portfolio = p.get(l); if ((portfolio.getCode() + "_" + portfolio.getType()).equals(po.getCode() + "_" + po.getType())) { if (portfolio.getBS().startsWith("B")) { spl += (cVal - portfolio.getPrice()) * portfolio.getQty() - portfolio.getCom(); dpl += dll.doubleValue() * portfolio.getQty(); mktVal += cVal * portfolio.getQty(); smtVal += cVal * portfolio.getQty(); shares += portfolio.getQty(); } else { spl += (cVal - portfolio.getPrice()) * (-portfolio.getQty()) - portfolio.getCom(); dpl += dll.doubleValue() * -portfolio.getQty(); mktVal += cVal * -portfolio.getQty(); smtVal += cVal * -portfolio.getQty(); shares -= portfolio.getQty(); Log.d("DPL", "Price-->" + (cVal - Double.parseDouble(JO.getString("3")))); } orig += portfolio.getPrice() * portfolio.getQty(); den += portfolio.getPrice() * portfolio.getQty(); day += (cVal - Double.parseDouble(JO.getString("3"))) * portfolio.getQty(); } } gl += spl; dp += dpl; double perc = spl * 100 / den; m.put("name", po.getName()); m.put("code", po.getType() + ":" + po.getCode()); m.put("shares", shares + ""); m.put("val", cVal + ""); m.put("change", JO.getString("3") + " " + JO.getString("1")); m.put("mkt", nf.format(smtVal)); m.put("pl", nf.format(spl)); m.put("pl_perc", nf.format(perc) + "%"); pAdd.add(m); } else{ /* *STARTS HERE */ NumberFormat format = NumberFormat.getInstance(Locale.US); Number number = format.parse(JO.getString("2").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0")); Double cVal = number.doubleValue(); Number oVal = format.parse(JO.getString("4").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0"). replace("\n", "")); double spl = 0; int shares = 0; double den = 0; day = 0; double smtVal = 0; for (int l = j; l < p.size(); ++l) { port portfolio = p.get(l); if ((portfolio.getCode() + "_" + portfolio.getType()).equals(po.getCode() + "_" + po.getType())) { if (portfolio.getBS().startsWith("B")) { spl += (cVal - portfolio.getPrice()) * portfolio.getQty() - portfolio.getCom(); mktVal += cVal * portfolio.getQty(); smtVal += cVal * portfolio.getQty(); shares += portfolio.getQty(); } else { spl += (cVal - portfolio.getPrice()) * (-portfolio.getQty()) - portfolio.getCom(); mktVal += cVal * -portfolio.getQty(); smtVal += cVal * -portfolio.getQty(); shares -= portfolio.getQty(); } orig += portfolio.getPrice() * portfolio.getQty(); den += portfolio.getPrice() * portfolio.getQty(); } } gl += spl; double perc = spl * 100 / den; m.put("name", po.getName().length()>23?po.getName().substring(0, 23)+"..":po.getName()); m.put("code", po.getType() + ":" + po.getCode()); m.put("shares", shares + ""); m.put("val", cVal + ""); m.put("change", JO.getString("3") + " " + JO.getString("1")); m.put("mkt", nf.format(smtVal)); m.put("pl", nf.format(spl)); m.put("pl_perc", nf.format(perc) + "%"); pAdd.add(m); } } } Log.d("DATA: ", "CUR = "+mktVal+", ORIGINAL = "+orig); if(err){ pl = (gl / orig) * 100; Double dplp = (dp / day) * 100; a[0] = nf.format(gl); a[1] = nf.format(pl) + "%"; a[2] = nf.format(mktVal); a[3] = "N/A"; a[4] = "N/A"; }else{ pl = (gl / orig) * 100; Double dplp = (dp / day) * 100; a[0] = nf.format(gl); a[1] = nf.format(pl) + "%"; a[2] = nf.format(mktVal); a[3] = nf.format(dp); a[4] = nf.format(dplp)+"%"; } } else{ pAdd = null; a[0] = "N/A"; a[1] = "N/A"; a[2] = "N/A"; a[3] = "N/A"; a[4] = "N/A"; errEx = 2; } } catch (Exception e) { Log.d("erroryash", e.toString()); Toast.makeText(getActivity(), "Server error, please try again", Toast.LENGTH_LONG).show(); this.cancel(true); } Log.d("arrayash", "A: "+a[0]+a[1]); return a; } @Override protected void onPostExecute(String e[]) { if(isAdded()&&!isCancelled()) { listAdd = pAdd; TextView plT = (TextView) view.findViewById(R.id.pl); TextView plT_perc = (TextView) view.findViewById(R.id.pl_perc); TextView dpl = (TextView) view.findViewById(R.id.dpl); TextView dpl_perc = (TextView) view.findViewById(R.id.dpl_perc); TextView mk = (TextView) view.findViewById(R.id.mktval); plT.setText(e[0]); plT_perc.setText(e[1]); Log.e("HERE IS THE ERROR", "HELLO"+e[1]); if(!e[1].contains("-")){ plT.setTextColor(getResources().getColor(R.color.graphg)); plT_perc.setTextColor(getResources().getColor(R.color.graphg)); }else{ plT.setTextColor(getResources().getColor(R.color.app_red)); plT_perc.setTextColor(getResources().getColor(R.color.app_red)); } mk.setText(e[2]); dpl.setText(e[3]); dpl_perc.setText(e[4]); if(!e[4].contains("-")){ dpl.setTextColor(getResources().getColor(R.color.graphg)); dpl_perc.setTextColor(getResources().getColor(R.color.graphg)); }else{ dpl.setTextColor(getResources().getColor(R.color.app_red)); dpl_perc.setTextColor(getResources().getColor(R.color.app_red)); } TextView message = (TextView) view.findViewById(R.id.message); Log.d("EXERROR", "Value="+errEx); ListView lv = (ListView) view.findViewById(R.id.portfolio_view_list); SimpleAdapter ad; if(errEx==0) { ad = new SimpleAdapter(getActivity(), listAdd, R.layout.portfolioview, new String[]{"name", "code", "shares", "val", "change", "mkt", "pl", "pl_perc"}, new int[]{R.id.stock_name, R.id.stock_code, R.id.stock_shares, R.id.stock_price, R.id.stock_change, R.id.stock_mktVal , R.id.stock_pl, R.id.stock_pl_perc}); SimpleAdapter.ViewBinder binder = new SimpleAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Object object, String value) { View p = (View) view.getParent(); TextView bk = (TextView) p.findViewById(R.id.stock_price); TextView bm = (TextView) view.findViewById(R.id.stock_change); TextView pl = (TextView) p.findViewById(R.id.stock_pl); TextView plp = (TextView) view.findViewById(R.id.stock_pl_perc); if (view.equals((TextView) view.findViewById(R.id.stock_change))) { if(value.contains("/")){ bk.setTextColor(getResources().getColor(R.color.White)); bm.setTextColor(getResources().getColor(R.color.White)); } else if (value.contains("-")) { bk.setTextColor(getResources().getColor(R.color.app_red)); bm.setTextColor(getResources().getColor(R.color.app_red)); } else { bk.setTextColor(getResources().getColor(R.color.graphg)); bm.setTextColor(getResources().getColor(R.color.graphg)); } } if (view.equals((TextView) view.findViewById(R.id.stock_pl_perc))) { if(value.contains("/")){ bk.setTextColor(getResources().getColor(R.color.White)); bm.setTextColor(getResources().getColor(R.color.White)); } else if (value.contains("-")) { pl.setTextColor(getResources().getColor(R.color.app_red)); plp.setTextColor(getResources().getColor(R.color.app_red)); } else { pl.setTextColor(getResources().getColor(R.color.graphg)); plp.setTextColor(getResources().getColor(R.color.graphg)); } } return false; } }; message.setVisibility(View.GONE); ad.setViewBinder(binder); lv.setAdapter(ad); }else if(errEx==1){ message.setVisibility(View.VISIBLE); message.setText("Data cannot be retrieved. Please try again later."); }else if(errEx==2){ ad = null; lv.setAdapter(ad); message.setVisibility(View.VISIBLE); message.setText("No transactions"); } fvp.setVisibility(View.INVISIBLE); refresh.setEnabled(true); } } } }
UTF-8
Java
25,659
java
PortView.java
Java
[]
null
[]
package com.infigent.stocksense; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import adapters.DatabaseHandler; import adapters.port; public class PortView extends Fragment { View view; int PORTFOLIO_ID; final int CONTEXT_MENU_EDIT =1; final int CONTEXT_MENU_DELETE =2; String DELETE_CODE, DELETE_TYPE; ImageButton refresh; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.portfolio_view, null); Bundle extras = getArguments(); final int id = extras.getInt("id"); PORTFOLIO_ID = id; final String name = extras.getString("name"); refresh = (ImageButton) view.findViewById(R.id.refresh); ImageButton add = (ImageButton) view.findViewById(R.id.addfromport); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Add a = new Add(); Bundle ex = new Bundle(); ex.putString("id", id+""); ex.putString("name", name); a.setArguments(ex); switchFragment(a); } }); final ListView lv = (ListView) view.findViewById(R.id.portfolio_view_list); registerForContextMenu(lv); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setup s = new setup(); s.execute(id); } }); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) { TextView cd = (TextView) v.findViewById(R.id.stock_code); String type = cd.getText().toString().substring(0, cd.getText().toString().indexOf(":")); String code = cd.getText().toString().substring(cd.getText().toString().indexOf(":")+1, cd.getText().toString().length()); DatabaseHandler db = new DatabaseHandler(getActivity()); List<port> trans = db.getAllTrans(PORTFOLIO_ID, code, type); ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); for(int j=0;j<trans.size();++j){ HashMap<String, String> map = new HashMap<String, String>(); port p = trans.get(j); map.put("q", String.valueOf(p.getQty())); map.put("p", String.valueOf(p.getPrice())); map.put("c", String.valueOf(p.getCom())); map.put("t", p.getBS().startsWith("B")?"Buy":"Sell"); list.add(map); } SimpleAdapter ad = new SimpleAdapter(getActivity(), list, R.layout.trans, new String[]{"t", "q", "p", "c"}, new int[]{R.id.tt, R.id.tq, R.id.tp, R.id.tc}); Dialog d = new Dialog(getActivity()); d.getWindow().setBackgroundDrawableResource(R.drawable.dialog_box); d.setTitle(cd.getText()+" Transactions"); d.setContentView(R.layout.transview); ListView lView = (ListView) d.findViewById(R.id.transList); lView.setAdapter(ad); d.show(); } }); TextView nameView = (TextView) view.findViewById(R.id.fName); nameView.setText(name); Log.d("NEW", name+id); setup s = new setup(); s.execute(id); return view; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; RelativeLayout s = (RelativeLayout) info.targetView; TextView codeView = (TextView) s.findViewById(R.id.stock_code); DELETE_TYPE = codeView.getText().toString().substring(0, codeView.getText().toString().indexOf(":")); DELETE_CODE = codeView.getText().toString().substring(codeView.getText().toString().indexOf(":")+1, codeView.getText().length()); //menu.add(Menu.NONE, CONTEXT_MENU_EDIT, Menu.NONE, "Edit"); menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete"); MenuItem.OnMenuItemClickListener listener = new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { onContextItemSelected(item); return true; } }; for (int i = 0, n = menu.size(); i < n; i++) menu.getItem(i).setOnMenuItemClickListener(listener); } @Override public boolean onContextItemSelected(MenuItem item) { Log.d("Clicked", "Menu"); switch(item.getItemId()){ case CONTEXT_MENU_EDIT: break; case CONTEXT_MENU_DELETE: AlertDialog.Builder alert = new AlertDialog.Builder( getActivity()); alert.setTitle("Delete"); alert.setMessage("Do you want delete this transaction?"); alert.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DatabaseHandler db = new DatabaseHandler(getActivity()); Log.d("VALS", String.valueOf(PORTFOLIO_ID)+ DELETE_CODE+ DELETE_TYPE); db.deleteTrans(String.valueOf(PORTFOLIO_ID), DELETE_CODE, DELETE_TYPE); setup s = new setup(); s.execute(PORTFOLIO_ID); } }); alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); break; } return super.onContextItemSelected(item); } private void switchFragment(Fragment fragment) { if (getActivity() == null) return; if (getActivity() instanceof MainActivity) { MainActivity fca = (MainActivity) getActivity(); fca.switchContent(fragment); } } public class setup extends AsyncTask<Integer, Integer, String[]> { ArrayList<HashMap<String, String>> pAdd = new ArrayList<HashMap<String, String>>(); ArrayList<HashMap<String, String>> listAdd = new ArrayList<HashMap<String, String>>(); DecimalFormat nf = new DecimalFormat("#.00"); ProgressBar fvp = (ProgressBar) view.findViewById(R.id.fvp); int errEx = 0; /* 0: okay 1: error 2: no transactions */ @Override protected void onPreExecute() { super.onPreExecute(); fvp.setVisibility(View.VISIBLE); refresh.setEnabled(false); } @Override protected String[] doInBackground(Integer... ints) { String a[] = new String[5]; int id = ints[0]; DatabaseHandler port = new DatabaseHandler(getActivity()); try { List<port> p = port.getAllPort(id); Log.d("ID HERE", ""+p.size()); JSONObject jObj = new JSONObject(); JSONArray arr = new JSONArray(); for(int i=0;i<p.size();++i){ port po = p.get(i); JSONObject jArr = new JSONObject(); jArr.put("name", po.getName()); jArr.put("code", po.getCode()); jArr.put("type", po.getType()); arr.put(jArr); } jObj.put("portfolio", arr); if(p.size()>0) { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(getResources().getString(R.string.website) + "port.php?j=" + URLEncoder.encode(jObj.toString(), "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpGet); InputStream inputStream = httpResponse.getEntity() .getContent(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream); BufferedReader bufferedReader = new BufferedReader( inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk; while ((bufferedStrChunk = bufferedReader.readLine()) != null) { stringBuilder.append(bufferedStrChunk); } Log.d("here", "DATA: "+stringBuilder.toString()); JSONObject jsonObj = new JSONObject(stringBuilder.toString()); double mktVal = 0, gl = 0, pl, orig = 0, dp=0, day = 0; ArrayList<String> stocks = new ArrayList<String>(); boolean err = false, derr=true; for (int j = 0; j < p.size(); ++j) { HashMap<String, String> m = new HashMap<String, String>(); port po = p.get(j); boolean eq = false; for(int l =0;l<stocks.size();++l) if (stocks.get(l).equals(po.getCode() + "_" + po.getType())) eq = true; if(!eq) { stocks.add(po.getCode() + "_" + po.getType()); JSONObject JO = jsonObj.getJSONObject(po.getCode() + "_" + po.getType()); if (JO.getString("3").equals("N/A")) { Log.d("Error", "N/A error trueee!!!!"); err = true; derr=true; //break; } if (!err) { NumberFormat format = NumberFormat.getInstance(Locale.US); Number number = format.parse(JO.getString("2").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0")); Double cVal = number.doubleValue(); Number oVal = format.parse(JO.getString("4").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0"). replace("\n", "")); Number dll = format.parse(JO.getString("3"). replace("+", "").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0")); Double ol = oVal.doubleValue(); double spl = 0, dpl = 0; int shares = 0; double den = 0; day = 0; double smtVal = 0; for (int l = j; l < p.size(); ++l) { port portfolio = p.get(l); if ((portfolio.getCode() + "_" + portfolio.getType()).equals(po.getCode() + "_" + po.getType())) { if (portfolio.getBS().startsWith("B")) { spl += (cVal - portfolio.getPrice()) * portfolio.getQty() - portfolio.getCom(); dpl += dll.doubleValue() * portfolio.getQty(); mktVal += cVal * portfolio.getQty(); smtVal += cVal * portfolio.getQty(); shares += portfolio.getQty(); } else { spl += (cVal - portfolio.getPrice()) * (-portfolio.getQty()) - portfolio.getCom(); dpl += dll.doubleValue() * -portfolio.getQty(); mktVal += cVal * -portfolio.getQty(); smtVal += cVal * -portfolio.getQty(); shares -= portfolio.getQty(); Log.d("DPL", "Price-->" + (cVal - Double.parseDouble(JO.getString("3")))); } orig += portfolio.getPrice() * portfolio.getQty(); den += portfolio.getPrice() * portfolio.getQty(); day += (cVal - Double.parseDouble(JO.getString("3"))) * portfolio.getQty(); } } gl += spl; dp += dpl; double perc = spl * 100 / den; m.put("name", po.getName()); m.put("code", po.getType() + ":" + po.getCode()); m.put("shares", shares + ""); m.put("val", cVal + ""); m.put("change", JO.getString("3") + " " + JO.getString("1")); m.put("mkt", nf.format(smtVal)); m.put("pl", nf.format(spl)); m.put("pl_perc", nf.format(perc) + "%"); pAdd.add(m); } else{ /* *STARTS HERE */ NumberFormat format = NumberFormat.getInstance(Locale.US); Number number = format.parse(JO.getString("2").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0")); Double cVal = number.doubleValue(); Number oVal = format.parse(JO.getString("4").replace("&nbsp;&nbsp;&nbsp;&nbsp;-", "0"). replace("\n", "")); double spl = 0; int shares = 0; double den = 0; day = 0; double smtVal = 0; for (int l = j; l < p.size(); ++l) { port portfolio = p.get(l); if ((portfolio.getCode() + "_" + portfolio.getType()).equals(po.getCode() + "_" + po.getType())) { if (portfolio.getBS().startsWith("B")) { spl += (cVal - portfolio.getPrice()) * portfolio.getQty() - portfolio.getCom(); mktVal += cVal * portfolio.getQty(); smtVal += cVal * portfolio.getQty(); shares += portfolio.getQty(); } else { spl += (cVal - portfolio.getPrice()) * (-portfolio.getQty()) - portfolio.getCom(); mktVal += cVal * -portfolio.getQty(); smtVal += cVal * -portfolio.getQty(); shares -= portfolio.getQty(); } orig += portfolio.getPrice() * portfolio.getQty(); den += portfolio.getPrice() * portfolio.getQty(); } } gl += spl; double perc = spl * 100 / den; m.put("name", po.getName().length()>23?po.getName().substring(0, 23)+"..":po.getName()); m.put("code", po.getType() + ":" + po.getCode()); m.put("shares", shares + ""); m.put("val", cVal + ""); m.put("change", JO.getString("3") + " " + JO.getString("1")); m.put("mkt", nf.format(smtVal)); m.put("pl", nf.format(spl)); m.put("pl_perc", nf.format(perc) + "%"); pAdd.add(m); } } } Log.d("DATA: ", "CUR = "+mktVal+", ORIGINAL = "+orig); if(err){ pl = (gl / orig) * 100; Double dplp = (dp / day) * 100; a[0] = nf.format(gl); a[1] = nf.format(pl) + "%"; a[2] = nf.format(mktVal); a[3] = "N/A"; a[4] = "N/A"; }else{ pl = (gl / orig) * 100; Double dplp = (dp / day) * 100; a[0] = nf.format(gl); a[1] = nf.format(pl) + "%"; a[2] = nf.format(mktVal); a[3] = nf.format(dp); a[4] = nf.format(dplp)+"%"; } } else{ pAdd = null; a[0] = "N/A"; a[1] = "N/A"; a[2] = "N/A"; a[3] = "N/A"; a[4] = "N/A"; errEx = 2; } } catch (Exception e) { Log.d("erroryash", e.toString()); Toast.makeText(getActivity(), "Server error, please try again", Toast.LENGTH_LONG).show(); this.cancel(true); } Log.d("arrayash", "A: "+a[0]+a[1]); return a; } @Override protected void onPostExecute(String e[]) { if(isAdded()&&!isCancelled()) { listAdd = pAdd; TextView plT = (TextView) view.findViewById(R.id.pl); TextView plT_perc = (TextView) view.findViewById(R.id.pl_perc); TextView dpl = (TextView) view.findViewById(R.id.dpl); TextView dpl_perc = (TextView) view.findViewById(R.id.dpl_perc); TextView mk = (TextView) view.findViewById(R.id.mktval); plT.setText(e[0]); plT_perc.setText(e[1]); Log.e("HERE IS THE ERROR", "HELLO"+e[1]); if(!e[1].contains("-")){ plT.setTextColor(getResources().getColor(R.color.graphg)); plT_perc.setTextColor(getResources().getColor(R.color.graphg)); }else{ plT.setTextColor(getResources().getColor(R.color.app_red)); plT_perc.setTextColor(getResources().getColor(R.color.app_red)); } mk.setText(e[2]); dpl.setText(e[3]); dpl_perc.setText(e[4]); if(!e[4].contains("-")){ dpl.setTextColor(getResources().getColor(R.color.graphg)); dpl_perc.setTextColor(getResources().getColor(R.color.graphg)); }else{ dpl.setTextColor(getResources().getColor(R.color.app_red)); dpl_perc.setTextColor(getResources().getColor(R.color.app_red)); } TextView message = (TextView) view.findViewById(R.id.message); Log.d("EXERROR", "Value="+errEx); ListView lv = (ListView) view.findViewById(R.id.portfolio_view_list); SimpleAdapter ad; if(errEx==0) { ad = new SimpleAdapter(getActivity(), listAdd, R.layout.portfolioview, new String[]{"name", "code", "shares", "val", "change", "mkt", "pl", "pl_perc"}, new int[]{R.id.stock_name, R.id.stock_code, R.id.stock_shares, R.id.stock_price, R.id.stock_change, R.id.stock_mktVal , R.id.stock_pl, R.id.stock_pl_perc}); SimpleAdapter.ViewBinder binder = new SimpleAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Object object, String value) { View p = (View) view.getParent(); TextView bk = (TextView) p.findViewById(R.id.stock_price); TextView bm = (TextView) view.findViewById(R.id.stock_change); TextView pl = (TextView) p.findViewById(R.id.stock_pl); TextView plp = (TextView) view.findViewById(R.id.stock_pl_perc); if (view.equals((TextView) view.findViewById(R.id.stock_change))) { if(value.contains("/")){ bk.setTextColor(getResources().getColor(R.color.White)); bm.setTextColor(getResources().getColor(R.color.White)); } else if (value.contains("-")) { bk.setTextColor(getResources().getColor(R.color.app_red)); bm.setTextColor(getResources().getColor(R.color.app_red)); } else { bk.setTextColor(getResources().getColor(R.color.graphg)); bm.setTextColor(getResources().getColor(R.color.graphg)); } } if (view.equals((TextView) view.findViewById(R.id.stock_pl_perc))) { if(value.contains("/")){ bk.setTextColor(getResources().getColor(R.color.White)); bm.setTextColor(getResources().getColor(R.color.White)); } else if (value.contains("-")) { pl.setTextColor(getResources().getColor(R.color.app_red)); plp.setTextColor(getResources().getColor(R.color.app_red)); } else { pl.setTextColor(getResources().getColor(R.color.graphg)); plp.setTextColor(getResources().getColor(R.color.graphg)); } } return false; } }; message.setVisibility(View.GONE); ad.setViewBinder(binder); lv.setAdapter(ad); }else if(errEx==1){ message.setVisibility(View.VISIBLE); message.setText("Data cannot be retrieved. Please try again later."); }else if(errEx==2){ ad = null; lv.setAdapter(ad); message.setVisibility(View.VISIBLE); message.setText("No transactions"); } fvp.setVisibility(View.INVISIBLE); refresh.setEnabled(true); } } } }
25,659
0.443002
0.438832
544
46.167278
30.396999
123
false
false
0
0
0
0
0
0
0.887868
false
false
5
003f726cabf992940bbad035790c8207126bd2b4
7,825,430,470,611
4659c2c3e7d8f5e85d1b1248134fc9cf802a2a14
/flink-learning-from-zhisheng-connectors/flink-learning-connectors-rabbitmq/src/main/java/com/shangbaishuyao/connectors/rabbitmq/utils/RabbitMQProducerUtil.java
4679d5f0b874ee64e32a14d2660079001f74e7e1
[ "Apache-2.0" ]
permissive
corersky/flink-learning-from-zhisheng
https://github.com/corersky/flink-learning-from-zhisheng
e68dfad1f91196d8cfeaaa0014fce7c55cb66847
9765eaee0e2cf49d2a925d8d55ebc069f9bdcda1
refs/heads/main
2023-05-14T07:12:49.610000
2021-06-06T15:21:17
2021-06-06T15:21:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shangbaishuyao.connectors.rabbitmq.utils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; /** * Desc: 生产消息 <br/> * create by shangbaishuyao on 2021/1/31 * @Author: 上白书妖 * @Date: 22:06 2021/1/31 */ public class RabbitMQProducerUtil { public final static String QUEUE_NAME = "shangbaishuyao"; public static void main(String[] args) throws Exception{ //创建连接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); //设置RibbitMQ相关信息 connectionFactory.setHost("127.0.0.1"); connectionFactory.setUsername("admin"); connectionFactory.setPassword("admin"); connectionFactory.setPort(5672); //创建一个新的连接 Connection connection = connectionFactory.newConnection(); //创建一个通道 Channel channel = connection.createChannel(); //声明一个队列 // channel.queueDeclare(QUEUE_NAME,false,false,false,null); //发送消息到队列中 String message = "hello shangbaishuyao"; for (int i = 0; i< 1000; i++){ channel.basicPublish("", QUEUE_NAME,null,(message + i).getBytes("UTF-8")); System.out.println("Producer Send +" + message + i); } //关闭通道和连接 channel.close(); connection.close(); } }
UTF-8
Java
1,463
java
RabbitMQProducerUtil.java
Java
[ { "context": "tionFactory;\n\n/**\n * Desc: 生产消息 <br/>\n * create by shangbaishuyao on 2021/1/31\n * @Author: 上白书妖\n * @Dat", "end": 216, "score": 0.598009467124939, "start": 214, "tag": "USERNAME", "value": "sh" }, { "context": " create by shangbaishuyao on 2021/1/31\n * @Author: 上白书妖\n * @Date: 22:06 2021/1/31\n */\npublic class Rabbit", "end": 258, "score": 0.9995838403701782, "start": 254, "tag": "NAME", "value": "上白书妖" }, { "context": "设置RibbitMQ相关信息\n connectionFactory.setHost(\"127.0.0.1\");\n connectionFactory.setUsername(\"admin\")", "end": 608, "score": 0.999730110168457, "start": 599, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "7.0.0.1\");\n connectionFactory.setUsername(\"admin\");\n connectionFactory.setPassword(\"admin\")", "end": 656, "score": 0.9517824649810791, "start": 651, "tag": "USERNAME", "value": "admin" }, { "context": "(\"admin\");\n connectionFactory.setPassword(\"admin\");\n connectionFactory.setPort(5672);\n\n ", "end": 704, "score": 0.9995568990707397, "start": 699, "tag": "PASSWORD", "value": "admin" } ]
null
[]
package com.shangbaishuyao.connectors.rabbitmq.utils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; /** * Desc: 生产消息 <br/> * create by shangbaishuyao on 2021/1/31 * @Author: 上白书妖 * @Date: 22:06 2021/1/31 */ public class RabbitMQProducerUtil { public final static String QUEUE_NAME = "shangbaishuyao"; public static void main(String[] args) throws Exception{ //创建连接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); //设置RibbitMQ相关信息 connectionFactory.setHost("127.0.0.1"); connectionFactory.setUsername("admin"); connectionFactory.setPassword("<PASSWORD>"); connectionFactory.setPort(5672); //创建一个新的连接 Connection connection = connectionFactory.newConnection(); //创建一个通道 Channel channel = connection.createChannel(); //声明一个队列 // channel.queueDeclare(QUEUE_NAME,false,false,false,null); //发送消息到队列中 String message = "hello shangbaishuyao"; for (int i = 0; i< 1000; i++){ channel.basicPublish("", QUEUE_NAME,null,(message + i).getBytes("UTF-8")); System.out.println("Producer Send +" + message + i); } //关闭通道和连接 channel.close(); connection.close(); } }
1,468
0.640059
0.61493
48
27.1875
23.783447
86
false
false
0
0
0
0
0
0
0.5625
false
false
5
ab3f14ba686f58ac7b4073a13d136142b7a76062
18,107,582,142,201
cdc0c97fa307da449ee684bbbb780727f356b30d
/pspmStreaming/src/main/java/newborn_town/pspm/online/bolt/PSPMClickToMongoBolt.java
3ef8958becc5da04ab72d1a40985f8a384645a17
[]
no_license
yujiwen-newbornTown/bigdata
https://github.com/yujiwen-newbornTown/bigdata
a513417c98f4997170dbe98a6ed8be94ae3aafb8
1b2901245d9751c138b608349c6ad257608bcb56
refs/heads/master
2021-05-02T04:17:11.575000
2016-12-14T05:46:35
2016-12-14T05:46:35
76,415,959
0
0
null
true
2016-12-14T02:11:03
2016-12-14T02:11:02
2016-12-14T02:02:53
2016-12-14T02:02:51
0
0
0
0
null
null
null
package newborn_town.pspm.online.bolt; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import newborn_town.commonpojo.ReportMongoBean; import newborn_town.dao.ApiReportDao; import newborn_town.dao.BaseReportDao; import newborn_town.dao.CampaignReportDao; import newborn_town.dao.CountryReportDao; import newborn_town.dao.impl.ApiReportDaoImpl; import newborn_town.dao.impl.BaseReportDaoImpl; import newborn_town.dao.impl.CampaignReportDaoImpl; import newborn_town.dao.impl.CountryReportDaoImpl; import newborn_town.rawlogclean.RecordQueueManager; import newborn_town.rawlogclean.TimeRecordBean; import newborn_town.util.DateUtil; import newborn_town.util.MongoUtil; import newborn_town.util.PublicUtill; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.storm.Config; import org.apache.storm.Constants; import org.apache.storm.topology.BasicOutputCollector; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseBasicBolt; import org.apache.storm.tuple.Tuple; import org.bson.Document; /** * @author yujiwen E-mail: yujiwen@newborn-town.com * @version 创建时间:2016年12月12日 下午5:51:55 * */ public class PSPMClickToMongoBolt extends BaseBasicBolt { private static final long serialVersionUID = 3694898337662243758L; static Logger logger = Logger.getLogger(PSPMClickToMongoBolt.class); static int MOGONDB_NUM = 5000; // 批量存储Mogondb的阈值 SimpleDateFormat timeDifferenceDF = null; int secondNum = 10; Queue<TimeRecordBean> recordQueue = null; Map<String, String> recordMap = null; HashMap<String, Integer> logNumber = null;// log日志区分map ArrayList<Document> updateStrDocs = null; ArrayList<Document> updateIncDocs = null; MongoUtil mongoUtilApi = null; MongoUtil mongoUtilBase = null; MongoUtil mongoUtilCampaign = null; MongoUtil mongoUtilCountry = null; IdentityHashMap<String,ReportMongoBean> apiUpdateMap = null; IdentityHashMap<String,ReportMongoBean> baseUpdateMap = null; IdentityHashMap<String,ReportMongoBean> campaignUpdateMap = null; IdentityHashMap<String,ReportMongoBean> countryUpdateMap = null; ApiReportDao apiReportDao = null; BaseReportDao baseReportDao = null; CampaignReportDao campaignReportDao = null; CountryReportDao countryReportDao = null; public void prepare(@SuppressWarnings("rawtypes") Map stormConf, org.apache.storm.task.TopologyContext context) { timeDifferenceDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); recordQueue = new LinkedList<TimeRecordBean>(); recordMap = new HashMap<String, String>(); mongoUtilApi = new MongoUtil("pspm", "apiReport"); mongoUtilBase = new MongoUtil("pspm", "baseReport"); mongoUtilCampaign = new MongoUtil("pspm", "campaignReport"); mongoUtilCountry = new MongoUtil("pspm", "countryReport"); apiUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); baseUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); campaignUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); countryUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); apiReportDao = new ApiReportDaoImpl(); baseReportDao = new BaseReportDaoImpl(); campaignReportDao = new CampaignReportDaoImpl(); countryReportDao = new CountryReportDaoImpl(); updateStrDocs = new ArrayList<Document>(); updateIncDocs = new ArrayList<Document>(); logNumber = new HashMap<String, Integer>(); }; @Override public void execute(Tuple input, BasicOutputCollector collector) { // 判断是否是定时任务的消息 if (input.getSourceComponent().equals(Constants.SYSTEM_COMPONENT_ID) && input.getSourceStreamId().equals( Constants.SYSTEM_TICK_STREAM_ID)) { if (apiUpdateMap.size() > 0 || baseUpdateMap.size() > 0 || campaignUpdateMap.size() > 0 || countryUpdateMap.size() > 0) { apiReportDao.insertIntoMongo(apiUpdateMap, mongoUtilApi); apiUpdateMap.clear(); baseReportDao.insertIntoMongo(baseUpdateMap, mongoUtilBase); baseUpdateMap.clear(); campaignReportDao.insertIntoMongo(campaignUpdateMap, mongoUtilCampaign); campaignUpdateMap.clear(); countryReportDao.insertIntoMongo(countryUpdateMap, mongoUtilCountry); countryUpdateMap.clear(); } return; } String[] sentence = (String[]) input.getValue(1); String str = (String) input.getValue(0); String create_time = sentence[38]; String campaign_id = sentence[2]; String platform = sentence[4]; String geo = sentence[5]; String publisher_id = sentence[7]; String publisher_slot = sentence[8]; String publisher_type = sentence[9]; String am_id = sentence[10]; String advertiser_id = sentence[11]; String advertiser_type = sentence[12]; String bd_id = sentence[13]; String pm_id = sentence[14]; String day = DateUtil.getDay(sentence[38]); if (StringUtils.isEmpty(advertiser_id) || StringUtils.isEmpty(advertiser_type) || StringUtils.isEmpty(publisher_id) || StringUtils.isEmpty(campaign_id) || StringUtils.isEmpty(platform) || StringUtils.isEmpty(publisher_type) || StringUtils.isEmpty(am_id) || StringUtils.isEmpty(bd_id) || StringUtils.isEmpty(pm_id)) { logger.error("click-log format error lack field: " + sentence); return; } if (logNumber.get(day) == null) { for (Map.Entry<String, Integer> entry : logNumber.entrySet()) { logger.info("PSPMClickToMongoBolt" + entry.getKey() + "消费了" + entry.getValue() + "条数据!"); } logNumber.clear(); logNumber.put(day, 1);// 根据时间区分消费数据量 } else { logNumber.put(day, logNumber.get(day) + 1); } String mogoDBApiMapKey = PublicUtill.MD5(day + publisher_slot + geo + campaign_id + publisher_id); // 拼接map中的key String mogoDBBaseMapKey = PublicUtill.MD5(day + publisher_id + publisher_slot + advertiser_id); // 拼接map中的key String mogoDBCampaignMapKey = PublicUtill.MD5(day + campaign_id); // 拼接map中的key String mogoDBCountryMapKey = PublicUtill.MD5(day + geo + advertiser_id + publisher_id); // 拼接map中的key // 按照campaign_id+publisher_id+click_ua+click_ip过滤 TimeRecordBean timeRecordBean = new TimeRecordBean(str, create_time); int unique_clicks = 0; int gross_clicks = 0; try { if (RecordQueueManager.updateRecordsQueue(timeRecordBean, recordQueue, recordMap, timeDifferenceDF)) { unique_clicks++; } gross_clicks++; ReportMongoBean reportMongoBean = new ReportMongoBean(); reportMongoBean.setDay(day); reportMongoBean.setCampaign_id(campaign_id); reportMongoBean.setCountry(geo); reportMongoBean.setGross_clicks(gross_clicks); reportMongoBean.setAdvertiser_id(advertiser_id); reportMongoBean.setPublisher_slot(publisher_slot); reportMongoBean.setPublisher_id(publisher_id); reportMongoBean.setUnique_clicks(unique_clicks); apiUpdateMap.put(mogoDBApiMapKey, reportMongoBean); baseUpdateMap.put(mogoDBBaseMapKey, reportMongoBean); campaignUpdateMap.put(mogoDBCampaignMapKey, reportMongoBean); countryUpdateMap.put(mogoDBCountryMapKey, reportMongoBean); if (apiUpdateMap.size() > MOGONDB_NUM || baseUpdateMap.size() > MOGONDB_NUM || campaignUpdateMap.size() > MOGONDB_NUM || countryUpdateMap.size() > MOGONDB_NUM) { apiReportDao.insertIntoMongo(apiUpdateMap, mongoUtilApi); apiUpdateMap.clear(); baseReportDao.insertIntoMongo(baseUpdateMap, mongoUtilBase); baseUpdateMap.clear(); campaignReportDao.insertIntoMongo(campaignUpdateMap, mongoUtilCampaign); campaignUpdateMap.clear(); countryReportDao.insertIntoMongo(countryUpdateMap, mongoUtilCountry); countryUpdateMap.clear(); } } catch (Exception e) { logger.error(e); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } // 设置定时任务 @Override public Map<String, Object> getComponentConfiguration() { Config config = new Config(); config.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, secondNum); return config; } }
UTF-8
Java
8,443
java
PSPMClickToMongoBolt.java
Java
[ { "context": "le;\r\nimport org.bson.Document;\r\n\r\n/**\r\n * @author yujiwen E-mail: yujiwen@newborn-town.com\r\n * @version 创建时", "end": 1286, "score": 0.9595436453819275, "start": 1279, "tag": "USERNAME", "value": "yujiwen" }, { "context": "bson.Document;\r\n\r\n/**\r\n * @author yujiwen E-mail: yujiwen@newborn-town.com\r\n * @version 创建时间:2016年12月12日 下午5:51:55\r\n * \r\n */", "end": 1319, "score": 0.9999324679374695, "start": 1295, "tag": "EMAIL", "value": "yujiwen@newborn-town.com" } ]
null
[]
package newborn_town.pspm.online.bolt; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import newborn_town.commonpojo.ReportMongoBean; import newborn_town.dao.ApiReportDao; import newborn_town.dao.BaseReportDao; import newborn_town.dao.CampaignReportDao; import newborn_town.dao.CountryReportDao; import newborn_town.dao.impl.ApiReportDaoImpl; import newborn_town.dao.impl.BaseReportDaoImpl; import newborn_town.dao.impl.CampaignReportDaoImpl; import newborn_town.dao.impl.CountryReportDaoImpl; import newborn_town.rawlogclean.RecordQueueManager; import newborn_town.rawlogclean.TimeRecordBean; import newborn_town.util.DateUtil; import newborn_town.util.MongoUtil; import newborn_town.util.PublicUtill; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.storm.Config; import org.apache.storm.Constants; import org.apache.storm.topology.BasicOutputCollector; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseBasicBolt; import org.apache.storm.tuple.Tuple; import org.bson.Document; /** * @author yujiwen E-mail: <EMAIL> * @version 创建时间:2016年12月12日 下午5:51:55 * */ public class PSPMClickToMongoBolt extends BaseBasicBolt { private static final long serialVersionUID = 3694898337662243758L; static Logger logger = Logger.getLogger(PSPMClickToMongoBolt.class); static int MOGONDB_NUM = 5000; // 批量存储Mogondb的阈值 SimpleDateFormat timeDifferenceDF = null; int secondNum = 10; Queue<TimeRecordBean> recordQueue = null; Map<String, String> recordMap = null; HashMap<String, Integer> logNumber = null;// log日志区分map ArrayList<Document> updateStrDocs = null; ArrayList<Document> updateIncDocs = null; MongoUtil mongoUtilApi = null; MongoUtil mongoUtilBase = null; MongoUtil mongoUtilCampaign = null; MongoUtil mongoUtilCountry = null; IdentityHashMap<String,ReportMongoBean> apiUpdateMap = null; IdentityHashMap<String,ReportMongoBean> baseUpdateMap = null; IdentityHashMap<String,ReportMongoBean> campaignUpdateMap = null; IdentityHashMap<String,ReportMongoBean> countryUpdateMap = null; ApiReportDao apiReportDao = null; BaseReportDao baseReportDao = null; CampaignReportDao campaignReportDao = null; CountryReportDao countryReportDao = null; public void prepare(@SuppressWarnings("rawtypes") Map stormConf, org.apache.storm.task.TopologyContext context) { timeDifferenceDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); recordQueue = new LinkedList<TimeRecordBean>(); recordMap = new HashMap<String, String>(); mongoUtilApi = new MongoUtil("pspm", "apiReport"); mongoUtilBase = new MongoUtil("pspm", "baseReport"); mongoUtilCampaign = new MongoUtil("pspm", "campaignReport"); mongoUtilCountry = new MongoUtil("pspm", "countryReport"); apiUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); baseUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); campaignUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); countryUpdateMap = new IdentityHashMap<String,ReportMongoBean>(); apiReportDao = new ApiReportDaoImpl(); baseReportDao = new BaseReportDaoImpl(); campaignReportDao = new CampaignReportDaoImpl(); countryReportDao = new CountryReportDaoImpl(); updateStrDocs = new ArrayList<Document>(); updateIncDocs = new ArrayList<Document>(); logNumber = new HashMap<String, Integer>(); }; @Override public void execute(Tuple input, BasicOutputCollector collector) { // 判断是否是定时任务的消息 if (input.getSourceComponent().equals(Constants.SYSTEM_COMPONENT_ID) && input.getSourceStreamId().equals( Constants.SYSTEM_TICK_STREAM_ID)) { if (apiUpdateMap.size() > 0 || baseUpdateMap.size() > 0 || campaignUpdateMap.size() > 0 || countryUpdateMap.size() > 0) { apiReportDao.insertIntoMongo(apiUpdateMap, mongoUtilApi); apiUpdateMap.clear(); baseReportDao.insertIntoMongo(baseUpdateMap, mongoUtilBase); baseUpdateMap.clear(); campaignReportDao.insertIntoMongo(campaignUpdateMap, mongoUtilCampaign); campaignUpdateMap.clear(); countryReportDao.insertIntoMongo(countryUpdateMap, mongoUtilCountry); countryUpdateMap.clear(); } return; } String[] sentence = (String[]) input.getValue(1); String str = (String) input.getValue(0); String create_time = sentence[38]; String campaign_id = sentence[2]; String platform = sentence[4]; String geo = sentence[5]; String publisher_id = sentence[7]; String publisher_slot = sentence[8]; String publisher_type = sentence[9]; String am_id = sentence[10]; String advertiser_id = sentence[11]; String advertiser_type = sentence[12]; String bd_id = sentence[13]; String pm_id = sentence[14]; String day = DateUtil.getDay(sentence[38]); if (StringUtils.isEmpty(advertiser_id) || StringUtils.isEmpty(advertiser_type) || StringUtils.isEmpty(publisher_id) || StringUtils.isEmpty(campaign_id) || StringUtils.isEmpty(platform) || StringUtils.isEmpty(publisher_type) || StringUtils.isEmpty(am_id) || StringUtils.isEmpty(bd_id) || StringUtils.isEmpty(pm_id)) { logger.error("click-log format error lack field: " + sentence); return; } if (logNumber.get(day) == null) { for (Map.Entry<String, Integer> entry : logNumber.entrySet()) { logger.info("PSPMClickToMongoBolt" + entry.getKey() + "消费了" + entry.getValue() + "条数据!"); } logNumber.clear(); logNumber.put(day, 1);// 根据时间区分消费数据量 } else { logNumber.put(day, logNumber.get(day) + 1); } String mogoDBApiMapKey = PublicUtill.MD5(day + publisher_slot + geo + campaign_id + publisher_id); // 拼接map中的key String mogoDBBaseMapKey = PublicUtill.MD5(day + publisher_id + publisher_slot + advertiser_id); // 拼接map中的key String mogoDBCampaignMapKey = PublicUtill.MD5(day + campaign_id); // 拼接map中的key String mogoDBCountryMapKey = PublicUtill.MD5(day + geo + advertiser_id + publisher_id); // 拼接map中的key // 按照campaign_id+publisher_id+click_ua+click_ip过滤 TimeRecordBean timeRecordBean = new TimeRecordBean(str, create_time); int unique_clicks = 0; int gross_clicks = 0; try { if (RecordQueueManager.updateRecordsQueue(timeRecordBean, recordQueue, recordMap, timeDifferenceDF)) { unique_clicks++; } gross_clicks++; ReportMongoBean reportMongoBean = new ReportMongoBean(); reportMongoBean.setDay(day); reportMongoBean.setCampaign_id(campaign_id); reportMongoBean.setCountry(geo); reportMongoBean.setGross_clicks(gross_clicks); reportMongoBean.setAdvertiser_id(advertiser_id); reportMongoBean.setPublisher_slot(publisher_slot); reportMongoBean.setPublisher_id(publisher_id); reportMongoBean.setUnique_clicks(unique_clicks); apiUpdateMap.put(mogoDBApiMapKey, reportMongoBean); baseUpdateMap.put(mogoDBBaseMapKey, reportMongoBean); campaignUpdateMap.put(mogoDBCampaignMapKey, reportMongoBean); countryUpdateMap.put(mogoDBCountryMapKey, reportMongoBean); if (apiUpdateMap.size() > MOGONDB_NUM || baseUpdateMap.size() > MOGONDB_NUM || campaignUpdateMap.size() > MOGONDB_NUM || countryUpdateMap.size() > MOGONDB_NUM) { apiReportDao.insertIntoMongo(apiUpdateMap, mongoUtilApi); apiUpdateMap.clear(); baseReportDao.insertIntoMongo(baseUpdateMap, mongoUtilBase); baseUpdateMap.clear(); campaignReportDao.insertIntoMongo(campaignUpdateMap, mongoUtilCampaign); campaignUpdateMap.clear(); countryReportDao.insertIntoMongo(countryUpdateMap, mongoUtilCountry); countryUpdateMap.clear(); } } catch (Exception e) { logger.error(e); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } // 设置定时任务 @Override public Map<String, Object> getComponentConfiguration() { Config config = new Config(); config.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, secondNum); return config; } }
8,426
0.730969
0.722162
246
31.695122
25.818325
164
false
false
0
0
0
0
0
0
2.426829
false
false
5
68bf249f34047b98af818a29716642e3b772471f
25,537,875,550,944
de2e8e5c96b3022bcd1f0579a55cc8c3e7ab63f0
/app/src/main/java/com/example/wudelin/forestterritory/fragment/DealFragment.java
2fdf185f071e7e5cbb64a98291ec6aff5d2d2ef8
[]
no_license
Wudelin/Forest
https://github.com/Wudelin/Forest
6f2bd07f101fb17370a06f58522384a3a6512702
12bdd1d916fbffb51020ec8ded2d260f0760b8ce
refs/heads/master
2020-03-09T02:12:29.190000
2018-04-17T12:40:07
2018-04-17T12:40:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.wudelin.forestterritory.fragment; import android.Manifest; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.PopupWindow; import com.example.wudelin.forestterritory.R; import com.example.wudelin.forestterritory.utils.Logger; import com.example.wudelin.forestterritory.utils.ToastUtil; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.imgproc.Imgproc; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static android.app.Activity.RESULT_OK; /** * 项目名: ForestTerritory * 包名: com.example.wudelin.forestterritory.fragment * 创建者: wdl * 创建时间: 2018/4/7 21:14 * 描述: 处理图片 */ public class DealFragment extends Fragment implements View.OnClickListener { private ImageView ivAddPic; private Button btnGray; private Button btnBinaryzation; private static final int PERMISSION_REQUEST = 101; private static final int REQUEST_CAMERA = 10; private static final int REQUEST_ALBUM = 11; private Uri imageUri; private PopupWindow popupWindow; //判断是否从相册或者拍照获取到图片 private boolean flag = false; static { boolean load = OpenCVLoader.initDebug(); if(load) { Logger.i( "Open CV Libraries loaded..."); }else{ Logger.i( "Open CV"); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_deal,null); findView(view); return view; } private void findView(View view) { ivAddPic = view.findViewById(R.id.iv_add_pic); ivAddPic.setOnClickListener(this); btnGray = view.findViewById(R.id.pic_gray); btnGray.setOnClickListener(this); btnBinaryzation = view.findViewById(R.id.pic_binaryzation); btnBinaryzation.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.iv_add_pic: //判断权限 checkPermission(); break; case R.id.pic_gray: //灰度化 if(flag){ gray(); }else { ToastUtil.showByStr(getActivity(),getString(R.string.no_select)); } break; case R.id.pic_binaryzation: //二值化 if(flag){ changeBitmap(); }else { ToastUtil.showByStr(getActivity(),getString(R.string.no_select)); } break; case R.id.select_camera: //拍照选取 toCamera(); popupWindow.dismiss(); break; case R.id.select_album: //相册选取 toAlbum(); popupWindow.dismiss(); break; case R.id.btn_cancel: popupWindow.dismiss(); break; default: } } //二值化 /* 名称 常量 二值阈值化 Imgproc.THRESH_BINARY 阈值化到零 Imgproc.THRESH_TOZERO 截断阈值化 Imgproc.THRESH_TRUNC 反转二值阈值化 Imgproc.THRESH_BINARY_INV 反转阈值化到零 Imgproc.THRESH_TOZERO_INV */ public void changeBitmap() { Bitmap bitmap = ((BitmapDrawable)ivAddPic.getDrawable()).getBitmap(); Mat rgbMat = new Mat(); Mat grayMat = new Mat(); Utils.bitmapToMat(bitmap,rgbMat); Imgproc.threshold(rgbMat,grayMat,100,255,Imgproc.THRESH_BINARY); Utils.matToBitmap(grayMat,bitmap); ivAddPic.setImageBitmap(bitmap); } //灰度化 private void gray() { Bitmap bitmap = ((BitmapDrawable)ivAddPic.getDrawable()).getBitmap(); Bitmap graybm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Mat src = new Mat(); Mat dst = new Mat(); //获取lena彩色图像所对应的像素数据 Utils.bitmapToMat(bitmap,src); //将彩色图像数据转换为灰度图像数据并存储到grayMat中 Imgproc.cvtColor(src,dst,Imgproc.COLOR_BGRA2GRAY); Utils.matToBitmap(dst,graybm); ivAddPic.setImageBitmap(graybm); } private void toAlbum() { //设置action Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent,REQUEST_ALBUM); } private void toCamera() { File outputImg = new File(Environment.getExternalStorageDirectory(), "output.jpg"); //创建 try { if(outputImg.exists()){ outputImg.delete(); } outputImg.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT > 23) { imageUri = FileProvider .getUriForFile(getActivity(), getActivity().getPackageName()+".fileProvider",outputImg); }else{ imageUri = Uri.fromFile(outputImg); } //拍照意图 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //访问权限 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //保存位置 intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri); startActivityForResult(intent,REQUEST_CAMERA); } //判断权限 private void checkPermission() { List<String> needList = new ArrayList<>(); if (ContextCompat.checkSelfPermission (getActivity(),Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){ needList.add(Manifest.permission.CAMERA); } if (ContextCompat.checkSelfPermission (getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ needList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if(!needList.isEmpty()){ requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST); }else{ showPopWindow(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode==RESULT_OK){ switch (requestCode){ case REQUEST_CAMERA: try { Bitmap bitmap = BitmapFactory .decodeStream(getActivity().getContentResolver() .openInputStream(imageUri)); ivAddPic.setImageBitmap(bitmap); flag = true; } catch (FileNotFoundException e) { e.printStackTrace(); } break; case REQUEST_ALBUM: //4.4后 if(Build.VERSION.SDK_INT>=19){ handleImageOnKitKat(data); }else{ handleImageBeforeKitKat(data); } flag = true; break; default: } } } private void handleImageBeforeKitKat(Intent data) { String imagePath = null; Uri uri = data.getData(); imagePath=getImagePath(uri,null); displayImage(imagePath); } //4.4以后 @RequiresApi(api = Build.VERSION_CODES.KITKAT) private void handleImageOnKitKat(Intent data) { String imagePath=null; Uri uri=data.getData(); if(DocumentsContract.isDocumentUri(getActivity(),uri)){ String docId=DocumentsContract.getDocumentId(uri); if("com.android.providers.media.documents".equals(uri.getAuthority())){ String id=docId.split(":")[1]; String selection=MediaStore.Images.Media._ID+"="+id; imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection); }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){ Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId)); imagePath=getImagePath(contentUri,null); } }else if("content".equalsIgnoreCase(uri.getScheme())){ imagePath=getImagePath(uri,null); }else if("file".equalsIgnoreCase(uri.getScheme())){ imagePath=uri.getPath(); } displayImage(imagePath); } private String getImagePath(Uri uri,String selection){ String Path=null; Cursor cursor=getActivity() .getContentResolver() .query(uri,null,selection,null,null); if(cursor!=null){ if(cursor.moveToFirst()){ Path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return Path; } private void displayImage(String Path){ Bitmap bm=BitmapFactory.decodeFile(Path); ivAddPic.setImageBitmap(bm); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(requestCode==PERMISSION_REQUEST){ if(grantResults.length>0) { for (int i = 0; i < grantResults.length; i++) { if(grantResults[i]!=PackageManager.PERMISSION_GRANTED) { ToastUtil.showByStr(getActivity(),getString(R.string.no_permission)); return; } } // showPopWindow(); } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } private void showPopWindow() { //设置pop_view View view = LayoutInflater .from(getActivity()) .inflate(R.layout.popwindow_layout,null); popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true); setBackgroundAlpha(0.5f);//设置屏幕透明度 popupWindow.setFocusable(true);// 点击空白处时,隐藏掉pop窗口 popupWindow.setContentView(view); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { // popupWindow隐藏时恢复屏幕正常透明度 setBackgroundAlpha(1.0f); } }); //设置各个控件的点击响应 Button btnSelectCamera = view.findViewById(R.id.select_camera); btnSelectCamera.setOnClickListener(this); Button btnSelectAlbum = view.findViewById(R.id.select_album); btnSelectAlbum.setOnClickListener(this); Button btnCancel = view.findViewById(R.id.btn_cancel); btnCancel.setOnClickListener(this); //显示PopupWindow的根布局 View rootview = LayoutInflater .from(getActivity()) .inflate(R.layout.fragment_deal, null); popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0); } /** * 设置添加屏幕的背景透明度 * * @param bgAlpha * 屏幕透明度0.0-1.0 1表示完全不透明 */ public void setBackgroundAlpha(float bgAlpha) { WindowManager.LayoutParams lp = getActivity().getWindow() .getAttributes(); lp.alpha = bgAlpha; getActivity().getWindow().setAttributes(lp); } }
UTF-8
Java
13,068
java
DealFragment.java
Java
[ { "context": "example.wudelin.forestterritory.fragment\n * 创建者: wdl\n * 创建时间: 2018/4/7 21:14\n * 描述: 处理图片\n */\n\npubli", "end": 1637, "score": 0.999685525894165, "start": 1634, "tag": "USERNAME", "value": "wdl" } ]
null
[]
package com.example.wudelin.forestterritory.fragment; import android.Manifest; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.PopupWindow; import com.example.wudelin.forestterritory.R; import com.example.wudelin.forestterritory.utils.Logger; import com.example.wudelin.forestterritory.utils.ToastUtil; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.imgproc.Imgproc; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static android.app.Activity.RESULT_OK; /** * 项目名: ForestTerritory * 包名: com.example.wudelin.forestterritory.fragment * 创建者: wdl * 创建时间: 2018/4/7 21:14 * 描述: 处理图片 */ public class DealFragment extends Fragment implements View.OnClickListener { private ImageView ivAddPic; private Button btnGray; private Button btnBinaryzation; private static final int PERMISSION_REQUEST = 101; private static final int REQUEST_CAMERA = 10; private static final int REQUEST_ALBUM = 11; private Uri imageUri; private PopupWindow popupWindow; //判断是否从相册或者拍照获取到图片 private boolean flag = false; static { boolean load = OpenCVLoader.initDebug(); if(load) { Logger.i( "Open CV Libraries loaded..."); }else{ Logger.i( "Open CV"); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_deal,null); findView(view); return view; } private void findView(View view) { ivAddPic = view.findViewById(R.id.iv_add_pic); ivAddPic.setOnClickListener(this); btnGray = view.findViewById(R.id.pic_gray); btnGray.setOnClickListener(this); btnBinaryzation = view.findViewById(R.id.pic_binaryzation); btnBinaryzation.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.iv_add_pic: //判断权限 checkPermission(); break; case R.id.pic_gray: //灰度化 if(flag){ gray(); }else { ToastUtil.showByStr(getActivity(),getString(R.string.no_select)); } break; case R.id.pic_binaryzation: //二值化 if(flag){ changeBitmap(); }else { ToastUtil.showByStr(getActivity(),getString(R.string.no_select)); } break; case R.id.select_camera: //拍照选取 toCamera(); popupWindow.dismiss(); break; case R.id.select_album: //相册选取 toAlbum(); popupWindow.dismiss(); break; case R.id.btn_cancel: popupWindow.dismiss(); break; default: } } //二值化 /* 名称 常量 二值阈值化 Imgproc.THRESH_BINARY 阈值化到零 Imgproc.THRESH_TOZERO 截断阈值化 Imgproc.THRESH_TRUNC 反转二值阈值化 Imgproc.THRESH_BINARY_INV 反转阈值化到零 Imgproc.THRESH_TOZERO_INV */ public void changeBitmap() { Bitmap bitmap = ((BitmapDrawable)ivAddPic.getDrawable()).getBitmap(); Mat rgbMat = new Mat(); Mat grayMat = new Mat(); Utils.bitmapToMat(bitmap,rgbMat); Imgproc.threshold(rgbMat,grayMat,100,255,Imgproc.THRESH_BINARY); Utils.matToBitmap(grayMat,bitmap); ivAddPic.setImageBitmap(bitmap); } //灰度化 private void gray() { Bitmap bitmap = ((BitmapDrawable)ivAddPic.getDrawable()).getBitmap(); Bitmap graybm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Mat src = new Mat(); Mat dst = new Mat(); //获取lena彩色图像所对应的像素数据 Utils.bitmapToMat(bitmap,src); //将彩色图像数据转换为灰度图像数据并存储到grayMat中 Imgproc.cvtColor(src,dst,Imgproc.COLOR_BGRA2GRAY); Utils.matToBitmap(dst,graybm); ivAddPic.setImageBitmap(graybm); } private void toAlbum() { //设置action Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent,REQUEST_ALBUM); } private void toCamera() { File outputImg = new File(Environment.getExternalStorageDirectory(), "output.jpg"); //创建 try { if(outputImg.exists()){ outputImg.delete(); } outputImg.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT > 23) { imageUri = FileProvider .getUriForFile(getActivity(), getActivity().getPackageName()+".fileProvider",outputImg); }else{ imageUri = Uri.fromFile(outputImg); } //拍照意图 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //访问权限 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //保存位置 intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri); startActivityForResult(intent,REQUEST_CAMERA); } //判断权限 private void checkPermission() { List<String> needList = new ArrayList<>(); if (ContextCompat.checkSelfPermission (getActivity(),Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){ needList.add(Manifest.permission.CAMERA); } if (ContextCompat.checkSelfPermission (getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ needList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if(!needList.isEmpty()){ requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST); }else{ showPopWindow(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode==RESULT_OK){ switch (requestCode){ case REQUEST_CAMERA: try { Bitmap bitmap = BitmapFactory .decodeStream(getActivity().getContentResolver() .openInputStream(imageUri)); ivAddPic.setImageBitmap(bitmap); flag = true; } catch (FileNotFoundException e) { e.printStackTrace(); } break; case REQUEST_ALBUM: //4.4后 if(Build.VERSION.SDK_INT>=19){ handleImageOnKitKat(data); }else{ handleImageBeforeKitKat(data); } flag = true; break; default: } } } private void handleImageBeforeKitKat(Intent data) { String imagePath = null; Uri uri = data.getData(); imagePath=getImagePath(uri,null); displayImage(imagePath); } //4.4以后 @RequiresApi(api = Build.VERSION_CODES.KITKAT) private void handleImageOnKitKat(Intent data) { String imagePath=null; Uri uri=data.getData(); if(DocumentsContract.isDocumentUri(getActivity(),uri)){ String docId=DocumentsContract.getDocumentId(uri); if("com.android.providers.media.documents".equals(uri.getAuthority())){ String id=docId.split(":")[1]; String selection=MediaStore.Images.Media._ID+"="+id; imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection); }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){ Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId)); imagePath=getImagePath(contentUri,null); } }else if("content".equalsIgnoreCase(uri.getScheme())){ imagePath=getImagePath(uri,null); }else if("file".equalsIgnoreCase(uri.getScheme())){ imagePath=uri.getPath(); } displayImage(imagePath); } private String getImagePath(Uri uri,String selection){ String Path=null; Cursor cursor=getActivity() .getContentResolver() .query(uri,null,selection,null,null); if(cursor!=null){ if(cursor.moveToFirst()){ Path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return Path; } private void displayImage(String Path){ Bitmap bm=BitmapFactory.decodeFile(Path); ivAddPic.setImageBitmap(bm); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(requestCode==PERMISSION_REQUEST){ if(grantResults.length>0) { for (int i = 0; i < grantResults.length; i++) { if(grantResults[i]!=PackageManager.PERMISSION_GRANTED) { ToastUtil.showByStr(getActivity(),getString(R.string.no_permission)); return; } } // showPopWindow(); } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } private void showPopWindow() { //设置pop_view View view = LayoutInflater .from(getActivity()) .inflate(R.layout.popwindow_layout,null); popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true); setBackgroundAlpha(0.5f);//设置屏幕透明度 popupWindow.setFocusable(true);// 点击空白处时,隐藏掉pop窗口 popupWindow.setContentView(view); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { // popupWindow隐藏时恢复屏幕正常透明度 setBackgroundAlpha(1.0f); } }); //设置各个控件的点击响应 Button btnSelectCamera = view.findViewById(R.id.select_camera); btnSelectCamera.setOnClickListener(this); Button btnSelectAlbum = view.findViewById(R.id.select_album); btnSelectAlbum.setOnClickListener(this); Button btnCancel = view.findViewById(R.id.btn_cancel); btnCancel.setOnClickListener(this); //显示PopupWindow的根布局 View rootview = LayoutInflater .from(getActivity()) .inflate(R.layout.fragment_deal, null); popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0); } /** * 设置添加屏幕的背景透明度 * * @param bgAlpha * 屏幕透明度0.0-1.0 1表示完全不透明 */ public void setBackgroundAlpha(float bgAlpha) { WindowManager.LayoutParams lp = getActivity().getWindow() .getAttributes(); lp.alpha = bgAlpha; getActivity().getWindow().setAttributes(lp); } }
13,068
0.59705
0.592848
354
34.627117
23.492804
130
false
false
0
0
0
0
0
0
0.621469
false
false
5
e39fcd570d253c1f720ae11901bed20db5fb6903
2,954,937,544,927
10a5990d0b938d7c988e1cb7cd63771f0f1c8d25
/museum/museum-web/src/main/java/com/brt/museum/module/market/MarketUserModule.java
1390f3afa5bc0ca3e0d919b39da4e37992794838
[]
no_license
lihongwu19921215/saidaoyou
https://github.com/lihongwu19921215/saidaoyou
a7ff5307b9eabff776af122579e8e4f7336557e2
27c8d4ad75fd8eefd86abd3e1b6514e7d7bb4edd
refs/heads/master
2018-04-01T00:11:27.109000
2017-04-13T07:24:02
2017-04-13T07:24:02
88,243,076
0
0
null
false
2017-04-14T08:54:20
2017-04-14T07:12:34
2017-04-14T08:44:16
2017-04-14T08:44:07
0
0
0
1
JavaScript
null
null
package com.brt.museum.module.market; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresRoles; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.dao.entity.Record; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.lang.Lang; import org.nutz.mvc.annotation.AdaptBy; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Attr; import org.nutz.mvc.annotation.GET; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.POST; import org.nutz.mvc.annotation.Param; import org.nutz.mvc.upload.TempFile; import org.nutz.mvc.upload.UploadAdaptor; import com.brt.museum.bean.auth.User; import com.brt.museum.bean.city.City; import com.brt.museum.bean.content.Region; import com.brt.museum.bean.market.MarketOrganization; import com.brt.museum.bean.market.MarketUser; import com.brt.museum.bean.youzan.YZanRegionRelate; import com.brt.museum.module.adminlogs.AdminLogsModule; import com.brt.museum.service.city.ICityService; import com.brt.museum.service.content.IRegionService; import com.brt.museum.service.market.IMarketUserService; import com.brt.museum.service.organization.IMarketOrganizationService; import com.brt.museum.service.youzan.IYZanProductService; import com.brt.museum.service.youzan.IYZanRegionRelateService; import com.brt.museum.utils.OtherUtils; import com.brt.museum.utils.TimeUtils; import com.brt.museum.vo.Consts.PermissionGroup; import com.brt.museum.vo.Consts.SessionKeys; import com.dgj.nutz.module.base.AbstractBaseModule; import com.dgj.utils.entries.Result; import com.dgj.utils.web.pager.Pager; @At("/marketuser") public class MarketUserModule extends AbstractBaseModule { @Inject IMarketUserService marketUserService; @Inject Dao dao; @Inject ICityService cityService; @Inject IMarketOrganizationService marketOrganizationService; @Inject private IRegionService regionService; @Override public String _getNameSpace() { return PermissionGroup.MARKET_ADMIN.getNameSpace(); } @At @GET @Ok("vel:market/marketuser/list.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result list(@Param(value = "page", df = "1") int page,String sysbml,@Attr(SessionKeys.SESSION_USER_KEY) User user,@Attr(SessionKeys.SESSION_REGION_KEY) Region region) { Pager<Record> pager = marketUserService.listByPage(page); pager.setUrl(_base() + "/marketuser/list"); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); List<City> city=cityService.list(); List<Region> records = regionService.findRegion(); return Result.success().addData("pager", pager).addData("sysbml",sysbml).addData("organization", organization).addData("city", city).addData("records", records); } @At @Ok("vel:market/marketuser/list.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result search(@Param(value = "page", df = "1") int page, @Param("key") String key,@Param("searchkey") int searchkey,@Attr(SessionKeys.SESSION_USER_KEY) User user,@Attr(SessionKeys.SESSION_REGION_KEY) Region region) { key = _fixSearchKey(key); Pager<Record> pager = marketUserService.searchByKey(page, key,searchkey); pager.setUrl(_base() + "/marketuser/search"); pager.addParas("key", key); pager.addParas("searchkey", searchkey); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); List<City> city=cityService.list(); List<Region> records = regionService.findRegion(); return Result.success().addData("pager", pager).addData("organization", organization).addData("city", city).addData("records", records); } @At @GET @Ok("vel:market/marketuser/add_edit.html") @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result add() { List<City> city=cityService.list(); //查询景区 List<Region> regions=regionService.findRegion(); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); return Result.success().addData("city", city).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); } @At @GET @Ok("vel:market/marketuser/batch/add_edit.html") @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result addbatch() { List<City> city=cityService.list(); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); //查询景区 List<Region> regions=regionService.findRegion(); return Result.success().addData("city", city).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); } @At @RequiresRoles(value = { "regionAdmin", "admin","manager" }, logical = Logical.OR) public Result searchCity(@Param("cityid") int cityid) { List<City> city=cityService.listByParentId(cityid); return Result.success().addData("citys", city); } @At("/edit/*") @GET @Ok("vel:market/marketuser/add_edit.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result edit(int id) { MarketUser marketuser = marketUserService.findById(id); //查询景区地图 List list=new ArrayList<>(); String imgs=marketuser.getIdcardImg(); String []img=null; if(imgs!=null&&!imgs.equals("")){ img=imgs.split(","); if(img.length>0){ for(int i=0;i<img.length;i++){ list.add(img[i]); } } } //查询景区 List<Region> regions=regionService.findRegion(); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); List<City> province=cityService.list(); List<City> provinces=new ArrayList<City>(); List<City> citys=new ArrayList<City>(); //已选择城市 City city = cityService.detailCity(marketuser.getCityid()); if(city!=null){ citys.add(city); //已选择省市 City provinceCity = cityService.detailCity(city.getParentid()); provinces.add(provinceCity); //排列组合 省市 for(int i=0;i<province.size();i++){ if(province.get(i).getId()!=provinceCity.getId()){ provinces.add(province.get(i)); }else{ continue; } } //查询该省市下的城市 List<City> provinceByCity=cityService.listByParentId(city.getParentid()); //排列组合 省市 for(int j=0;j<provinceByCity.size();j++){ if(provinceByCity.get(j).getId()!=city.getId()){ citys.add(provinceByCity.get(j)); }else{ continue; } } return Result.success().addData("marketuser", marketuser).addData("provinces", provinces).addData("citys", citys).addData("sysbml", 1).addData("list", list).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); }else{ return Result.success().addData("marketuser", marketuser).addData("provinces", province).addData("sysbml", 0).addData("list", list).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); } } @At @POST @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result update(@Param("..") MarketUser marketUser,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"修改营销用户,ID:"+marketUser.getId()+",名称:"+marketUser.getUserName(); adminlogs.add(request,dao,user,"修改营销用户",2,remark); MarketUser mu=marketUserService.findById(marketUser.getId()); if(!mu.getPwd().equals(marketUser.getPwd())){ marketUser.setPwd(Lang.md5(marketUser.getPwd()).substring(6, 22)); } if(marketUser.getOrganizationId()==0){ marketUser.setRegisterReward(marketUser.getRegisterReward()); marketUser.setCardorderProportion(marketUser.getCardorderProportion()); }else{ MarketOrganization organ=marketOrganizationService.findById(marketUser.getOrganizationId()); marketUser.setRegisterReward(organ.getMemberRegisterReward()); marketUser.setCardorderProportion(organ.getMemberCardorderProportion()); } return marketUserService.update(marketUser, "userName", "phone", "pwd", "realName", "head", "gender", "cityid","idcardNo", "idcardImg","locked","registerReward","cardorderProportion","webchatOpenid","alipayAccount","organizationId","annualCardorderProportion","cardorderForRegions"); } @At @POST @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result add(@Param("..") MarketUser marketUser,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"添加营销用户,ID:"+marketUser.getId(); adminlogs.add(request,dao,user,"添加营销用户",2,remark); marketUser.setPwd(Lang.md5(marketUser.getPwd()).substring(6, 22)); marketUser.setRegisterTime(new Date()); if(marketUser.getOrganizationId()==0){ marketUser.setRegisterReward(marketUser.getRegisterReward()); marketUser.setCardorderProportion(marketUser.getCardorderProportion()); }else{ MarketOrganization organ=marketOrganizationService.findById(marketUser.getOrganizationId()); marketUser.setRegisterReward(organ.getMemberRegisterReward()); marketUser.setCardorderProportion(organ.getMemberCardorderProportion()); } marketUser = marketUserService.addMarketUser(marketUser); return marketUser != null ? Result.success() : Result.fail("添加营销用户失败"); } @At @POST @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" }) public Result addbatch(@Param("file") TempFile file,@Param("..") MarketUser marketUser,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ int organid=marketUser.getOrganizationId(); double registerReward=0; double cardorderProportion=0; double annualCardorderProportion=0; String cardorderForRegions=""; if(organid==0){ registerReward=marketUser.getRegisterReward(); cardorderProportion=marketUser.getCardorderProportion(); annualCardorderProportion=marketUser.getAnnualCardorderProportion(); cardorderForRegions=marketUser.getCardorderForRegions(); }else{ MarketOrganization organ=marketOrganizationService.findById(marketUser.getOrganizationId()); registerReward=organ.getMemberRegisterReward(); cardorderProportion=organ.getMemberCardorderProportion(); annualCardorderProportion=organ.getMemberAnnualCardorderProportion(); cardorderForRegions=organ.getCardorderForRegions(); } List<MarketUser> muser=readExcelPublic(file.getFile().getAbsolutePath()); if(muser==null){ return Result.fail("数据导入失败,请重新导入"); } for (MarketUser newMarketUser : muser) { //pwd 密码 int pwd=(int)((Math.random()*9+1)*10000000); newMarketUser.setOrganizationId(organid);//旅行社id newMarketUser.setUserName("user_"+getUUID());//登录名 newMarketUser.setRegisterTime(new Date());//注册时间 newMarketUser.setLocked(0);//是否锁定 newMarketUser.setRegisterReward(registerReward);//注册用户奖励额度 newMarketUser.setCardorderProportion(cardorderProportion);//导览卡分成比例 newMarketUser.setAnnualCardorderProportion(annualCardorderProportion);//会员通票分成比例 newMarketUser.setCardorderForRegions(cardorderForRegions); } List<MarketUser> mu=dao.insert(muser); if(mu.size()>0){ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"批量添加营销用户,ID:"+marketUser.getId(); adminlogs.add(request,dao,user,"批量添加营销用户",2,remark); return Result.success(); }else{ return Result.fail("批量添加营销用户失败"); } } @At("/delete/*") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result delete(int id,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"删除营销用户信息,ID:"+id; adminlogs.add(request,dao,user,"删除营销用户信息",2,remark); return marketUserService.deleteMarketUser(id) ? Result.success() : Result.fail("删除营销用户信息"); } @At("/detail/*") @GET @Ok("vel:market/marketuser/detail.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result detail(int id) { MarketUser marketuser = marketUserService.findById(id); City city=cityService.detailCity(marketuser.getCityid()); String citys= cityService.detailCity(city.getParentid()).getCnname()+" "+city.getCnname(); List list=new ArrayList<>(); String imgs=marketuser.getIdcardImg(); String []img=null; if(imgs!=null&&!imgs.equals("")){ img=imgs.split(","); if(img.length>0){ for(int i=0;i<img.length;i++){ list.add(img[i]); } } } return Result.success().addData("marketuser", marketuser).addData("citys",citys).addData("list", list); } @At @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result deleteHead(@Param("id") int id) { MarketUser marketuser = marketUserService.findById(id); marketuser.setHead(""); if(dao.update(marketuser)>0){ return Result.success(); }else{ return Result.fail("删除失败"); } } @At @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result phone(@Param("phone") String phone) { try { MarketUser marketuser = dao.fetch(MarketUser.class ,Cnd.where("phone", "=", phone)); if(marketuser==null){ return Result.success(); }else{ return Result.fail("手机号已存在"); } } catch (Exception e) { // TODO: handle exception return Result.fail("手机号已存在"); } } /** * 解析excel文件 ,并把数据放入数组中 格式 xlsx xls * @param path 从ftp上下载到本地的文件的路径 * @return 数据数组集合 */ public List<MarketUser> readExcelPublic(String path) throws Exception{ List<MarketUser> list = new ArrayList<MarketUser>(); try { FileInputStream is = new FileInputStream(path); //文件流 Workbook workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的 Sheet sheet = workbook.getSheetAt(0);//得到excel第一页的内容 //获取总行数 int rowNum=sheet.getPhysicalNumberOfRows(); for (int i = 1; i < rowNum; i++) { //循环行数 Row row = sheet.getRow(i); //获取当前行的列长度 int cols_length = row.getPhysicalNumberOfCells(); //设置当前数组长度 5 MarketUser info=new MarketUser(); //使用实体类封装单元格数据 //String 类型 //姓名 if(row.getCell(0)!=null){ row.getCell(0).setCellType(Cell.CELL_TYPE_STRING); info.setRealName(row.getCell(0).getStringCellValue()); }else{ info.setRealName(""); } //联系方式 if(row.getCell(1)!=null){ row.getCell(1).setCellType(Cell.CELL_TYPE_STRING); info.setPhone(row.getCell(1).getStringCellValue()); }else{ info.setPhone(""); } //int 类型 //性别 if(row.getCell(2)!=null){ row.getCell(2).setCellType(Cell.CELL_TYPE_STRING); String sex=row.getCell(2).getStringCellValue(); if(sex.equals("男")){ info.setGender(1); }else{ info.setGender(0); } }else{ info.setGender(1); } //String 类型 //身份证号 if(row.getCell(3)!=null){ row.getCell(3).setCellType(Cell.CELL_TYPE_STRING); info.setIdcardNo(row.getCell(3).getStringCellValue()); }else{ info.setIdcardNo(""); } //String 类型 //所属城市 if(row.getCell(4)!=null){ row.getCell(4).setCellType(Cell.CELL_TYPE_STRING); City city=dao.fetch(City.class, Cnd.wrap("cnname like '%"+row.getCell(4).getStringCellValue()+"%' and parentid != 0")); if(city!=null){ info.setCityid(city.getId()); } } //String 类型 //登录密码 if(row.getCell(5)!=null){ row.getCell(5).setCellType(Cell.CELL_TYPE_STRING); info.setPwd(Lang.md5(row.getCell(5).getStringCellValue()).substring(6, 22)); }else{ info.setPwd(""); } //String 类型 //支付宝账号 if(row.getCell(6)!=null){ row.getCell(6).setCellType(Cell.CELL_TYPE_STRING); info.setAlipayAccount(row.getCell(6).getStringCellValue()); }else{ info.setAlipayAccount(""); } list.add(info); } } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (InvalidFormatException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } return list; } public static String getUUID(){ UUID uuid = UUID.randomUUID(); String s = uuid.toString();// int p = 0; int j = 0; char[] buf = new char[32]; while(p<s.length()){ char c = s.charAt(p); p+=1; if(c=='-')continue; buf[j]=c;j+=1; } return new String(buf); } /*** * 导出excel 功能 * * */ @At @GET @Ok("void") @RequiresRoles(value = { "regionAdmin", "admin","jingqu" ,"manager"}, logical = Logical.OR) public Result downloadExcel(HttpServletRequest request, HttpServletResponse response,String downloadtime,String starttime,String endtime,int organizationId,int cityid,int regionId,@Attr(SessionKeys.SESSION_USER_KEY) User user,@Attr(SessionKeys.SESSION_REGION_KEY) Region region)throws Exception { //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"下载营销人员名单"; adminlogs.add(request,dao,user,"下载营销人员名单",2,remark); String excelName =""; try { if(downloadtime.equals("today")){ starttime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesmorning()); endtime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesnight()); }else if(downloadtime.equals("weekday")){ starttime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesByWeek(TimeUtils.getTimesnight())); endtime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesnight()); }else if(downloadtime.equals("months")){ starttime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesByMonth(TimeUtils.getTimesnight())); endtime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesnight()); }else{ starttime=starttime; endtime=endtime; } OutputStream out = response.getOutputStream(); if(getList(downloadtime,starttime,endtime,organizationId,cityid,user,region,regionId).size()==0){ String path=request.getContextPath(); response.sendRedirect(path+"/marketuser/list?sysbml=1"); }else{ response.setContentType("octets/stream"); excelName =starttime.replace("-", "_").substring(0, 10)+"至"+endtime.replace("-", "_").substring(0, 10)+ "营销用户表"; //excelName = "2016_06_07至2018_07_07订单记录表"; //转码防止乱码 response.addHeader("Content-Disposition", "attachment;filename="+new String( excelName.getBytes("gb2312"), "ISO8859-1" )+".xls"); String[] headers = new String[]{"编号","组织名称","登录名","联系方式","真实姓名","性别","所属城市","身份证号","注册时间","是否锁定","总金额","注册分成","导览卡分成比例","会员通票分成比例","微信账号","支付宝账号"}; exportExcel(excelName,headers, getList(downloadtime,starttime,endtime,organizationId,cityid,user,region,regionId),out,"yyyy-MM-dd"); } out.flush(); out.close(); //System.out.println("excel导出成功!"); } catch (FileNotFoundException e) { // e.printStackTrace(); } catch (IOException e) { // e.printStackTrace(); } return Result.success(); } public List<Map<String,Object>> getList(String downloadtime,String starttime,String endtime,int organizationId,int cityid,User user,Region region,int regionId ){ List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); List<Record> listExcel=marketUserService.findOagnizationUserToExcel(downloadtime,starttime, endtime,organizationId,cityid, user, region,regionId); if(listExcel==null){ return null; } if(listExcel!=null&&listExcel.size()>0){ for(int i = 0; i<listExcel.size();i++){ Map<String,Object> map = new HashMap<String, Object>(); map.put("number",listExcel.get(i).getInt("id")); if(listExcel.get(i).getInt("organizationId")==0){ map.put("organizationName", "野导游"); }else{ map.put("organizationName", listExcel.get(i).getString("oName")); } map.put("userName", listExcel.get(i).getString("userName")); map.put("phone", listExcel.get(i).getString("phone")); map.put("realName", listExcel.get(i).getString("realName")); if(listExcel.get(i).getInt("gender")==1){ map.put("gender","男"); }else{ map.put("gender","女"); } map.put("cName", listExcel.get(i).getString("cName")); map.put("idcardNo",listExcel.get(i).getString("idcardNo")); map.put("registerTime", listExcel.get(i).getString("registerTime")); if(listExcel.get(i).getInt("locked")==1){ map.put("locked","锁定"); }else{ map.put("locked","未锁定"); } map.put("balance",listExcel.get(i).getString("balance")); if(listExcel.get(i).getInt("organizationId")==0){ map.put("registerReward",listExcel.get(i).getString("registerReward")); map.put("cardorderProportion",listExcel.get(i).getString("cardorderProportion")); map.put("annualCardorderProportion",listExcel.get(i).getString("annualCardorderProportion")); }else{ MarketOrganization or=marketOrganizationService.findById(listExcel.get(i).getInt("organizationId")); map.put("registerReward",or.getMemberRegisterReward()); map.put("cardorderProportion",or.getMemberCardorderProportion()); map.put("annualCardorderProportion",or.getAnnualCardorderProportion()); } map.put("webchatOpenid",listExcel.get(i).getString("webchatOpenid")); map.put("alipayAccount",listExcel.get(i).getString("alipayAccount")); list.add(map); } } return list; } /** * * @Description: 生成excel并导出到客户端(本地) * @Auther: lihongwu * @Date: */ protected void exportExcel(String title,String[] headers,List mapList,OutputStream out,String pattern){ //声明一个工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); //生成一个表格 HSSFSheet sheet = workbook.createSheet(title); //设置表格默认列宽度为15个字符 sheet.setDefaultColumnWidth((short)20); //生成一个样式,用来设置标题样式 HSSFCellStyle style = workbook.createCellStyle(); //设置这些样式 style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //生成一个字体 HSSFFont font = workbook.createFont(); font.setColor(HSSFColor.VIOLET.index); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //把字体应用到当前的样式 style.setFont(font); // 生成并设置另一个样式,用于设置内容样式 HSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成另一个字体 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 把字体应用到当前的样式 style2.setFont(font2); //产生表格标题行 HSSFRow row = sheet.createRow(0); for(int i = 0; i<headers.length;i++){ HSSFCell cell = row.createCell((short)i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } for (int i=0;i<mapList.size();i++) { Map<String,Object> map = (Map<String, Object>) mapList.get(i); row = sheet.createRow(i+1); int j = 0; Object value = null; value=map.get("number"); if(value instanceof Integer){ row.createCell((short)j++).setCellValue(String.valueOf(value)); } if(map.get("organizationName")!=null&&!map.get("organizationName").equals("")){ row.createCell((short)j++).setCellValue(map.get("organizationName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("userName")!=null&&!map.get("userName").equals("")){ row.createCell((short)j++).setCellValue(map.get("userName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("phone")!=null&&!map.get("phone").equals("")){ row.createCell((short)j++).setCellValue(map.get("phone").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("realName")!=null&&!map.get("realName").equals("")){ row.createCell((short)j++).setCellValue(map.get("realName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("gender")!=null&&!map.get("gender").equals("")){ row.createCell((short)j++).setCellValue(map.get("gender").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("cName")!=null&&!map.get("cName").equals("")){ row.createCell((short)j++).setCellValue(map.get("cName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("idcardNo")!=null&&!map.get("idcardNo").equals("")){ row.createCell((short)j++).setCellValue(map.get("idcardNo").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("registerTime")!=null&&!map.get("registerTime").equals("")){ row.createCell((short)j++).setCellValue(map.get("registerTime").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("locked")!=null&&!map.get("locked").equals("")){ row.createCell((short)j++).setCellValue(map.get("locked").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("balance")!=null&&!map.get("balance").equals("")){ row.createCell((short)j++).setCellValue(map.get("balance").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("registerReward")!=null&&!map.get("registerReward").equals("")){ row.createCell((short)j++).setCellValue(map.get("registerReward").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("cardorderProportion")!=null&&!map.get("cardorderProportion").equals("")){ row.createCell((short)j++).setCellValue(map.get("cardorderProportion").toString()+"%"); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("annualCardorderProportion")!=null&&!map.get("annualCardorderProportion").equals("")){ row.createCell((short)j++).setCellValue(map.get("annualCardorderProportion").toString()+"%"); }else{ row.createCell((short)j++).setCellValue(""); } /*value=map.get("price"); if(value instanceof Double){ row.createCell((short)j++).setCellValue(String.valueOf(value)); }*/ if(map.get("webchatOpenid")!=null&&!map.get("webchatOpenid").equals("")){ row.createCell((short)j++).setCellValue(map.get("webchatOpenid").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("alipayAccount")!=null&&!map.get("alipayAccount").equals("")){ row.createCell((short)j++).setCellValue(map.get("alipayAccount").toString()); }else{ row.createCell((short)j++).setCellValue(""); } } try { workbook.write(out); } catch (IOException e) { //e.printStackTrace(); } } public static void main(String[] args) { int random=(int)((Math.random()*9+1)*10000000); // System.out.println(random); UUID.randomUUID(); System.out.println(getUUID()); /*for(int i=0;i<10;i++){ Random rad=new Random(); long s= Math.abs(rad.nextLong()); String ss=Long.toString(s); //System.out.println(rad.nextLong()); System.out.println("绝对值:"+s); System.out.println("字符串:"+ss); }*/ } }
UTF-8
Java
32,335
java
MarketUserModule.java
Java
[ { "context": "}\r\n\t\treturn marketUserService.update(marketUser, \"userName\", \"phone\", \"pwd\", \"realName\", \"head\", \"gender\", \"", "end": 9531, "score": 0.9978219270706177, "start": 9523, "tag": "USERNAME", "value": "userName" }, { "context": "or (MarketUser newMarketUser : muser) {\r\n\t\t\t//pwd 密码\r\n\t\t\tint pwd=(int)((Math.random()*9+1)*10000000);\r", "end": 12303, "score": 0.9591916799545288, "start": 12301, "tag": "PASSWORD", "value": "密码" }, { "context": "d(organid);//旅行社id\r\n\t\t\tnewMarketUser.setUserName(\"user_\"+getUUID());//登录名\r\n\t\t\tnewMarketUser.setRegisterT", "end": 12441, "score": 0.6848961114883423, "start": 12437, "tag": "USERNAME", "value": "user" }, { "context": "\t\tmap.put(\"userName\", listExcel.get(i).getString(\"userName\"));\r\n\t\t\t\tmap.put(\"phone\", listExcel.get(i).getStr", "end": 23279, "score": 0.8885738253593445, "start": 23271, "tag": "USERNAME", "value": "userName" }, { "context": "\t * @Description: 生成excel并导出到客户端(本地)\r\n\t * @Auther: lihongwu\r\n\t * @Date:\r\n\t */\r\n\tprotected void exportExcel(St", "end": 24857, "score": 0.9988918304443359, "start": 24849, "tag": "USERNAME", "value": "lihongwu" }, { "context": "hort)j++).setCellValue(\"\");\r\n\t\t\t}\r\n\t\t\tif(map.get(\"userName\")!=null&&!map.get(\"userName\").equals(\"\")){\r\n\t\t\t\tr", "end": 27338, "score": 0.9989645481109619, "start": 27330, "tag": "USERNAME", "value": "userName" }, { "context": "\n\t\t\t}\r\n\t\t\tif(map.get(\"userName\")!=null&&!map.get(\"userName\").equals(\"\")){\r\n\t\t\t\trow.createCell((short)j++).se", "end": 27366, "score": 0.9986044764518738, "start": 27358, "tag": "USERNAME", "value": "userName" }, { "context": "\trow.createCell((short)j++).setCellValue(map.get(\"userName\").toString());\r\n\t\t\t}else{\r\n\t\t\t\trow.createCell((sh", "end": 27444, "score": 0.9988435506820679, "start": 27436, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.brt.museum.module.market; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresRoles; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.dao.entity.Record; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.lang.Lang; import org.nutz.mvc.annotation.AdaptBy; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Attr; import org.nutz.mvc.annotation.GET; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.POST; import org.nutz.mvc.annotation.Param; import org.nutz.mvc.upload.TempFile; import org.nutz.mvc.upload.UploadAdaptor; import com.brt.museum.bean.auth.User; import com.brt.museum.bean.city.City; import com.brt.museum.bean.content.Region; import com.brt.museum.bean.market.MarketOrganization; import com.brt.museum.bean.market.MarketUser; import com.brt.museum.bean.youzan.YZanRegionRelate; import com.brt.museum.module.adminlogs.AdminLogsModule; import com.brt.museum.service.city.ICityService; import com.brt.museum.service.content.IRegionService; import com.brt.museum.service.market.IMarketUserService; import com.brt.museum.service.organization.IMarketOrganizationService; import com.brt.museum.service.youzan.IYZanProductService; import com.brt.museum.service.youzan.IYZanRegionRelateService; import com.brt.museum.utils.OtherUtils; import com.brt.museum.utils.TimeUtils; import com.brt.museum.vo.Consts.PermissionGroup; import com.brt.museum.vo.Consts.SessionKeys; import com.dgj.nutz.module.base.AbstractBaseModule; import com.dgj.utils.entries.Result; import com.dgj.utils.web.pager.Pager; @At("/marketuser") public class MarketUserModule extends AbstractBaseModule { @Inject IMarketUserService marketUserService; @Inject Dao dao; @Inject ICityService cityService; @Inject IMarketOrganizationService marketOrganizationService; @Inject private IRegionService regionService; @Override public String _getNameSpace() { return PermissionGroup.MARKET_ADMIN.getNameSpace(); } @At @GET @Ok("vel:market/marketuser/list.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result list(@Param(value = "page", df = "1") int page,String sysbml,@Attr(SessionKeys.SESSION_USER_KEY) User user,@Attr(SessionKeys.SESSION_REGION_KEY) Region region) { Pager<Record> pager = marketUserService.listByPage(page); pager.setUrl(_base() + "/marketuser/list"); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); List<City> city=cityService.list(); List<Region> records = regionService.findRegion(); return Result.success().addData("pager", pager).addData("sysbml",sysbml).addData("organization", organization).addData("city", city).addData("records", records); } @At @Ok("vel:market/marketuser/list.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result search(@Param(value = "page", df = "1") int page, @Param("key") String key,@Param("searchkey") int searchkey,@Attr(SessionKeys.SESSION_USER_KEY) User user,@Attr(SessionKeys.SESSION_REGION_KEY) Region region) { key = _fixSearchKey(key); Pager<Record> pager = marketUserService.searchByKey(page, key,searchkey); pager.setUrl(_base() + "/marketuser/search"); pager.addParas("key", key); pager.addParas("searchkey", searchkey); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); List<City> city=cityService.list(); List<Region> records = regionService.findRegion(); return Result.success().addData("pager", pager).addData("organization", organization).addData("city", city).addData("records", records); } @At @GET @Ok("vel:market/marketuser/add_edit.html") @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result add() { List<City> city=cityService.list(); //查询景区 List<Region> regions=regionService.findRegion(); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); return Result.success().addData("city", city).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); } @At @GET @Ok("vel:market/marketuser/batch/add_edit.html") @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result addbatch() { List<City> city=cityService.list(); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); //查询景区 List<Region> regions=regionService.findRegion(); return Result.success().addData("city", city).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); } @At @RequiresRoles(value = { "regionAdmin", "admin","manager" }, logical = Logical.OR) public Result searchCity(@Param("cityid") int cityid) { List<City> city=cityService.listByParentId(cityid); return Result.success().addData("citys", city); } @At("/edit/*") @GET @Ok("vel:market/marketuser/add_edit.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result edit(int id) { MarketUser marketuser = marketUserService.findById(id); //查询景区地图 List list=new ArrayList<>(); String imgs=marketuser.getIdcardImg(); String []img=null; if(imgs!=null&&!imgs.equals("")){ img=imgs.split(","); if(img.length>0){ for(int i=0;i<img.length;i++){ list.add(img[i]); } } } //查询景区 List<Region> regions=regionService.findRegion(); List<MarketOrganization> organization=dao.query(MarketOrganization.class, Cnd.where(null)); List<City> province=cityService.list(); List<City> provinces=new ArrayList<City>(); List<City> citys=new ArrayList<City>(); //已选择城市 City city = cityService.detailCity(marketuser.getCityid()); if(city!=null){ citys.add(city); //已选择省市 City provinceCity = cityService.detailCity(city.getParentid()); provinces.add(provinceCity); //排列组合 省市 for(int i=0;i<province.size();i++){ if(province.get(i).getId()!=provinceCity.getId()){ provinces.add(province.get(i)); }else{ continue; } } //查询该省市下的城市 List<City> provinceByCity=cityService.listByParentId(city.getParentid()); //排列组合 省市 for(int j=0;j<provinceByCity.size();j++){ if(provinceByCity.get(j).getId()!=city.getId()){ citys.add(provinceByCity.get(j)); }else{ continue; } } return Result.success().addData("marketuser", marketuser).addData("provinces", provinces).addData("citys", citys).addData("sysbml", 1).addData("list", list).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); }else{ return Result.success().addData("marketuser", marketuser).addData("provinces", province).addData("sysbml", 0).addData("list", list).addData("proportion", OtherUtils.list()).addData("organization", organization).addData("regions", regions); } } @At @POST @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result update(@Param("..") MarketUser marketUser,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"修改营销用户,ID:"+marketUser.getId()+",名称:"+marketUser.getUserName(); adminlogs.add(request,dao,user,"修改营销用户",2,remark); MarketUser mu=marketUserService.findById(marketUser.getId()); if(!mu.getPwd().equals(marketUser.getPwd())){ marketUser.setPwd(Lang.md5(marketUser.getPwd()).substring(6, 22)); } if(marketUser.getOrganizationId()==0){ marketUser.setRegisterReward(marketUser.getRegisterReward()); marketUser.setCardorderProportion(marketUser.getCardorderProportion()); }else{ MarketOrganization organ=marketOrganizationService.findById(marketUser.getOrganizationId()); marketUser.setRegisterReward(organ.getMemberRegisterReward()); marketUser.setCardorderProportion(organ.getMemberCardorderProportion()); } return marketUserService.update(marketUser, "userName", "phone", "pwd", "realName", "head", "gender", "cityid","idcardNo", "idcardImg","locked","registerReward","cardorderProportion","webchatOpenid","alipayAccount","organizationId","annualCardorderProportion","cardorderForRegions"); } @At @POST @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result add(@Param("..") MarketUser marketUser,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"添加营销用户,ID:"+marketUser.getId(); adminlogs.add(request,dao,user,"添加营销用户",2,remark); marketUser.setPwd(Lang.md5(marketUser.getPwd()).substring(6, 22)); marketUser.setRegisterTime(new Date()); if(marketUser.getOrganizationId()==0){ marketUser.setRegisterReward(marketUser.getRegisterReward()); marketUser.setCardorderProportion(marketUser.getCardorderProportion()); }else{ MarketOrganization organ=marketOrganizationService.findById(marketUser.getOrganizationId()); marketUser.setRegisterReward(organ.getMemberRegisterReward()); marketUser.setCardorderProportion(organ.getMemberCardorderProportion()); } marketUser = marketUserService.addMarketUser(marketUser); return marketUser != null ? Result.success() : Result.fail("添加营销用户失败"); } @At @POST @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" }) public Result addbatch(@Param("file") TempFile file,@Param("..") MarketUser marketUser,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ int organid=marketUser.getOrganizationId(); double registerReward=0; double cardorderProportion=0; double annualCardorderProportion=0; String cardorderForRegions=""; if(organid==0){ registerReward=marketUser.getRegisterReward(); cardorderProportion=marketUser.getCardorderProportion(); annualCardorderProportion=marketUser.getAnnualCardorderProportion(); cardorderForRegions=marketUser.getCardorderForRegions(); }else{ MarketOrganization organ=marketOrganizationService.findById(marketUser.getOrganizationId()); registerReward=organ.getMemberRegisterReward(); cardorderProportion=organ.getMemberCardorderProportion(); annualCardorderProportion=organ.getMemberAnnualCardorderProportion(); cardorderForRegions=organ.getCardorderForRegions(); } List<MarketUser> muser=readExcelPublic(file.getFile().getAbsolutePath()); if(muser==null){ return Result.fail("数据导入失败,请重新导入"); } for (MarketUser newMarketUser : muser) { //pwd 密码 int pwd=(int)((Math.random()*9+1)*10000000); newMarketUser.setOrganizationId(organid);//旅行社id newMarketUser.setUserName("user_"+getUUID());//登录名 newMarketUser.setRegisterTime(new Date());//注册时间 newMarketUser.setLocked(0);//是否锁定 newMarketUser.setRegisterReward(registerReward);//注册用户奖励额度 newMarketUser.setCardorderProportion(cardorderProportion);//导览卡分成比例 newMarketUser.setAnnualCardorderProportion(annualCardorderProportion);//会员通票分成比例 newMarketUser.setCardorderForRegions(cardorderForRegions); } List<MarketUser> mu=dao.insert(muser); if(mu.size()>0){ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"批量添加营销用户,ID:"+marketUser.getId(); adminlogs.add(request,dao,user,"批量添加营销用户",2,remark); return Result.success(); }else{ return Result.fail("批量添加营销用户失败"); } } @At("/delete/*") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result delete(int id,@Attr(SessionKeys.SESSION_USER_KEY) User user,HttpServletRequest request) throws Exception{ //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"删除营销用户信息,ID:"+id; adminlogs.add(request,dao,user,"删除营销用户信息",2,remark); return marketUserService.deleteMarketUser(id) ? Result.success() : Result.fail("删除营销用户信息"); } @At("/detail/*") @GET @Ok("vel:market/marketuser/detail.html") @RequiresRoles(value = { "regionAdmin", "admin","manager"}, logical = Logical.OR) public Result detail(int id) { MarketUser marketuser = marketUserService.findById(id); City city=cityService.detailCity(marketuser.getCityid()); String citys= cityService.detailCity(city.getParentid()).getCnname()+" "+city.getCnname(); List list=new ArrayList<>(); String imgs=marketuser.getIdcardImg(); String []img=null; if(imgs!=null&&!imgs.equals("")){ img=imgs.split(","); if(img.length>0){ for(int i=0;i<img.length;i++){ list.add(img[i]); } } } return Result.success().addData("marketuser", marketuser).addData("citys",citys).addData("list", list); } @At @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result deleteHead(@Param("id") int id) { MarketUser marketuser = marketUserService.findById(id); marketuser.setHead(""); if(dao.update(marketuser)>0){ return Result.success(); }else{ return Result.fail("删除失败"); } } @At @RequiresRoles(value = { "regionAdmin", "admin" ,"manager"}, logical = Logical.OR) public Result phone(@Param("phone") String phone) { try { MarketUser marketuser = dao.fetch(MarketUser.class ,Cnd.where("phone", "=", phone)); if(marketuser==null){ return Result.success(); }else{ return Result.fail("手机号已存在"); } } catch (Exception e) { // TODO: handle exception return Result.fail("手机号已存在"); } } /** * 解析excel文件 ,并把数据放入数组中 格式 xlsx xls * @param path 从ftp上下载到本地的文件的路径 * @return 数据数组集合 */ public List<MarketUser> readExcelPublic(String path) throws Exception{ List<MarketUser> list = new ArrayList<MarketUser>(); try { FileInputStream is = new FileInputStream(path); //文件流 Workbook workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的 Sheet sheet = workbook.getSheetAt(0);//得到excel第一页的内容 //获取总行数 int rowNum=sheet.getPhysicalNumberOfRows(); for (int i = 1; i < rowNum; i++) { //循环行数 Row row = sheet.getRow(i); //获取当前行的列长度 int cols_length = row.getPhysicalNumberOfCells(); //设置当前数组长度 5 MarketUser info=new MarketUser(); //使用实体类封装单元格数据 //String 类型 //姓名 if(row.getCell(0)!=null){ row.getCell(0).setCellType(Cell.CELL_TYPE_STRING); info.setRealName(row.getCell(0).getStringCellValue()); }else{ info.setRealName(""); } //联系方式 if(row.getCell(1)!=null){ row.getCell(1).setCellType(Cell.CELL_TYPE_STRING); info.setPhone(row.getCell(1).getStringCellValue()); }else{ info.setPhone(""); } //int 类型 //性别 if(row.getCell(2)!=null){ row.getCell(2).setCellType(Cell.CELL_TYPE_STRING); String sex=row.getCell(2).getStringCellValue(); if(sex.equals("男")){ info.setGender(1); }else{ info.setGender(0); } }else{ info.setGender(1); } //String 类型 //身份证号 if(row.getCell(3)!=null){ row.getCell(3).setCellType(Cell.CELL_TYPE_STRING); info.setIdcardNo(row.getCell(3).getStringCellValue()); }else{ info.setIdcardNo(""); } //String 类型 //所属城市 if(row.getCell(4)!=null){ row.getCell(4).setCellType(Cell.CELL_TYPE_STRING); City city=dao.fetch(City.class, Cnd.wrap("cnname like '%"+row.getCell(4).getStringCellValue()+"%' and parentid != 0")); if(city!=null){ info.setCityid(city.getId()); } } //String 类型 //登录密码 if(row.getCell(5)!=null){ row.getCell(5).setCellType(Cell.CELL_TYPE_STRING); info.setPwd(Lang.md5(row.getCell(5).getStringCellValue()).substring(6, 22)); }else{ info.setPwd(""); } //String 类型 //支付宝账号 if(row.getCell(6)!=null){ row.getCell(6).setCellType(Cell.CELL_TYPE_STRING); info.setAlipayAccount(row.getCell(6).getStringCellValue()); }else{ info.setAlipayAccount(""); } list.add(info); } } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (InvalidFormatException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } return list; } public static String getUUID(){ UUID uuid = UUID.randomUUID(); String s = uuid.toString();// int p = 0; int j = 0; char[] buf = new char[32]; while(p<s.length()){ char c = s.charAt(p); p+=1; if(c=='-')continue; buf[j]=c;j+=1; } return new String(buf); } /*** * 导出excel 功能 * * */ @At @GET @Ok("void") @RequiresRoles(value = { "regionAdmin", "admin","jingqu" ,"manager"}, logical = Logical.OR) public Result downloadExcel(HttpServletRequest request, HttpServletResponse response,String downloadtime,String starttime,String endtime,int organizationId,int cityid,int regionId,@Attr(SessionKeys.SESSION_USER_KEY) User user,@Attr(SessionKeys.SESSION_REGION_KEY) Region region)throws Exception { //记录操作 AdminLogsModule adminlogs=new AdminLogsModule(); String remark=""; remark="UserID:"+user.getId()+","+"下载营销人员名单"; adminlogs.add(request,dao,user,"下载营销人员名单",2,remark); String excelName =""; try { if(downloadtime.equals("today")){ starttime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesmorning()); endtime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesnight()); }else if(downloadtime.equals("weekday")){ starttime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesByWeek(TimeUtils.getTimesnight())); endtime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesnight()); }else if(downloadtime.equals("months")){ starttime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesByMonth(TimeUtils.getTimesnight())); endtime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(TimeUtils.getTimesnight()); }else{ starttime=starttime; endtime=endtime; } OutputStream out = response.getOutputStream(); if(getList(downloadtime,starttime,endtime,organizationId,cityid,user,region,regionId).size()==0){ String path=request.getContextPath(); response.sendRedirect(path+"/marketuser/list?sysbml=1"); }else{ response.setContentType("octets/stream"); excelName =starttime.replace("-", "_").substring(0, 10)+"至"+endtime.replace("-", "_").substring(0, 10)+ "营销用户表"; //excelName = "2016_06_07至2018_07_07订单记录表"; //转码防止乱码 response.addHeader("Content-Disposition", "attachment;filename="+new String( excelName.getBytes("gb2312"), "ISO8859-1" )+".xls"); String[] headers = new String[]{"编号","组织名称","登录名","联系方式","真实姓名","性别","所属城市","身份证号","注册时间","是否锁定","总金额","注册分成","导览卡分成比例","会员通票分成比例","微信账号","支付宝账号"}; exportExcel(excelName,headers, getList(downloadtime,starttime,endtime,organizationId,cityid,user,region,regionId),out,"yyyy-MM-dd"); } out.flush(); out.close(); //System.out.println("excel导出成功!"); } catch (FileNotFoundException e) { // e.printStackTrace(); } catch (IOException e) { // e.printStackTrace(); } return Result.success(); } public List<Map<String,Object>> getList(String downloadtime,String starttime,String endtime,int organizationId,int cityid,User user,Region region,int regionId ){ List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); List<Record> listExcel=marketUserService.findOagnizationUserToExcel(downloadtime,starttime, endtime,organizationId,cityid, user, region,regionId); if(listExcel==null){ return null; } if(listExcel!=null&&listExcel.size()>0){ for(int i = 0; i<listExcel.size();i++){ Map<String,Object> map = new HashMap<String, Object>(); map.put("number",listExcel.get(i).getInt("id")); if(listExcel.get(i).getInt("organizationId")==0){ map.put("organizationName", "野导游"); }else{ map.put("organizationName", listExcel.get(i).getString("oName")); } map.put("userName", listExcel.get(i).getString("userName")); map.put("phone", listExcel.get(i).getString("phone")); map.put("realName", listExcel.get(i).getString("realName")); if(listExcel.get(i).getInt("gender")==1){ map.put("gender","男"); }else{ map.put("gender","女"); } map.put("cName", listExcel.get(i).getString("cName")); map.put("idcardNo",listExcel.get(i).getString("idcardNo")); map.put("registerTime", listExcel.get(i).getString("registerTime")); if(listExcel.get(i).getInt("locked")==1){ map.put("locked","锁定"); }else{ map.put("locked","未锁定"); } map.put("balance",listExcel.get(i).getString("balance")); if(listExcel.get(i).getInt("organizationId")==0){ map.put("registerReward",listExcel.get(i).getString("registerReward")); map.put("cardorderProportion",listExcel.get(i).getString("cardorderProportion")); map.put("annualCardorderProportion",listExcel.get(i).getString("annualCardorderProportion")); }else{ MarketOrganization or=marketOrganizationService.findById(listExcel.get(i).getInt("organizationId")); map.put("registerReward",or.getMemberRegisterReward()); map.put("cardorderProportion",or.getMemberCardorderProportion()); map.put("annualCardorderProportion",or.getAnnualCardorderProportion()); } map.put("webchatOpenid",listExcel.get(i).getString("webchatOpenid")); map.put("alipayAccount",listExcel.get(i).getString("alipayAccount")); list.add(map); } } return list; } /** * * @Description: 生成excel并导出到客户端(本地) * @Auther: lihongwu * @Date: */ protected void exportExcel(String title,String[] headers,List mapList,OutputStream out,String pattern){ //声明一个工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); //生成一个表格 HSSFSheet sheet = workbook.createSheet(title); //设置表格默认列宽度为15个字符 sheet.setDefaultColumnWidth((short)20); //生成一个样式,用来设置标题样式 HSSFCellStyle style = workbook.createCellStyle(); //设置这些样式 style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //生成一个字体 HSSFFont font = workbook.createFont(); font.setColor(HSSFColor.VIOLET.index); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //把字体应用到当前的样式 style.setFont(font); // 生成并设置另一个样式,用于设置内容样式 HSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成另一个字体 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 把字体应用到当前的样式 style2.setFont(font2); //产生表格标题行 HSSFRow row = sheet.createRow(0); for(int i = 0; i<headers.length;i++){ HSSFCell cell = row.createCell((short)i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } for (int i=0;i<mapList.size();i++) { Map<String,Object> map = (Map<String, Object>) mapList.get(i); row = sheet.createRow(i+1); int j = 0; Object value = null; value=map.get("number"); if(value instanceof Integer){ row.createCell((short)j++).setCellValue(String.valueOf(value)); } if(map.get("organizationName")!=null&&!map.get("organizationName").equals("")){ row.createCell((short)j++).setCellValue(map.get("organizationName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("userName")!=null&&!map.get("userName").equals("")){ row.createCell((short)j++).setCellValue(map.get("userName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("phone")!=null&&!map.get("phone").equals("")){ row.createCell((short)j++).setCellValue(map.get("phone").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("realName")!=null&&!map.get("realName").equals("")){ row.createCell((short)j++).setCellValue(map.get("realName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("gender")!=null&&!map.get("gender").equals("")){ row.createCell((short)j++).setCellValue(map.get("gender").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("cName")!=null&&!map.get("cName").equals("")){ row.createCell((short)j++).setCellValue(map.get("cName").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("idcardNo")!=null&&!map.get("idcardNo").equals("")){ row.createCell((short)j++).setCellValue(map.get("idcardNo").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("registerTime")!=null&&!map.get("registerTime").equals("")){ row.createCell((short)j++).setCellValue(map.get("registerTime").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("locked")!=null&&!map.get("locked").equals("")){ row.createCell((short)j++).setCellValue(map.get("locked").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("balance")!=null&&!map.get("balance").equals("")){ row.createCell((short)j++).setCellValue(map.get("balance").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("registerReward")!=null&&!map.get("registerReward").equals("")){ row.createCell((short)j++).setCellValue(map.get("registerReward").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("cardorderProportion")!=null&&!map.get("cardorderProportion").equals("")){ row.createCell((short)j++).setCellValue(map.get("cardorderProportion").toString()+"%"); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("annualCardorderProportion")!=null&&!map.get("annualCardorderProportion").equals("")){ row.createCell((short)j++).setCellValue(map.get("annualCardorderProportion").toString()+"%"); }else{ row.createCell((short)j++).setCellValue(""); } /*value=map.get("price"); if(value instanceof Double){ row.createCell((short)j++).setCellValue(String.valueOf(value)); }*/ if(map.get("webchatOpenid")!=null&&!map.get("webchatOpenid").equals("")){ row.createCell((short)j++).setCellValue(map.get("webchatOpenid").toString()); }else{ row.createCell((short)j++).setCellValue(""); } if(map.get("alipayAccount")!=null&&!map.get("alipayAccount").equals("")){ row.createCell((short)j++).setCellValue(map.get("alipayAccount").toString()); }else{ row.createCell((short)j++).setCellValue(""); } } try { workbook.write(out); } catch (IOException e) { //e.printStackTrace(); } } public static void main(String[] args) { int random=(int)((Math.random()*9+1)*10000000); // System.out.println(random); UUID.randomUUID(); System.out.println(getUUID()); /*for(int i=0;i<10;i++){ Random rad=new Random(); long s= Math.abs(rad.nextLong()); String ss=Long.toString(s); //System.out.println(rad.nextLong()); System.out.println("绝对值:"+s); System.out.println("字符串:"+ss); }*/ } }
32,335
0.658306
0.652943
751
39.463383
35.341717
297
false
false
0
0
0
0
0
0
2.876165
false
false
5
52d7198d14ecf4a91b31aca02054a7f458d86e33
20,667,382,629,938
ccf82688f082e26cba5fc397c76c77cc007ab2e8
/Mage/src/main/java/mage/abilities/keyword/HeroicAbility.java
a7e22c11e43b38c83815053e54e4f40e86a6c1b5
[ "MIT" ]
permissive
magefree/mage
https://github.com/magefree/mage
3261a89320f586d698dd03ca759a7562829f247f
5dba61244c738f4a184af0d256046312ce21d911
refs/heads/master
2023-09-03T15:55:36.650000
2023-09-03T03:53:12
2023-09-03T03:53:12
4,158,448
1,803
1,133
MIT
false
2023-09-14T20:18:55
2012-04-27T13:18:34
2023-09-11T18:25:38
2023-09-14T20:18:55
801,396
1,632
712
1,307
Java
false
false
package mage.abilities.keyword; import mage.abilities.Mode; import mage.abilities.SpellAbility; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.Effect; import mage.constants.AbilityWord; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.stack.Spell; import mage.target.Target; import java.util.UUID; /** * Heroic * * @author LevelX2 */ public class HeroicAbility extends TriggeredAbilityImpl { public HeroicAbility(Effect effect) { this(effect, false); } public HeroicAbility(Effect effect, boolean optional) { this(effect, optional, true); } public HeroicAbility(Effect effect, boolean optional, boolean isHeroic) { super(Zone.BATTLEFIELD, effect, optional); if (isHeroic) { this.setAbilityWord(AbilityWord.HEROIC); } this.replaceRuleText = false; setTriggerPhrase("Whenever you cast a spell that targets {this}, "); } protected HeroicAbility(final HeroicAbility ability) { super(ability); } @Override public HeroicAbility copy() { return new HeroicAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.SPELL_CAST; } @Override public boolean checkTrigger(GameEvent event, Game game) { if (event.getPlayerId().equals(this.getControllerId())) { Spell spell = game.getStack().getSpell(event.getTargetId()); if (checkSpell(spell, game)) { return true; } } return false; } private boolean checkSpell(Spell spell, Game game) { if (spell == null) { return false; } SpellAbility sa = spell.getSpellAbility(); for (UUID modeId : sa.getModes().getSelectedModes()) { Mode mode = sa.getModes().get(modeId); for (Target target : mode.getTargets()) { if (!target.isNotTarget() && target.getTargets().contains(this.getSourceId())) { return true; } } for (Effect effect : mode.getEffects()) { for (UUID targetId : effect.getTargetPointer().getTargets(game, sa)) { if (targetId.equals(this.getSourceId())) { return true; } } } } return false; } }
UTF-8
Java
2,517
java
HeroicAbility.java
Java
[ { "context": "mport java.util.UUID;\n\n/**\n * Heroic\n *\n * @author LevelX2\n */\npublic class HeroicAbility extends TriggeredAb", "end": 418, "score": 0.986748993396759, "start": 411, "tag": "USERNAME", "value": "LevelX2" } ]
null
[]
package mage.abilities.keyword; import mage.abilities.Mode; import mage.abilities.SpellAbility; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.Effect; import mage.constants.AbilityWord; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.stack.Spell; import mage.target.Target; import java.util.UUID; /** * Heroic * * @author LevelX2 */ public class HeroicAbility extends TriggeredAbilityImpl { public HeroicAbility(Effect effect) { this(effect, false); } public HeroicAbility(Effect effect, boolean optional) { this(effect, optional, true); } public HeroicAbility(Effect effect, boolean optional, boolean isHeroic) { super(Zone.BATTLEFIELD, effect, optional); if (isHeroic) { this.setAbilityWord(AbilityWord.HEROIC); } this.replaceRuleText = false; setTriggerPhrase("Whenever you cast a spell that targets {this}, "); } protected HeroicAbility(final HeroicAbility ability) { super(ability); } @Override public HeroicAbility copy() { return new HeroicAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.SPELL_CAST; } @Override public boolean checkTrigger(GameEvent event, Game game) { if (event.getPlayerId().equals(this.getControllerId())) { Spell spell = game.getStack().getSpell(event.getTargetId()); if (checkSpell(spell, game)) { return true; } } return false; } private boolean checkSpell(Spell spell, Game game) { if (spell == null) { return false; } SpellAbility sa = spell.getSpellAbility(); for (UUID modeId : sa.getModes().getSelectedModes()) { Mode mode = sa.getModes().get(modeId); for (Target target : mode.getTargets()) { if (!target.isNotTarget() && target.getTargets().contains(this.getSourceId())) { return true; } } for (Effect effect : mode.getEffects()) { for (UUID targetId : effect.getTargetPointer().getTargets(game, sa)) { if (targetId.equals(this.getSourceId())) { return true; } } } } return false; } }
2,517
0.601907
0.60151
87
27.91954
23.789894
96
false
false
0
0
0
0
0
0
0.505747
false
false
5
a0fb690b1cc557aedede3c2bfbe5efc7dc2079d9
23,407,571,807,315
72647d8c0c2f6eb21641d5d9f29338d6ba0f5591
/src/examen_a/Exer2.java
da3fea463d8e0c3b8b6d1b0ac4f3dad712dc2dc6
[]
no_license
surr6/Examen_Prog
https://github.com/surr6/Examen_Prog
933a8401bd4bba1495f30660f473ae43ff7992f2
f901afbdc13543bc288577a76a0e2365b67ee26d
refs/heads/master
2020-12-31T00:03:58.318000
2017-03-29T10:11:08
2017-03-29T10:11:08
86,567,078
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Matriz escalar Una matriz escalar e unha matriz diagonal na que os elementos da diagonal principal son iguales. 1 2 3 5 1 9 5 4 1 Fai un programa o que se lle pasa primeiro o numero de filas e o numero de columnas , despois asignalle valores de forma aleatoria do 0-9 e diga si a matriz e escalar 1.5 1 */ package examen_a; import java.util.*; /*Examen Josué García*/ public class Exer2 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc=new Scanner(System.in); Random rnd=new Random(); int f=0, c=0; System.out.println("Introduce o número de filas"); f=sc.nextInt(); System.out.println("Introduce o número de columnas"); c=sc.nextInt(); int[][] escalar=new int[f][c]; int aux=escalar[0][0], cont=0; if(f!=c){ System.out.println("A matriz non é cadrada polo que non é escalar"); } else{ System.out.println("Matriz:"); for (int i=0;i<f;i++){ for (int j=0;j<c;j++){ escalar[i][j]=rnd.nextInt(10); System.out.print(" "+escalar[i][j]); } System.out.println(""); } for (int i=0;i<f;i++){ for (int j=0;j<c;j++){ if((i==j)&&(escalar[i][j]==aux)){ cont++; } } } if(cont==f){ System.out.println("Matriz escalar"); } else{ System.out.println("Matriz non escalar"); } } } }
UTF-8
Java
1,788
java
Exer2.java
Java
[ { "context": "\r\npackage examen_a;\r\nimport java.util.*;\r\n/*Examen Josué García*/\r\n\r\npublic class Exer2 {\r\n\r\n /**\r\n ", "end": 395, "score": 0.7254126667976379, "start": 390, "tag": "NAME", "value": "Josué" }, { "context": "e examen_a;\r\nimport java.util.*;\r\n/*Examen Josué García*/\r\n\r\npublic class Exer2 {\r\n\r\n /**\r\n * @par", "end": 402, "score": 0.7102352380752563, "start": 397, "tag": "NAME", "value": "arcía" } ]
null
[]
/* Matriz escalar Una matriz escalar e unha matriz diagonal na que os elementos da diagonal principal son iguales. 1 2 3 5 1 9 5 4 1 Fai un programa o que se lle pasa primeiro o numero de filas e o numero de columnas , despois asignalle valores de forma aleatoria do 0-9 e diga si a matriz e escalar 1.5 1 */ package examen_a; import java.util.*; /*Examen Josué García*/ public class Exer2 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc=new Scanner(System.in); Random rnd=new Random(); int f=0, c=0; System.out.println("Introduce o número de filas"); f=sc.nextInt(); System.out.println("Introduce o número de columnas"); c=sc.nextInt(); int[][] escalar=new int[f][c]; int aux=escalar[0][0], cont=0; if(f!=c){ System.out.println("A matriz non é cadrada polo que non é escalar"); } else{ System.out.println("Matriz:"); for (int i=0;i<f;i++){ for (int j=0;j<c;j++){ escalar[i][j]=rnd.nextInt(10); System.out.print(" "+escalar[i][j]); } System.out.println(""); } for (int i=0;i<f;i++){ for (int j=0;j<c;j++){ if((i==j)&&(escalar[i][j]==aux)){ cont++; } } } if(cont==f){ System.out.println("Matriz escalar"); } else{ System.out.println("Matriz non escalar"); } } } }
1,788
0.464646
0.450056
68
24.205883
24.207777
138
false
false
0
0
0
0
0
0
0.441176
false
false
5
2265c6cba0a84f702fd68aa1191146449ee9a022
33,818,572,512,085
e8f5b2bf65a8f9de9d65b66eb5ad1ac95f11b50d
/src/main/java/pl/enigmatic/time/TimeCounterDouble.java
7a766a97c4551e6a13864bf46d5df471f072613c
[]
no_license
reggie7/enigmatic-tools
https://github.com/reggie7/enigmatic-tools
0153472a90ec8e006e4ae849f39458f4a7c7bde3
41968355b04b52b1dacf1c8796e68b1680f12375
refs/heads/master
2018-12-28T22:45:28.326000
2013-03-04T10:47:17
2013-03-04T10:47:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.enigmatic.time; import pl.enigmatic.util.Metrics; public class TimeCounterDouble { private final TimeCounterLong longCounter; private final double factor; public TimeCounterDouble(final boolean nano) { if (nano) { longCounter = new TimeCounterNano(); factor = Metrics.NANO; } else { longCounter = new TimeCounterMilli(); factor = Metrics.MILLI; } } public TimeCounterDouble() { this(true); } public double restart() { return factor * longCounter.restart(); } /** * @return * @see pl.enigmatic.time.TimeCounterLong#getMeasuredTime() */ public double getMeasuredTime() { return factor * longCounter.getMeasuredTime(); } /** * @return * @see pl.enigmatic.time.TimeCounterLong#getElapsedTime() */ public double getElapsedTime() { return factor * longCounter.getElapsedTime(); } public double getDelta() { return factor * longCounter.getDelta(); } }
UTF-8
Java
970
java
TimeCounterDouble.java
Java
[]
null
[]
package pl.enigmatic.time; import pl.enigmatic.util.Metrics; public class TimeCounterDouble { private final TimeCounterLong longCounter; private final double factor; public TimeCounterDouble(final boolean nano) { if (nano) { longCounter = new TimeCounterNano(); factor = Metrics.NANO; } else { longCounter = new TimeCounterMilli(); factor = Metrics.MILLI; } } public TimeCounterDouble() { this(true); } public double restart() { return factor * longCounter.restart(); } /** * @return * @see pl.enigmatic.time.TimeCounterLong#getMeasuredTime() */ public double getMeasuredTime() { return factor * longCounter.getMeasuredTime(); } /** * @return * @see pl.enigmatic.time.TimeCounterLong#getElapsedTime() */ public double getElapsedTime() { return factor * longCounter.getElapsedTime(); } public double getDelta() { return factor * longCounter.getDelta(); } }
970
0.669072
0.669072
48
18.208334
18.450336
60
false
false
0
0
0
0
0
0
1.3125
false
false
5
e88168012e9144426656399314ba4a767a74676e
29,351,806,539,881
f1bdb1593f7149e257886dd41296f5bf10984c58
/src/main/java/stepdefinitions/HomePageStepDefs.java
47d7558b53c19ed7347f283c711a4d8d1989c5ef
[]
no_license
sooryashibu/idexxAssignmentCopy
https://github.com/sooryashibu/idexxAssignmentCopy
8adb0b5c12ab1e5441fddefd2cfc80abd5f6d977
21e6736500cf28939dc750429aee73a1025c22b8
refs/heads/master
2020-08-29T04:33:19.397000
2019-10-27T23:12:47
2019-10-27T23:12:47
217,928,178
0
0
null
false
2019-10-27T23:12:48
2019-10-27T23:02:01
2019-10-27T23:03:08
2019-10-27T23:12:48
0
0
0
0
Java
false
false
package stepdefinitions; import cucumber.api.java.en.And; import handlers.TestContext; import pageobjects.HomePage; import pageobjects.SearchResultPage;; public class HomePageStepDefs { HomePage homePage; SearchResultPage searchResultPage; public HomePageStepDefs() { homePage = TestContext.pageObjectManager.getHomePage(); searchResultPage = TestContext.pageObjectManager.getSearchResultPage(); } @And("^Verify customer is navigated to Home Page$") public void verifyCustomerIsNavigatedToHomePage() { homePage.verifyHomePageDisplayed(); } @And("^Verify New Contact icon on Home Page$") public void VerifyNewContacticononHomePage() { homePage.verifyNewContactIconDisplayed(); } @And("^verify search functionality for \"(.*)\"$") public void verifySearchFunctionality(String testCaseNumber) { homePage.enterTheGivenSearchKeyword(testCaseNumber); homePage.selectTheGivenSearchType(testCaseNumber); searchResultPage.verifySearchResutPageDisplayed(); searchResultPage.verifySearchResultDisplayedIsForTheGivenName(testCaseNumber); } }
UTF-8
Java
1,066
java
HomePageStepDefs.java
Java
[]
null
[]
package stepdefinitions; import cucumber.api.java.en.And; import handlers.TestContext; import pageobjects.HomePage; import pageobjects.SearchResultPage;; public class HomePageStepDefs { HomePage homePage; SearchResultPage searchResultPage; public HomePageStepDefs() { homePage = TestContext.pageObjectManager.getHomePage(); searchResultPage = TestContext.pageObjectManager.getSearchResultPage(); } @And("^Verify customer is navigated to Home Page$") public void verifyCustomerIsNavigatedToHomePage() { homePage.verifyHomePageDisplayed(); } @And("^Verify New Contact icon on Home Page$") public void VerifyNewContacticononHomePage() { homePage.verifyNewContactIconDisplayed(); } @And("^verify search functionality for \"(.*)\"$") public void verifySearchFunctionality(String testCaseNumber) { homePage.enterTheGivenSearchKeyword(testCaseNumber); homePage.selectTheGivenSearchType(testCaseNumber); searchResultPage.verifySearchResutPageDisplayed(); searchResultPage.verifySearchResultDisplayedIsForTheGivenName(testCaseNumber); } }
1,066
0.80863
0.80863
35
29.457144
24.160585
80
false
false
0
0
0
0
0
0
1.285714
false
false
5
5da48175757576fbf0fcb590a9b341ed6e7096dd
34,497,177,352,499
677b5928103219f5cec985626194b26555a0ce49
/src/main/java/com/myfactory/SBootWebProject/controller/ControllerWebEmpleados.java
54806b7eba1ac2a6374f27e2dd87405f9ae1c413
[]
no_license
JoseLuis19-cloud/SpringBootProyect
https://github.com/JoseLuis19-cloud/SpringBootProyect
0e7393e946bf22607fbd099c79ac1006a95195ae
ea55acc2bd373af4b813bc3c5cc035fe50e396cc
refs/heads/master
2023-04-26T05:27:09.470000
2021-05-23T21:39:08
2021-05-23T21:39:08
325,054,501
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myfactory.SBootWebProject.controller; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.sql.Blob; import java.util.Optional; import javax.validation.Valid; import java.util.Base64; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; 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.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.myfactory.SBootWebProject.beanForm.BeanCamposBusqueda; import com.myfactory.SBootWebProject.beanForm.BeanEmpleadoWeb; import com.myfactory.SBootWebProject.beanForm.BeanErrorValidacion; import com.myfactory.SBootWebProject.beanForm.BeanUsuarioSession; import com.myfactory.SBootWebProject.beanForm.BeanUsuarioWeb; import com.myfactory.SBootWebProject.beanForm.CargaBeansDatos; import com.myfactory.SBootWebProject.common.CrearBotoneraPag; import com.myfactory.SBootWebProject.constantes.ConstantesAplicacion; import com.myfactory.SBootWebProject.model.Empleado; import com.myfactory.SBootWebProject.model.Pais; import com.myfactory.SBootWebProject.model.PuestoTrabajo; import com.myfactory.SBootWebProject.servicesJPA.ServJPAEmpleado; import com.myfactory.SBootWebProject.servicesJPA.ServJPAUsuario; @Controller @RequestMapping("/gestionWeb/empleados") @PropertySource("classpath:parametrosAplicacion.properties") public class ControllerWebEmpleados { @Autowired ServJPAEmpleado servJPAEmpleado; @Autowired BeanEmpleadoWeb beanEmpleadoWeb; @Autowired CargaBeansDatos cargarBeansDatos; @Autowired ServJPAUsuario servJPAUsuario; @Autowired BeanUsuarioSession beanUsuarioSession; private static final Logger logger = LogManager.getLogger(); @Value("${path.MACOSDescargaFicheros}") private String pathMacOS; @GetMapping("/formeditarempleado") public String formEditarEmpleado(Model modelo, @RequestParam(value = "idEmpleado", required = true) Integer idEmpleado, @RequestParam(value = "errorValidacion", required = false) Boolean errorValidacion, @RequestParam(value = "mensajeError", required = false) String mensajeError, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "numPos", required = false) String numPos) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(idEmpleado); modelo.addAttribute("empleadoWeb", cargarBeansDatos.cargarBeanEmpleado(empleado.get())); if (empleado.get().getImagenFotoEmpleado() != null ) { try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado"); } } else { modelo.addAttribute("imgFoto", null); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("idEmpleadoImg", idEmpleado); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); beanUsuarioWeb.setFecAltaUsuarioWeb(Calendar.getInstance()); beanUsuarioWeb.setRolUsuarioWeb(servJPAUsuario.obtenerRoles()); if (errorValidacion != null) { if (errorValidacion) { modelo.addAttribute("errorValidacion", true); modelo.addAttribute("mensajeError", mensajeError ); } else { modelo.addAttribute("errorValidacion", false); } } modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormEditarEmpleado"; } @GetMapping("/formbajaempleado") public String formBajaEmpleado(Model modelo, @RequestParam(value = "idEmpleado", required = true) Integer idEmpleado) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( idEmpleado ); BeanEmpleadoWeb beanEmpleadoWeb = new BeanEmpleadoWeb(); beanEmpleadoWeb = cargarBeansDatos.cargarBeanEmpleado(empleado.get()); beanEmpleadoWeb.setFecBajaEmpleadoWeb(Calendar.getInstance()); modelo.addAttribute("empleadoWeb", beanEmpleadoWeb); if (empleado.get().getImagenFotoEmpleado() != null ) { try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado" ); modelo.addAttribute("imgFoto", null); } } else { modelo.addAttribute("imgFoto", null); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormBajaEmpleado"; } @RequestMapping(value = "/bajaempleado", method = RequestMethod.POST) public String bajaempleado(Model modelo, @ModelAttribute("formEmpleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb) { Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( datosEmpleadoWeb.getIdEmpleadoWeb() ); empleado.get().setFecBajaEmplelado(datosEmpleadoWeb.getFecBajaEmpleadoWeb()) ; empleado.get().setIndbajaEmpleado(true); servJPAEmpleado.bajaEmpleado(empleado.get()); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "redirect:/gestionWeb/empleados/" + "pagempleados10"; } @GetMapping("/formactivarempleado") public String formActivarEmpleado(Model modelo, @RequestParam(value = "idEmpleado", required = true) Integer idEmpleado) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( idEmpleado ); BeanEmpleadoWeb beanEmpleadoWeb = new BeanEmpleadoWeb(); beanEmpleadoWeb = cargarBeansDatos.cargarBeanEmpleado(empleado.get()); beanEmpleadoWeb.setFecBajaEmpleadoWeb(Calendar.getInstance()); modelo.addAttribute("empleadoWeb", beanEmpleadoWeb); if (empleado.get().getImagenFotoEmpleado() != null ) { try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado" ); modelo.addAttribute("imgFoto", null); } } else { modelo.addAttribute("imgFoto", null); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormActivarEmpleado"; } @RequestMapping(value = "/activarempleado", method = RequestMethod.POST) public String activarEmpleado(Model modelo, @ModelAttribute("empleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb) { Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( datosEmpleadoWeb.getIdEmpleadoWeb() ); // SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); empleado.get().setFecAltaEmplelado(datosEmpleadoWeb.getFecAltaEmpleadoWeb()) ; empleado.get().setIndbajaEmpleado(false); servJPAEmpleado.bajaEmpleado(empleado.get()); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "redirect:/gestionWeb/empleados/" + "pagempleados10"; } @GetMapping("/formaltaempleado") public String formAltaEmpleado(Model modelo) { boolean nuevaAlta = true; BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); beanUsuarioWeb.setFecAltaUsuarioWeb(Calendar.getInstance()); beanUsuarioWeb.setRolUsuarioWeb(servJPAUsuario.obtenerRoles()); BeanEmpleadoWeb beanEmpleadoWeb = new BeanEmpleadoWeb(); beanEmpleadoWeb.setFecAltaEmpleadoWeb(Calendar.getInstance()); beanEmpleadoWeb.setImpBrutoAnualWeb(0F); beanEmpleadoWeb.setImpFacturadoMes(0F); beanEmpleadoWeb.setPaisWeb(servJPAEmpleado.obtenerPaises()); beanEmpleadoWeb.setPuestoTrabajoWeb(servJPAEmpleado.obtenerPuestoTrabajo() ); modelo.addAttribute("empleadoWeb", beanEmpleadoWeb); modelo.addAttribute("mostrarModalFoto", "N"); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); modelo.addAttribute("nuevaAlta" , nuevaAlta); // modelo.addAttribute("urlActualizacion" , ""); return "GestionWeb/empleados/FormAltaEmpleado"; } @RequestMapping(value = "/altaempleado", method = RequestMethod.POST) public String altaEmpleado(@Valid @ModelAttribute("empleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb, BindingResult resultValidacion, RedirectAttributes redirectAttrs, Model modelo, @RequestParam(value = "paisEmpleado", required = true) String codPais, @RequestParam(value = "puestoTrabajoEmpleado", required = true) String codPuestoTrabajo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "numPos", required = false) String numPos) { modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); Empleado empleado = null; BeanErrorValidacion datosError = null; Empleado empleadoNuevo = null; boolean esModif = false; boolean nuevaAlta = true; modelo.addAttribute("nuevaAlta" , nuevaAlta); if (! resultValidacion.hasErrors()) { try { Map<String, Object> resultValEmpleado; resultValEmpleado = validarDatosEmpleado(datosEmpleadoWeb, codPais, codPuestoTrabajo, esModif); datosError = (BeanErrorValidacion) resultValEmpleado.get("errorValidacion"); if (datosError.getCodError().intValue() != 0 ) { modelo.addAttribute("errorValidacion" , true); modelo.addAttribute("mensajeError", datosError.getCodError().toString() + ", " + datosError.getDesError() ); } else { empleado = (Empleado) resultValEmpleado.get("empleadoValidacion" ); // Dar de alta Empleado empleadoNuevo = servJPAEmpleado.altaEmpleado(empleado); redirectAttrs.addAttribute("idEmpleado" , empleadoNuevo.getIdEmpleado() ) ; redirectAttrs.addAttribute("numPag", numPag); redirectAttrs.addAttribute("numPos", numPos); modelo.addAttribute("errorValidacion" , false); modelo.addAttribute("mensajeError", "" ); return "redirect:/gestionWeb/empleados/formeditarempleado"; } } catch (Exception e) { logger.error("Se ha producido un error en el alta de un empleado" ); modelo.addAttribute("errorValidacion" , true); modelo.addAttribute("mensajeError", datosError.getCodError().toString() + ", " + datosError.getDesError() ); } modelo.addAttribute("mostrarModalFoto", "S"); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); modelo.addAttribute("idEmpleadoNuevo", empleadoNuevo.getIdEmpleado()); return "GestionWeb/empleados/FormAltaEmpleado"; } else { datosEmpleadoWeb.setPaisWeb(servJPAEmpleado.obtenerPaises()); datosEmpleadoWeb.setPuestoTrabajoWeb(servJPAEmpleado.obtenerPuestoTrabajo() ); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); return "GestionWeb/empleados/FormAltaEmpleado"; } } @RequestMapping(value = "/modifempleado", method = RequestMethod.POST) public String modifEmpleado(@Valid @ModelAttribute("empleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb, BindingResult resultValidacion, // RedirectAttributes redirectAttrs, Model modelo, @RequestParam(value = "paisEmpleado", required = true) String codPais, @RequestParam(value = "puestoTrabajo", required = true) String codPuestoTrabajo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "numPos", required = false) String numPos) { modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); Empleado modifEmpleado; Boolean errorValidacion = true; Map<String, Object> resultValEmpleado; boolean esModif = true; BeanErrorValidacion datosError = null; if (! resultValidacion.hasErrors() ) { resultValEmpleado = validarDatosEmpleado(datosEmpleadoWeb, codPais, codPuestoTrabajo, esModif); datosError = (BeanErrorValidacion) resultValEmpleado.get("errorValidacion"); if (datosError.getCodError().intValue() != 0) { modelo.addAttribute("errorValidacion" , true); modelo.addAttribute("mensajeError", datosError.getCodError().toString() + ", " + datosError.getCodError() ); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); return "GestionWeb/empleados/FormEditarEmpleado"; } else { modelo.addAttribute("errorValidacion" , false); modelo.addAttribute("mensajeError", "" ); // Modificar un Empleado modifEmpleado = (Empleado) resultValEmpleado.get("empleadoValidacion"); servJPAEmpleado.modifEmpleado(modifEmpleado); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); return "redirect:/gestionWeb/empleados/" + "pagempleados10"; } } else { // List<FieldError> listError = resultValidacion.getFieldErrors(); // Este es un error de validacion automatica de Spring por lo que ponemos false a nuestra variable de error. errorValidacion = false; modelo.addAttribute("errorValidacion", errorValidacion); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); return "GestionWeb/empleados/FormEditarEmpleado"; } } @PostMapping("/uploadimagenempleado") public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value="empleadoImg", required = true) Integer idEmpleado, @RequestParam(value = "numPag", required = true) String numPag, @RequestParam(value = "numPos", required = true) String numPos, RedirectAttributes redirectAttrs, Model modelo) { byte[] arrayBytesImagen = null; // check if file is empty if (file.isEmpty()) { redirectAttrs.addAttribute("errorValidacion", true); redirectAttrs.addAttribute("mensajeError", "51, " + "El fichero enviado está vacio"); logger.error("El fichero enviado está vacio"); redirectAttrs.addAttribute("idEmpleado", idEmpleado); redirectAttrs.addAttribute("numPag", numPag); redirectAttrs.addAttribute("numPos", numPos); return "redirect:/gestionWeb/empleados/formeditarempleado"; } // normalize the file path String fileName = StringUtils.cleanPath(file.getOriginalFilename()); Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(idEmpleado); try { if ( file.getSize() > 65535L) { System.out.println("El tamaño de la foto no puede superar los 65.535 bytes"); logger.error("El tamaño de la foto no puede superar los 65.535 bytes"); redirectAttrs.addAttribute("errorValidacion", true); redirectAttrs.addAttribute("mensajeError", "52, " + "El tamaño de la foto no puede superar los 65.535 bytes"); } else { arrayBytesImagen = file.getBytes(); java.sql.Blob blobImagen = new javax.sql.rowset.serial.SerialBlob(arrayBytesImagen); empleado.get().setImagenFotoEmpleado(blobImagen); // Grabar Imagen en la tabla servJPAEmpleado.grabarImagen(empleado.get()); modelo.addAttribute("imgFoto", this.getImgData(arrayBytesImagen) ); } } catch (Exception exp) { logger.error("Se ha producido un error al enviar la imagen del empleado"); redirectAttrs.addAttribute("errorValidacion", true); redirectAttrs.addAttribute("mensajeError", "53" + "Se ha producido un error en la inserción de la imagen"); } BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); try { // Esto puede sobrar no ? // save the file on the local file system Path path = Paths.get(this.getPathMacOS() + fileName); Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { logger.error("Se ha producido un error al grabar la imagen del empleado en el disco" ); e.printStackTrace(); } redirectAttrs.addAttribute("idEmpleado", idEmpleado); redirectAttrs.addAttribute("numPag", numPag); redirectAttrs.addAttribute("numPos", numPos); return "redirect:/gestionWeb/empleados/formeditarempleado"; } @PostMapping("/cargarfotoempleado") public String uploadFotoEmpleado(@RequestParam("file") MultipartFile file, RedirectAttributes attributes, Model modelo) { // check if file is empty if (file.isEmpty()) { attributes.addFlashAttribute("message", "Seleccione una imagen a enviar"); return "redirect:/"; } // normalize the file path String fileName = StringUtils.cleanPath(file.getOriginalFilename()); // Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(new Long(1)); try { byte[] arrayBytesImagen = file.getBytes(); // java.sql.Blob blobImagen = new javax.sql.rowset.serial.SerialBlob(arrayBytesImagen); BeanEmpleadoWeb datosEmpleadoWeb = new BeanEmpleadoWeb(); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); modelo.addAttribute("imgFoto", this.getImgData(arrayBytesImagen) ); // empleado.get().setImagenFotoEmpleado(blobImagen); } catch (Exception exp) { System.out.println("Error conversion"); } // servJPAEmpleado.grabarImagen(empleado.get()); // try { // save the file on the local file system // Path path = Paths.get(this.getPathMacOS() + fileName); // Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // e.printStackTrace(); // } BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); return "GestionWeb/empleados/FormAltaEmpleado"; } @RequestMapping("/cargarImagenEmpleado") public String cargarImagenEmpleado(Model modelo) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(new Integer(1)); try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado en el disco" ); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormVerFotoEmpleado"; } @RequestMapping("/pagempleadosNue") public String paginacionEmpleadosNue(Model modelo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "tpoAccion", required = false) String tpoAccion, @RequestParam(value = "numPos", required = false) String numPos, @RequestParam(value = "numBloquePag", required = false) Integer numBloquePag, @RequestParam(value = "apellidosBus", required = false) String apellidosBus, @ModelAttribute("objBusqueda") BeanCamposBusqueda busquedaCampo ) { // Con esta variable sabemos la pagina exacta, dentro de todas paginacias posibles, de donde llega a la paginacion. int numPagInt = 0; int numPosInt = 0; HashMap<String, Integer> paramBotonera = null; CrearBotoneraPag botoneraPag = null; if (numBloquePag == null) { numBloquePag = 0; } // La primera vez que entra if (numPag == null && tpoAccion == null) { numPagInt = 0; } else //No es la primera vez que entra { // Ha pinchado o avance o retroceso serguro if (tpoAccion != null) { if (tpoAccion.equals("avan")) { numPagInt = Integer.parseInt(numPag) + 1; } else { numPagInt = Integer.parseInt(numPag) - 1; } } else { // Ha pinchado el numero de pagina numPagInt = Integer.parseInt(numPag); } } if (busquedaCampo.getApellidosBusqueda() == null) { busquedaCampo = new BeanCamposBusqueda(); if (apellidosBus == null) { busquedaCampo.setApellidosBusqueda(""); } else { busquedaCampo.setApellidosBusqueda(apellidosBus); } } else { busquedaCampo.setApellidosBusqueda(busquedaCampo.getApellidosBusqueda()); } modelo.addAttribute("objBusqueda", busquedaCampo); Page<Empleado> pagEmpleados = servJPAEmpleado.pagEmpleados(new Integer(numPagInt), ConstantesAplicacion.REG_POR_PAGINA, busquedaCampo.getApellidosBusqueda().trim()); modelo.addAttribute("pagGenerica", pagEmpleados); modelo.addAttribute("numPag", String.valueOf(numPagInt)); modelo.addAttribute("numRegPag", pagEmpleados.getContent().size()); try { botoneraPag = new CrearBotoneraPag(); paramBotonera = CrearBotoneraPag.calculaNumPagBotoneraNue(numPagInt, tpoAccion, numPos, pagEmpleados.getTotalElements(), new Double(numBloquePag.intValue()) ); } catch (Exception exp) { logger.error("Se ha producido un error en la creacion de botonera de la paginación de los empleados" ); exp.printStackTrace(); } String URLPag = "/gestionWeb/empleados/pagempleadosNue?numPag=" ; CrearBotoneraPag.montarEnlacesBotonera(paramBotonera, modelo, numPagInt, URLPag, busquedaCampo.getApellidosBusqueda().trim()); // Si ha pinchado avance o retroceso de pagina. if (tpoAccion != null) { // Detectamos cambio de bloque ponerlo if (paramBotonera.get("numBloquePag").intValue() != numBloquePag.intValue() ) { if (tpoAccion.equals("avan")) { numPosInt = 1; } else { numPosInt = 5; } } else { // Si es el mismo bloque la paginacion if (paramBotonera.get("numBloquePag").intValue() == 0) { numPosInt = numPagInt + 1; } else { numPosInt = numPagInt - 5 ; } } } else { // Si es primera vez que entra if (numPos == null) { numPosInt = 1; } else { // Si ha pinchado boton pagina numPosInt = Integer.parseInt(numPos); } } switch (numPosInt) { case 1: modelo.addAttribute("numPagAct1", "S" ); break; case 2: modelo.addAttribute("numPagAct2", "S" ); break; case 3: modelo.addAttribute("numPagAct3", "S" ); break; case 4: modelo.addAttribute("numPagAct4", "S" ); break; case 5: modelo.addAttribute("numPagAct5", "S" ); break; } if ( pagEmpleados.isLast() ) { modelo.addAttribute("indUltPag", "S"); } else { modelo.addAttribute("indUltPag", "N"); } modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/PagEmpleados"; } @RequestMapping("/pagempleados10") public String paginacionEmpleados10(Model modelo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "tpoAccion", required = false) String tpoAccion, @RequestParam(value = "numPos", required = false) String numPos, @RequestParam(value = "numBloquePag", required = false) Integer numBloquePag, @RequestParam(value = "apellidosBus", required = false) String apellidosBus, @ModelAttribute("objBusqueda") BeanCamposBusqueda busquedaCampo ) { // Con esta variable sabemos la pagina exacta, dentro de todas paginacias posibles, de donde llega a la paginacion. int numPagInt = 0; int numPosInt = 0; HashMap<String, Integer> paramBotonera = null; CrearBotoneraPag botoneraPag = null; if (numBloquePag == null) { numBloquePag = 0; } // La primera vez que entra if (numPag == null && tpoAccion == null) { numPagInt = 0; } else //No es la primera vez que entra { // Ha pinchado o avance o retroceso serguro if (tpoAccion != null) { if (tpoAccion.equals("avan")) { numPagInt = Integer.parseInt(numPag) + 1; } else { numPagInt = Integer.parseInt(numPag) - 1; } } else { // Ha pinchado el numero de pagina numPagInt = Integer.parseInt(numPag); } } if (busquedaCampo.getApellidosBusqueda() == null) { busquedaCampo = new BeanCamposBusqueda(); if (apellidosBus == null) { busquedaCampo.setApellidosBusqueda(""); } else { busquedaCampo.setApellidosBusqueda(apellidosBus); } } else { busquedaCampo.setApellidosBusqueda(busquedaCampo.getApellidosBusqueda()); } modelo.addAttribute("objBusqueda", busquedaCampo); Page<Empleado> pagEmpleados = servJPAEmpleado.pagEmpleados(new Integer(numPagInt), ConstantesAplicacion.REG_POR_PAGINA_10, busquedaCampo.getApellidosBusqueda().trim()); modelo.addAttribute("pagGenerica", pagEmpleados); modelo.addAttribute("numPag", String.valueOf(numPagInt)); modelo.addAttribute("numRegPag", pagEmpleados.getContent().size()); try { botoneraPag = new CrearBotoneraPag(); paramBotonera = CrearBotoneraPag.calculaNumPagBotonera10(numPagInt, tpoAccion, numPos, pagEmpleados.getTotalElements(), new Double(numBloquePag.intValue()) ); } catch (Exception exp) { exp.printStackTrace(); } String URLPag = "/gestionWeb/empleados/pagempleados10?numPag=" ; // CrearBotoneraPag.montarEnlacesBotonera10(paramBotonera, modelo, numPagInt, URLPag, busquedaCampo.getApellidosBusqueda().trim()); // Si ha pinchado avance o retroceso de pagina. if (tpoAccion != null) { // Detectamoos cambio de bloque ponerlo if (paramBotonera.get("numBloquePag").intValue() != numBloquePag.intValue() ) { if (tpoAccion.equals("avan")) { numPosInt = 1; } else { numPosInt = 5; } } else { // Si es el mismo bloque la paginacion if (paramBotonera.get("numBloquePag").intValue() == 0) { numPosInt = numPagInt + 1; } else { numPosInt = numPagInt - 5 ; } } } else { // Si es primera vez que entra if (numPos == null) { numPosInt = 1; } else { // Si ha pinchado boton pagina numPosInt = Integer.parseInt(numPos); } } switch (numPosInt) { case 1: modelo.addAttribute("numPagAct1", "S" ); break; case 2: modelo.addAttribute("numPagAct2", "S" ); break; case 3: modelo.addAttribute("numPagAct3", "S" ); break; case 4: modelo.addAttribute("numPagAct4", "S" ); break; case 5: modelo.addAttribute("numPagAct5", "S" ); break; } if ( pagEmpleados.isLast() ) { modelo.addAttribute("indUltPag", "S"); } else { modelo.addAttribute("indUltPag", "N"); } modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/PagEmpleados10"; } @RequestMapping("/pagempleados10nuemod") public String paginacionEmpleados10NueMod(Model modelo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "tpoAccion", required = false) String tpoAccion, @RequestParam(value = "numPos", required = false) String numPos, @RequestParam(value = "numBloquePag", required = false) Integer numBloquePag, @RequestParam(value = "apellidosBus", required = false) String apellidosBus, @ModelAttribute("objBusqueda") BeanCamposBusqueda busquedaCampo ) { // Con esta variable sabemos la pagina exacta, dentro de todas paginacias posibles, de donde llega a la paginacion. int numPagInt = 0; int numPosInt = 0; HashMap<String, Integer> paramBotonera = null; CrearBotoneraPag botoneraPag = null; // Si es la primera vez que entra a la paginación if (numBloquePag == null) { numBloquePag = 0; } // Si es la primera vez que entra a la paginacion // Con este bloque de codigo sabemos el numero de pagina siguiente que tiene que resaltar. if (numPag == null && tpoAccion == null) { numPagInt = 0; } else //No es la primera vez que entra { // Ha pinchado boton avance o retroceso seguro if (tpoAccion != null) { if (tpoAccion.equals("avan")) { numPagInt = Integer.parseInt(numPag) + 1; } else { numPagInt = Integer.parseInt(numPag) - 1; } } else { // Ha pinchado el numero de pagina numPagInt = Integer.parseInt(numPag); } } // Si ha rellenado el campo de filtro busqueda para filtrar por en la paginación if (busquedaCampo.getApellidosBusqueda() == null) { busquedaCampo = new BeanCamposBusqueda(); if (apellidosBus == null) { busquedaCampo.setApellidosBusqueda(""); } else { busquedaCampo.setApellidosBusqueda(apellidosBus); } } else { busquedaCampo.setApellidosBusqueda(busquedaCampo.getApellidosBusqueda()); } modelo.addAttribute("objBusqueda", busquedaCampo); Page<Empleado> pagEmpleados = servJPAEmpleado.pagEmpleados(new Integer(numPagInt), ConstantesAplicacion.REG_POR_PAGINA_10, busquedaCampo.getApellidosBusqueda().trim()); modelo.addAttribute("pagGenerica", pagEmpleados); modelo.addAttribute("numPag", String.valueOf(numPagInt)); modelo.addAttribute("numRegPag", pagEmpleados.getContent().size()); try { botoneraPag = new CrearBotoneraPag(); // Utilizamos esta clase para paramBotonera = CrearBotoneraPag.calculaNumPagBotonera10(numPagInt, tpoAccion, numPos, pagEmpleados.getTotalElements(), new Double(numBloquePag.intValue()) ); } catch (Exception exp) { exp.printStackTrace(); } // Si ha pinchado avance o retroceso de pagina. if (tpoAccion != null) { // Detectamoos cambio de bloque ponerlo if (paramBotonera.get("numBloquePag").intValue() != numBloquePag.intValue() ) { if (tpoAccion.equals("avan")) { numPosInt = 1; } else { numPosInt = 5; } } else { // Si es el mismo bloque la paginacion if (paramBotonera.get("numBloquePag").intValue() == 0) { numPosInt = numPagInt + 1; } else { numPosInt = numPagInt - 5 ; } } } else { // Si es primera vez que entra if (numPos == null) { numPosInt = 1; } else { // Si ha pinchado boton pagina numPosInt = Integer.parseInt(numPos); } } modelo.addAttribute("numPos", numPosInt); String URLPag = "/gestionWeb/empleados/pagempleados10nuemod?numPag=" ; CrearBotoneraPag.montarEnlacesBotonera10(paramBotonera, modelo, numPagInt, URLPag, busquedaCampo.getApellidosBusqueda().trim(), numPosInt); if (pagEmpleados.isLast() ) { modelo.addAttribute("indUltPag", "S"); } else { modelo.addAttribute("indUltPag", "N"); } modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/PagEmpleados10"; } public String getPathMacOS() { return pathMacOS; } public void setPathMacOS(String pathMacOS) { this.pathMacOS = pathMacOS; } public String getImgData(byte[] byteData) { return Base64.getMimeEncoder().encodeToString(byteData); } private Map<String, Object> validarDatosEmpleado(BeanEmpleadoWeb datosEmpleadoWeb, String codPais, String codPuestoTrabajo, boolean esModificacion) { Map<String, Object> resultadoValidacion = new HashMap<>(); BeanErrorValidacion datosErrorValidacion = new BeanErrorValidacion(new Integer(0)); Empleado empleado = new Empleado(); Pais pais = new Pais(); PuestoTrabajo puestoTrabajo = new PuestoTrabajo(); if (esModificacion) { empleado.setIdEmpleado(datosEmpleadoWeb.getIdEmpleadoWeb()); } empleado.setApellidos(datosEmpleadoWeb.getApellidosWeb()); empleado.setNombre(datosEmpleadoWeb.getNombreWeb()); empleado.setDireccion(datosEmpleadoWeb.getDireccionWeb()); empleado.setEmail(datosEmpleadoWeb.getEmailWeb()); empleado.setCodPostal(datosEmpleadoWeb.getCodPostalWeb()); empleado.setNif(datosEmpleadoWeb.getNifWeb()); empleado.setNumCuentaCorriente(datosEmpleadoWeb.getNumCuentaCorrienteWeb()); empleado.setNumSeguridaSocial(datosEmpleadoWeb.getNumSeguridaSocialWeb()); empleado.setImpFacturadoMes(datosEmpleadoWeb.getImpFacturadoMes()); empleado.setFecAltaEmplelado(datosEmpleadoWeb.getFecAltaEmpleadoWeb()) ; empleado.setImpBrutoAnual( datosEmpleadoWeb.getImpBrutoAnualWeb()); empleado.setTelefMovil(datosEmpleadoWeb.getTelefMovilWeb()); empleado.setTelefono2(datosEmpleadoWeb.getTelefono2()); // User usuario = new User(); // empleado.setUsuario(usuario); pais.setIdPais(new Integer(codPais)); puestoTrabajo.setIdPuestoTrabajo( new Integer(codPuestoTrabajo) ); empleado.setPais(pais); empleado.setPuestoTrabajo(puestoTrabajo); resultadoValidacion.put("empleadoValidacion", empleado); resultadoValidacion.put("errorValidacion" , datosErrorValidacion); return resultadoValidacion; } }
UTF-8
Java
36,656
java
ControllerWebEmpleados.java
Java
[]
null
[]
package com.myfactory.SBootWebProject.controller; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.sql.Blob; import java.util.Optional; import javax.validation.Valid; import java.util.Base64; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; 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.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.myfactory.SBootWebProject.beanForm.BeanCamposBusqueda; import com.myfactory.SBootWebProject.beanForm.BeanEmpleadoWeb; import com.myfactory.SBootWebProject.beanForm.BeanErrorValidacion; import com.myfactory.SBootWebProject.beanForm.BeanUsuarioSession; import com.myfactory.SBootWebProject.beanForm.BeanUsuarioWeb; import com.myfactory.SBootWebProject.beanForm.CargaBeansDatos; import com.myfactory.SBootWebProject.common.CrearBotoneraPag; import com.myfactory.SBootWebProject.constantes.ConstantesAplicacion; import com.myfactory.SBootWebProject.model.Empleado; import com.myfactory.SBootWebProject.model.Pais; import com.myfactory.SBootWebProject.model.PuestoTrabajo; import com.myfactory.SBootWebProject.servicesJPA.ServJPAEmpleado; import com.myfactory.SBootWebProject.servicesJPA.ServJPAUsuario; @Controller @RequestMapping("/gestionWeb/empleados") @PropertySource("classpath:parametrosAplicacion.properties") public class ControllerWebEmpleados { @Autowired ServJPAEmpleado servJPAEmpleado; @Autowired BeanEmpleadoWeb beanEmpleadoWeb; @Autowired CargaBeansDatos cargarBeansDatos; @Autowired ServJPAUsuario servJPAUsuario; @Autowired BeanUsuarioSession beanUsuarioSession; private static final Logger logger = LogManager.getLogger(); @Value("${path.MACOSDescargaFicheros}") private String pathMacOS; @GetMapping("/formeditarempleado") public String formEditarEmpleado(Model modelo, @RequestParam(value = "idEmpleado", required = true) Integer idEmpleado, @RequestParam(value = "errorValidacion", required = false) Boolean errorValidacion, @RequestParam(value = "mensajeError", required = false) String mensajeError, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "numPos", required = false) String numPos) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(idEmpleado); modelo.addAttribute("empleadoWeb", cargarBeansDatos.cargarBeanEmpleado(empleado.get())); if (empleado.get().getImagenFotoEmpleado() != null ) { try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado"); } } else { modelo.addAttribute("imgFoto", null); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("idEmpleadoImg", idEmpleado); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); beanUsuarioWeb.setFecAltaUsuarioWeb(Calendar.getInstance()); beanUsuarioWeb.setRolUsuarioWeb(servJPAUsuario.obtenerRoles()); if (errorValidacion != null) { if (errorValidacion) { modelo.addAttribute("errorValidacion", true); modelo.addAttribute("mensajeError", mensajeError ); } else { modelo.addAttribute("errorValidacion", false); } } modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormEditarEmpleado"; } @GetMapping("/formbajaempleado") public String formBajaEmpleado(Model modelo, @RequestParam(value = "idEmpleado", required = true) Integer idEmpleado) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( idEmpleado ); BeanEmpleadoWeb beanEmpleadoWeb = new BeanEmpleadoWeb(); beanEmpleadoWeb = cargarBeansDatos.cargarBeanEmpleado(empleado.get()); beanEmpleadoWeb.setFecBajaEmpleadoWeb(Calendar.getInstance()); modelo.addAttribute("empleadoWeb", beanEmpleadoWeb); if (empleado.get().getImagenFotoEmpleado() != null ) { try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado" ); modelo.addAttribute("imgFoto", null); } } else { modelo.addAttribute("imgFoto", null); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormBajaEmpleado"; } @RequestMapping(value = "/bajaempleado", method = RequestMethod.POST) public String bajaempleado(Model modelo, @ModelAttribute("formEmpleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb) { Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( datosEmpleadoWeb.getIdEmpleadoWeb() ); empleado.get().setFecBajaEmplelado(datosEmpleadoWeb.getFecBajaEmpleadoWeb()) ; empleado.get().setIndbajaEmpleado(true); servJPAEmpleado.bajaEmpleado(empleado.get()); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "redirect:/gestionWeb/empleados/" + "pagempleados10"; } @GetMapping("/formactivarempleado") public String formActivarEmpleado(Model modelo, @RequestParam(value = "idEmpleado", required = true) Integer idEmpleado) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( idEmpleado ); BeanEmpleadoWeb beanEmpleadoWeb = new BeanEmpleadoWeb(); beanEmpleadoWeb = cargarBeansDatos.cargarBeanEmpleado(empleado.get()); beanEmpleadoWeb.setFecBajaEmpleadoWeb(Calendar.getInstance()); modelo.addAttribute("empleadoWeb", beanEmpleadoWeb); if (empleado.get().getImagenFotoEmpleado() != null ) { try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado" ); modelo.addAttribute("imgFoto", null); } } else { modelo.addAttribute("imgFoto", null); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormActivarEmpleado"; } @RequestMapping(value = "/activarempleado", method = RequestMethod.POST) public String activarEmpleado(Model modelo, @ModelAttribute("empleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb) { Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado( datosEmpleadoWeb.getIdEmpleadoWeb() ); // SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); empleado.get().setFecAltaEmplelado(datosEmpleadoWeb.getFecAltaEmpleadoWeb()) ; empleado.get().setIndbajaEmpleado(false); servJPAEmpleado.bajaEmpleado(empleado.get()); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "redirect:/gestionWeb/empleados/" + "pagempleados10"; } @GetMapping("/formaltaempleado") public String formAltaEmpleado(Model modelo) { boolean nuevaAlta = true; BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); beanUsuarioWeb.setFecAltaUsuarioWeb(Calendar.getInstance()); beanUsuarioWeb.setRolUsuarioWeb(servJPAUsuario.obtenerRoles()); BeanEmpleadoWeb beanEmpleadoWeb = new BeanEmpleadoWeb(); beanEmpleadoWeb.setFecAltaEmpleadoWeb(Calendar.getInstance()); beanEmpleadoWeb.setImpBrutoAnualWeb(0F); beanEmpleadoWeb.setImpFacturadoMes(0F); beanEmpleadoWeb.setPaisWeb(servJPAEmpleado.obtenerPaises()); beanEmpleadoWeb.setPuestoTrabajoWeb(servJPAEmpleado.obtenerPuestoTrabajo() ); modelo.addAttribute("empleadoWeb", beanEmpleadoWeb); modelo.addAttribute("mostrarModalFoto", "N"); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); modelo.addAttribute("nuevaAlta" , nuevaAlta); // modelo.addAttribute("urlActualizacion" , ""); return "GestionWeb/empleados/FormAltaEmpleado"; } @RequestMapping(value = "/altaempleado", method = RequestMethod.POST) public String altaEmpleado(@Valid @ModelAttribute("empleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb, BindingResult resultValidacion, RedirectAttributes redirectAttrs, Model modelo, @RequestParam(value = "paisEmpleado", required = true) String codPais, @RequestParam(value = "puestoTrabajoEmpleado", required = true) String codPuestoTrabajo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "numPos", required = false) String numPos) { modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); Empleado empleado = null; BeanErrorValidacion datosError = null; Empleado empleadoNuevo = null; boolean esModif = false; boolean nuevaAlta = true; modelo.addAttribute("nuevaAlta" , nuevaAlta); if (! resultValidacion.hasErrors()) { try { Map<String, Object> resultValEmpleado; resultValEmpleado = validarDatosEmpleado(datosEmpleadoWeb, codPais, codPuestoTrabajo, esModif); datosError = (BeanErrorValidacion) resultValEmpleado.get("errorValidacion"); if (datosError.getCodError().intValue() != 0 ) { modelo.addAttribute("errorValidacion" , true); modelo.addAttribute("mensajeError", datosError.getCodError().toString() + ", " + datosError.getDesError() ); } else { empleado = (Empleado) resultValEmpleado.get("empleadoValidacion" ); // Dar de alta Empleado empleadoNuevo = servJPAEmpleado.altaEmpleado(empleado); redirectAttrs.addAttribute("idEmpleado" , empleadoNuevo.getIdEmpleado() ) ; redirectAttrs.addAttribute("numPag", numPag); redirectAttrs.addAttribute("numPos", numPos); modelo.addAttribute("errorValidacion" , false); modelo.addAttribute("mensajeError", "" ); return "redirect:/gestionWeb/empleados/formeditarempleado"; } } catch (Exception e) { logger.error("Se ha producido un error en el alta de un empleado" ); modelo.addAttribute("errorValidacion" , true); modelo.addAttribute("mensajeError", datosError.getCodError().toString() + ", " + datosError.getDesError() ); } modelo.addAttribute("mostrarModalFoto", "S"); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); modelo.addAttribute("idEmpleadoNuevo", empleadoNuevo.getIdEmpleado()); return "GestionWeb/empleados/FormAltaEmpleado"; } else { datosEmpleadoWeb.setPaisWeb(servJPAEmpleado.obtenerPaises()); datosEmpleadoWeb.setPuestoTrabajoWeb(servJPAEmpleado.obtenerPuestoTrabajo() ); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); return "GestionWeb/empleados/FormAltaEmpleado"; } } @RequestMapping(value = "/modifempleado", method = RequestMethod.POST) public String modifEmpleado(@Valid @ModelAttribute("empleadoWeb") BeanEmpleadoWeb datosEmpleadoWeb, BindingResult resultValidacion, // RedirectAttributes redirectAttrs, Model modelo, @RequestParam(value = "paisEmpleado", required = true) String codPais, @RequestParam(value = "puestoTrabajo", required = true) String codPuestoTrabajo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "numPos", required = false) String numPos) { modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); Empleado modifEmpleado; Boolean errorValidacion = true; Map<String, Object> resultValEmpleado; boolean esModif = true; BeanErrorValidacion datosError = null; if (! resultValidacion.hasErrors() ) { resultValEmpleado = validarDatosEmpleado(datosEmpleadoWeb, codPais, codPuestoTrabajo, esModif); datosError = (BeanErrorValidacion) resultValEmpleado.get("errorValidacion"); if (datosError.getCodError().intValue() != 0) { modelo.addAttribute("errorValidacion" , true); modelo.addAttribute("mensajeError", datosError.getCodError().toString() + ", " + datosError.getCodError() ); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); return "GestionWeb/empleados/FormEditarEmpleado"; } else { modelo.addAttribute("errorValidacion" , false); modelo.addAttribute("mensajeError", "" ); // Modificar un Empleado modifEmpleado = (Empleado) resultValEmpleado.get("empleadoValidacion"); servJPAEmpleado.modifEmpleado(modifEmpleado); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); return "redirect:/gestionWeb/empleados/" + "pagempleados10"; } } else { // List<FieldError> listError = resultValidacion.getFieldErrors(); // Este es un error de validacion automatica de Spring por lo que ponemos false a nuestra variable de error. errorValidacion = false; modelo.addAttribute("errorValidacion", errorValidacion); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); modelo.addAttribute("numPag", numPag); modelo.addAttribute("numPos", numPos); return "GestionWeb/empleados/FormEditarEmpleado"; } } @PostMapping("/uploadimagenempleado") public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value="empleadoImg", required = true) Integer idEmpleado, @RequestParam(value = "numPag", required = true) String numPag, @RequestParam(value = "numPos", required = true) String numPos, RedirectAttributes redirectAttrs, Model modelo) { byte[] arrayBytesImagen = null; // check if file is empty if (file.isEmpty()) { redirectAttrs.addAttribute("errorValidacion", true); redirectAttrs.addAttribute("mensajeError", "51, " + "El fichero enviado está vacio"); logger.error("El fichero enviado está vacio"); redirectAttrs.addAttribute("idEmpleado", idEmpleado); redirectAttrs.addAttribute("numPag", numPag); redirectAttrs.addAttribute("numPos", numPos); return "redirect:/gestionWeb/empleados/formeditarempleado"; } // normalize the file path String fileName = StringUtils.cleanPath(file.getOriginalFilename()); Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(idEmpleado); try { if ( file.getSize() > 65535L) { System.out.println("El tamaño de la foto no puede superar los 65.535 bytes"); logger.error("El tamaño de la foto no puede superar los 65.535 bytes"); redirectAttrs.addAttribute("errorValidacion", true); redirectAttrs.addAttribute("mensajeError", "52, " + "El tamaño de la foto no puede superar los 65.535 bytes"); } else { arrayBytesImagen = file.getBytes(); java.sql.Blob blobImagen = new javax.sql.rowset.serial.SerialBlob(arrayBytesImagen); empleado.get().setImagenFotoEmpleado(blobImagen); // Grabar Imagen en la tabla servJPAEmpleado.grabarImagen(empleado.get()); modelo.addAttribute("imgFoto", this.getImgData(arrayBytesImagen) ); } } catch (Exception exp) { logger.error("Se ha producido un error al enviar la imagen del empleado"); redirectAttrs.addAttribute("errorValidacion", true); redirectAttrs.addAttribute("mensajeError", "53" + "Se ha producido un error en la inserción de la imagen"); } BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); try { // Esto puede sobrar no ? // save the file on the local file system Path path = Paths.get(this.getPathMacOS() + fileName); Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { logger.error("Se ha producido un error al grabar la imagen del empleado en el disco" ); e.printStackTrace(); } redirectAttrs.addAttribute("idEmpleado", idEmpleado); redirectAttrs.addAttribute("numPag", numPag); redirectAttrs.addAttribute("numPos", numPos); return "redirect:/gestionWeb/empleados/formeditarempleado"; } @PostMapping("/cargarfotoempleado") public String uploadFotoEmpleado(@RequestParam("file") MultipartFile file, RedirectAttributes attributes, Model modelo) { // check if file is empty if (file.isEmpty()) { attributes.addFlashAttribute("message", "Seleccione una imagen a enviar"); return "redirect:/"; } // normalize the file path String fileName = StringUtils.cleanPath(file.getOriginalFilename()); // Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(new Long(1)); try { byte[] arrayBytesImagen = file.getBytes(); // java.sql.Blob blobImagen = new javax.sql.rowset.serial.SerialBlob(arrayBytesImagen); BeanEmpleadoWeb datosEmpleadoWeb = new BeanEmpleadoWeb(); modelo.addAttribute("empleadoWeb", datosEmpleadoWeb); modelo.addAttribute("imgFoto", this.getImgData(arrayBytesImagen) ); // empleado.get().setImagenFotoEmpleado(blobImagen); } catch (Exception exp) { System.out.println("Error conversion"); } // servJPAEmpleado.grabarImagen(empleado.get()); // try { // save the file on the local file system // Path path = Paths.get(this.getPathMacOS() + fileName); // Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // e.printStackTrace(); // } BeanUsuarioWeb beanUsuarioWeb = new BeanUsuarioWeb(); modelo.addAttribute("usuarioWeb", beanUsuarioWeb); return "GestionWeb/empleados/FormAltaEmpleado"; } @RequestMapping("/cargarImagenEmpleado") public String cargarImagenEmpleado(Model modelo) { byte[] blobBytes = null; byte[] encode =null; Optional<Empleado> empleado = servJPAEmpleado.buscarIdEmpleado(new Integer(1)); try { Blob blobImg = empleado.get().getImagenFotoEmpleado(); blobBytes = blobImg.getBytes(1, (int) blobImg.length()); modelo.addAttribute("imgFoto", this.getImgData(blobBytes)); } catch (Exception e) { logger.error("Se ha producido un error al cargar la imagen del empleado en el disco" ); } modelo.addAttribute("empleado", empleado); modelo.addAttribute("objImagen", encode); modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/FormVerFotoEmpleado"; } @RequestMapping("/pagempleadosNue") public String paginacionEmpleadosNue(Model modelo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "tpoAccion", required = false) String tpoAccion, @RequestParam(value = "numPos", required = false) String numPos, @RequestParam(value = "numBloquePag", required = false) Integer numBloquePag, @RequestParam(value = "apellidosBus", required = false) String apellidosBus, @ModelAttribute("objBusqueda") BeanCamposBusqueda busquedaCampo ) { // Con esta variable sabemos la pagina exacta, dentro de todas paginacias posibles, de donde llega a la paginacion. int numPagInt = 0; int numPosInt = 0; HashMap<String, Integer> paramBotonera = null; CrearBotoneraPag botoneraPag = null; if (numBloquePag == null) { numBloquePag = 0; } // La primera vez que entra if (numPag == null && tpoAccion == null) { numPagInt = 0; } else //No es la primera vez que entra { // Ha pinchado o avance o retroceso serguro if (tpoAccion != null) { if (tpoAccion.equals("avan")) { numPagInt = Integer.parseInt(numPag) + 1; } else { numPagInt = Integer.parseInt(numPag) - 1; } } else { // Ha pinchado el numero de pagina numPagInt = Integer.parseInt(numPag); } } if (busquedaCampo.getApellidosBusqueda() == null) { busquedaCampo = new BeanCamposBusqueda(); if (apellidosBus == null) { busquedaCampo.setApellidosBusqueda(""); } else { busquedaCampo.setApellidosBusqueda(apellidosBus); } } else { busquedaCampo.setApellidosBusqueda(busquedaCampo.getApellidosBusqueda()); } modelo.addAttribute("objBusqueda", busquedaCampo); Page<Empleado> pagEmpleados = servJPAEmpleado.pagEmpleados(new Integer(numPagInt), ConstantesAplicacion.REG_POR_PAGINA, busquedaCampo.getApellidosBusqueda().trim()); modelo.addAttribute("pagGenerica", pagEmpleados); modelo.addAttribute("numPag", String.valueOf(numPagInt)); modelo.addAttribute("numRegPag", pagEmpleados.getContent().size()); try { botoneraPag = new CrearBotoneraPag(); paramBotonera = CrearBotoneraPag.calculaNumPagBotoneraNue(numPagInt, tpoAccion, numPos, pagEmpleados.getTotalElements(), new Double(numBloquePag.intValue()) ); } catch (Exception exp) { logger.error("Se ha producido un error en la creacion de botonera de la paginación de los empleados" ); exp.printStackTrace(); } String URLPag = "/gestionWeb/empleados/pagempleadosNue?numPag=" ; CrearBotoneraPag.montarEnlacesBotonera(paramBotonera, modelo, numPagInt, URLPag, busquedaCampo.getApellidosBusqueda().trim()); // Si ha pinchado avance o retroceso de pagina. if (tpoAccion != null) { // Detectamos cambio de bloque ponerlo if (paramBotonera.get("numBloquePag").intValue() != numBloquePag.intValue() ) { if (tpoAccion.equals("avan")) { numPosInt = 1; } else { numPosInt = 5; } } else { // Si es el mismo bloque la paginacion if (paramBotonera.get("numBloquePag").intValue() == 0) { numPosInt = numPagInt + 1; } else { numPosInt = numPagInt - 5 ; } } } else { // Si es primera vez que entra if (numPos == null) { numPosInt = 1; } else { // Si ha pinchado boton pagina numPosInt = Integer.parseInt(numPos); } } switch (numPosInt) { case 1: modelo.addAttribute("numPagAct1", "S" ); break; case 2: modelo.addAttribute("numPagAct2", "S" ); break; case 3: modelo.addAttribute("numPagAct3", "S" ); break; case 4: modelo.addAttribute("numPagAct4", "S" ); break; case 5: modelo.addAttribute("numPagAct5", "S" ); break; } if ( pagEmpleados.isLast() ) { modelo.addAttribute("indUltPag", "S"); } else { modelo.addAttribute("indUltPag", "N"); } modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/PagEmpleados"; } @RequestMapping("/pagempleados10") public String paginacionEmpleados10(Model modelo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "tpoAccion", required = false) String tpoAccion, @RequestParam(value = "numPos", required = false) String numPos, @RequestParam(value = "numBloquePag", required = false) Integer numBloquePag, @RequestParam(value = "apellidosBus", required = false) String apellidosBus, @ModelAttribute("objBusqueda") BeanCamposBusqueda busquedaCampo ) { // Con esta variable sabemos la pagina exacta, dentro de todas paginacias posibles, de donde llega a la paginacion. int numPagInt = 0; int numPosInt = 0; HashMap<String, Integer> paramBotonera = null; CrearBotoneraPag botoneraPag = null; if (numBloquePag == null) { numBloquePag = 0; } // La primera vez que entra if (numPag == null && tpoAccion == null) { numPagInt = 0; } else //No es la primera vez que entra { // Ha pinchado o avance o retroceso serguro if (tpoAccion != null) { if (tpoAccion.equals("avan")) { numPagInt = Integer.parseInt(numPag) + 1; } else { numPagInt = Integer.parseInt(numPag) - 1; } } else { // Ha pinchado el numero de pagina numPagInt = Integer.parseInt(numPag); } } if (busquedaCampo.getApellidosBusqueda() == null) { busquedaCampo = new BeanCamposBusqueda(); if (apellidosBus == null) { busquedaCampo.setApellidosBusqueda(""); } else { busquedaCampo.setApellidosBusqueda(apellidosBus); } } else { busquedaCampo.setApellidosBusqueda(busquedaCampo.getApellidosBusqueda()); } modelo.addAttribute("objBusqueda", busquedaCampo); Page<Empleado> pagEmpleados = servJPAEmpleado.pagEmpleados(new Integer(numPagInt), ConstantesAplicacion.REG_POR_PAGINA_10, busquedaCampo.getApellidosBusqueda().trim()); modelo.addAttribute("pagGenerica", pagEmpleados); modelo.addAttribute("numPag", String.valueOf(numPagInt)); modelo.addAttribute("numRegPag", pagEmpleados.getContent().size()); try { botoneraPag = new CrearBotoneraPag(); paramBotonera = CrearBotoneraPag.calculaNumPagBotonera10(numPagInt, tpoAccion, numPos, pagEmpleados.getTotalElements(), new Double(numBloquePag.intValue()) ); } catch (Exception exp) { exp.printStackTrace(); } String URLPag = "/gestionWeb/empleados/pagempleados10?numPag=" ; // CrearBotoneraPag.montarEnlacesBotonera10(paramBotonera, modelo, numPagInt, URLPag, busquedaCampo.getApellidosBusqueda().trim()); // Si ha pinchado avance o retroceso de pagina. if (tpoAccion != null) { // Detectamoos cambio de bloque ponerlo if (paramBotonera.get("numBloquePag").intValue() != numBloquePag.intValue() ) { if (tpoAccion.equals("avan")) { numPosInt = 1; } else { numPosInt = 5; } } else { // Si es el mismo bloque la paginacion if (paramBotonera.get("numBloquePag").intValue() == 0) { numPosInt = numPagInt + 1; } else { numPosInt = numPagInt - 5 ; } } } else { // Si es primera vez que entra if (numPos == null) { numPosInt = 1; } else { // Si ha pinchado boton pagina numPosInt = Integer.parseInt(numPos); } } switch (numPosInt) { case 1: modelo.addAttribute("numPagAct1", "S" ); break; case 2: modelo.addAttribute("numPagAct2", "S" ); break; case 3: modelo.addAttribute("numPagAct3", "S" ); break; case 4: modelo.addAttribute("numPagAct4", "S" ); break; case 5: modelo.addAttribute("numPagAct5", "S" ); break; } if ( pagEmpleados.isLast() ) { modelo.addAttribute("indUltPag", "S"); } else { modelo.addAttribute("indUltPag", "N"); } modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/PagEmpleados10"; } @RequestMapping("/pagempleados10nuemod") public String paginacionEmpleados10NueMod(Model modelo, @RequestParam(value = "numPag", required = false) String numPag, @RequestParam(value = "tpoAccion", required = false) String tpoAccion, @RequestParam(value = "numPos", required = false) String numPos, @RequestParam(value = "numBloquePag", required = false) Integer numBloquePag, @RequestParam(value = "apellidosBus", required = false) String apellidosBus, @ModelAttribute("objBusqueda") BeanCamposBusqueda busquedaCampo ) { // Con esta variable sabemos la pagina exacta, dentro de todas paginacias posibles, de donde llega a la paginacion. int numPagInt = 0; int numPosInt = 0; HashMap<String, Integer> paramBotonera = null; CrearBotoneraPag botoneraPag = null; // Si es la primera vez que entra a la paginación if (numBloquePag == null) { numBloquePag = 0; } // Si es la primera vez que entra a la paginacion // Con este bloque de codigo sabemos el numero de pagina siguiente que tiene que resaltar. if (numPag == null && tpoAccion == null) { numPagInt = 0; } else //No es la primera vez que entra { // Ha pinchado boton avance o retroceso seguro if (tpoAccion != null) { if (tpoAccion.equals("avan")) { numPagInt = Integer.parseInt(numPag) + 1; } else { numPagInt = Integer.parseInt(numPag) - 1; } } else { // Ha pinchado el numero de pagina numPagInt = Integer.parseInt(numPag); } } // Si ha rellenado el campo de filtro busqueda para filtrar por en la paginación if (busquedaCampo.getApellidosBusqueda() == null) { busquedaCampo = new BeanCamposBusqueda(); if (apellidosBus == null) { busquedaCampo.setApellidosBusqueda(""); } else { busquedaCampo.setApellidosBusqueda(apellidosBus); } } else { busquedaCampo.setApellidosBusqueda(busquedaCampo.getApellidosBusqueda()); } modelo.addAttribute("objBusqueda", busquedaCampo); Page<Empleado> pagEmpleados = servJPAEmpleado.pagEmpleados(new Integer(numPagInt), ConstantesAplicacion.REG_POR_PAGINA_10, busquedaCampo.getApellidosBusqueda().trim()); modelo.addAttribute("pagGenerica", pagEmpleados); modelo.addAttribute("numPag", String.valueOf(numPagInt)); modelo.addAttribute("numRegPag", pagEmpleados.getContent().size()); try { botoneraPag = new CrearBotoneraPag(); // Utilizamos esta clase para paramBotonera = CrearBotoneraPag.calculaNumPagBotonera10(numPagInt, tpoAccion, numPos, pagEmpleados.getTotalElements(), new Double(numBloquePag.intValue()) ); } catch (Exception exp) { exp.printStackTrace(); } // Si ha pinchado avance o retroceso de pagina. if (tpoAccion != null) { // Detectamoos cambio de bloque ponerlo if (paramBotonera.get("numBloquePag").intValue() != numBloquePag.intValue() ) { if (tpoAccion.equals("avan")) { numPosInt = 1; } else { numPosInt = 5; } } else { // Si es el mismo bloque la paginacion if (paramBotonera.get("numBloquePag").intValue() == 0) { numPosInt = numPagInt + 1; } else { numPosInt = numPagInt - 5 ; } } } else { // Si es primera vez que entra if (numPos == null) { numPosInt = 1; } else { // Si ha pinchado boton pagina numPosInt = Integer.parseInt(numPos); } } modelo.addAttribute("numPos", numPosInt); String URLPag = "/gestionWeb/empleados/pagempleados10nuemod?numPag=" ; CrearBotoneraPag.montarEnlacesBotonera10(paramBotonera, modelo, numPagInt, URLPag, busquedaCampo.getApellidosBusqueda().trim(), numPosInt); if (pagEmpleados.isLast() ) { modelo.addAttribute("indUltPag", "S"); } else { modelo.addAttribute("indUltPag", "N"); } modelo.addAttribute("opcionesMenuUsuario", beanUsuarioSession.getListBeanMenuUsuarioSession()); return "GestionWeb/empleados/PagEmpleados10"; } public String getPathMacOS() { return pathMacOS; } public void setPathMacOS(String pathMacOS) { this.pathMacOS = pathMacOS; } public String getImgData(byte[] byteData) { return Base64.getMimeEncoder().encodeToString(byteData); } private Map<String, Object> validarDatosEmpleado(BeanEmpleadoWeb datosEmpleadoWeb, String codPais, String codPuestoTrabajo, boolean esModificacion) { Map<String, Object> resultadoValidacion = new HashMap<>(); BeanErrorValidacion datosErrorValidacion = new BeanErrorValidacion(new Integer(0)); Empleado empleado = new Empleado(); Pais pais = new Pais(); PuestoTrabajo puestoTrabajo = new PuestoTrabajo(); if (esModificacion) { empleado.setIdEmpleado(datosEmpleadoWeb.getIdEmpleadoWeb()); } empleado.setApellidos(datosEmpleadoWeb.getApellidosWeb()); empleado.setNombre(datosEmpleadoWeb.getNombreWeb()); empleado.setDireccion(datosEmpleadoWeb.getDireccionWeb()); empleado.setEmail(datosEmpleadoWeb.getEmailWeb()); empleado.setCodPostal(datosEmpleadoWeb.getCodPostalWeb()); empleado.setNif(datosEmpleadoWeb.getNifWeb()); empleado.setNumCuentaCorriente(datosEmpleadoWeb.getNumCuentaCorrienteWeb()); empleado.setNumSeguridaSocial(datosEmpleadoWeb.getNumSeguridaSocialWeb()); empleado.setImpFacturadoMes(datosEmpleadoWeb.getImpFacturadoMes()); empleado.setFecAltaEmplelado(datosEmpleadoWeb.getFecAltaEmpleadoWeb()) ; empleado.setImpBrutoAnual( datosEmpleadoWeb.getImpBrutoAnualWeb()); empleado.setTelefMovil(datosEmpleadoWeb.getTelefMovilWeb()); empleado.setTelefono2(datosEmpleadoWeb.getTelefono2()); // User usuario = new User(); // empleado.setUsuario(usuario); pais.setIdPais(new Integer(codPais)); puestoTrabajo.setIdPuestoTrabajo( new Integer(codPuestoTrabajo) ); empleado.setPais(pais); empleado.setPuestoTrabajo(puestoTrabajo); resultadoValidacion.put("empleadoValidacion", empleado); resultadoValidacion.put("errorValidacion" , datosErrorValidacion); return resultadoValidacion; } }
36,656
0.677654
0.673971
1,100
31.315454
32.0266
170
false
false
0
0
0
0
0
0
3.154546
false
false
5
b62a78a5e983ef6799cea3671ca6354839c39f52
9,629,316,680,952
f7e662faede3d54c610a764c1033ab8e00f42813
/app/src/main/java/kx/rnd/com/permissionstest/view/PathMesureTestView.java
cc64afe19aeb3f8cd73b377af978d6d973683d1f
[]
no_license
252162875/XyDemos
https://github.com/252162875/XyDemos
b24268516dbf8abb5662ff42292f8b0d2768d617
78ff7993279b88fc3f4f21a09cf3a170e561a2f9
refs/heads/master
2020-12-30T12:23:22.908000
2018-06-25T03:15:31
2018-06-25T03:15:31
91,429,334
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kx.rnd.com.permissionstest.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathMeasure; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; import com.caverock.androidsvg.SVG; import com.caverock.androidsvg.SVGParseException; import kx.rnd.com.permissionstest.R; /** * */ public class PathMesureTestView extends View { private static final float C = 0.551915024494f; // 一个常量,用来计算绘制圆形贝塞尔曲线控制点的位置 private int mCenterX, mCenterY; private Paint mPaint; private int mWidth; private int mHeight; private float currentValue = 0; // 用于纪录当前的位置,取值范围[0,1]映射Path的整个长度 private float[] pos; // 当前点的实际位置 private float[] tan; // 当前点的tangent值,用于计算图片所需旋转的角度 private Bitmap mBitmap; // 箭头图片 private Matrix mMatrix; // 矩阵,用于对图片进行一些操作 private float[] mData = new float[8]; // 顺时针记录绘制圆形的四个数据点 private float[] mCtrl = new float[16]; // 顺时针记录绘制圆形的八个控制点 private int mCircleRadius = 200; // 圆的半径 private float mDifference = mCircleRadius * C; // 圆形的控制点与数据点的差值 public PathMesureTestView(Context context) { super(context); init(null, 0); } public PathMesureTestView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public PathMesureTestView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } private void init(AttributeSet attrs, int defStyle) { mPaint = new Paint(); pos = new float[2]; tan = new float[2]; BitmapFactory.Options options = new BitmapFactory.Options(); mBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.arrow, options); mMatrix = new Matrix(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // allocations per draw cycle. int paddingLeft = getPaddingLeft(); int paddingTop = getPaddingTop(); int paddingRight = getPaddingRight(); int paddingBottom = getPaddingBottom(); int contentWidth = getWidth() - paddingLeft - paddingRight; int contentHeight = getHeight() - paddingTop - paddingBottom; canvas.translate(mCenterX, mCenterY); // 将坐标系移动到画布中央 /** * 在这里额外测试了com.caverock:androidsvg:1.2.2-beta-1这个SVG解析库 */ canvas.save(); try { SVG svg = SVG.getFromResource(getContext(), R.raw.monitor); svg.setDocumentHeight(mHeight); svg.setDocumentWidth(mWidth); float documentWidth = svg.getDocumentWidth(); float documentHeight = svg.getDocumentHeight(); canvas.translate(-documentWidth / 2, -documentHeight / 2); RectF rectF = new RectF(-mWidth / 2, -mHeight / 2, mWidth / 2, mHeight / 2); svg.renderToCanvas(canvas,rectF); } catch (SVGParseException e) { e.printStackTrace(); } canvas.restore(); mPaint.setColor(Color.RED); mPaint.setStrokeWidth(8); mPaint.setStyle(Paint.Style.STROKE); // Path path = new Path(); // 创建 Path // path.addCircle(0, 0, mWidth < mHeight ? mWidth * 2 / 5 : mHeight * 2 / 5, Path.Direction.CW); // 添加一个圆形 Path path = new Path(); path.moveTo(mData[0], mData[1]); path.cubicTo(mCtrl[2], mCtrl[3], mCtrl[4], mCtrl[5], mData[2], mData[3]); path.cubicTo(mCtrl[6], mCtrl[7], mCtrl[8], mCtrl[9], mData[4], mData[5]); path.cubicTo(mCtrl[10], mCtrl[11], mCtrl[12], mCtrl[13], mData[6], mData[7]); path.cubicTo(mCtrl[14], mCtrl[15], mCtrl[0], mCtrl[1], mData[0], mData[1]); canvas.drawPath(path, mPaint); PathMeasure measure = new PathMeasure(path, false); // 创建 PathMeasure currentValue += 0.001; // 计算当前的位置在总长度上的比例[0,1] if (currentValue >= 1) { currentValue = 0; } measure.getPosTan(measure.getLength() * currentValue, pos, tan); // 获取当前位置的坐标以及趋势 mMatrix.reset(); // 重置Matrix float degrees = (float) (Math.atan2(tan[1], tan[0]) * 180.0 / Math.PI); // 计算图片旋转角度 mMatrix.postRotate(degrees + 90, mBitmap.getWidth() / 2, mBitmap.getHeight() / 2); // 旋转图片 mMatrix.postTranslate(pos[0] - mBitmap.getWidth() / 2, pos[1] - mBitmap.getHeight() / 2); // 将图片绘制中心调整到与当前点重合 canvas.drawPath(path, mPaint); // 绘制 Path canvas.drawBitmap(mBitmap, mMatrix, mPaint); // 绘制箭头 invalidate();//页面刷新此处是在 onDraw 里面调用了 invalidate 方法来保持界面不断刷新,但并不提倡这么做,正确对做法应该是使用 线程 或者 ValueAnimator 来控制界面的刷新,关于控制页面刷新这一部分会在后续的 动画部分 详细讲解,同样敬请期待 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthsize = MeasureSpec.getSize(widthMeasureSpec); //取出宽度的确切数值 int widthmode = MeasureSpec.getMode(widthMeasureSpec); //取出宽度的测量模式 int heightsize = MeasureSpec.getSize(heightMeasureSpec); //取出高度的确切数值 int heightmode = MeasureSpec.getMode(heightMeasureSpec); //取出高度的测量模式 super.onMeasure(widthMeasureSpec, heightMeasureSpec);//注意:如果对View的宽高进行修改了,不要调用 super.onMeasure( widthMeasureSpec, heightMeasureSpec); 要调用 setMeasuredDimension( widthsize, heightsize); 这个函数。 } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mWidth = w; mHeight = h; initData(); } private void initData() { mCenterX = mWidth / 2; mCenterY = mHeight / 2; mCircleRadius = Math.min(mWidth, mHeight) * 2 / 5; mDifference = mCircleRadius * C; // 顺时针初始化数据点 mData[0] = 0; mData[1] = -mCircleRadius * 2 / 5; mData[2] = mCircleRadius; mData[3] = 0; mData[4] = 0; mData[5] = mCircleRadius; mData[6] = -mCircleRadius; mData[7] = 0; // 顺时针初始化控制点 mCtrl[0] = mData[0] - mDifference; mCtrl[1] = mData[1] * 5 / 2; mCtrl[2] = mData[0] + mDifference; mCtrl[3] = mData[1] * 5 / 2; mCtrl[4] = mData[2]; mCtrl[5] = mData[3] - mDifference; mCtrl[6] = mData[2] - mCircleRadius * 1 / 10; mCtrl[7] = mData[3] + mDifference; mCtrl[8] = mData[4] + mDifference; mCtrl[9] = mData[5] - mCircleRadius * 2 / 5; mCtrl[10] = mData[4] - mDifference; mCtrl[11] = mData[5] - mCircleRadius * 2 / 5; mCtrl[12] = mData[6] + mCircleRadius * 1 / 10; mCtrl[13] = mData[7] + mDifference; mCtrl[14] = mData[6]; mCtrl[15] = mData[7] - mDifference; } }
UTF-8
Java
7,950
java
PathMesureTestView.java
Java
[]
null
[]
package kx.rnd.com.permissionstest.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathMeasure; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; import com.caverock.androidsvg.SVG; import com.caverock.androidsvg.SVGParseException; import kx.rnd.com.permissionstest.R; /** * */ public class PathMesureTestView extends View { private static final float C = 0.551915024494f; // 一个常量,用来计算绘制圆形贝塞尔曲线控制点的位置 private int mCenterX, mCenterY; private Paint mPaint; private int mWidth; private int mHeight; private float currentValue = 0; // 用于纪录当前的位置,取值范围[0,1]映射Path的整个长度 private float[] pos; // 当前点的实际位置 private float[] tan; // 当前点的tangent值,用于计算图片所需旋转的角度 private Bitmap mBitmap; // 箭头图片 private Matrix mMatrix; // 矩阵,用于对图片进行一些操作 private float[] mData = new float[8]; // 顺时针记录绘制圆形的四个数据点 private float[] mCtrl = new float[16]; // 顺时针记录绘制圆形的八个控制点 private int mCircleRadius = 200; // 圆的半径 private float mDifference = mCircleRadius * C; // 圆形的控制点与数据点的差值 public PathMesureTestView(Context context) { super(context); init(null, 0); } public PathMesureTestView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public PathMesureTestView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } private void init(AttributeSet attrs, int defStyle) { mPaint = new Paint(); pos = new float[2]; tan = new float[2]; BitmapFactory.Options options = new BitmapFactory.Options(); mBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.arrow, options); mMatrix = new Matrix(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // allocations per draw cycle. int paddingLeft = getPaddingLeft(); int paddingTop = getPaddingTop(); int paddingRight = getPaddingRight(); int paddingBottom = getPaddingBottom(); int contentWidth = getWidth() - paddingLeft - paddingRight; int contentHeight = getHeight() - paddingTop - paddingBottom; canvas.translate(mCenterX, mCenterY); // 将坐标系移动到画布中央 /** * 在这里额外测试了com.caverock:androidsvg:1.2.2-beta-1这个SVG解析库 */ canvas.save(); try { SVG svg = SVG.getFromResource(getContext(), R.raw.monitor); svg.setDocumentHeight(mHeight); svg.setDocumentWidth(mWidth); float documentWidth = svg.getDocumentWidth(); float documentHeight = svg.getDocumentHeight(); canvas.translate(-documentWidth / 2, -documentHeight / 2); RectF rectF = new RectF(-mWidth / 2, -mHeight / 2, mWidth / 2, mHeight / 2); svg.renderToCanvas(canvas,rectF); } catch (SVGParseException e) { e.printStackTrace(); } canvas.restore(); mPaint.setColor(Color.RED); mPaint.setStrokeWidth(8); mPaint.setStyle(Paint.Style.STROKE); // Path path = new Path(); // 创建 Path // path.addCircle(0, 0, mWidth < mHeight ? mWidth * 2 / 5 : mHeight * 2 / 5, Path.Direction.CW); // 添加一个圆形 Path path = new Path(); path.moveTo(mData[0], mData[1]); path.cubicTo(mCtrl[2], mCtrl[3], mCtrl[4], mCtrl[5], mData[2], mData[3]); path.cubicTo(mCtrl[6], mCtrl[7], mCtrl[8], mCtrl[9], mData[4], mData[5]); path.cubicTo(mCtrl[10], mCtrl[11], mCtrl[12], mCtrl[13], mData[6], mData[7]); path.cubicTo(mCtrl[14], mCtrl[15], mCtrl[0], mCtrl[1], mData[0], mData[1]); canvas.drawPath(path, mPaint); PathMeasure measure = new PathMeasure(path, false); // 创建 PathMeasure currentValue += 0.001; // 计算当前的位置在总长度上的比例[0,1] if (currentValue >= 1) { currentValue = 0; } measure.getPosTan(measure.getLength() * currentValue, pos, tan); // 获取当前位置的坐标以及趋势 mMatrix.reset(); // 重置Matrix float degrees = (float) (Math.atan2(tan[1], tan[0]) * 180.0 / Math.PI); // 计算图片旋转角度 mMatrix.postRotate(degrees + 90, mBitmap.getWidth() / 2, mBitmap.getHeight() / 2); // 旋转图片 mMatrix.postTranslate(pos[0] - mBitmap.getWidth() / 2, pos[1] - mBitmap.getHeight() / 2); // 将图片绘制中心调整到与当前点重合 canvas.drawPath(path, mPaint); // 绘制 Path canvas.drawBitmap(mBitmap, mMatrix, mPaint); // 绘制箭头 invalidate();//页面刷新此处是在 onDraw 里面调用了 invalidate 方法来保持界面不断刷新,但并不提倡这么做,正确对做法应该是使用 线程 或者 ValueAnimator 来控制界面的刷新,关于控制页面刷新这一部分会在后续的 动画部分 详细讲解,同样敬请期待 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthsize = MeasureSpec.getSize(widthMeasureSpec); //取出宽度的确切数值 int widthmode = MeasureSpec.getMode(widthMeasureSpec); //取出宽度的测量模式 int heightsize = MeasureSpec.getSize(heightMeasureSpec); //取出高度的确切数值 int heightmode = MeasureSpec.getMode(heightMeasureSpec); //取出高度的测量模式 super.onMeasure(widthMeasureSpec, heightMeasureSpec);//注意:如果对View的宽高进行修改了,不要调用 super.onMeasure( widthMeasureSpec, heightMeasureSpec); 要调用 setMeasuredDimension( widthsize, heightsize); 这个函数。 } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mWidth = w; mHeight = h; initData(); } private void initData() { mCenterX = mWidth / 2; mCenterY = mHeight / 2; mCircleRadius = Math.min(mWidth, mHeight) * 2 / 5; mDifference = mCircleRadius * C; // 顺时针初始化数据点 mData[0] = 0; mData[1] = -mCircleRadius * 2 / 5; mData[2] = mCircleRadius; mData[3] = 0; mData[4] = 0; mData[5] = mCircleRadius; mData[6] = -mCircleRadius; mData[7] = 0; // 顺时针初始化控制点 mCtrl[0] = mData[0] - mDifference; mCtrl[1] = mData[1] * 5 / 2; mCtrl[2] = mData[0] + mDifference; mCtrl[3] = mData[1] * 5 / 2; mCtrl[4] = mData[2]; mCtrl[5] = mData[3] - mDifference; mCtrl[6] = mData[2] - mCircleRadius * 1 / 10; mCtrl[7] = mData[3] + mDifference; mCtrl[8] = mData[4] + mDifference; mCtrl[9] = mData[5] - mCircleRadius * 2 / 5; mCtrl[10] = mData[4] - mDifference; mCtrl[11] = mData[5] - mCircleRadius * 2 / 5; mCtrl[12] = mData[6] + mCircleRadius * 1 / 10; mCtrl[13] = mData[7] + mDifference; mCtrl[14] = mData[6]; mCtrl[15] = mData[7] - mDifference; } }
7,950
0.602015
0.578505
188
37.010639
31.958416
197
false
false
0
0
0
0
0
0
1.010638
false
false
5
803b757c3a57f63134fb701021b6068b2376dd86
35,974,646,095,740
f3b885fb8af820c3cd8f75a119c0658712ceb218
/DerkaServ1.10_source_from_jdcore/net/minecraft/server/v1_10_R1/PacketPlayOutKickDisconnect.java
6c81f262d4f3b2de377b4775af3793711d6362bd
[]
no_license
XtremePlayzCODE/spigot-res
https://github.com/XtremePlayzCODE/spigot-res
3711818f01be5f7135f01f10faeb8fcce2cb3a7f
82f7ce0809e56745aa556d7828467be33eaeef65
refs/heads/master
2017-10-15T09:57:11.090000
2017-03-29T01:06:28
2017-03-29T01:06:28
86,525,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.minecraft.server.v1_10_R1; import java.io.IOException; public class PacketPlayOutKickDisconnect implements Packet<PacketListenerPlayOut> { private IChatBaseComponent a; public PacketPlayOutKickDisconnect() {} public PacketPlayOutKickDisconnect(IChatBaseComponent paramIChatBaseComponent) { a = paramIChatBaseComponent; } public void a(PacketDataSerializer paramPacketDataSerializer) throws IOException { a = paramPacketDataSerializer.f(); } public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException { paramPacketDataSerializer.a(a); } public void a(PacketListenerPlayOut paramPacketListenerPlayOut) { paramPacketListenerPlayOut.a(this); } }
UTF-8
Java
742
java
PacketPlayOutKickDisconnect.java
Java
[]
null
[]
package net.minecraft.server.v1_10_R1; import java.io.IOException; public class PacketPlayOutKickDisconnect implements Packet<PacketListenerPlayOut> { private IChatBaseComponent a; public PacketPlayOutKickDisconnect() {} public PacketPlayOutKickDisconnect(IChatBaseComponent paramIChatBaseComponent) { a = paramIChatBaseComponent; } public void a(PacketDataSerializer paramPacketDataSerializer) throws IOException { a = paramPacketDataSerializer.f(); } public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException { paramPacketDataSerializer.a(a); } public void a(PacketListenerPlayOut paramPacketListenerPlayOut) { paramPacketListenerPlayOut.a(this); } }
742
0.774933
0.769542
34
20.82353
25.905338
82
false
false
0
0
0
0
0
0
0.205882
false
false
5
e518efad5973d4fa5f664a4179542734a0533484
14,980,845,995,864
bbf19fcef9b169a022b6f31de61077b7435010e8
/test/exam/src/org/guangyu/model/PersonStatus.java
2ecc3d9ea9796df90dc3d039b7f3dd9930ba57ca
[]
no_license
crsstchh/yrcrs
https://github.com/crsstchh/yrcrs
d7892dc895ace048eec9ef44a26c27f3d29e031f
d7ce9c3ac6991b0962db2e0bec06c93090b301f1
refs/heads/master
2016-08-03T19:43:46.101000
2014-05-07T15:07:43
2014-05-07T15:07:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.guangyu.model; import java.io.Serializable; import java.util.List; public class PersonStatus implements Serializable{ /** * */ private static final long serialVersionUID = 1L; String temp; List<String> pre; String pulse; String isNormal;//0正常一,1不正常 public String getIsNormal() { return isNormal; } public void setIsNormal(String isNormal) { this.isNormal = isNormal; } public PersonStatus() { } public String getTemp() { return temp; } public void setTemp(String temp) { this.temp = temp; } public List<String> getPre() { return pre; } public void setPre(List<String> pre) { this.pre = pre; } public String getPulse() { return pulse; } public void setPulse(String pulse) { this.pulse = pulse; } }
UTF-8
Java
822
java
PersonStatus.java
Java
[]
null
[]
package org.guangyu.model; import java.io.Serializable; import java.util.List; public class PersonStatus implements Serializable{ /** * */ private static final long serialVersionUID = 1L; String temp; List<String> pre; String pulse; String isNormal;//0正常一,1不正常 public String getIsNormal() { return isNormal; } public void setIsNormal(String isNormal) { this.isNormal = isNormal; } public PersonStatus() { } public String getTemp() { return temp; } public void setTemp(String temp) { this.temp = temp; } public List<String> getPre() { return pre; } public void setPre(List<String> pre) { this.pre = pre; } public String getPulse() { return pulse; } public void setPulse(String pulse) { this.pulse = pulse; } }
822
0.652228
0.648515
46
15.565217
14.510345
51
false
false
0
0
0
0
0
0
0.717391
false
false
5
9859769df070da5a932f553b17091f1baa7d0822
10,823,317,623,461
f299c1091b2064a742577dcc8e497579a885317b
/src/main/java/io/github/primepotato/jandas/utils/DoubleMatrixList.java
0836b99b63d85fb8d78c76eb62bca7ade5c3b7c5
[ "MIT" ]
permissive
PrimePotato/jandas
https://github.com/PrimePotato/jandas
40e22b1c1b65e71f4073891842921df47fa872ad
2204c7269d2e9a6c9d93564625b8b15f2dec2b18
refs/heads/master
2021-12-31T09:49:55.877000
2020-03-05T14:01:50
2020-03-05T14:01:50
166,845,203
2
0
MIT
false
2021-12-14T21:17:06
2019-01-21T16:27:23
2020-03-05T14:02:01
2021-12-14T21:17:04
1,862
1
0
7
Java
false
false
package io.github.primepotato.jandas.utils; import org.ejml.data.DMatrixRMaj; import java.util.Arrays; public class DoubleMatrixList extends DMatrixRMaj { private static double GROWTH_BASE = 2; public DoubleMatrixList(double[] vals) { double[] a = Arrays.copyOf(vals, dataSize(vals.length)); double[] b = new double[1]; DMatrixRMaj mat = new DMatrixRMaj(a); } private static double log(int x) { return Math.ceil(Math.log(x) / Math.log(GROWTH_BASE)); } private static int dataSize(int x) { return (int) Math.ceil(Math.pow(GROWTH_BASE, log(x))); } }
UTF-8
Java
592
java
DoubleMatrixList.java
Java
[ { "context": "package io.github.primepotato.jandas.utils;\n\nimport org.ejml.data.DMatrixRMaj;\n", "end": 29, "score": 0.9883103370666504, "start": 18, "tag": "USERNAME", "value": "primepotato" } ]
null
[]
package io.github.primepotato.jandas.utils; import org.ejml.data.DMatrixRMaj; import java.util.Arrays; public class DoubleMatrixList extends DMatrixRMaj { private static double GROWTH_BASE = 2; public DoubleMatrixList(double[] vals) { double[] a = Arrays.copyOf(vals, dataSize(vals.length)); double[] b = new double[1]; DMatrixRMaj mat = new DMatrixRMaj(a); } private static double log(int x) { return Math.ceil(Math.log(x) / Math.log(GROWTH_BASE)); } private static int dataSize(int x) { return (int) Math.ceil(Math.pow(GROWTH_BASE, log(x))); } }
592
0.692568
0.689189
27
20.925926
22.272596
60
false
false
0
0
0
0
0
0
0.407407
false
false
5
caf11962d82deeaf948c0838153bf4886cb3a804
19,318,762,958,243
f31fe8ee211c64be0ffacaa6810c6191e07d1b74
/src/com/xrtb/bidder/DeadmanSwitch.java
0564d8731ff9dc13885ee3fe57123869f5c21125
[ "Apache-2.0" ]
permissive
vki/XRTB
https://github.com/vki/XRTB
1453ac0f1813bfa21f52f0d378b2953cc7c9b2cd
2420a81dc0ca3983fefe6b7663a18dfa2e841384
refs/heads/master
2021-01-19T23:39:47.693000
2017-03-03T00:50:05
2017-03-03T00:50:05
83,786,482
1
0
null
true
2017-03-03T10:24:37
2017-03-03T10:24:37
2017-02-26T21:52:49
2017-03-03T00:50:20
199,754
0
0
0
null
null
null
package com.xrtb.bidder; import com.aerospike.client.AerospikeClient; import com.aerospike.redisson.RedissonClient; import com.xrtb.commands.StopBidder; import com.xrtb.common.Configuration; /** * A class used to stop runaway bidders. If deadmanswitch is set in the startup json, it must be present in the * REDIs store before the bidder will bid. The switch is set by the accounting program. * @author Ben M. Faul * */ public class DeadmanSwitch implements Runnable { RedissonClient redisson; Thread me; String key; boolean sentStop = false; public static boolean testmode = false; public DeadmanSwitch(RedissonClient redisson, String key) { this.redisson = redisson; this.key = key; me = new Thread(this); me.start(); } public DeadmanSwitch(String host, int port, String key) { AerospikeClient spike = new AerospikeClient(host,port); redisson = new RedissonClient(spike); this.key = key; me = new Thread(this); me.start(); } public DeadmanSwitch() { } @Override public void run() { while(true) { try { if (canRun() == false) { if (sentStop == false) { try { if (!testmode) { Controller.getInstance().sendLog(1, "DeadmanSwitch", ("Switch error: " + key + ", does not exist, no bidding allowed!")); StopBidder cmd = new StopBidder(); cmd.from = Configuration.getInstance().instanceName; Controller.getInstance().stopBidder(cmd); } else { System.out.println("Deadman Switch is thrown"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } sentStop = true; } else { sentStop = false; } Thread.sleep(60000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public String getKey() { return key; } public boolean canRun() { String value = redisson.get(key); if (value == null) { return false; } sentStop = false; return true; } }
UTF-8
Java
2,050
java
DeadmanSwitch.java
Java
[ { "context": "witch is set by the accounting program.\n * @author Ben M. Faul\n *\n */\npublic class DeadmanSwitch implements Runn", "end": 419, "score": 0.999866783618927, "start": 408, "tag": "NAME", "value": "Ben M. Faul" } ]
null
[]
package com.xrtb.bidder; import com.aerospike.client.AerospikeClient; import com.aerospike.redisson.RedissonClient; import com.xrtb.commands.StopBidder; import com.xrtb.common.Configuration; /** * A class used to stop runaway bidders. If deadmanswitch is set in the startup json, it must be present in the * REDIs store before the bidder will bid. The switch is set by the accounting program. * @author <NAME> * */ public class DeadmanSwitch implements Runnable { RedissonClient redisson; Thread me; String key; boolean sentStop = false; public static boolean testmode = false; public DeadmanSwitch(RedissonClient redisson, String key) { this.redisson = redisson; this.key = key; me = new Thread(this); me.start(); } public DeadmanSwitch(String host, int port, String key) { AerospikeClient spike = new AerospikeClient(host,port); redisson = new RedissonClient(spike); this.key = key; me = new Thread(this); me.start(); } public DeadmanSwitch() { } @Override public void run() { while(true) { try { if (canRun() == false) { if (sentStop == false) { try { if (!testmode) { Controller.getInstance().sendLog(1, "DeadmanSwitch", ("Switch error: " + key + ", does not exist, no bidding allowed!")); StopBidder cmd = new StopBidder(); cmd.from = Configuration.getInstance().instanceName; Controller.getInstance().stopBidder(cmd); } else { System.out.println("Deadman Switch is thrown"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } sentStop = true; } else { sentStop = false; } Thread.sleep(60000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public String getKey() { return key; } public boolean canRun() { String value = redisson.get(key); if (value == null) { return false; } sentStop = false; return true; } }
2,045
0.647317
0.64439
89
22.033709
21.544024
111
false
false
0
0
0
0
0
0
3.011236
false
false
5
5c7c1965a34b7554cd178d8556b0d85065420160
17,463,337,033,093
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Shopping/ebay_source/src/com/ebay/mobile/analytics/RoiTrackEventRequest.java
0a6b2e097f7bf7eccdf3c875248017b2349a9a58
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
2018-03-23T04:15:18.480000
2015-12-19T01:29:58
2015-12-19T01:29:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.ebay.mobile.analytics; import android.text.TextUtils; import com.ebay.nautilus.domain.EbaySite; import com.ebay.nautilus.domain.data.ItemCurrency; import com.ebay.nautilus.domain.net.EbaySoaRequest; import com.ebay.nautilus.domain.net.XmlSerializerHelper; import com.ebay.nautilus.kernel.NautilusKernel; import com.ebay.nautilus.kernel.net.IHeaders; import com.ebay.nautilus.kernel.net.Response; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.xmlpull.v1.XmlSerializer; // Referenced classes of package com.ebay.mobile.analytics: // RoiTrackEventResponse public class RoiTrackEventRequest extends EbaySoaRequest implements com.ebay.nautilus.domain.net.XmlSerializerHelper.IXmlRequestBuilder { public static final class ItemData { private final String itemId; private final ItemCurrency orderTotal; private final String primaryCategoryId; private final String quantity; private final String secondaryCategoryId; private final String sellerName; private final String uniqueTransactionId; final void add(XmlSerializer xmlserializer) throws IOException { XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "sellerName", sellerName); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "itemId", itemId); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "uniqueTransactionId", uniqueTransactionId); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "quantity", quantity); if (orderTotal != null) { xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "orderTotal"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "currencyId", orderTotal.code); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "amount", orderTotal.value); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "orderTotal"); } XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "primaryCategoryId", primaryCategoryId); if (!TextUtils.isEmpty(secondaryCategoryId)) { XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "secondaryCategoryId", secondaryCategoryId); } } public ItemData(String s, String s1, String s2, String s3, ItemCurrency itemcurrency, String s4, String s5) { sellerName = s; itemId = s1; uniqueTransactionId = s2; quantity = s3; orderTotal = itemcurrency; primaryCategoryId = s4; secondaryCategoryId = s5; if (TextUtils.isEmpty(s)) { throw new NullPointerException("sellerName"); } if (TextUtils.isEmpty(s1)) { throw new NullPointerException("itemId"); } if (TextUtils.isEmpty(s2)) { throw new NullPointerException("uniqueTransactionId"); } if (TextUtils.isEmpty(s3)) { throw new NullPointerException("quantity"); } if (TextUtils.isEmpty(s4)) { throw new NullPointerException("primaryCategoryId"); } else { return; } } } private final ItemData itemData; private final String trackingAppId; private final String transactionType; private final String userId; public RoiTrackEventRequest(String s, EbaySite ebaysite, String s1) { this("Reg-MobileApp", s, ebaysite, null, s1, null); } public RoiTrackEventRequest(String s, String s1, EbaySite ebaysite, String s2, String s3, ItemData itemdata) { super("MobileTrackingService", true, "roiTrackEvent"); soaGlobalId = ebaysite.idString; soaAppIdHeaderName = "x-ebay-soa-security-appname"; iafToken = s2; trackingAppId = s1; transactionType = s; userId = s3; itemData = itemdata; if (TextUtils.isEmpty(s)) { throw new NullPointerException("transactionType"); } if (TextUtils.isEmpty(s1)) { throw new NullPointerException("trackingAppId"); } if (TextUtils.isEmpty(s2) && TextUtils.isEmpty(s3)) { throw new NullPointerException("iafToken or userId"); } else { return; } } public byte[] buildRequest() throws com.ebay.nautilus.kernel.net.Connector.BuildRequestDataException { return XmlSerializerHelper.buildXmlRequest(this); } public void buildXmlRequest(XmlSerializer xmlserializer) throws IOException { xmlserializer.setPrefix(null, "http://www.ebay.com/marketplace/mobile/v1/services"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiTrackEventRequest"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiFactory"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "inputParams"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "transactionType", transactionType); if (itemData != null) { itemData.add(xmlserializer); } XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "client", "ebay"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "vendorName", "Mediaplex"); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "inputParams"); if (!TextUtils.isEmpty(userId)) { xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "optionalParams"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "trackingParameter"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "key", "username"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "value", userId); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "trackingParameter"); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "optionalParams"); } xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiFactory"); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiTrackEventRequest"); } public URL getRequestUrl() { Object obj = "https://svcs.ebay.com/services/mobile/v1/MobileTrackingService"; if (NautilusKernel.isQaMode()) { obj = "http://mobitrack.qa.ebay.com/services/mobile/v1/MobileTrackingService"; } try { obj = new URL(((String) (obj))); } catch (MalformedURLException malformedurlexception) { malformedurlexception.printStackTrace(); return null; } return ((URL) (obj)); } public RoiTrackEventResponse getResponse() { return new RoiTrackEventResponse(); } public volatile Response getResponse() { return getResponse(); } public void onAddHeaders(IHeaders iheaders) { super.onAddHeaders(iheaders); iheaders.setHeader("x-ebay-mobile-mts-appid", trackingAppId); } }
UTF-8
Java
8,340
java
RoiTrackEventRequest.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996308088302612, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" }, { "context": " s4, String s5)\n {\n sellerName = s;\n itemId = s1;\n uniqueTrans", "end": 3104, "score": 0.6905161738395691, "start": 3103, "tag": "NAME", "value": "s" }, { "context": "ebay.com/marketplace/mobile/v1/services\", \"key\", \"username\");\n XmlSerializerHelper.writeSimple(xm", "end": 6861, "score": 0.7693424224853516, "start": 6853, "tag": "KEY", "value": "username" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.ebay.mobile.analytics; import android.text.TextUtils; import com.ebay.nautilus.domain.EbaySite; import com.ebay.nautilus.domain.data.ItemCurrency; import com.ebay.nautilus.domain.net.EbaySoaRequest; import com.ebay.nautilus.domain.net.XmlSerializerHelper; import com.ebay.nautilus.kernel.NautilusKernel; import com.ebay.nautilus.kernel.net.IHeaders; import com.ebay.nautilus.kernel.net.Response; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.xmlpull.v1.XmlSerializer; // Referenced classes of package com.ebay.mobile.analytics: // RoiTrackEventResponse public class RoiTrackEventRequest extends EbaySoaRequest implements com.ebay.nautilus.domain.net.XmlSerializerHelper.IXmlRequestBuilder { public static final class ItemData { private final String itemId; private final ItemCurrency orderTotal; private final String primaryCategoryId; private final String quantity; private final String secondaryCategoryId; private final String sellerName; private final String uniqueTransactionId; final void add(XmlSerializer xmlserializer) throws IOException { XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "sellerName", sellerName); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "itemId", itemId); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "uniqueTransactionId", uniqueTransactionId); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "quantity", quantity); if (orderTotal != null) { xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "orderTotal"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "currencyId", orderTotal.code); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "amount", orderTotal.value); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "orderTotal"); } XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "primaryCategoryId", primaryCategoryId); if (!TextUtils.isEmpty(secondaryCategoryId)) { XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "secondaryCategoryId", secondaryCategoryId); } } public ItemData(String s, String s1, String s2, String s3, ItemCurrency itemcurrency, String s4, String s5) { sellerName = s; itemId = s1; uniqueTransactionId = s2; quantity = s3; orderTotal = itemcurrency; primaryCategoryId = s4; secondaryCategoryId = s5; if (TextUtils.isEmpty(s)) { throw new NullPointerException("sellerName"); } if (TextUtils.isEmpty(s1)) { throw new NullPointerException("itemId"); } if (TextUtils.isEmpty(s2)) { throw new NullPointerException("uniqueTransactionId"); } if (TextUtils.isEmpty(s3)) { throw new NullPointerException("quantity"); } if (TextUtils.isEmpty(s4)) { throw new NullPointerException("primaryCategoryId"); } else { return; } } } private final ItemData itemData; private final String trackingAppId; private final String transactionType; private final String userId; public RoiTrackEventRequest(String s, EbaySite ebaysite, String s1) { this("Reg-MobileApp", s, ebaysite, null, s1, null); } public RoiTrackEventRequest(String s, String s1, EbaySite ebaysite, String s2, String s3, ItemData itemdata) { super("MobileTrackingService", true, "roiTrackEvent"); soaGlobalId = ebaysite.idString; soaAppIdHeaderName = "x-ebay-soa-security-appname"; iafToken = s2; trackingAppId = s1; transactionType = s; userId = s3; itemData = itemdata; if (TextUtils.isEmpty(s)) { throw new NullPointerException("transactionType"); } if (TextUtils.isEmpty(s1)) { throw new NullPointerException("trackingAppId"); } if (TextUtils.isEmpty(s2) && TextUtils.isEmpty(s3)) { throw new NullPointerException("iafToken or userId"); } else { return; } } public byte[] buildRequest() throws com.ebay.nautilus.kernel.net.Connector.BuildRequestDataException { return XmlSerializerHelper.buildXmlRequest(this); } public void buildXmlRequest(XmlSerializer xmlserializer) throws IOException { xmlserializer.setPrefix(null, "http://www.ebay.com/marketplace/mobile/v1/services"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiTrackEventRequest"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiFactory"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "inputParams"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "transactionType", transactionType); if (itemData != null) { itemData.add(xmlserializer); } XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "client", "ebay"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "vendorName", "Mediaplex"); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "inputParams"); if (!TextUtils.isEmpty(userId)) { xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "optionalParams"); xmlserializer.startTag("http://www.ebay.com/marketplace/mobile/v1/services", "trackingParameter"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "key", "username"); XmlSerializerHelper.writeSimple(xmlserializer, "http://www.ebay.com/marketplace/mobile/v1/services", "value", userId); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "trackingParameter"); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "optionalParams"); } xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiFactory"); xmlserializer.endTag("http://www.ebay.com/marketplace/mobile/v1/services", "roiTrackEventRequest"); } public URL getRequestUrl() { Object obj = "https://svcs.ebay.com/services/mobile/v1/MobileTrackingService"; if (NautilusKernel.isQaMode()) { obj = "http://mobitrack.qa.ebay.com/services/mobile/v1/MobileTrackingService"; } try { obj = new URL(((String) (obj))); } catch (MalformedURLException malformedurlexception) { malformedurlexception.printStackTrace(); return null; } return ((URL) (obj)); } public RoiTrackEventResponse getResponse() { return new RoiTrackEventResponse(); } public volatile Response getResponse() { return getResponse(); } public void onAddHeaders(IHeaders iheaders) { super.onAddHeaders(iheaders); iheaders.setHeader("x-ebay-mobile-mts-appid", trackingAppId); } }
8,330
0.653357
0.646043
199
40.909546
39.352955
161
false
false
0
0
0
0
0
0
0.809045
false
false
5
1b555b0548e1a92cf2806ba6e53e1cc8ad16cf26
1,408,749,298,122
4aa9beb0c15cd2faadce920d653bea2e9c3cb9b3
/third-integration/devCloud/src/main/java/nl/sri/devCloud/mapper/VRequirementSectionMapper.java
44735dfa86911289d005b620ebe495e12de04ca4
[ "Apache-2.0" ]
permissive
songdi676/paas-admin
https://github.com/songdi676/paas-admin
ac8cba2b020593f46e239b7d2b515223d1c1f472
cccf3c8b6a367d3d3bb96ffd9aa034dfb9abf3f7
refs/heads/master
2022-12-04T22:11:22.295000
2020-08-18T02:31:26
2020-08-18T02:31:26
277,461,170
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.sri.devCloud.mapper; import nl.sri.devCloud.entity.VRequirementSection; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * VIEW Mapper 接口 * </p> * * @author wurunxiang * @since 2020-07-21 */ public interface VRequirementSectionMapper extends BaseMapper<VRequirementSection> { }
UTF-8
Java
320
java
VRequirementSectionMapper.java
Java
[ { "context": "/**\n * <p>\n * VIEW Mapper 接口\n * </p>\n *\n * @author wurunxiang\n * @since 2020-07-21\n */\npublic interface VRequir", "end": 202, "score": 0.9996083974838257, "start": 192, "tag": "USERNAME", "value": "wurunxiang" } ]
null
[]
package nl.sri.devCloud.mapper; import nl.sri.devCloud.entity.VRequirementSection; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * VIEW Mapper 接口 * </p> * * @author wurunxiang * @since 2020-07-21 */ public interface VRequirementSectionMapper extends BaseMapper<VRequirementSection> { }
320
0.75
0.724684
16
18.75
23.920441
84
false
false
0
0
0
0
0
0
0.1875
false
false
5
43e1f498e4bf4c4faed77b9d5c7d7eb9a4674fe4
1,408,749,298,892
5c4cfa76deafadb1c73f2dc41e26063a05be1715
/src/main/java/com/avi/ihw/groups/ParisGrp.java
e2bf75a31934c8294daf4a74104604bb75a98ff5
[]
no_license
avinashmoram/paris-ihw
https://github.com/avinashmoram/paris-ihw
04f253667e360a3da25a23a2b946b9e64a0ca9a0
93422a12219dc0e0703362d53042352a68d11c1a
refs/heads/master
2021-08-30T16:51:59.473000
2017-12-18T19:02:09
2017-12-18T19:02:09
114,675,584
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.avi.ihw.groups; /**<b>Author:</b> Avinash Moram *<p><b>Date:</b> 04-11-2017 * *<p><b>PAGE DESCRIPTION: This is the parent group of all groups under PARIS *==================================================================================</b> * * *<p><b>CHANGE LOG: *================================================================================== *Date UserName PhoneEx. - Comment </b><p> *04-11-2017 AMORAM x0821 Initial creation * */ public interface ParisGrp { // ParisGroup Conversation Group }
UTF-8
Java
531
java
ParisGrp.java
Java
[ { "context": "package com.avi.ihw.groups;\n\n/**<b>Author:</b>\tAvinash Moram\n *<p><b>Date:</b>\t04-11-2017\n *\n *<p><b>PAGE DESC", "end": 60, "score": 0.9996352195739746, "start": 47, "tag": "NAME", "value": "Avinash Moram" }, { "context": "\tUserName\tPhoneEx.\t- Comment </b><p>\n *04-11-2017\tAMORAM\t\tx0821\t\tInitial creation\n *\n */\npublic interface ", "end": 434, "score": 0.657156229019165, "start": 428, "tag": "USERNAME", "value": "AMORAM" } ]
null
[]
package com.avi.ihw.groups; /**<b>Author:</b> <NAME> *<p><b>Date:</b> 04-11-2017 * *<p><b>PAGE DESCRIPTION: This is the parent group of all groups under PARIS *==================================================================================</b> * * *<p><b>CHANGE LOG: *================================================================================== *Date UserName PhoneEx. - Comment </b><p> *04-11-2017 AMORAM x0821 Initial creation * */ public interface ParisGrp { // ParisGroup Conversation Group }
524
0.450094
0.412429
18
28.5
28.388672
88
false
false
0
0
0
0
83
0.310734
0.777778
false
false
5
f8473334c20775f1c2e46328d66a3292b7921f45
28,595,892,284,270
c287d7b53a448e1d03f3ad3f62e7ad1e5809dfc0
/src/datasal/Narag/breakout/Breakout_GRAN.java
eb4210b1417afcaa6c8ee3dc4f2aaa259f43bc2e
[]
no_license
melvincabatuan/DATASALChecking
https://github.com/melvincabatuan/DATASALChecking
8f4153ca83f57ca5d81419eb4dd18ea6ef9a7f1c
53906a38ce07bd0b5a39d1e735d77eb2d17a3ad0
refs/heads/master
2021-01-22T18:27:57.799000
2017-08-21T23:10:41
2017-08-21T23:10:41
100,757,463
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package datasal.Narag.breakout; import acm.graphics.*; import acm.program.*; import acm.util.*; import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import datasal.Narag.myarraylist.ListCanvas; import datasal.Narag.myarraylist.MyArrayList; public class Breakout_GRAN extends GraphicsProgram { private MyArrayList<String> hiScore = new MyArrayList<String>(); /** Width and height of application window in pixels */ public static final int APPLICATION_WIDTH = 800; public static final int APPLICATION_HEIGHT = 600; /** Dimensions of game board (usually the same) */ private static final int WIDTH = APPLICATION_WIDTH-400; private static final int HEIGHT = APPLICATION_HEIGHT; /** Dimensions of the paddle */ private static final int PADDLE_WIDTH = 60; private static final int PADDLE_HEIGHT = 10; /** Offset of the paddle up from the bottom */ private static final int PADDLE_Y_OFFSET = 30; /** Number of bricks per row */ private static final int NBRICKS_PER_ROW = 10; /** Number of rows of bricks */ private static final int NBRICK_ROWS = 10; /** Separation between bricks */ private static final int BRICK_SEP = 4; /** Width of a brick */ private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW; /** Height of a brick */ private static final int BRICK_HEIGHT = 8; /** Radius of the ball in pixels */ private static final int BALL_RADIUS = 10; /** Offset of the top brick row from the top */ private static final int BRICK_Y_OFFSET = 70; /** Number of turns */ private static final int NTURNS = 3; /**velocity**/ private double vy, vx; /**RNG be praised**/ private RandomGenerator rng = RandomGenerator.getInstance(); /**number of bricks**/ int counter=100; int destroyed=0; private JFrame frame; /**canvas**/ private ListCanvas leaderboard; int score1, score2, score3, score4, score5, score6, score7, score8, score9, score10; String scorename; public void init() { hiScore.createList(); hiScore.add(1, ""+score1); hiScore.add(2, ""+score2); hiScore.add(3, ""+score3); hiScore.add(4, ""+score4); hiScore.add(5, ""+score5); hiScore.add(6, ""+score6); hiScore.add(7, ""+score7); hiScore.add(8, ""+score8); hiScore.add(9, ""+score9); hiScore.add(10, ""+score10); leaderboard = new ListCanvas(); leaderboard.setBackground(Color.black); add(leaderboard); } @Override public void run(){ //removeAll(); destroyed = 0; counter = 100; scoreboard = new GLabel("Score: " + destroyed,0, 10); buildWall(); for(int i=0; i < NTURNS; i++) { paddle(); ball(); StartGame(); if(counter==0) { ball.setVisible(false); Winscreen(); scorename = JOptionPane.showInputDialog("Input name"); highScore(); waitForClick(); run(); } if(counter > 0) { remove(pdl); remove(ball); } } if(counter > 0) { GOscreen(); scorename = JOptionPane.showInputDialog("Input name"); highScore(); waitForClick(); run(); } } //G A M E S E C T I O N private double XLoc() { return 0.5 * (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP - BRICK_WIDTH * NBRICKS_PER_ROW); } private GRect brick; //D R A W B R I C K S private void drawWall(int row, int cols){ double x, y; brick = new GRect (BRICK_WIDTH, BRICK_HEIGHT); JComponent brickC = new JComponent() {}; x = XLoc() + cols * (BRICK_WIDTH + BRICK_SEP); y = BRICK_Y_OFFSET + row * (BRICK_HEIGHT + BRICK_SEP); brick.setFilled(true); //B R I C K C O L O R switch (row) { case 0: case 1: brick.setFillColor(Color.RED); break; case 2: case 3: brick.setFillColor(Color.ORANGE); break; case 4: case 5: brick.setFillColor(Color.YELLOW); break; case 6: case 7: brick.setFillColor(Color.GREEN); break; case 8: case 9: brick.setFillColor(Color.CYAN); } //B R I C K C O L O R E N D add (brick, x, y); } //B U I L D W A L L private void buildWall(){ for (int a = 0; a<NBRICKS_PER_ROW; a++) for (int b = 0; b<NBRICKS_PER_ROW; b++) drawWall(a, b); } //P A D D L E private GRect pdl; private void paddle(){ pdl = new GRect(0.5*(WIDTH - PADDLE_WIDTH), HEIGHT -PADDLE_Y_OFFSET - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT); pdl.setFilled(true); add(pdl); addMouseListeners(); } //B A L L private GOval ball; private void ball(){ ball = new GOval(BALL_RADIUS, BALL_RADIUS); ball.setFilled(true); add(ball, 0.5*(WIDTH - BALL_RADIUS), 400 ); } //actual game private void StartGame() { waitForClick(); getBallVelocity(); while (true) { moveBall(); if (ball.getY() >= getHeight()) { break; } if(counter == 0) { break; } } } //checks if mouse in bounds private boolean mousebounds(int g){ return ((g > 0.5 * PADDLE_WIDTH)) && ((g < (WIDTH - (0.5 * PADDLE_WIDTH)))); } //moves the paddle public void mouseMoved(MouseEvent me){ if (mousebounds(me.getX())) { pdl.setLocation(me.getX()-0.5 * PADDLE_WIDTH, pdl.getY()); } } //gets the ball's velocity private void getBallVelocity() { vy = 3.0; vx = rng.nextDouble(1.0, 3.0); if (rng.nextBoolean(0.5)) { vx = -vx; } } private GObject collider; //moves the ball private void moveBall() { ball.move(vx, vy); //check for walls if ((ball.getX() - vx <= 0 && vx < 0 )|| (ball.getX() + vx >= (getWidth() - BALL_RADIUS*2) && vx>0) || ball.getX()<=400 && ball.getX()>390) { vx = -vx; } if ((ball.getY() - vy <= 0 && vy < 0 )) { vy = -vy; } //checks for collision collider = getCollidingObject(); if (collider == pdl) { vy = -vy; } else if(collider !=null && collider != pdl && collider!=scoreboard) { scoring(); remove(collider); destroyed = destroyed + 1; counter = counter - 1; vy = -vy; } pause (15); } //collisions and stuff private GObject getCollidingObject() { if((getElementAt(ball.getX(), ball.getY())) != null) { return getElementAt(ball.getX(), ball.getY()); } else if (getElementAt( (ball.getX() + BALL_RADIUS*2), ball.getY()) != null ){ return getElementAt(ball.getX() + BALL_RADIUS*2, ball.getY()); } else if(getElementAt(ball.getX(), (ball.getY() + BALL_RADIUS*2)) != null ){ return getElementAt(ball.getX(), ball.getY() + BALL_RADIUS*2); } else if(getElementAt((ball.getX() + BALL_RADIUS*2), (ball.getY() + BALL_RADIUS*2)) != null ){ return getElementAt(ball.getX() + BALL_RADIUS*2, ball.getY() + BALL_RADIUS*2); } else return null; } //when you get rekt private void GOscreen() { GLabel GO = new GLabel ("Game Over", (getWidth()/2)-200, getHeight()/2); GO.move(-GO.getWidth()/2, -GO.getHeight()); GO.setColor(Color.RED); add (GO); waitForClick(); remove(GO); } //when you win private void Winscreen() { GLabel Winner = new GLabel ("Winner!!", (getWidth()/2)-200, getHeight()/2); Winner.move(-Winner.getWidth()/2, -Winner.getHeight()); Winner.setColor(Color.RED); add (Winner); waitForClick(); remove(Winner); } //score private GLabel scoreboard; private void scoring(){ remove(scoreboard); if (collider!=null && collider !=pdl) { scoreboard.setLabel("Score: " + (destroyed+1)); } add(scoreboard); } private void highScore(){ if (destroyed>score1){ hiScore.remove(10); hiScore.add(1, scorename + " - " +destroyed); score1=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score2){ hiScore.remove(10); hiScore.add(2, scorename + " - "+destroyed); score2=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score3){ hiScore.remove(10); hiScore.add(3, scorename + " - "+destroyed); score3=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score4){ hiScore.remove(10); hiScore.add(4, scorename + " - "+destroyed); score4=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score5){ hiScore.remove(10); hiScore.add(5, scorename + " - "+destroyed); score5=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score6){ hiScore.remove(10); hiScore.add(6, scorename + " - "+destroyed); score6=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score7){ hiScore.remove(10); hiScore.add(7, scorename + " - "+destroyed); score7=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score8){ hiScore.remove(10); hiScore.add(8, scorename + " - " +destroyed); score8=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score9){ hiScore.remove(10); hiScore.add(9, scorename + " - "+destroyed); score9=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score10){ hiScore.remove(10); hiScore.add(10, scorename + " - "+destroyed); score10=destroyed; leaderboard.displayList(hiScore); } else { leaderboard.displayList(hiScore); } } public void runBreakout() { GCanvas frame; new Breakout_GRAN().start(); } }
UTF-8
Java
12,050
java
Breakout_GRAN.java
Java
[]
null
[]
package datasal.Narag.breakout; import acm.graphics.*; import acm.program.*; import acm.util.*; import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import datasal.Narag.myarraylist.ListCanvas; import datasal.Narag.myarraylist.MyArrayList; public class Breakout_GRAN extends GraphicsProgram { private MyArrayList<String> hiScore = new MyArrayList<String>(); /** Width and height of application window in pixels */ public static final int APPLICATION_WIDTH = 800; public static final int APPLICATION_HEIGHT = 600; /** Dimensions of game board (usually the same) */ private static final int WIDTH = APPLICATION_WIDTH-400; private static final int HEIGHT = APPLICATION_HEIGHT; /** Dimensions of the paddle */ private static final int PADDLE_WIDTH = 60; private static final int PADDLE_HEIGHT = 10; /** Offset of the paddle up from the bottom */ private static final int PADDLE_Y_OFFSET = 30; /** Number of bricks per row */ private static final int NBRICKS_PER_ROW = 10; /** Number of rows of bricks */ private static final int NBRICK_ROWS = 10; /** Separation between bricks */ private static final int BRICK_SEP = 4; /** Width of a brick */ private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW; /** Height of a brick */ private static final int BRICK_HEIGHT = 8; /** Radius of the ball in pixels */ private static final int BALL_RADIUS = 10; /** Offset of the top brick row from the top */ private static final int BRICK_Y_OFFSET = 70; /** Number of turns */ private static final int NTURNS = 3; /**velocity**/ private double vy, vx; /**RNG be praised**/ private RandomGenerator rng = RandomGenerator.getInstance(); /**number of bricks**/ int counter=100; int destroyed=0; private JFrame frame; /**canvas**/ private ListCanvas leaderboard; int score1, score2, score3, score4, score5, score6, score7, score8, score9, score10; String scorename; public void init() { hiScore.createList(); hiScore.add(1, ""+score1); hiScore.add(2, ""+score2); hiScore.add(3, ""+score3); hiScore.add(4, ""+score4); hiScore.add(5, ""+score5); hiScore.add(6, ""+score6); hiScore.add(7, ""+score7); hiScore.add(8, ""+score8); hiScore.add(9, ""+score9); hiScore.add(10, ""+score10); leaderboard = new ListCanvas(); leaderboard.setBackground(Color.black); add(leaderboard); } @Override public void run(){ //removeAll(); destroyed = 0; counter = 100; scoreboard = new GLabel("Score: " + destroyed,0, 10); buildWall(); for(int i=0; i < NTURNS; i++) { paddle(); ball(); StartGame(); if(counter==0) { ball.setVisible(false); Winscreen(); scorename = JOptionPane.showInputDialog("Input name"); highScore(); waitForClick(); run(); } if(counter > 0) { remove(pdl); remove(ball); } } if(counter > 0) { GOscreen(); scorename = JOptionPane.showInputDialog("Input name"); highScore(); waitForClick(); run(); } } //G A M E S E C T I O N private double XLoc() { return 0.5 * (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP - BRICK_WIDTH * NBRICKS_PER_ROW); } private GRect brick; //D R A W B R I C K S private void drawWall(int row, int cols){ double x, y; brick = new GRect (BRICK_WIDTH, BRICK_HEIGHT); JComponent brickC = new JComponent() {}; x = XLoc() + cols * (BRICK_WIDTH + BRICK_SEP); y = BRICK_Y_OFFSET + row * (BRICK_HEIGHT + BRICK_SEP); brick.setFilled(true); //B R I C K C O L O R switch (row) { case 0: case 1: brick.setFillColor(Color.RED); break; case 2: case 3: brick.setFillColor(Color.ORANGE); break; case 4: case 5: brick.setFillColor(Color.YELLOW); break; case 6: case 7: brick.setFillColor(Color.GREEN); break; case 8: case 9: brick.setFillColor(Color.CYAN); } //B R I C K C O L O R E N D add (brick, x, y); } //B U I L D W A L L private void buildWall(){ for (int a = 0; a<NBRICKS_PER_ROW; a++) for (int b = 0; b<NBRICKS_PER_ROW; b++) drawWall(a, b); } //P A D D L E private GRect pdl; private void paddle(){ pdl = new GRect(0.5*(WIDTH - PADDLE_WIDTH), HEIGHT -PADDLE_Y_OFFSET - PADDLE_HEIGHT, PADDLE_WIDTH, PADDLE_HEIGHT); pdl.setFilled(true); add(pdl); addMouseListeners(); } //B A L L private GOval ball; private void ball(){ ball = new GOval(BALL_RADIUS, BALL_RADIUS); ball.setFilled(true); add(ball, 0.5*(WIDTH - BALL_RADIUS), 400 ); } //actual game private void StartGame() { waitForClick(); getBallVelocity(); while (true) { moveBall(); if (ball.getY() >= getHeight()) { break; } if(counter == 0) { break; } } } //checks if mouse in bounds private boolean mousebounds(int g){ return ((g > 0.5 * PADDLE_WIDTH)) && ((g < (WIDTH - (0.5 * PADDLE_WIDTH)))); } //moves the paddle public void mouseMoved(MouseEvent me){ if (mousebounds(me.getX())) { pdl.setLocation(me.getX()-0.5 * PADDLE_WIDTH, pdl.getY()); } } //gets the ball's velocity private void getBallVelocity() { vy = 3.0; vx = rng.nextDouble(1.0, 3.0); if (rng.nextBoolean(0.5)) { vx = -vx; } } private GObject collider; //moves the ball private void moveBall() { ball.move(vx, vy); //check for walls if ((ball.getX() - vx <= 0 && vx < 0 )|| (ball.getX() + vx >= (getWidth() - BALL_RADIUS*2) && vx>0) || ball.getX()<=400 && ball.getX()>390) { vx = -vx; } if ((ball.getY() - vy <= 0 && vy < 0 )) { vy = -vy; } //checks for collision collider = getCollidingObject(); if (collider == pdl) { vy = -vy; } else if(collider !=null && collider != pdl && collider!=scoreboard) { scoring(); remove(collider); destroyed = destroyed + 1; counter = counter - 1; vy = -vy; } pause (15); } //collisions and stuff private GObject getCollidingObject() { if((getElementAt(ball.getX(), ball.getY())) != null) { return getElementAt(ball.getX(), ball.getY()); } else if (getElementAt( (ball.getX() + BALL_RADIUS*2), ball.getY()) != null ){ return getElementAt(ball.getX() + BALL_RADIUS*2, ball.getY()); } else if(getElementAt(ball.getX(), (ball.getY() + BALL_RADIUS*2)) != null ){ return getElementAt(ball.getX(), ball.getY() + BALL_RADIUS*2); } else if(getElementAt((ball.getX() + BALL_RADIUS*2), (ball.getY() + BALL_RADIUS*2)) != null ){ return getElementAt(ball.getX() + BALL_RADIUS*2, ball.getY() + BALL_RADIUS*2); } else return null; } //when you get rekt private void GOscreen() { GLabel GO = new GLabel ("Game Over", (getWidth()/2)-200, getHeight()/2); GO.move(-GO.getWidth()/2, -GO.getHeight()); GO.setColor(Color.RED); add (GO); waitForClick(); remove(GO); } //when you win private void Winscreen() { GLabel Winner = new GLabel ("Winner!!", (getWidth()/2)-200, getHeight()/2); Winner.move(-Winner.getWidth()/2, -Winner.getHeight()); Winner.setColor(Color.RED); add (Winner); waitForClick(); remove(Winner); } //score private GLabel scoreboard; private void scoring(){ remove(scoreboard); if (collider!=null && collider !=pdl) { scoreboard.setLabel("Score: " + (destroyed+1)); } add(scoreboard); } private void highScore(){ if (destroyed>score1){ hiScore.remove(10); hiScore.add(1, scorename + " - " +destroyed); score1=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score2){ hiScore.remove(10); hiScore.add(2, scorename + " - "+destroyed); score2=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score3){ hiScore.remove(10); hiScore.add(3, scorename + " - "+destroyed); score3=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score4){ hiScore.remove(10); hiScore.add(4, scorename + " - "+destroyed); score4=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score5){ hiScore.remove(10); hiScore.add(5, scorename + " - "+destroyed); score5=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score6){ hiScore.remove(10); hiScore.add(6, scorename + " - "+destroyed); score6=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score7){ hiScore.remove(10); hiScore.add(7, scorename + " - "+destroyed); score7=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score8){ hiScore.remove(10); hiScore.add(8, scorename + " - " +destroyed); score8=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score9){ hiScore.remove(10); hiScore.add(9, scorename + " - "+destroyed); score9=destroyed; leaderboard.displayList(hiScore); } else if (destroyed>score10){ hiScore.remove(10); hiScore.add(10, scorename + " - "+destroyed); score10=destroyed; leaderboard.displayList(hiScore); } else { leaderboard.displayList(hiScore); } } public void runBreakout() { GCanvas frame; new Breakout_GRAN().start(); } }
12,050
0.480166
0.463402
407
27.58231
20.975767
143
false
false
0
0
0
0
0
0
1.076167
false
false
5
bbe4866704f14944ba4569e8cf34fad6d18693f0
5,239,860,137,854
4db048132ade6f26a079f47900a4f655faf6ef04
/JiraPlugins/atlassian-jira-4.4.3-source/embedded-crowd-api/src/main/java/com/atlassian/crowd/embedded/api/PasswordCredential.java
31f791661a01dabfa2a6dfd2157e9ac0daf0e586
[]
no_license
JCVI-VIRIFX/SampleTracking
https://github.com/JCVI-VIRIFX/SampleTracking
045f3a690161cd6735dda6cf53964a89910c2d32
8f68cf385a083dcef055605dc040a224576a16fe
refs/heads/master
2018-01-07T23:30:42.211000
2015-12-11T04:23:38
2015-12-11T04:23:38
47,804,829
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atlassian.crowd.embedded.api; import org.apache.commons.lang.builder.ToStringBuilder; import java.io.Serializable; /** * Password based authentication information. * * @author Justen Stepka <jstepka@atlassian.com> * @version 1.0 */ public class PasswordCredential implements Serializable { public static final PasswordCredential NONE = encrypted("X"); // Can't use empty string because Oracle will think it is null private boolean encryptedCredential = false; protected String credential; public static PasswordCredential encrypted(String encryptedCredential) { return new PasswordCredential(encryptedCredential, true); } public static PasswordCredential unencrypted(String unencryptedCredential) { return new PasswordCredential(unencryptedCredential, false); } /** * Default constructor used by hibernate * @deprecated since 1.3.2, please use any other PasswordCredential constructor, * this constructor should only be used by hibernate. If this constructor is used, * please be aware that you must set {@link PasswordCredential#setEncryptedCredential(boolean)} */ public PasswordCredential() { this.encryptedCredential = true; } public PasswordCredential(PasswordCredential passwordCredential) { if (passwordCredential != null) { setCredential(passwordCredential.getCredential()); setEncryptedCredential(passwordCredential.isEncryptedCredential()); } } /** * Constructor that takes an unencrypted credential. ie {@link PasswordCredential#encryptedCredential} * is false. * * @param unencryptedCredential the unencrypted password credential */ public PasswordCredential(String unencryptedCredential) { this.encryptedCredential = false; this.credential = unencryptedCredential; } public PasswordCredential(String credential, boolean encryptedCredential) { this.credential = credential; this.encryptedCredential = encryptedCredential; } /** * Gets the password credential. * * @return The credential. */ public String getCredential() { return credential; } /** * Sets the password credential. * * @param credential The credential. */ public void setCredential(String credential) { this.credential = credential; } public boolean isEncryptedCredential() { return encryptedCredential; } public void setEncryptedCredential(boolean encryptedCredential) { this.encryptedCredential = encryptedCredential; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PasswordCredential that = (PasswordCredential) o; return credential != null ? credential.equals(that.credential) : that.credential == null; } public int hashCode() { return (credential != null ? credential.hashCode() : 0); } public String toString() { return new ToStringBuilder(this). append("credential", credential). append("encryptedCredential", encryptedCredential). toString(); } }
UTF-8
Java
3,414
java
PasswordCredential.java
Java
[ { "context": "rd based authentication information.\n *\n * @author Justen Stepka <jstepka@atlassian.com>\n * @version 1.0\n */\npubli", "end": 207, "score": 0.999886691570282, "start": 194, "tag": "NAME", "value": "Justen Stepka" }, { "context": "ication information.\n *\n * @author Justen Stepka <jstepka@atlassian.com>\n * @version 1.0\n */\npublic class PasswordCredent", "end": 230, "score": 0.999923825263977, "start": 209, "tag": "EMAIL", "value": "jstepka@atlassian.com" } ]
null
[]
package com.atlassian.crowd.embedded.api; import org.apache.commons.lang.builder.ToStringBuilder; import java.io.Serializable; /** * Password based authentication information. * * @author <NAME> <<EMAIL>> * @version 1.0 */ public class PasswordCredential implements Serializable { public static final PasswordCredential NONE = encrypted("X"); // Can't use empty string because Oracle will think it is null private boolean encryptedCredential = false; protected String credential; public static PasswordCredential encrypted(String encryptedCredential) { return new PasswordCredential(encryptedCredential, true); } public static PasswordCredential unencrypted(String unencryptedCredential) { return new PasswordCredential(unencryptedCredential, false); } /** * Default constructor used by hibernate * @deprecated since 1.3.2, please use any other PasswordCredential constructor, * this constructor should only be used by hibernate. If this constructor is used, * please be aware that you must set {@link PasswordCredential#setEncryptedCredential(boolean)} */ public PasswordCredential() { this.encryptedCredential = true; } public PasswordCredential(PasswordCredential passwordCredential) { if (passwordCredential != null) { setCredential(passwordCredential.getCredential()); setEncryptedCredential(passwordCredential.isEncryptedCredential()); } } /** * Constructor that takes an unencrypted credential. ie {@link PasswordCredential#encryptedCredential} * is false. * * @param unencryptedCredential the unencrypted password credential */ public PasswordCredential(String unencryptedCredential) { this.encryptedCredential = false; this.credential = unencryptedCredential; } public PasswordCredential(String credential, boolean encryptedCredential) { this.credential = credential; this.encryptedCredential = encryptedCredential; } /** * Gets the password credential. * * @return The credential. */ public String getCredential() { return credential; } /** * Sets the password credential. * * @param credential The credential. */ public void setCredential(String credential) { this.credential = credential; } public boolean isEncryptedCredential() { return encryptedCredential; } public void setEncryptedCredential(boolean encryptedCredential) { this.encryptedCredential = encryptedCredential; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PasswordCredential that = (PasswordCredential) o; return credential != null ? credential.equals(that.credential) : that.credential == null; } public int hashCode() { return (credential != null ? credential.hashCode() : 0); } public String toString() { return new ToStringBuilder(this). append("credential", credential). append("encryptedCredential", encryptedCredential). toString(); } }
3,393
0.657001
0.655243
126
26.103174
28.544821
129
false
false
0
0
0
0
0
0
0.277778
false
false
5
9fc5cbebabe650d2acb534b52977189c9f59c9ce
446,676,620,170
3440f1d49bc89a491dbc3134e2a2be4c60e1c8df
/src/main/java/team/abc/ssm/common/utils/UserUtils.java
2b4d4982d445e0ae521d500ea006a94fcd01b3ca
[]
no_license
casuak/Document-Management-System
https://github.com/casuak/Document-Management-System
3d0b21bebe7c934865f991ea603244b322fee445
3bf0f337e0b2e841132c3ac04241ea915691a2af
refs/heads/master
2022-12-25T08:13:01.783000
2020-06-25T06:46:19
2020-06-25T06:46:19
176,279,162
2
4
null
false
2022-12-16T06:11:30
2019-03-18T12:24:14
2020-06-25T06:46:50
2022-12-16T06:11:29
45,299
0
2
27
JavaScript
false
false
package team.abc.ssm.common.utils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import team.abc.ssm.modules.sys.entity.User; import team.abc.ssm.modules.sys.service.UserService; /** * 用户工具类 */ public class UserUtils { private static UserService userService = SpringContextHolder.getBean(UserService.class); /** * 返回当前登陆用户 */ public static User getCurrentUser() { refreshCurrentUser(); Subject subject = SecurityUtils.getSubject(); return (User) subject.getSession().getAttribute("user"); } /** * 刷新当前登陆用户的信息 */ public static User refreshCurrentUser() { String username = (String) SecurityUtils.getSubject().getPrincipal(); Subject subject = SecurityUtils.getSubject(); User _user = new User(); _user.setUsername(username); User user = userService.getUserByUsername(_user); subject.getSession().setAttribute("user", user); return user; } }
UTF-8
Java
1,057
java
UserUtils.java
Java
[ { "context": "ser _user = new User();\n _user.setUsername(username);\n User user = userService.getUserByUserna", "end": 862, "score": 0.9468213319778442, "start": 854, "tag": "USERNAME", "value": "username" } ]
null
[]
package team.abc.ssm.common.utils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import team.abc.ssm.modules.sys.entity.User; import team.abc.ssm.modules.sys.service.UserService; /** * 用户工具类 */ public class UserUtils { private static UserService userService = SpringContextHolder.getBean(UserService.class); /** * 返回当前登陆用户 */ public static User getCurrentUser() { refreshCurrentUser(); Subject subject = SecurityUtils.getSubject(); return (User) subject.getSession().getAttribute("user"); } /** * 刷新当前登陆用户的信息 */ public static User refreshCurrentUser() { String username = (String) SecurityUtils.getSubject().getPrincipal(); Subject subject = SecurityUtils.getSubject(); User _user = new User(); _user.setUsername(username); User user = userService.getUserByUsername(_user); subject.getSession().setAttribute("user", user); return user; } }
1,057
0.668979
0.668979
36
27.027779
24.582611
92
false
false
0
0
0
0
0
0
0.472222
false
false
5
d4e5757ff4d224d6b7e0dd29af877f3dea0d11d7
8,589,934,620,339
e1f09447cb194736ee9dbc0aae4142ce231ff9bb
/src/main/java/copado/onpremise/connector/salesforce/TestLevelBuilder.java
95fae6245321ab6afb9766bbb54c016d67bfbfc6
[ "Apache-2.0" ]
permissive
CopadoSolutions/copado-deployment-service
https://github.com/CopadoSolutions/copado-deployment-service
0af67df69cd6414b86fc17c91bf3037e5861b44d
87e335e5beea9f35645f759c60e9f499a19bd8c5
refs/heads/master
2021-12-01T15:56:59.744000
2021-11-18T12:35:51
2021-11-18T12:35:51
148,326,781
1
1
NOASSERTION
false
2021-11-18T12:35:52
2018-09-11T14:03:08
2021-03-15T12:28:50
2021-11-18T12:35:51
305
0
1
3
Shell
false
false
package copado.onpremise.connector.salesforce; import com.sforce.soap.metadata.TestLevel; public class TestLevelBuilder { private TestLevelBuilder(){} public static TestLevel build(String testLevel){ switch (testLevel) { case "RunAllTestsInOrg": return TestLevel.RunAllTestsInOrg; case "RunLocalTests": return TestLevel.RunLocalTests; case "RunSpecifiedTests": return TestLevel.RunSpecifiedTests; case "NoTestRun": return TestLevel.NoTestRun; default: return TestLevel.NoTestRun; } } }
UTF-8
Java
658
java
TestLevelBuilder.java
Java
[]
null
[]
package copado.onpremise.connector.salesforce; import com.sforce.soap.metadata.TestLevel; public class TestLevelBuilder { private TestLevelBuilder(){} public static TestLevel build(String testLevel){ switch (testLevel) { case "RunAllTestsInOrg": return TestLevel.RunAllTestsInOrg; case "RunLocalTests": return TestLevel.RunLocalTests; case "RunSpecifiedTests": return TestLevel.RunSpecifiedTests; case "NoTestRun": return TestLevel.NoTestRun; default: return TestLevel.NoTestRun; } } }
658
0.607903
0.607903
23
27.608696
18.570053
52
false
false
0
0
0
0
0
0
0.304348
false
false
5