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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3dbf6fbbcec90e4a8e83fec9f222313cbf981584
| 3,985,729,717,984 |
db15f75c284fe3df64bf4eb7b9e40bc516c9fed1
|
/src/main/java/com/TrackApp/TrackApp/services/security/SecurityService.java
|
b8cb7422b15d26860b5ba3ab604ad18d398a288b
|
[] |
no_license
|
OanaChis/TrackApp
|
https://github.com/OanaChis/TrackApp
|
6de106f3c8d0f77cbe2cba6205dc95625de8018c
|
8de73f7dadcb861b7d718a54386d601c7c191746
|
refs/heads/master
| 2021-01-21T21:06:16.918000 | 2017-06-19T17:41:52 | 2017-06-19T17:41:52 | 94,775,648 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.TrackApp.TrackApp.services.security;
/**
* Created by oana_ on 6/15/2017.
*/
public interface SecurityService {
String findLoggedInUserName();
void autoLogin(String userName,String pass);
}
|
UTF-8
|
Java
| 217 |
java
|
SecurityService.java
|
Java
|
[
{
"context": "App.TrackApp.services.security;\n\n/**\n * Created by oana_ on 6/15/2017.\n */\npublic interface SecurityServic",
"end": 73,
"score": 0.9996291995048523,
"start": 68,
"tag": "USERNAME",
"value": "oana_"
}
] | null |
[] |
package com.TrackApp.TrackApp.services.security;
/**
* Created by oana_ on 6/15/2017.
*/
public interface SecurityService {
String findLoggedInUserName();
void autoLogin(String userName,String pass);
}
| 217 | 0.723502 | 0.691244 | 11 | 18.727272 | 19.854429 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
0
|
800f85cbf4fa9becf97facfb95f5358e20820317
| 10,402,410,818,022 |
9a984dfb52b195c0e6997f5bf58f8b8dc868d015
|
/JavaCore/eGain_Java_Material_Examples/MisccJAVA_(3)/src/ThreadGroupManager.java
|
110f360960119b74f9b683f5a45cceae68c3ac6b
|
[] |
no_license
|
akkhil2012/DsAndAlgo
|
https://github.com/akkhil2012/DsAndAlgo
|
2788d8b0068579452a64b52562636b5999ea4117
|
e3d0fb625d1c06c1c26e58d66dc007b17df71bed
|
refs/heads/master
| 2015-09-25T18:06:53.725000 | 2015-08-18T06:08:00 | 2015-08-18T06:08:00 | 40,953,772 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class ThreadGroupManager {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("My thread group");
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
Thread th1 = new Thread(group, t1);
Thread th2 = new Thread(group, t2);
th1.start();
th2.start();
}
}
class Thread1 implements Runnable {
public void run() {
System.out.println("Inside run of Thread 1");
}
}
class Thread2 implements Runnable {
public void run() {
System.out.println("Inside run of Thread 2");
}
}
|
UTF-8
|
Java
| 608 |
java
|
ThreadGroupManager.java
|
Java
|
[] | null |
[] |
public class ThreadGroupManager {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("My thread group");
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
Thread th1 = new Thread(group, t1);
Thread th2 = new Thread(group, t2);
th1.start();
th2.start();
}
}
class Thread1 implements Runnable {
public void run() {
System.out.println("Inside run of Thread 1");
}
}
class Thread2 implements Runnable {
public void run() {
System.out.println("Inside run of Thread 2");
}
}
| 608 | 0.592105 | 0.565789 | 27 | 21.555555 | 19.820179 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false |
0
|
5066bf0722be085df8fec87381346ca6de575939
| 19,189,913,904,922 |
d276feb190a6b3ce6ad8e7d00df212513f473ef2
|
/sspp01/src/test/java/com/starterkit/controller/TwilioControllerTest.java
|
9519f515b66866df2d33e369fd467be68d192778
|
[] |
no_license
|
SanthoshkumarAR/testpublic-repository
|
https://github.com/SanthoshkumarAR/testpublic-repository
|
a1f82b302df17cbe475de990d0ed4720f067d597
|
4528fc08724b04f30e2ffd5c95deca803a80709f
|
refs/heads/master
| 2020-05-29T14:37:02.496000 | 2017-04-03T03:58:29 | 2017-04-03T03:58:29 | 60,689,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.starterkit.controller;
/**
*
*/
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.starterkit.Application;
import com.starterkit.controller.TwilioController;
import com.starterkit.service.TwilioService;
/**
* @author narendra.gurram@cognizant.com
*
*/
@SpringApplicationConfiguration(classes = Application.class)
public class TwilioControllerTest {
private MockMvc mockMvc;
@InjectMocks
private TwilioService twilioService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(new TwilioController()).build();
}
@Test
public void twilioController() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/api/sms"));
}
}
|
UTF-8
|
Java
| 1,120 |
java
|
TwilioControllerTest.java
|
Java
|
[
{
"context": "arterkit.service.TwilioService;\r\n\r\n/**\r\n * @author narendra.gurram@cognizant.com\r\n *\r\n */\r\n@SpringApplicationConfiguration(classes",
"end": 628,
"score": 0.9908295273780823,
"start": 599,
"tag": "EMAIL",
"value": "narendra.gurram@cognizant.com"
}
] | null |
[] |
package com.starterkit.controller;
/**
*
*/
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.starterkit.Application;
import com.starterkit.controller.TwilioController;
import com.starterkit.service.TwilioService;
/**
* @author <EMAIL>
*
*/
@SpringApplicationConfiguration(classes = Application.class)
public class TwilioControllerTest {
private MockMvc mockMvc;
@InjectMocks
private TwilioService twilioService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(new TwilioController()).build();
}
@Test
public void twilioController() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/api/sms"));
}
}
| 1,098 | 0.775 | 0.775 | 41 | 25.317074 | 24.692686 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.780488 | false | false |
0
|
68640227e728ef435010e7188e619600632221ea
| 22,608,707,860,471 |
57ebfc8e1fa89366f5bcb8d56a0aded110f15f7b
|
/auth-service/auth-service-api/src/main/java/com/jiejie/mall/auth/request/AuthRequest.java
|
7100fd78261f6b69f5ebf41eaae2f75197ef7838
|
[] |
no_license
|
linyelai/jiejie-mall
|
https://github.com/linyelai/jiejie-mall
|
aa2dd6f9c4d560bcbf53bac0fe5f2d2eebc89939
|
e1bbd5e5edefbc0154bfb63f2914df5551b9a329
|
refs/heads/master
| 2022-12-21T06:23:04.622000 | 2020-08-22T14:08:40 | 2020-08-22T14:08:40 | 212,304,140 | 0 | 1 | null | false | 2022-12-16T04:47:20 | 2019-10-02T09:47:24 | 2020-08-22T14:09:20 | 2022-12-16T04:47:16 | 396 | 0 | 1 | 42 |
Java
| false | false |
package com.jiejie.mall.auth.request;
import lombok.Data;
@Data
public class AuthRequest {
private Integer id;
private String name;//权限名称
private Integer platform;//平台
}
|
UTF-8
|
Java
| 196 |
java
|
AuthRequest.java
|
Java
|
[] | null |
[] |
package com.jiejie.mall.auth.request;
import lombok.Data;
@Data
public class AuthRequest {
private Integer id;
private String name;//权限名称
private Integer platform;//平台
}
| 196 | 0.728261 | 0.728261 | 10 | 17.4 | 13.865064 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
b96272dfb97fc03f31046b22e7a0c523b812639f
| 22,608,707,861,992 |
fdd84f72b9fa697f55f2b33c631da16d2a860b8e
|
/iveely.brain/src/com/iveely/brain/index/Inverted.java
|
556c1bff6328a4e0332cabb94f136a196146e588
|
[] |
no_license
|
gaoyanfeng2016/iveely.search
|
https://github.com/gaoyanfeng2016/iveely.search
|
5cd496768af1a610861a37e6c26ea70e665e1269
|
ce589fb3d1c5caecd3d8a5875cc7a60fbf74942e
|
refs/heads/master
| 2023-08-17T08:48:32.055000 | 2019-08-02T10:11:06 | 2019-08-02T10:11:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* date : 2016年1月30日 author : Iveely Liu contact: sea11510@mail.ustc.edu.cn
*/
package com.iveely.brain.index;
import com.iveely.framework.text.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author {Iveely Liu}
*/
public class Inverted {
/**
* Single instance.
*/
private static Inverted inverted;
/**
* Inverted index memory.
*/
private static HashMap<Integer, HashMap<Integer, Double>> list;
private Inverted() {
list = new HashMap<>();
}
/**
* Get instance of inverted index.
* @return instance
*/
public static Inverted getInstance() {
if (inverted == null) {
synchronized (Inverted.class) {
if (inverted == null) {
inverted = new Inverted();
}
}
}
return inverted;
}
/**
* Add words to index.
* @param docId doc id
* @param text The words to index.
*/
public void set(int docId, String text) {
if (text == null) {
return;
}
String[] words = StringUtil.split(text);
int size = words.length;
if (size > 0) {
double rank = 1 % size;
for (String word : words) {
int code = word.hashCode();
if (Inverted.list.containsKey(code)) {
if (Inverted.list.get(code).containsKey(docId)) {
double oval = Inverted.list.get(code).get(docId) + rank;
Inverted.list.get(code).put(docId, oval);
} else {
Inverted.list.get(code).put(docId, rank);
}
} else {
HashMap<Integer, Double> map = new HashMap<>();
map.put(docId, rank);
Inverted.list.put(code, map);
}
}
}
}
/**
* Get best doc id by words.
* @param text text
* @return document ids
*/
public List<Integer> get(String text) {
if (text == null) {
return null;
}
String[] words = StringUtil.split(text);
if (words.length > 0) {
// 1. Check all.
Map<Integer, Double> ret = new HashMap<>();
for (String word : words) {
int code = word.hashCode();
if (Inverted.list.containsKey(code)) {
Map<Integer, Double> map = Inverted.list.get(code);
Iterator<Map.Entry<Integer, Double>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Double> entry = entries.next();
Integer key = entry.getKey();
Double value = entry.getValue();
if (ret.containsKey(key)) {
value += map.get(key);
}
ret.put(key, value);
}
}
}
// 2. Find best ones which value = 1.
List<Integer> collections = new ArrayList<>();
Iterator<Map.Entry<Integer, Double>> ultimate = ret.entrySet().iterator();
while (ultimate.hasNext()) {
Map.Entry<Integer, Double> entry = ultimate.next();
if (entry.getValue() > 0.9999) {
collections.add(entry.getKey());
}
}
return collections;
}
return null;
}
}
|
UTF-8
|
Java
| 3,123 |
java
|
Inverted.java
|
Java
|
[
{
"context": "/**\n * date : 2016年1月30日 author : Iveely Liu contact: sea11510@mail.ustc.edu.cn\n */\npackage co",
"end": 46,
"score": 0.999901294708252,
"start": 36,
"tag": "NAME",
"value": "Iveely Liu"
},
{
"context": "* date : 2016年1月30日 author : Iveely Liu contact: sea11510@mail.ustc.edu.cn\n */\npackage com.iveely.brain.index;\n\nimport com.i",
"end": 81,
"score": 0.9999312162399292,
"start": 56,
"tag": "EMAIL",
"value": "sea11510@mail.ustc.edu.cn"
},
{
"context": "util.List;\nimport java.util.Map;\n\n/**\n * @author {Iveely Liu}\n */\npublic class Inverted {\n\n /**\n * Single i",
"end": 318,
"score": 0.9998921155929565,
"start": 308,
"tag": "NAME",
"value": "Iveely Liu"
}
] | null |
[] |
/**
* date : 2016年1月30日 author : <NAME> contact: <EMAIL>
*/
package com.iveely.brain.index;
import com.iveely.framework.text.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author {<NAME>}
*/
public class Inverted {
/**
* Single instance.
*/
private static Inverted inverted;
/**
* Inverted index memory.
*/
private static HashMap<Integer, HashMap<Integer, Double>> list;
private Inverted() {
list = new HashMap<>();
}
/**
* Get instance of inverted index.
* @return instance
*/
public static Inverted getInstance() {
if (inverted == null) {
synchronized (Inverted.class) {
if (inverted == null) {
inverted = new Inverted();
}
}
}
return inverted;
}
/**
* Add words to index.
* @param docId doc id
* @param text The words to index.
*/
public void set(int docId, String text) {
if (text == null) {
return;
}
String[] words = StringUtil.split(text);
int size = words.length;
if (size > 0) {
double rank = 1 % size;
for (String word : words) {
int code = word.hashCode();
if (Inverted.list.containsKey(code)) {
if (Inverted.list.get(code).containsKey(docId)) {
double oval = Inverted.list.get(code).get(docId) + rank;
Inverted.list.get(code).put(docId, oval);
} else {
Inverted.list.get(code).put(docId, rank);
}
} else {
HashMap<Integer, Double> map = new HashMap<>();
map.put(docId, rank);
Inverted.list.put(code, map);
}
}
}
}
/**
* Get best doc id by words.
* @param text text
* @return document ids
*/
public List<Integer> get(String text) {
if (text == null) {
return null;
}
String[] words = StringUtil.split(text);
if (words.length > 0) {
// 1. Check all.
Map<Integer, Double> ret = new HashMap<>();
for (String word : words) {
int code = word.hashCode();
if (Inverted.list.containsKey(code)) {
Map<Integer, Double> map = Inverted.list.get(code);
Iterator<Map.Entry<Integer, Double>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Double> entry = entries.next();
Integer key = entry.getKey();
Double value = entry.getValue();
if (ret.containsKey(key)) {
value += map.get(key);
}
ret.put(key, value);
}
}
}
// 2. Find best ones which value = 1.
List<Integer> collections = new ArrayList<>();
Iterator<Map.Entry<Integer, Double>> ultimate = ret.entrySet().iterator();
while (ultimate.hasNext()) {
Map.Entry<Integer, Double> entry = ultimate.next();
if (entry.getValue() > 0.9999) {
collections.add(entry.getKey());
}
}
return collections;
}
return null;
}
}
| 3,097 | 0.558871 | 0.551492 | 123 | 24.341463 | 19.804256 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447154 | false | false |
0
|
0b6c835b9478d96a1ff6ccef5955615e752bdb56
| 28,638,841,996,490 |
180f4155105680e17fd3551512640a5994be6df5
|
/7ADMVENTASREMOTASSISTEMA/src/com/sevensoft/admvrs/encapsulacion/EmpresasN.java
|
7458ca364faa19321be4ccb7a72bbaad2aae85e4
|
[] |
no_license
|
manuelisc17/VentasRemotas7Soft
|
https://github.com/manuelisc17/VentasRemotas7Soft
|
37943a87060cf0b60947fcc89ad2cbcccda3d186
|
5f9f3ce2f8dc01028a461cef16dc9740e599da06
|
refs/heads/master
| 2016-06-05T09:53:57.465000 | 2016-03-09T11:02:55 | 2016-03-09T11:02:55 | 47,875,515 | 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 com.sevensoft.admvrs.encapsulacion;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author 7soft
*/
@Entity
@Table(name = "empresas_n")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "EmpresasN.findAll", query = "SELECT e FROM EmpresasN e"),
@NamedQuery(name = "EmpresasN.findById", query = "SELECT e FROM EmpresasN e WHERE e.id = :id"),
@NamedQuery(name = "EmpresasN.findByEmpresa", query = "SELECT e FROM EmpresasN e WHERE e.empresa = :empresa"),
@NamedQuery(name = "EmpresasN.findByActiva", query = "SELECT e FROM EmpresasN e WHERE e.activa = :activa"),
@NamedQuery(name = "EmpresasN.findByContrasena", query = "SELECT e FROM EmpresasN e WHERE e.contrasena = :contrasena")})
public class EmpresasN implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "empresa")
private String empresa;
@Basic(optional = false)
@Column(name = "activa")
private boolean activa;
@Basic(optional = false)
@Column(name = "contrasena")
private String contrasena;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<ProductosN> productosNList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<ClientesN> clientesNList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<UsuariosN> usuariosNList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<VersionesN> versionesNList;
public EmpresasN() {
}
public EmpresasN(Integer id) {
this.id = id;
}
public EmpresasN(Integer id, String empresa, boolean activa, String contrasena) {
this.id = id;
this.empresa = empresa;
this.activa = activa;
this.contrasena = contrasena;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public boolean getActiva() {
return activa;
}
public void setActiva(boolean activa) {
this.activa = activa;
}
public String getContrasena() {
return contrasena;
}
public void setContrasena(String contrasena) {
this.contrasena = contrasena;
}
@XmlTransient
public List<ProductosN> getProductosNList() {
return productosNList;
}
public void setProductosNList(List<ProductosN> productosNList) {
this.productosNList = productosNList;
}
@XmlTransient
public List<ClientesN> getClientesNList() {
return clientesNList;
}
public void setClientesNList(List<ClientesN> clientesNList) {
this.clientesNList = clientesNList;
}
@XmlTransient
public List<UsuariosN> getUsuariosNList() {
return usuariosNList;
}
public void setUsuariosNList(List<UsuariosN> usuariosNList) {
this.usuariosNList = usuariosNList;
}
@XmlTransient
public List<VersionesN> getVersionesNList() {
return versionesNList;
}
public void setVersionesNList(List<VersionesN> versionesNList) {
this.versionesNList = versionesNList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof EmpresasN)) {
return false;
}
EmpresasN other = (EmpresasN) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.sevensoft.admvrs.encapsulacion.EmpresasN[ id=" + id + " ]";
}
}
|
UTF-8
|
Java
| 4,849 |
java
|
EmpresasN.java
|
Java
|
[
{
"context": "l.bind.annotation.XmlTransient;\n\n/**\n *\n * @author 7soft\n */\n@Entity\n@Table(name = \"empresas_n\")\n@Xml",
"end": 787,
"score": 0.8098800778388977,
"start": 787,
"tag": "USERNAME",
"value": ""
},
{
"context": ".bind.annotation.XmlTransient;\n\n/**\n *\n * @author 7soft\n */\n@Entity\n@Table(name = \"empresas_n\")\n@XmlRootE",
"end": 793,
"score": 0.9668043255805969,
"start": 788,
"tag": "USERNAME",
"value": "7soft"
}
] | 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.sevensoft.admvrs.encapsulacion;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author 7soft
*/
@Entity
@Table(name = "empresas_n")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "EmpresasN.findAll", query = "SELECT e FROM EmpresasN e"),
@NamedQuery(name = "EmpresasN.findById", query = "SELECT e FROM EmpresasN e WHERE e.id = :id"),
@NamedQuery(name = "EmpresasN.findByEmpresa", query = "SELECT e FROM EmpresasN e WHERE e.empresa = :empresa"),
@NamedQuery(name = "EmpresasN.findByActiva", query = "SELECT e FROM EmpresasN e WHERE e.activa = :activa"),
@NamedQuery(name = "EmpresasN.findByContrasena", query = "SELECT e FROM EmpresasN e WHERE e.contrasena = :contrasena")})
public class EmpresasN implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "empresa")
private String empresa;
@Basic(optional = false)
@Column(name = "activa")
private boolean activa;
@Basic(optional = false)
@Column(name = "contrasena")
private String contrasena;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<ProductosN> productosNList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<ClientesN> clientesNList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<UsuariosN> usuariosNList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "empresa")
private List<VersionesN> versionesNList;
public EmpresasN() {
}
public EmpresasN(Integer id) {
this.id = id;
}
public EmpresasN(Integer id, String empresa, boolean activa, String contrasena) {
this.id = id;
this.empresa = empresa;
this.activa = activa;
this.contrasena = contrasena;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public boolean getActiva() {
return activa;
}
public void setActiva(boolean activa) {
this.activa = activa;
}
public String getContrasena() {
return contrasena;
}
public void setContrasena(String contrasena) {
this.contrasena = contrasena;
}
@XmlTransient
public List<ProductosN> getProductosNList() {
return productosNList;
}
public void setProductosNList(List<ProductosN> productosNList) {
this.productosNList = productosNList;
}
@XmlTransient
public List<ClientesN> getClientesNList() {
return clientesNList;
}
public void setClientesNList(List<ClientesN> clientesNList) {
this.clientesNList = clientesNList;
}
@XmlTransient
public List<UsuariosN> getUsuariosNList() {
return usuariosNList;
}
public void setUsuariosNList(List<UsuariosN> usuariosNList) {
this.usuariosNList = usuariosNList;
}
@XmlTransient
public List<VersionesN> getVersionesNList() {
return versionesNList;
}
public void setVersionesNList(List<VersionesN> versionesNList) {
this.versionesNList = versionesNList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof EmpresasN)) {
return false;
}
EmpresasN other = (EmpresasN) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.sevensoft.admvrs.encapsulacion.EmpresasN[ id=" + id + " ]";
}
}
| 4,849 | 0.665498 | 0.664673 | 170 | 27.523529 | 25.382301 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.441176 | false | false |
0
|
09bf8273f7a7e00621c816090187db073d87e99f
| 2,156,073,616,479 |
88a21329858dd94f81c7b8479e517db75335c595
|
/src/main/java/fr/ensimag/deca/codegen/VirtualStaticRegisterOffset.java
|
3f5d38c34939944c34f32b41ab3e005b88d19cd5
|
[] |
no_license
|
ChristopheEhret/SE_Project
|
https://github.com/ChristopheEhret/SE_Project
|
4add274f01b6a4e2ed58f529879d24ae83ca3e3d
|
c7307b5b74e6fa98c399b1472bb2dbdc9e3a9782
|
refs/heads/main
| 2023-08-11T18:35:29.234000 | 2021-09-21T02:40:58 | 2021-09-21T02:40:58 | 408,665,555 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fr.ensimag.deca.codegen;
import fr.ensimag.deca.DecacCompiler;
import fr.ensimag.pseudocode.DAddr;
import fr.ensimag.pseudocode.DVal;
import fr.ensimag.pseudocode.Register;
import fr.ensimag.pseudocode.gba.GRegisterOffset;
import fr.ensimag.pseudocode.gba.instructions.GLDR;
import fr.ensimag.pseudocode.ima.RegisterOffset;
import fr.ensimag.pseudocode.ima.instructions.LOAD;
public class VirtualStaticRegisterOffset extends VirtualDAddr{
private final Register register;
private final int offset;
public VirtualStaticRegisterOffset(RegistersHandler handler, Register register, int offset) {
super(handler);
this.register = register;
this.offset = offset;
}
@Override
public DAddr getDAddr(DecacCompiler compiler, boolean canBeR0) {
if(compiler.getCompilerOptions().isForGBA())
return new GRegisterOffset(register, offset);
else
return new RegisterOffset(offset, register);
}
@Override
public DVal getDVal(DecacCompiler compiler, boolean canBeR0) {
return this.getDAddr(compiler, canBeR0);
}
@Override
public VirtualRegister getVRegister(DecacCompiler compiler) {
VirtualRegister vRegister = handler.getNewRegister(compiler);
if(compiler.getCompilerOptions().isForGBA())
compiler.addInstruction(new GLDR(vRegister.getRegister(compiler, false), this.getDAddr(compiler, true)));
else
compiler.addInstruction(new LOAD(this.getDAddr(compiler, true), vRegister.getRegister(compiler, false)));
return vRegister;
}
}
|
UTF-8
|
Java
| 1,602 |
java
|
VirtualStaticRegisterOffset.java
|
Java
|
[] | null |
[] |
package fr.ensimag.deca.codegen;
import fr.ensimag.deca.DecacCompiler;
import fr.ensimag.pseudocode.DAddr;
import fr.ensimag.pseudocode.DVal;
import fr.ensimag.pseudocode.Register;
import fr.ensimag.pseudocode.gba.GRegisterOffset;
import fr.ensimag.pseudocode.gba.instructions.GLDR;
import fr.ensimag.pseudocode.ima.RegisterOffset;
import fr.ensimag.pseudocode.ima.instructions.LOAD;
public class VirtualStaticRegisterOffset extends VirtualDAddr{
private final Register register;
private final int offset;
public VirtualStaticRegisterOffset(RegistersHandler handler, Register register, int offset) {
super(handler);
this.register = register;
this.offset = offset;
}
@Override
public DAddr getDAddr(DecacCompiler compiler, boolean canBeR0) {
if(compiler.getCompilerOptions().isForGBA())
return new GRegisterOffset(register, offset);
else
return new RegisterOffset(offset, register);
}
@Override
public DVal getDVal(DecacCompiler compiler, boolean canBeR0) {
return this.getDAddr(compiler, canBeR0);
}
@Override
public VirtualRegister getVRegister(DecacCompiler compiler) {
VirtualRegister vRegister = handler.getNewRegister(compiler);
if(compiler.getCompilerOptions().isForGBA())
compiler.addInstruction(new GLDR(vRegister.getRegister(compiler, false), this.getDAddr(compiler, true)));
else
compiler.addInstruction(new LOAD(this.getDAddr(compiler, true), vRegister.getRegister(compiler, false)));
return vRegister;
}
}
| 1,602 | 0.730961 | 0.729089 | 46 | 33.826088 | 29.270332 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.913043 | false | false |
0
|
bd9239032f41d446873e99a19dbed225a8359ec3
| 32,684,701,167,778 |
36ecf4dd4d99467e25aff43cc3acb29c1777613e
|
/ProyectoBAD/src/java/beans/DocenteController.java
|
3aaa4703328e75b6d46256f1d869b635d1576b14
|
[] |
no_license
|
manu23/ProyectoBAD
|
https://github.com/manu23/ProyectoBAD
|
2abdf555cb4076cbf5e47cad19b5872732f64d26
|
bf2e1056cc0f9fbad905820ed9a5a4bed3b16385
|
refs/heads/master
| 2020-05-18T10:28:06.489000 | 2013-07-01T02:39:10 | 2013-07-01T02:39:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package beans;
import beans.util.Auxiliares;
import entidades.Docente;
import controladores.DocenteFacade;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
@ManagedBean(name = "docenteController")
@ViewScoped
public class DocenteController extends AbstractController<Docente> implements Serializable {
private int contadorID=0;
@EJB
private DocenteFacade ejbFacade;
public DocenteController() {
super(Docente.class);
}
@PostConstruct
public void init() {
super.setFacade(ejbFacade);
}
//Funcion mejorada para crear un docente
public void CrearNew(ActionEvent e) {
String id = "DOC";
super.getSelected().setCargo("Docente");
boolean salir = false;
int cont = 0;
List<Docente> R = null;
while(!salir){
super.getSelected().setIddocente(id + cont);
R = ejbFacade.existeDocente(super.getSelected().getIddocente());
if(R.isEmpty()){
salir = true;
}else{
salir = false;
R.clear();
cont++;
}
}//FIN WHILE
super.saveNew(e);
}
}
|
UTF-8
|
Java
| 1,357 |
java
|
DocenteController.java
|
Java
|
[] | null |
[] |
package beans;
import beans.util.Auxiliares;
import entidades.Docente;
import controladores.DocenteFacade;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
@ManagedBean(name = "docenteController")
@ViewScoped
public class DocenteController extends AbstractController<Docente> implements Serializable {
private int contadorID=0;
@EJB
private DocenteFacade ejbFacade;
public DocenteController() {
super(Docente.class);
}
@PostConstruct
public void init() {
super.setFacade(ejbFacade);
}
//Funcion mejorada para crear un docente
public void CrearNew(ActionEvent e) {
String id = "DOC";
super.getSelected().setCargo("Docente");
boolean salir = false;
int cont = 0;
List<Docente> R = null;
while(!salir){
super.getSelected().setIddocente(id + cont);
R = ejbFacade.existeDocente(super.getSelected().getIddocente());
if(R.isEmpty()){
salir = true;
}else{
salir = false;
R.clear();
cont++;
}
}//FIN WHILE
super.saveNew(e);
}
}
| 1,357 | 0.625645 | 0.624171 | 52 | 25.096153 | 18.190508 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.519231 | false | false |
0
|
063abca5002d91ed5105a93ea3688bd44fc132f7
| 21,122,649,176,893 |
f141a3902ae8a470b13346a7b59f1ca7ba092dfe
|
/Lab 8/MyFirstHbaseTable.java
|
718338c4e879dcbd62c6e540cbfc512d38f9e6cb
|
[] |
no_license
|
NghiepNguyenQuoc/BigDataTechnology
|
https://github.com/NghiepNguyenQuoc/BigDataTechnology
|
850458f6581b2d8c7be5592f9b6970d871c39d1c
|
8beec92e4d6a7618097b754f4403edaaffc13696
|
refs/heads/master
| 2020-03-14T12:25:12.440000 | 2018-05-26T15:27:20 | 2018-05-26T15:27:24 | 131,611,371 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
import org.apache.hadoop.hbase.util.Bytes;
public class MyFirstHbaseTable {
private static final String TABLE_NAME = "user";
private static final String CF_PERSONAL_DETAIL = "Personal Details";
private static final String CF_PROFESSIONAL_DETAIL = "Professional Details";
private static final String CELL_NAME = "Name";
private static final String CELL_CITY = "City";
private static final String CELL_DESIGNATION = "Designation";
private static final String CELL_SALARY = "Salary";
public static void main(String... args) throws IOException {
Configuration config = HBaseConfiguration.create();
initTable(config);
insertData(config, "1", "John", "Boston", "Manager", "150000");
insertData(config, "2", "Mary", "New York", "Sr. Engineer",
"130000");
insertData(config, "3", "Bob", "Fremont", "Jr. Engineer", "90000");
// update John's salary to 160000
udpateSalary(config, "1", "160000");
getNumberOfRow(config);
}
public static void initTable(Configuration config) throws IOException {
try (Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin()) {
HTableDescriptor table = new HTableDescriptor(
TableName.valueOf(TABLE_NAME));
table.addFamily(new HColumnDescriptor(CF_PERSONAL_DETAIL)
.setCompressionType(Algorithm.NONE));
table.addFamily(new HColumnDescriptor(CF_PROFESSIONAL_DETAIL));
System.out.print("Creating table.... ");
if (admin.tableExists(table.getTableName())) {
admin.disableTable(table.getTableName());
admin.deleteTable(table.getTableName());
}
admin.createTable(table);
System.out.println(" Done!");
}
}
@SuppressWarnings("deprecation")
public static void insertData(Configuration config, String rowid,
String name, String city, String designation, String salary)
throws IOException {
// Instantiating HTable class
HTable hTable = new HTable(config, TABLE_NAME);
// Instantiating Put class
// accepts a row name.
Put p = new Put(Bytes.toBytes(rowid));
// adding values using add() method
// accepts column family name, qualifier/row name ,value
p.add(Bytes.toBytes(CF_PERSONAL_DETAIL), Bytes.toBytes(CELL_NAME),
Bytes.toBytes(name));
p.add(Bytes.toBytes(CF_PERSONAL_DETAIL), Bytes.toBytes(CELL_CITY),
Bytes.toBytes(city));
p.add(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_DESIGNATION), Bytes.toBytes(designation));
p.add(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_SALARY), Bytes.toBytes(salary));
// Saving the put Instance to the HTable.
hTable.put(p);
System.out.println(rowid + "data inserted");
// closing HTable
hTable.close();
}
@SuppressWarnings("deprecation")
public static void udpateSalary(Configuration config, String rowId,
String salary) throws IOException {
// Instantiating HTable class
HTable hTable = new HTable(config, TABLE_NAME);
// Instantiating Put class
// accepts a row name
Put p = new Put(Bytes.toBytes(rowId));
// Updating a cell value
p.add(Bytes.toBytes(CF_PROFESSIONAL_DETAIL), Bytes.toBytes(CELL_SALARY),
Bytes.toBytes(salary));
// Saving the put Instance to the HTable.
hTable.put(p);
System.out.println("data Updated");
// closing HTable
hTable.close();
}
@SuppressWarnings("resource")
public static void getNumberOfRow(Configuration config) throws IOException {
// Instantiating HTable class
HTable hTable = new HTable(config, TABLE_NAME);
// Instantiating the Scan class
Scan scan = new Scan();
// Scanning the required columns
scan.addColumn(Bytes.toBytes(CF_PERSONAL_DETAIL),
Bytes.toBytes(CELL_NAME));
scan.addColumn(Bytes.toBytes(CF_PERSONAL_DETAIL),
Bytes.toBytes(CELL_CITY));
scan.addColumn(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_DESIGNATION));
scan.addColumn(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_SALARY));
// Getting the scan result
ResultScanner scanner = hTable.getScanner(scan);
int numberOfRow = 0;
// Reading values from scan result
for (Result result = scanner.next(); result != null; result = scanner
.next()) {
numberOfRow++;
}
System.out.println("Number of row in " + TABLE_NAME + " table: "
+ numberOfRow);
// closing the scanner
scanner.close();
}
}
|
UTF-8
|
Java
| 5,022 |
java
|
MyFirstHbaseTable.java
|
Java
|
[
{
"context": "\t\t initTable(config);\n\t\t insertData(config, \"1\", \"John\", \"Boston\", \"Manager\", \"150000\");\n\t\t insertData(c",
"end": 1378,
"score": 0.999860942363739,
"start": 1374,
"tag": "NAME",
"value": "John"
},
{
"context": "able(config);\n\t\t insertData(config, \"1\", \"John\", \"Boston\", \"Manager\", \"150000\");\n\t\t insertData(config, \"2\"",
"end": 1388,
"score": 0.9933255910873413,
"start": 1382,
"tag": "NAME",
"value": "Boston"
},
{
"context": "\"Manager\", \"150000\");\n\t\t insertData(config, \"2\", \"Mary\", \"New York\", \"Sr. Engineer\",\n\t\t \"130000\");\n\t\t in",
"end": 1445,
"score": 0.9997713565826416,
"start": 1441,
"tag": "NAME",
"value": "Mary"
},
{
"context": "ineer\",\n\t\t \"130000\");\n\t\t insertData(config, \"3\", \"Bob\", \"Fremont\", \"Jr. Engineer\", \"90000\");\n\n\t\t// upda",
"end": 1521,
"score": 0.9998661279678345,
"start": 1518,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\n\t\t \"130000\");\n\t\t insertData(config, \"3\", \"Bob\", \"Fremont\", \"Jr. Engineer\", \"90000\");\n\n\t\t// update John's s",
"end": 1532,
"score": 0.9994702339172363,
"start": 1525,
"tag": "NAME",
"value": "Fremont"
}
] | null |
[] |
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
import org.apache.hadoop.hbase.util.Bytes;
public class MyFirstHbaseTable {
private static final String TABLE_NAME = "user";
private static final String CF_PERSONAL_DETAIL = "Personal Details";
private static final String CF_PROFESSIONAL_DETAIL = "Professional Details";
private static final String CELL_NAME = "Name";
private static final String CELL_CITY = "City";
private static final String CELL_DESIGNATION = "Designation";
private static final String CELL_SALARY = "Salary";
public static void main(String... args) throws IOException {
Configuration config = HBaseConfiguration.create();
initTable(config);
insertData(config, "1", "John", "Boston", "Manager", "150000");
insertData(config, "2", "Mary", "New York", "Sr. Engineer",
"130000");
insertData(config, "3", "Bob", "Fremont", "Jr. Engineer", "90000");
// update John's salary to 160000
udpateSalary(config, "1", "160000");
getNumberOfRow(config);
}
public static void initTable(Configuration config) throws IOException {
try (Connection connection = ConnectionFactory.createConnection(config);
Admin admin = connection.getAdmin()) {
HTableDescriptor table = new HTableDescriptor(
TableName.valueOf(TABLE_NAME));
table.addFamily(new HColumnDescriptor(CF_PERSONAL_DETAIL)
.setCompressionType(Algorithm.NONE));
table.addFamily(new HColumnDescriptor(CF_PROFESSIONAL_DETAIL));
System.out.print("Creating table.... ");
if (admin.tableExists(table.getTableName())) {
admin.disableTable(table.getTableName());
admin.deleteTable(table.getTableName());
}
admin.createTable(table);
System.out.println(" Done!");
}
}
@SuppressWarnings("deprecation")
public static void insertData(Configuration config, String rowid,
String name, String city, String designation, String salary)
throws IOException {
// Instantiating HTable class
HTable hTable = new HTable(config, TABLE_NAME);
// Instantiating Put class
// accepts a row name.
Put p = new Put(Bytes.toBytes(rowid));
// adding values using add() method
// accepts column family name, qualifier/row name ,value
p.add(Bytes.toBytes(CF_PERSONAL_DETAIL), Bytes.toBytes(CELL_NAME),
Bytes.toBytes(name));
p.add(Bytes.toBytes(CF_PERSONAL_DETAIL), Bytes.toBytes(CELL_CITY),
Bytes.toBytes(city));
p.add(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_DESIGNATION), Bytes.toBytes(designation));
p.add(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_SALARY), Bytes.toBytes(salary));
// Saving the put Instance to the HTable.
hTable.put(p);
System.out.println(rowid + "data inserted");
// closing HTable
hTable.close();
}
@SuppressWarnings("deprecation")
public static void udpateSalary(Configuration config, String rowId,
String salary) throws IOException {
// Instantiating HTable class
HTable hTable = new HTable(config, TABLE_NAME);
// Instantiating Put class
// accepts a row name
Put p = new Put(Bytes.toBytes(rowId));
// Updating a cell value
p.add(Bytes.toBytes(CF_PROFESSIONAL_DETAIL), Bytes.toBytes(CELL_SALARY),
Bytes.toBytes(salary));
// Saving the put Instance to the HTable.
hTable.put(p);
System.out.println("data Updated");
// closing HTable
hTable.close();
}
@SuppressWarnings("resource")
public static void getNumberOfRow(Configuration config) throws IOException {
// Instantiating HTable class
HTable hTable = new HTable(config, TABLE_NAME);
// Instantiating the Scan class
Scan scan = new Scan();
// Scanning the required columns
scan.addColumn(Bytes.toBytes(CF_PERSONAL_DETAIL),
Bytes.toBytes(CELL_NAME));
scan.addColumn(Bytes.toBytes(CF_PERSONAL_DETAIL),
Bytes.toBytes(CELL_CITY));
scan.addColumn(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_DESIGNATION));
scan.addColumn(Bytes.toBytes(CF_PROFESSIONAL_DETAIL),
Bytes.toBytes(CELL_SALARY));
// Getting the scan result
ResultScanner scanner = hTable.getScanner(scan);
int numberOfRow = 0;
// Reading values from scan result
for (Result result = scanner.next(); result != null; result = scanner
.next()) {
numberOfRow++;
}
System.out.println("Number of row in " + TABLE_NAME + " table: "
+ numberOfRow);
// closing the scanner
scanner.close();
}
}
| 5,022 | 0.734767 | 0.727997 | 151 | 32.258278 | 23.012943 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.291391 | false | false |
0
|
5368cec76e74d192ab8d7fef852dd4cf195a04b9
| 29,454,885,760,902 |
49885bca32532faac93cb461b0c6875cdd29516c
|
/Java/OOP/OOPLab3/TaskCInternetMailServer/MailServer.java
|
961869f992ebb281e57aa8d95a7c331ec7b7a8a3
|
[] |
no_license
|
charlottepierce/Scratchpad
|
https://github.com/charlottepierce/Scratchpad
|
746173412001af794995360db56d44c8ce8bad96
|
94a9d6d8dfbc30a558d559273777bce23c034e53
|
refs/heads/master
| 2016-09-08T19:20:08.988000 | 2016-08-24T12:36:16 | 2016-08-24T12:36:16 | 5,909,770 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
/**
* A simple model of a mail server. The server is able to receive
* mail items for storage, and deliver them to clients on demand.
* @author David J. Barnes and Michael Kolling
* @version 2008.03.30
*/
public class MailServer
{
// Storage for the arbitrary number of mail items to be stored
// on the server.
private List<MailItem> items;
//Name of server
private String name;
//Reference to internet
private Internet internet;
/**
* Construct a mail server.
*/
public MailServer(String name, Internet internet)
{
items = new ArrayList<MailItem>();
this.name = name;
this.internet = internet;
//'Add' server to the internet
internet.addServer(this);
}
/**
* Return how many mail items are waiting for a user.
* @param who The user to check for.
* @return How many items are waiting.
*/
public int howManyMailItems(String who)
{
int count = 0;
for(MailItem item : items) {
if(item.getTo().equals(who)) {
count++;
}
}
return count;
}
/**
* Return the next mail item for a user or null if there
* are none.
* @param who The user requesting their next item.
* @return The user's next item.
*/
public MailItem getNextMailItem(String who)
{
Iterator<MailItem> it = items.iterator();
while(it.hasNext()) {
MailItem item = it.next();
if(item.getTo().equals(who)) {
it.remove();
return item;
}
}
return null;
}
/**
* Add the given mail item to the message list.
* @param item The mail item to be stored on the server.
*/
public void post(MailItem item)
{
String temp;
temp = splitServer(item.getTo());
if(temp.equals(this.getName())){
items.add(item);
}
else{
internet.sendMail(item, temp);
}
}
public String getName()
{
return name;
}
//Splits an email to find its server
private String splitServer(String email)
{
String[] temp;
temp = email.split("@");
return temp[(temp.length - 1)];
}
}
|
UTF-8
|
Java
| 2,389 |
java
|
MailServer.java
|
Java
|
[
{
"context": " and deliver them to clients on demand.\n * @author David J. Barnes and Michael Kolling\n * @version 2008.03.30\n */\npu",
"end": 241,
"score": 0.9998825192451477,
"start": 226,
"tag": "NAME",
"value": "David J. Barnes"
},
{
"context": " clients on demand.\n * @author David J. Barnes and Michael Kolling\n * @version 2008.03.30\n */\npublic class MailServe",
"end": 261,
"score": 0.9998794198036194,
"start": 246,
"tag": "NAME",
"value": "Michael Kolling"
}
] | null |
[] |
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
/**
* A simple model of a mail server. The server is able to receive
* mail items for storage, and deliver them to clients on demand.
* @author <NAME> and <NAME>
* @version 2008.03.30
*/
public class MailServer
{
// Storage for the arbitrary number of mail items to be stored
// on the server.
private List<MailItem> items;
//Name of server
private String name;
//Reference to internet
private Internet internet;
/**
* Construct a mail server.
*/
public MailServer(String name, Internet internet)
{
items = new ArrayList<MailItem>();
this.name = name;
this.internet = internet;
//'Add' server to the internet
internet.addServer(this);
}
/**
* Return how many mail items are waiting for a user.
* @param who The user to check for.
* @return How many items are waiting.
*/
public int howManyMailItems(String who)
{
int count = 0;
for(MailItem item : items) {
if(item.getTo().equals(who)) {
count++;
}
}
return count;
}
/**
* Return the next mail item for a user or null if there
* are none.
* @param who The user requesting their next item.
* @return The user's next item.
*/
public MailItem getNextMailItem(String who)
{
Iterator<MailItem> it = items.iterator();
while(it.hasNext()) {
MailItem item = it.next();
if(item.getTo().equals(who)) {
it.remove();
return item;
}
}
return null;
}
/**
* Add the given mail item to the message list.
* @param item The mail item to be stored on the server.
*/
public void post(MailItem item)
{
String temp;
temp = splitServer(item.getTo());
if(temp.equals(this.getName())){
items.add(item);
}
else{
internet.sendMail(item, temp);
}
}
public String getName()
{
return name;
}
//Splits an email to find its server
private String splitServer(String email)
{
String[] temp;
temp = email.split("@");
return temp[(temp.length - 1)];
}
}
| 2,371 | 0.55923 | 0.555044 | 96 | 23.895834 | 18.132889 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.302083 | false | false |
0
|
757f82f92f47b7de521b54bc55359c89ad854528
| 35,175,782,178,173 |
0b88b9b7b8202fae9ac0c1447e2971355f9bf31d
|
/book-shop-manager/book-manager-mapper/src/main/java/com/team/dao/BookTypeMapper.java
|
7032a32e974a003b53d8270f37e49e7a1cd4a3e7
|
[] |
no_license
|
389091912/book-shop-parent
|
https://github.com/389091912/book-shop-parent
|
69530c2d267d9746433366217b628668b9d5fe82
|
cf7eae4f3294b431ed4335a07cbffd2bd4254249
|
refs/heads/master
| 2020-03-25T01:15:19.129000 | 2018-08-02T01:39:41 | 2018-08-02T01:39:41 | 143,227,068 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.team.dao;
import com.team.pojo.BookType;
import tk.mybatis.mapper.common.Mapper;
public interface BookTypeMapper extends Mapper<BookType> {
}
|
UTF-8
|
Java
| 156 |
java
|
BookTypeMapper.java
|
Java
|
[] | null |
[] |
package com.team.dao;
import com.team.pojo.BookType;
import tk.mybatis.mapper.common.Mapper;
public interface BookTypeMapper extends Mapper<BookType> {
}
| 156 | 0.801282 | 0.801282 | 8 | 18.625 | 20.772202 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
0
|
093b62f25673ce8c7da7f121981abb3e373922e2
| 34,488,587,410,983 |
6412a3ed2680e32df63d64f6e035b49705ac7896
|
/src/com/foodget/store/blog/model/BlogRankInfoDto.java
|
6e88754383981f2727f04822bb2b094b088b4002
|
[] |
no_license
|
tmqeh/foodget
|
https://github.com/tmqeh/foodget
|
f5420412e0d89ed75a387bacedb287e374256f08
|
ae338f9c2db7179b4ef036cb0b76a1dd5a055da7
|
refs/heads/master
| 2021-01-17T21:07:16.900000 | 2016-07-22T07:34:50 | 2016-07-22T07:34:50 | 62,538,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.foodget.store.blog.model;
import java.util.List;
public class BlogRankInfoDto extends BlogDto{
private String blog_writer_id;
private int comment_count;
private int body_lenth;
private int image_count;
BlogImgInfoDto blogImgInfoDto;
public String getBlog_writer_id() {
return blog_writer_id;
}
@Override
public String toString() {
return "BlogRankInfoDto [blog_writer_id=" + blog_writer_id + ", comment_count=" + comment_count
+ ", body_lenth=" + body_lenth + ", image_count=" + image_count + ", blogImgInfoDto=" + blogImgInfoDto
+ "]";
}
public void setBlog_writer_id(String blog_writer_id) {
this.blog_writer_id = blog_writer_id;
}
public int getComment_count() {
return comment_count;
}
public void setComment_count(int comment_count) {
this.comment_count = comment_count;
}
public int getBody_lenth() {
return body_lenth;
}
public void setBody_lenth(int body_lenth) {
this.body_lenth = body_lenth;
}
public int getImage_count() {
return image_count;
}
public void setImage_count(int image_count) {
this.image_count = image_count;
}
public BlogImgInfoDto getBlogImgInfoDto() {
return blogImgInfoDto;
}
public void setBlogImgInfoDto(BlogImgInfoDto blogImgInfoDto) {
this.blogImgInfoDto = blogImgInfoDto;
}
}
|
UTF-8
|
Java
| 1,291 |
java
|
BlogRankInfoDto.java
|
Java
|
[] | null |
[] |
package com.foodget.store.blog.model;
import java.util.List;
public class BlogRankInfoDto extends BlogDto{
private String blog_writer_id;
private int comment_count;
private int body_lenth;
private int image_count;
BlogImgInfoDto blogImgInfoDto;
public String getBlog_writer_id() {
return blog_writer_id;
}
@Override
public String toString() {
return "BlogRankInfoDto [blog_writer_id=" + blog_writer_id + ", comment_count=" + comment_count
+ ", body_lenth=" + body_lenth + ", image_count=" + image_count + ", blogImgInfoDto=" + blogImgInfoDto
+ "]";
}
public void setBlog_writer_id(String blog_writer_id) {
this.blog_writer_id = blog_writer_id;
}
public int getComment_count() {
return comment_count;
}
public void setComment_count(int comment_count) {
this.comment_count = comment_count;
}
public int getBody_lenth() {
return body_lenth;
}
public void setBody_lenth(int body_lenth) {
this.body_lenth = body_lenth;
}
public int getImage_count() {
return image_count;
}
public void setImage_count(int image_count) {
this.image_count = image_count;
}
public BlogImgInfoDto getBlogImgInfoDto() {
return blogImgInfoDto;
}
public void setBlogImgInfoDto(BlogImgInfoDto blogImgInfoDto) {
this.blogImgInfoDto = blogImgInfoDto;
}
}
| 1,291 | 0.717273 | 0.717273 | 52 | 23.826923 | 23.352419 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false |
0
|
d60a4ce926b89f3632e62d4a0a87a274c05fecee
| 35,974,646,092,643 |
0727c56b55f1eb60510019fbedc2603d329660da
|
/src/org/ucnj/paccess/News.java
|
251fe194e9c56c2e4463b5de74112addd6d9fa75
|
[] |
no_license
|
drshiller/UCPA
|
https://github.com/drshiller/UCPA
|
4d819f4dbc57fa718b0f724135937e1dbdc1361f
|
ac9351f2010c18a4365e9afcec44006e8f271701
|
refs/heads/main
| 2023-06-03T00:45:37.159000 | 2021-06-27T20:18:48 | 2021-06-27T20:18:48 | 380,830,547 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.ucnj.paccess;
import java.io.Serializable;
import java.util.List;
public class News implements Serializable {
private static final long serialVersionUID = 1L;
private List<NewsItem> news;
public List<NewsItem> getNews() {
return news;
}
public void setNews(List<NewsItem> news) {
this.news = news;
}
}
|
UTF-8
|
Java
| 350 |
java
|
News.java
|
Java
|
[] | null |
[] |
package org.ucnj.paccess;
import java.io.Serializable;
import java.util.List;
public class News implements Serializable {
private static final long serialVersionUID = 1L;
private List<NewsItem> news;
public List<NewsItem> getNews() {
return news;
}
public void setNews(List<NewsItem> news) {
this.news = news;
}
}
| 350 | 0.694286 | 0.691429 | 19 | 16.421053 | 16.909405 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.947368 | false | false |
0
|
595e97718df1c92d30b086da3ce2e8d82dc7b3b7
| 8,409,546,007,622 |
a95fbe4532cd3eb84f63906167f3557eda0e1fa3
|
/src/main/java/l2f/gameserver/model/items/ItemInstance.java
|
e29f5dc17bc14771f589bf638c36a6ff86c64988
|
[
"MIT"
] |
permissive
|
Kryspo/L2jRamsheart
|
https://github.com/Kryspo/L2jRamsheart
|
a20395f7d1f0f3909ae2c30ff181c47302d3b906
|
98c39d754f5aba1806f92acc9e8e63b3b827be49
|
refs/heads/master
| 2021-04-12T10:34:51.419000 | 2018-03-26T22:41:39 | 2018-03-26T22:41:39 | 126,892,421 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package l2f.gameserver.model.items;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import org.napile.primitive.Containers;
import org.napile.primitive.sets.IntSet;
import org.napile.primitive.sets.impl.HashIntSet;
import l2f.commons.configuration.Config;
import l2f.commons.dao.JdbcEntity;
import l2f.commons.dao.JdbcEntityState;
import l2f.gameserver.ai.CtrlIntention;
import l2f.gameserver.dao.ItemsDAO;
import l2f.gameserver.data.xml.holder.ItemHolder;
import l2f.gameserver.geodata.GeoEngine;
import l2f.gameserver.instancemanager.CursedWeaponsManager;
import l2f.gameserver.instancemanager.ReflectionManager;
import l2f.gameserver.model.Creature;
import l2f.gameserver.model.GameObject;
import l2f.gameserver.model.GameObjectsStorage;
import l2f.gameserver.model.Playable;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.base.Element;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.model.items.attachment.FlagItemAttachment;
import l2f.gameserver.model.items.attachment.ItemAttachment;
import l2f.gameserver.model.items.listeners.ItemEnchantOptionsListener;
import l2f.gameserver.network.serverpackets.DropItem;
import l2f.gameserver.network.serverpackets.L2GameServerPacket;
import l2f.gameserver.network.serverpackets.SpawnItem;
import l2f.gameserver.scripts.Events;
import l2f.gameserver.stats.Env;
import l2f.gameserver.stats.Stats;
import l2f.gameserver.stats.funcs.Func;
import l2f.gameserver.stats.funcs.FuncTemplate;
import l2f.gameserver.tables.PetDataTable;
import l2f.gameserver.taskmanager.ItemsAutoDestroy;
import l2f.gameserver.taskmanager.LazyPrecisionTaskManager;
import l2f.gameserver.templates.item.ItemTemplate;
import l2f.gameserver.templates.item.ItemTemplate.Grade;
import l2f.gameserver.templates.item.ItemTemplate.ItemClass;
import l2f.gameserver.templates.item.ItemType;
import l2f.gameserver.utils.ItemFunctions;
import l2f.gameserver.utils.Location;
public final class ItemInstance extends GameObject implements JdbcEntity
{
public static final int[] EMPTY_AUGMENTATIONS = new int[2];
public static final int[] EMPTY_ENCHANT_OPTIONS = new int[3];
private static final long serialVersionUID = 3162753878915133228L;
private static final ItemsDAO _itemsDAO = ItemsDAO.getInstance();
/** Enumeration of locations for item */
public static enum ItemLocation
{
VOID,
INVENTORY,
PAPERDOLL,
PET_INVENTORY,
PET_PAPERDOLL,
WAREHOUSE,
CLANWH,
FREIGHT, //restored used Dimension Manager
@Deprecated
LEASE,
MAIL,
AUCTION
}
public static final int CHARGED_NONE = 0;
public static final int CHARGED_SOULSHOT = 1;
public static final int CHARGED_SPIRITSHOT = 1;
public static final int CHARGED_BLESSED_SPIRITSHOT = 2;
public static final int FLAG_NO_DROP = 1 << 0;
public static final int FLAG_NO_TRADE = 1 << 1;
public static final int FLAG_NO_TRANSFER = 1 << 2;
public static final int FLAG_NO_CRYSTALLIZE = 1 << 3;
public static final int FLAG_NO_ENCHANT = 1 << 4;
public static final int FLAG_NO_DESTROY = 1 << 5;
public static final int FLAG_NO_UNEQUIP = 1 << 6;
//public static final int FLAG_ALWAYS_DROP_ON_DIE = 1 << 7;
public static final int FLAG_EQUIP_ON_PICKUP = 1 << 7;
//public static final int FLAG_NO_RIDER_PICKUP = 1 << 9;
//public static final int FLAG_PET_EQUIPPED = 1 << 10;
/** ID of the owner */
private int ownerId;
/** ID of the item */
private int itemId;
private int visualItemId = 0;
/** Quantity of the item */
private long count;
/** Level of enchantment of the item */
private int enchantLevel = -1;
/** Location of the item */
private ItemLocation loc;
/** Slot where item is stored */
private int locData;
/** Custom item types (used loto, race tickets) */
private int customType1;
private int customType2;
/** Время жизни временных вещей */
private int lifeTime;
/** Спецфлаги для конкретного инстанса */
private int customFlags;
/** Атрибуты вещи */
private ItemAttributes attrs = new ItemAttributes();
/** Аугментация вещи */
private int[] _enchantOptions = EMPTY_ENCHANT_OPTIONS;
/** Object L2Item associated to the item */
private ItemTemplate template;
/** Флаг, что вещь одета, выставляется в инвентаре **/
private boolean isEquipped;
/** Item drop time for autodestroy task */
private long timeToDeleteAfterDrop;
private IntSet _dropPlayers = Containers.EMPTY_INT_SET;
private long _dropTimeOwner;
private int _chargedSoulshot = CHARGED_NONE;
private int _chargedSpiritshot = CHARGED_NONE;
private boolean _chargedFishtshot = false;
private int _augmentationId;
private int _agathionEnergy;
private int[] _augmentations = EMPTY_AUGMENTATIONS;
private ItemAttachment _attachment;
private JdbcEntityState _state = JdbcEntityState.CREATED;
public ItemInstance(int objectId)
{
super(objectId);
}
/**
* Constructor<?> of the L2ItemInstance from the objectId and the itemId.
* @param objectId : int designating the ID of the object in the world
* @param itemId : int designating the ID of the item
*/
public ItemInstance(int objectId, int itemId)
{
super(objectId);
setItemId(itemId);
setLifeTime(getTemplate().isTemporal() ? (int) (System.currentTimeMillis() / 1000L) + getTemplate().getDurability() * 60 : getTemplate().getDurability());
setAgathionEnergy(getTemplate().getAgathionEnergy());
setLocData(-1);
setEnchantLevel(0);
}
public int getOwnerId()
{
return ownerId;
}
public void setOwnerId(int ownerId)
{
this.ownerId = ownerId;
}
public int getItemId()
{
return itemId;
}
public void setItemId(int id)
{
itemId = id;
template = ItemHolder.getInstance().getTemplate(id);
setCustomFlags(getCustomFlags());
}
public long getCount()
{
return count;
}
public void setCount(long count)
{
if (count < 0)
count = 0;
if (!isStackable() && count > 1L)
{
this.count = 1L;
return;
}
this.count = count;
}
public int getEnchantLevel()
{
return enchantLevel;
}
public void setEnchantLevel(int enchantLevel)
{
final int old = this.enchantLevel;
this.enchantLevel = enchantLevel;
if (old != this.enchantLevel && getTemplate().getEnchantOptions().size() > 0)
{
Player player = GameObjectsStorage.getPlayer(ownerId);
if (isEquipped() && player != null)
ItemEnchantOptionsListener.getInstance().onUnequip(getEquipSlot(), this, player);
int[] enchantOptions = getTemplate().getEnchantOptions().get(this.enchantLevel);
_enchantOptions = enchantOptions == null ? EMPTY_ENCHANT_OPTIONS : enchantOptions;
if (isEquipped() && player != null)
ItemEnchantOptionsListener.getInstance().onEquip(getEquipSlot(), this, player);
}
}
public void setLocName(String loc)
{
this.loc = ItemLocation.valueOf(loc);
}
public String getLocName()
{
return loc.name();
}
public void setLocation(ItemLocation loc)
{
this.loc = loc;
}
public ItemLocation getLocation()
{
return loc;
}
public void setLocData(int locData)
{
this.locData = locData;
}
public int getLocData()
{
return locData;
}
public int getCustomType1()
{
return customType1;
}
public void setCustomType1(int newtype)
{
customType1 = newtype;
}
public int getCustomType2()
{
return customType2;
}
public void setCustomType2(int newtype)
{
customType2 = newtype;
}
public int getLifeTime()
{
return lifeTime;
}
public void setLifeTime(int lifeTime)
{
this.lifeTime = Math.max(0, lifeTime);
}
public int getCustomFlags()
{
return customFlags;
}
public void setCustomFlags(int flags)
{
customFlags = flags;
}
public ItemAttributes getAttributes()
{
return attrs;
}
public void setAttributes(ItemAttributes attrs)
{
this.attrs = attrs;
}
public int getShadowLifeTime()
{
if (!isShadowItem())
return 0;
return getLifeTime();
}
public int getTemporalLifeTime()
{
if (!isTemporalItem())
return 0;
return getLifeTime() - (int) (System.currentTimeMillis() / 1000L);
}
private ScheduledFuture<?> _timerTask;
public void startTimer(Runnable r)
{
_timerTask = LazyPrecisionTaskManager.getInstance().scheduleAtFixedRate(r, 0, 60000L);
}
public void stopTimer()
{
if (_timerTask != null)
{
_timerTask.cancel(false);
_timerTask = null;
}
}
/**
* Returns if item is equipable
* @return boolean
*/
public boolean isEquipable()
{
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isEquipable();
}
/**
* Returns if item is equipped
* @return boolean
*/
public boolean isEquipped()
{
return isEquipped;
}
public void setEquipped(boolean isEquipped)
{
this.isEquipped = isEquipped;
}
public int getBodyPart()
{
return template.getBodyPart();
}
/**
* Returns the slot where the item is stored
* @return int
*/
public int getEquipSlot()
{
return getLocData();
}
/**
* Returns the characteristics of the item
* @return L2Item
*/
public ItemTemplate getTemplate()
{
return template;
}
public void setTimeToDeleteAfterDrop(long time)
{
timeToDeleteAfterDrop = time;
}
public long getTimeToDeleteAfterDrop()
{
return timeToDeleteAfterDrop;
}
public long getDropTimeOwner()
{
return _dropTimeOwner;
}
/**
* Returns the type of item
* @return Enum
*/
public ItemType getItemType()
{
return template.getItemType();
}
public boolean isArmor()
{
return template.isArmor();
}
public boolean isAccessory()
{
return template.isAccessory();
}
public boolean isNoEnchant()
{
return template.isNoEnchant();
}
public boolean isShieldNoEnchant()
{
return template.isShieldNoEnchant();
}
public boolean isSigelNoEnchant()
{
return template.isSigelNoEnchant();
}
public boolean isWeapon()
{
return template.isWeapon();
}
public boolean isNotAugmented()
{
return template.isNotAugmented();
}
public boolean isArrow()
{
return template.isArrow();
}
public boolean isUnderwear()
{
return template.isUnderwear();
}
/**
* Returns the reference price of the item
* @return int
*/
public int getReferencePrice()
{
return template.getReferencePrice();
}
/**
* Returns if item is stackable
* @return boolean
*/
public boolean isStackable()
{
return template.isStackable();
}
@Override
public void onAction(Player player, boolean shift)
{
if (Events.onAction(player, this, shift))
return;
if (player.isCursedWeaponEquipped() && CursedWeaponsManager.getInstance().isCursed(itemId))
return;
player.getAI().setIntention(CtrlIntention.AI_INTENTION_PICK_UP, this, null);
}
public boolean isAugmented()
{
return getAugmentationId() != 0;
}
// public boolean isAugmented()
// {
// return _augmentationId != 0;
// }
public int getAugmentationId()
{
return _augmentationId;
}
public void setAugmentationId(int val)
{
_augmentationId = val;
}
/**
* Returns the type of charge with SoulShot of the item.
* @return int (CHARGED_NONE, CHARGED_SOULSHOT)
*/
public int getChargedSoulshot()
{
return _chargedSoulshot;
}
/**
* Returns the type of charge with SpiritShot of the item
* @return int (CHARGED_NONE, CHARGED_SPIRITSHOT, CHARGED_BLESSED_SPIRITSHOT)
*/
public int getChargedSpiritshot()
{
return _chargedSpiritshot;
}
public boolean getChargedFishshot()
{
return _chargedFishtshot;
}
/**
* Sets the type of charge with SoulShot of the item
* @param type : int (CHARGED_NONE, CHARGED_SOULSHOT)
*/
public void setChargedSoulshot(int type)
{
_chargedSoulshot = type;
}
/**
* Sets the type of charge with SpiritShot of the item
* @param type : int (CHARGED_NONE, CHARGED_SPIRITSHOT, CHARGED_BLESSED_SPIRITSHOT)
*/
public void setChargedSpiritshot(int type)
{
_chargedSpiritshot = type;
}
public void setChargedFishshot(boolean type)
{
_chargedFishtshot = type;
}
public class FuncAttack extends Func
{
private final Element element;
public FuncAttack(Element element, int order, Object owner)
{
super(element.getAttack(), order, owner);
this.element = element;
}
@Override
public void calc(Env env)
{
env.value += getAttributeElementValue(element, true);
}
}
public class FuncDefence extends Func
{
private final Element element;
public FuncDefence(Element element, int order, Object owner)
{
super(element.getDefence(), order, owner);
this.element = element;
}
@Override
public void calc(Env env)
{
env.value += getAttributeElementValue(element, true);
}
}
/**
* This function basically returns a set of functions from
* L2Item/L2Armor/L2Weapon, but may add additional
* functions, if this particular item instance is enhanched
* for a particular player.
* @return Func[]
*/
public Func[] getStatFuncs()
{
Func[] result = Func.EMPTY_FUNC_ARRAY;
List<Func> funcs = new ArrayList<>();
if (template.getAttachedFuncs().length > 0)
for (FuncTemplate t : template.getAttachedFuncs())
{
Func f = t.getFunc(this);
if (f != null)
funcs.add(f);
}
for (Element e : Element.VALUES)
{
if (isWeapon())
funcs.add(new FuncAttack(e, 0x40, this));
if (isArmor())
funcs.add(new FuncDefence(e, 0x40, this));
}
if (!funcs.isEmpty())
result = funcs.toArray(new Func[funcs.size()]);
return result;
}
/**
* Return true if item is hero-item
* @return boolean
*/
public boolean isHeroWeapon()
{
return template.isHeroWeapon();
}
/**
* Return true if item can be destroyed
* @param player
* @return
*/
public boolean canBeDestroyed(Player player)
{
if ((customFlags & FLAG_NO_DESTROY) == FLAG_NO_DESTROY)
return false;
if (isHeroWeapon())
return false;
if (PetDataTable.isPetControlItem(this) && player.isMounted())
return false;
if (player.getPetControlItem() == this)
return false;
if (player.getEnchantScroll() == this)
return false;
if (isCursed())
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isDestroyable();
}
/**
* Return true if item can be dropped
* @param player
* @param pk
* @return
*/
public boolean canBeDropped(Player player, boolean pk)
{
if (player.isGM())
return true;
if ((customFlags & FLAG_NO_DROP) == FLAG_NO_DROP)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (isAugmented() && (!pk || !Config.DROP_ITEMS_AUGMENTED) && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!template.isDropable())
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return true;
}
public boolean canBeTraded(Player player)
{
if (isEquipped())
return false;
if (player.isGM())
return true;
if ((customFlags & FLAG_NO_TRADE) == FLAG_NO_TRADE)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (isAugmented() && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!template.isTradeable() && !Config.CAN_BE_TRADED_NO_TARADEABLE)
return false;
if (!template.isSellable() && !Config.CAN_BE_TRADED_NO_SELLABLE)
return false;
if (!template.isStoreable() && !Config.CAN_BE_TRADED_NO_STOREABLE)
return false;
if (isShadowItem() && !Config.CAN_BE_TRADED_SHADOW_ITEM)
return false;
if (isHeroWeapon() && !Config.CAN_BE_TRADED_HERO_WEAPON)
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return true;
}
/**
* Можно ли продать в магазин NPC
* @param player
* @return
*/
public boolean canBeSold(Player player)
{
if ((customFlags & FLAG_NO_DESTROY) == FLAG_NO_DESTROY)
return false;
if (getItemId() == ItemTemplate.ITEM_ID_ADENA)
return false;
if (template.getReferencePrice() == 0)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (isAugmented() && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (isEquipped())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!template.isTradeable())
return false;
if (!template.isSellable())
return false;
if (!template.isStoreable())
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return true;
}
/**
* Можно ли положить на клановый склад
* @param player
* @param privatewh
* @return
*/
public boolean canBeStored(Player player, boolean privatewh)
{
if ((customFlags & FLAG_NO_TRANSFER) == FLAG_NO_TRANSFER)
return false;
if (!getTemplate().isStoreable())
return false;
if (!privatewh && (isShadowItem() || isTemporalItem()))
return false;
if (!privatewh && isAugmented() && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (isEquipped())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!privatewh && isAugmented() && !Config.CAN_BE_CWH_IS_AUGMENTED)
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return privatewh || template.isTradeable();
}
public boolean canBeCrystallized(Player player)
{
if ((customFlags & FLAG_NO_CRYSTALLIZE) == FLAG_NO_CRYSTALLIZE)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isCrystallizable();
}
public boolean canBeEnchanted(boolean gradeCheck)
{
if ((customFlags & FLAG_NO_ENCHANT) == FLAG_NO_ENCHANT)
return false;
return template.canBeEnchanted(gradeCheck);
}
public boolean canBeAugmented(Player player, boolean isAccessoryLifeStone)
{
if (!canBeEnchanted(true))
return false;
if (isAugmented())
return false;
if (isCommonItem())
return false;
if (isTerritoryAccessory())
return false;
if (getTemplate().getItemGrade().ordinal() < Grade.C.ordinal())
return false;
if (!getTemplate().isAugmentable())
return false;
if (isAccessory())
return isAccessoryLifeStone;
if (isArmor())
return Config.ALT_ALLOW_AUGMENT_ALL;
if (isWeapon())
return !isAccessoryLifeStone;
return true;
}
public boolean canBeExchanged(Player player)
{
if ((customFlags & FLAG_NO_DESTROY) == FLAG_NO_DESTROY)
return false;
if (isShadowItem())
return false;
if (isHeroWeapon())
return false;
if (isTemporalItem())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isDestroyable();
}
public boolean isTerritoryAccessory()
{
return template.isTerritoryAccessory();
}
public boolean isShadowItem()
{
return template.isShadowItem();
}
public boolean isTemporalItem()
{
return template.isTemporal();
}
public boolean isCommonItem()
{
return template.isCommonItem();
}
public boolean isAltSeed()
{
return template.isAltSeed();
}
public boolean isAdena()
{
return template.isAdena();
}
public boolean isCursed()
{
return template.isCursed();
}
/**
* Бросает на землю лут с NPC
* @param lastAttacker
* @param fromNpc
*/
public void dropToTheGround(Player lastAttacker, NpcInstance fromNpc)
{
Creature dropper = fromNpc;
if (dropper == null)
dropper = lastAttacker;
Location pos = Location.findAroundPosition(dropper, 100);
// activate non owner penalty
if (lastAttacker != null) // lastAttacker в данном случае top damager
{
_dropPlayers = new HashIntSet(1, 2);
for (Player $member : lastAttacker.getPlayerGroup())
_dropPlayers.add($member.getObjectId());
_dropTimeOwner = System.currentTimeMillis() + Config.NONOWNER_ITEM_PICKUP_DELAY + (fromNpc != null && fromNpc.isRaid() ? 285000 : 0);
}
// Init the dropped L2ItemInstance and add it in the world as a visible object at the position where mob was last
dropMe(dropper, pos);
// Add drop to auto destroy item task
if (isHerb())
ItemsAutoDestroy.getInstance().addHerb(this);
else if (Config.AUTODESTROY_ITEM_AFTER > 0 && !isCursed() && _attachment == null)
ItemsAutoDestroy.getInstance().addItem(this, Config.AUTODESTROY_ITEM_AFTER * 1000L);
}
/**
* Бросает вещь на землю туда, где ее можно поднять
* @param dropper
* @param dropPos
*/
public void dropToTheGround(Creature dropper, Location dropPos)
{
if (GeoEngine.canMoveToCoord(dropper.getX(), dropper.getY(), dropper.getZ(), dropPos.x, dropPos.y, dropPos.z, dropper.getGeoIndex()))
dropMe(dropper, dropPos);
else
dropMe(dropper, dropper.getLoc());
}
/**
* Бросает вещь на землю из инвентаря туда, где ее можно поднять
* @param dropper
* @param dropPos
*/
public void dropToTheGround(Playable dropper, Location dropPos)
{
setLocation(ItemLocation.VOID);
if (getJdbcState().isPersisted())
{
setJdbcState(JdbcEntityState.UPDATED);
update();
}
if (GeoEngine.canMoveToCoord(dropper.getX(), dropper.getY(), dropper.getZ(), dropPos.x, dropPos.y, dropPos.z, dropper.getGeoIndex()))
dropMe(dropper, dropPos);
else
dropMe(dropper, dropper.getLoc());
// Add drop to auto destroy item task from player items.
if (Config.AUTODESTROY_PLAYER_ITEM_AFTER > 0 && _attachment == null)
ItemsAutoDestroy.getInstance().addItem(this, Config.AUTODESTROY_PLAYER_ITEM_AFTER * 1000L);
}
/**
* Init a dropped L2ItemInstance and add it in the world as a visible object.<BR><BR>
*
* <B><U> Actions</U> :</B><BR><BR>
* <li>Set the x,y,z position of the L2ItemInstance dropped and update its _worldregion </li>
* <li>Add the L2ItemInstance dropped to _visibleObjects of its L2WorldRegion</li>
* <li>Add the L2ItemInstance dropped in the world as a <B>visible</B> object</li><BR><BR>
*
* <FONT COLOR=#FF0000><B> <U>Caution</U> : This method DOESN'T ADD the object to _allObjects of L2World </B></FONT><BR><BR>
*
* <B><U> Assert </U> :</B><BR><BR>
* <li> this instanceof L2ItemInstance</li>
* <li> _worldRegion == null <I>(L2Object is invisible at the beginning)</I></li><BR><BR>
*
* <B><U> Example of use </U> :</B><BR><BR>
* <li> Drop item</li>
* <li> Call Pet</li><BR>
*
* @param dropper Char that dropped item
* @param loc drop coordinates
*/
public void dropMe(Creature dropper, Location loc)
{
if (dropper != null)
setReflection(dropper.getReflection());
spawnMe0(loc, dropper);
if (isHerb())
{
ItemsAutoDestroy.getInstance().addHerb(this);
}
else if ((Config.AUTODESTROY_ITEM_AFTER > 0) && (!isCursed()))
{
ItemsAutoDestroy.getInstance().addItem(this, 100000L);
}
}
public final void pickupMe()
{
decayMe();
setReflection(ReflectionManager.DEFAULT);
}
public ItemClass getItemClass()
{
return template.getItemClass();
}
/**
* Возвращает защиту от элемента.
* @param element
* @return значение защиты
*/
private int getDefence(Element element)
{
return isArmor() ? getAttributeElementValue(element, true) : 0;
}
/**
* Возвращает защиту от элемента: огонь.
* @return значение защиты
*/
public int getDefenceFire()
{
return getDefence(Element.FIRE);
}
/**
* Возвращает защиту от элемента: вода.
* @return значение защиты
*/
public int getDefenceWater()
{
return getDefence(Element.WATER);
}
/**
* Возвращает защиту от элемента: воздух.
* @return значение защиты
*/
public int getDefenceWind()
{
return getDefence(Element.WIND);
}
/**
* Возвращает защиту от элемента: земля.
* @return значение защиты
*/
public int getDefenceEarth()
{
return getDefence(Element.EARTH);
}
/**
* Возвращает защиту от элемента: свет.
* @return значение защиты
*/
public int getDefenceHoly()
{
return getDefence(Element.HOLY);
}
/**
* Возвращает защиту от элемента: тьма.
* @return значение защиты
*/
public int getDefenceUnholy()
{
return getDefence(Element.UNHOLY);
}
/**
* Возвращает значение элемента.
* @param element
* @param withBase
* @return
*/
public int getAttributeElementValue(Element element, boolean withBase)
{
return attrs.getValue(element) + (withBase ? template.getBaseAttributeValue(element) : 0);
}
/**
* Возвращает элемент атрибуции предмета.<br>
* @return
*/
public Element getAttributeElement()
{
return attrs.getElement();
}
public int getAttributeElementValue()
{
return attrs.getValue();
}
public Element getAttackElement()
{
Element element = isWeapon() ? getAttributeElement() : Element.NONE;
if (element == Element.NONE)
for (Element e : Element.VALUES)
if (template.getBaseAttributeValue(e) > 0)
return e;
return element;
}
public int getAttackElementValue()
{
return isWeapon() ? getAttributeElementValue(getAttackElement(), true) : 0;
}
/**
* Устанавливает элемент атрибуции предмета.<br>
* Element (0 - Fire, 1 - Water, 2 - Wind, 3 - Earth, 4 - Holy, 5 - Dark, -1 - None)
* @param element элемент
* @param value
*/
public void setAttributeElement(Element element, int value)
{
attrs.setValue(element, value);
}
/**
* Проверяет, является ли данный инстанс предмета хербом
* @return true если предмет является хербом
*/
public boolean isHerb()
{
if (getTemplate().isHerb())
return true;
return false;
}
public Grade getCrystalType()
{
return template.getCrystalType();
}
@Override
public String getName()
{
return getTemplate().getName();
}
@Override
public void save()
{
_itemsDAO.save(this);
}
@Override
public void update()
{
_itemsDAO.update(this);
}
@Override
public void delete()
{
_itemsDAO.delete(this);
}
@Override
public List<L2GameServerPacket> addPacketList(Player forPlayer, Creature dropper)
{
L2GameServerPacket packet = null;
if (dropper != null)
packet = new DropItem(this, dropper.getObjectId());
else
packet = new SpawnItem(this);
return Collections.singletonList(packet);
}
/**
* Returns the item in String format
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(getTemplate().getItemId());
sb.append(" ");
if (getEnchantLevel() > 0)
{
sb.append("+");
sb.append(getEnchantLevel());
sb.append(" ");
}
sb.append(getTemplate().getName());
if (!getTemplate().getAdditionalName().isEmpty())
{
sb.append(" ");
sb.append("\\").append(getTemplate().getAdditionalName()).append("\\");
}
sb.append(" ");
sb.append("(");
sb.append(getCount());
sb.append(")");
sb.append("[");
sb.append(getObjectId());
sb.append("]");
return sb.toString();
}
@Override
public void setJdbcState(JdbcEntityState state)
{
_state = state;
}
@Override
public JdbcEntityState getJdbcState()
{
return _state;
}
@Override
public boolean isItem()
{
return true;
}
public ItemAttachment getAttachment()
{
return _attachment;
}
public void setAttachment(ItemAttachment attachment)
{
ItemAttachment old = _attachment;
_attachment = attachment;
if (_attachment != null)
_attachment.setItem(this);
if (old != null)
old.setItem(null);
}
public int getAgathionEnergy()
{
return _agathionEnergy;
}
public void setAgathionEnergy(int agathionEnergy)
{
_agathionEnergy = agathionEnergy;
}
public int[] getEnchantOptions()
{
return _enchantOptions;
}
public IntSet getDropPlayers()
{
return _dropPlayers;
}
/**
* sending item stat like pAtk or mDef
* @param stat
* @return
*/
public double getStatFunc(Stats stat)
{
for (FuncTemplate func : template.getAttachedFuncs())
if (func._stat == stat)
return func._value;
return 0.0;
}
/**
* @return
*/
public int getVisualItemId()
{
return visualItemId;
}
public void setVisualItemId(int visualItemId)
{
this.visualItemId = visualItemId;
}
public int getAugmentationMineralId()
{
return _augmentationId;
}
public void setAugmentation(int mineralId, int[] augmentations)
{
_augmentationId = mineralId;
_augmentations = augmentations;
}
public int[] getAugmentations()
{
return _augmentations;
}
}
|
UTF-8
|
Java
| 29,784 |
java
|
ItemInstance.java
|
Java
|
[] | null |
[] |
package l2f.gameserver.model.items;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import org.napile.primitive.Containers;
import org.napile.primitive.sets.IntSet;
import org.napile.primitive.sets.impl.HashIntSet;
import l2f.commons.configuration.Config;
import l2f.commons.dao.JdbcEntity;
import l2f.commons.dao.JdbcEntityState;
import l2f.gameserver.ai.CtrlIntention;
import l2f.gameserver.dao.ItemsDAO;
import l2f.gameserver.data.xml.holder.ItemHolder;
import l2f.gameserver.geodata.GeoEngine;
import l2f.gameserver.instancemanager.CursedWeaponsManager;
import l2f.gameserver.instancemanager.ReflectionManager;
import l2f.gameserver.model.Creature;
import l2f.gameserver.model.GameObject;
import l2f.gameserver.model.GameObjectsStorage;
import l2f.gameserver.model.Playable;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.base.Element;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.model.items.attachment.FlagItemAttachment;
import l2f.gameserver.model.items.attachment.ItemAttachment;
import l2f.gameserver.model.items.listeners.ItemEnchantOptionsListener;
import l2f.gameserver.network.serverpackets.DropItem;
import l2f.gameserver.network.serverpackets.L2GameServerPacket;
import l2f.gameserver.network.serverpackets.SpawnItem;
import l2f.gameserver.scripts.Events;
import l2f.gameserver.stats.Env;
import l2f.gameserver.stats.Stats;
import l2f.gameserver.stats.funcs.Func;
import l2f.gameserver.stats.funcs.FuncTemplate;
import l2f.gameserver.tables.PetDataTable;
import l2f.gameserver.taskmanager.ItemsAutoDestroy;
import l2f.gameserver.taskmanager.LazyPrecisionTaskManager;
import l2f.gameserver.templates.item.ItemTemplate;
import l2f.gameserver.templates.item.ItemTemplate.Grade;
import l2f.gameserver.templates.item.ItemTemplate.ItemClass;
import l2f.gameserver.templates.item.ItemType;
import l2f.gameserver.utils.ItemFunctions;
import l2f.gameserver.utils.Location;
public final class ItemInstance extends GameObject implements JdbcEntity
{
public static final int[] EMPTY_AUGMENTATIONS = new int[2];
public static final int[] EMPTY_ENCHANT_OPTIONS = new int[3];
private static final long serialVersionUID = 3162753878915133228L;
private static final ItemsDAO _itemsDAO = ItemsDAO.getInstance();
/** Enumeration of locations for item */
public static enum ItemLocation
{
VOID,
INVENTORY,
PAPERDOLL,
PET_INVENTORY,
PET_PAPERDOLL,
WAREHOUSE,
CLANWH,
FREIGHT, //restored used Dimension Manager
@Deprecated
LEASE,
MAIL,
AUCTION
}
public static final int CHARGED_NONE = 0;
public static final int CHARGED_SOULSHOT = 1;
public static final int CHARGED_SPIRITSHOT = 1;
public static final int CHARGED_BLESSED_SPIRITSHOT = 2;
public static final int FLAG_NO_DROP = 1 << 0;
public static final int FLAG_NO_TRADE = 1 << 1;
public static final int FLAG_NO_TRANSFER = 1 << 2;
public static final int FLAG_NO_CRYSTALLIZE = 1 << 3;
public static final int FLAG_NO_ENCHANT = 1 << 4;
public static final int FLAG_NO_DESTROY = 1 << 5;
public static final int FLAG_NO_UNEQUIP = 1 << 6;
//public static final int FLAG_ALWAYS_DROP_ON_DIE = 1 << 7;
public static final int FLAG_EQUIP_ON_PICKUP = 1 << 7;
//public static final int FLAG_NO_RIDER_PICKUP = 1 << 9;
//public static final int FLAG_PET_EQUIPPED = 1 << 10;
/** ID of the owner */
private int ownerId;
/** ID of the item */
private int itemId;
private int visualItemId = 0;
/** Quantity of the item */
private long count;
/** Level of enchantment of the item */
private int enchantLevel = -1;
/** Location of the item */
private ItemLocation loc;
/** Slot where item is stored */
private int locData;
/** Custom item types (used loto, race tickets) */
private int customType1;
private int customType2;
/** Время жизни временных вещей */
private int lifeTime;
/** Спецфлаги для конкретного инстанса */
private int customFlags;
/** Атрибуты вещи */
private ItemAttributes attrs = new ItemAttributes();
/** Аугментация вещи */
private int[] _enchantOptions = EMPTY_ENCHANT_OPTIONS;
/** Object L2Item associated to the item */
private ItemTemplate template;
/** Флаг, что вещь одета, выставляется в инвентаре **/
private boolean isEquipped;
/** Item drop time for autodestroy task */
private long timeToDeleteAfterDrop;
private IntSet _dropPlayers = Containers.EMPTY_INT_SET;
private long _dropTimeOwner;
private int _chargedSoulshot = CHARGED_NONE;
private int _chargedSpiritshot = CHARGED_NONE;
private boolean _chargedFishtshot = false;
private int _augmentationId;
private int _agathionEnergy;
private int[] _augmentations = EMPTY_AUGMENTATIONS;
private ItemAttachment _attachment;
private JdbcEntityState _state = JdbcEntityState.CREATED;
public ItemInstance(int objectId)
{
super(objectId);
}
/**
* Constructor<?> of the L2ItemInstance from the objectId and the itemId.
* @param objectId : int designating the ID of the object in the world
* @param itemId : int designating the ID of the item
*/
public ItemInstance(int objectId, int itemId)
{
super(objectId);
setItemId(itemId);
setLifeTime(getTemplate().isTemporal() ? (int) (System.currentTimeMillis() / 1000L) + getTemplate().getDurability() * 60 : getTemplate().getDurability());
setAgathionEnergy(getTemplate().getAgathionEnergy());
setLocData(-1);
setEnchantLevel(0);
}
public int getOwnerId()
{
return ownerId;
}
public void setOwnerId(int ownerId)
{
this.ownerId = ownerId;
}
public int getItemId()
{
return itemId;
}
public void setItemId(int id)
{
itemId = id;
template = ItemHolder.getInstance().getTemplate(id);
setCustomFlags(getCustomFlags());
}
public long getCount()
{
return count;
}
public void setCount(long count)
{
if (count < 0)
count = 0;
if (!isStackable() && count > 1L)
{
this.count = 1L;
return;
}
this.count = count;
}
public int getEnchantLevel()
{
return enchantLevel;
}
public void setEnchantLevel(int enchantLevel)
{
final int old = this.enchantLevel;
this.enchantLevel = enchantLevel;
if (old != this.enchantLevel && getTemplate().getEnchantOptions().size() > 0)
{
Player player = GameObjectsStorage.getPlayer(ownerId);
if (isEquipped() && player != null)
ItemEnchantOptionsListener.getInstance().onUnequip(getEquipSlot(), this, player);
int[] enchantOptions = getTemplate().getEnchantOptions().get(this.enchantLevel);
_enchantOptions = enchantOptions == null ? EMPTY_ENCHANT_OPTIONS : enchantOptions;
if (isEquipped() && player != null)
ItemEnchantOptionsListener.getInstance().onEquip(getEquipSlot(), this, player);
}
}
public void setLocName(String loc)
{
this.loc = ItemLocation.valueOf(loc);
}
public String getLocName()
{
return loc.name();
}
public void setLocation(ItemLocation loc)
{
this.loc = loc;
}
public ItemLocation getLocation()
{
return loc;
}
public void setLocData(int locData)
{
this.locData = locData;
}
public int getLocData()
{
return locData;
}
public int getCustomType1()
{
return customType1;
}
public void setCustomType1(int newtype)
{
customType1 = newtype;
}
public int getCustomType2()
{
return customType2;
}
public void setCustomType2(int newtype)
{
customType2 = newtype;
}
public int getLifeTime()
{
return lifeTime;
}
public void setLifeTime(int lifeTime)
{
this.lifeTime = Math.max(0, lifeTime);
}
public int getCustomFlags()
{
return customFlags;
}
public void setCustomFlags(int flags)
{
customFlags = flags;
}
public ItemAttributes getAttributes()
{
return attrs;
}
public void setAttributes(ItemAttributes attrs)
{
this.attrs = attrs;
}
public int getShadowLifeTime()
{
if (!isShadowItem())
return 0;
return getLifeTime();
}
public int getTemporalLifeTime()
{
if (!isTemporalItem())
return 0;
return getLifeTime() - (int) (System.currentTimeMillis() / 1000L);
}
private ScheduledFuture<?> _timerTask;
public void startTimer(Runnable r)
{
_timerTask = LazyPrecisionTaskManager.getInstance().scheduleAtFixedRate(r, 0, 60000L);
}
public void stopTimer()
{
if (_timerTask != null)
{
_timerTask.cancel(false);
_timerTask = null;
}
}
/**
* Returns if item is equipable
* @return boolean
*/
public boolean isEquipable()
{
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isEquipable();
}
/**
* Returns if item is equipped
* @return boolean
*/
public boolean isEquipped()
{
return isEquipped;
}
public void setEquipped(boolean isEquipped)
{
this.isEquipped = isEquipped;
}
public int getBodyPart()
{
return template.getBodyPart();
}
/**
* Returns the slot where the item is stored
* @return int
*/
public int getEquipSlot()
{
return getLocData();
}
/**
* Returns the characteristics of the item
* @return L2Item
*/
public ItemTemplate getTemplate()
{
return template;
}
public void setTimeToDeleteAfterDrop(long time)
{
timeToDeleteAfterDrop = time;
}
public long getTimeToDeleteAfterDrop()
{
return timeToDeleteAfterDrop;
}
public long getDropTimeOwner()
{
return _dropTimeOwner;
}
/**
* Returns the type of item
* @return Enum
*/
public ItemType getItemType()
{
return template.getItemType();
}
public boolean isArmor()
{
return template.isArmor();
}
public boolean isAccessory()
{
return template.isAccessory();
}
public boolean isNoEnchant()
{
return template.isNoEnchant();
}
public boolean isShieldNoEnchant()
{
return template.isShieldNoEnchant();
}
public boolean isSigelNoEnchant()
{
return template.isSigelNoEnchant();
}
public boolean isWeapon()
{
return template.isWeapon();
}
public boolean isNotAugmented()
{
return template.isNotAugmented();
}
public boolean isArrow()
{
return template.isArrow();
}
public boolean isUnderwear()
{
return template.isUnderwear();
}
/**
* Returns the reference price of the item
* @return int
*/
public int getReferencePrice()
{
return template.getReferencePrice();
}
/**
* Returns if item is stackable
* @return boolean
*/
public boolean isStackable()
{
return template.isStackable();
}
@Override
public void onAction(Player player, boolean shift)
{
if (Events.onAction(player, this, shift))
return;
if (player.isCursedWeaponEquipped() && CursedWeaponsManager.getInstance().isCursed(itemId))
return;
player.getAI().setIntention(CtrlIntention.AI_INTENTION_PICK_UP, this, null);
}
public boolean isAugmented()
{
return getAugmentationId() != 0;
}
// public boolean isAugmented()
// {
// return _augmentationId != 0;
// }
public int getAugmentationId()
{
return _augmentationId;
}
public void setAugmentationId(int val)
{
_augmentationId = val;
}
/**
* Returns the type of charge with SoulShot of the item.
* @return int (CHARGED_NONE, CHARGED_SOULSHOT)
*/
public int getChargedSoulshot()
{
return _chargedSoulshot;
}
/**
* Returns the type of charge with SpiritShot of the item
* @return int (CHARGED_NONE, CHARGED_SPIRITSHOT, CHARGED_BLESSED_SPIRITSHOT)
*/
public int getChargedSpiritshot()
{
return _chargedSpiritshot;
}
public boolean getChargedFishshot()
{
return _chargedFishtshot;
}
/**
* Sets the type of charge with SoulShot of the item
* @param type : int (CHARGED_NONE, CHARGED_SOULSHOT)
*/
public void setChargedSoulshot(int type)
{
_chargedSoulshot = type;
}
/**
* Sets the type of charge with SpiritShot of the item
* @param type : int (CHARGED_NONE, CHARGED_SPIRITSHOT, CHARGED_BLESSED_SPIRITSHOT)
*/
public void setChargedSpiritshot(int type)
{
_chargedSpiritshot = type;
}
public void setChargedFishshot(boolean type)
{
_chargedFishtshot = type;
}
public class FuncAttack extends Func
{
private final Element element;
public FuncAttack(Element element, int order, Object owner)
{
super(element.getAttack(), order, owner);
this.element = element;
}
@Override
public void calc(Env env)
{
env.value += getAttributeElementValue(element, true);
}
}
public class FuncDefence extends Func
{
private final Element element;
public FuncDefence(Element element, int order, Object owner)
{
super(element.getDefence(), order, owner);
this.element = element;
}
@Override
public void calc(Env env)
{
env.value += getAttributeElementValue(element, true);
}
}
/**
* This function basically returns a set of functions from
* L2Item/L2Armor/L2Weapon, but may add additional
* functions, if this particular item instance is enhanched
* for a particular player.
* @return Func[]
*/
public Func[] getStatFuncs()
{
Func[] result = Func.EMPTY_FUNC_ARRAY;
List<Func> funcs = new ArrayList<>();
if (template.getAttachedFuncs().length > 0)
for (FuncTemplate t : template.getAttachedFuncs())
{
Func f = t.getFunc(this);
if (f != null)
funcs.add(f);
}
for (Element e : Element.VALUES)
{
if (isWeapon())
funcs.add(new FuncAttack(e, 0x40, this));
if (isArmor())
funcs.add(new FuncDefence(e, 0x40, this));
}
if (!funcs.isEmpty())
result = funcs.toArray(new Func[funcs.size()]);
return result;
}
/**
* Return true if item is hero-item
* @return boolean
*/
public boolean isHeroWeapon()
{
return template.isHeroWeapon();
}
/**
* Return true if item can be destroyed
* @param player
* @return
*/
public boolean canBeDestroyed(Player player)
{
if ((customFlags & FLAG_NO_DESTROY) == FLAG_NO_DESTROY)
return false;
if (isHeroWeapon())
return false;
if (PetDataTable.isPetControlItem(this) && player.isMounted())
return false;
if (player.getPetControlItem() == this)
return false;
if (player.getEnchantScroll() == this)
return false;
if (isCursed())
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isDestroyable();
}
/**
* Return true if item can be dropped
* @param player
* @param pk
* @return
*/
public boolean canBeDropped(Player player, boolean pk)
{
if (player.isGM())
return true;
if ((customFlags & FLAG_NO_DROP) == FLAG_NO_DROP)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (isAugmented() && (!pk || !Config.DROP_ITEMS_AUGMENTED) && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!template.isDropable())
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return true;
}
public boolean canBeTraded(Player player)
{
if (isEquipped())
return false;
if (player.isGM())
return true;
if ((customFlags & FLAG_NO_TRADE) == FLAG_NO_TRADE)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (isAugmented() && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!template.isTradeable() && !Config.CAN_BE_TRADED_NO_TARADEABLE)
return false;
if (!template.isSellable() && !Config.CAN_BE_TRADED_NO_SELLABLE)
return false;
if (!template.isStoreable() && !Config.CAN_BE_TRADED_NO_STOREABLE)
return false;
if (isShadowItem() && !Config.CAN_BE_TRADED_SHADOW_ITEM)
return false;
if (isHeroWeapon() && !Config.CAN_BE_TRADED_HERO_WEAPON)
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return true;
}
/**
* Можно ли продать в магазин NPC
* @param player
* @return
*/
public boolean canBeSold(Player player)
{
if ((customFlags & FLAG_NO_DESTROY) == FLAG_NO_DESTROY)
return false;
if (getItemId() == ItemTemplate.ITEM_ID_ADENA)
return false;
if (template.getReferencePrice() == 0)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (isAugmented() && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (isEquipped())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!template.isTradeable())
return false;
if (!template.isSellable())
return false;
if (!template.isStoreable())
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return true;
}
/**
* Можно ли положить на клановый склад
* @param player
* @param privatewh
* @return
*/
public boolean canBeStored(Player player, boolean privatewh)
{
if ((customFlags & FLAG_NO_TRANSFER) == FLAG_NO_TRANSFER)
return false;
if (!getTemplate().isStoreable())
return false;
if (!privatewh && (isShadowItem() || isTemporalItem()))
return false;
if (!privatewh && isAugmented() && !Config.ALT_ALLOW_DROP_AUGMENTED)
return false;
if (isEquipped())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (!privatewh && isAugmented() && !Config.CAN_BE_CWH_IS_AUGMENTED)
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return privatewh || template.isTradeable();
}
public boolean canBeCrystallized(Player player)
{
if ((customFlags & FLAG_NO_CRYSTALLIZE) == FLAG_NO_CRYSTALLIZE)
return false;
if (isShadowItem())
return false;
if (isTemporalItem())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isCrystallizable();
}
public boolean canBeEnchanted(boolean gradeCheck)
{
if ((customFlags & FLAG_NO_ENCHANT) == FLAG_NO_ENCHANT)
return false;
return template.canBeEnchanted(gradeCheck);
}
public boolean canBeAugmented(Player player, boolean isAccessoryLifeStone)
{
if (!canBeEnchanted(true))
return false;
if (isAugmented())
return false;
if (isCommonItem())
return false;
if (isTerritoryAccessory())
return false;
if (getTemplate().getItemGrade().ordinal() < Grade.C.ordinal())
return false;
if (!getTemplate().isAugmentable())
return false;
if (isAccessory())
return isAccessoryLifeStone;
if (isArmor())
return Config.ALT_ALLOW_AUGMENT_ALL;
if (isWeapon())
return !isAccessoryLifeStone;
return true;
}
public boolean canBeExchanged(Player player)
{
if ((customFlags & FLAG_NO_DESTROY) == FLAG_NO_DESTROY)
return false;
if (isShadowItem())
return false;
if (isHeroWeapon())
return false;
if (isTemporalItem())
return false;
if (!ItemFunctions.checkIfCanDiscard(player, this))
return false;
if (getAttachment() != null && (getAttachment() instanceof FlagItemAttachment) && !((FlagItemAttachment)getAttachment()).canBeLost())
return false;
return template.isDestroyable();
}
public boolean isTerritoryAccessory()
{
return template.isTerritoryAccessory();
}
public boolean isShadowItem()
{
return template.isShadowItem();
}
public boolean isTemporalItem()
{
return template.isTemporal();
}
public boolean isCommonItem()
{
return template.isCommonItem();
}
public boolean isAltSeed()
{
return template.isAltSeed();
}
public boolean isAdena()
{
return template.isAdena();
}
public boolean isCursed()
{
return template.isCursed();
}
/**
* Бросает на землю лут с NPC
* @param lastAttacker
* @param fromNpc
*/
public void dropToTheGround(Player lastAttacker, NpcInstance fromNpc)
{
Creature dropper = fromNpc;
if (dropper == null)
dropper = lastAttacker;
Location pos = Location.findAroundPosition(dropper, 100);
// activate non owner penalty
if (lastAttacker != null) // lastAttacker в данном случае top damager
{
_dropPlayers = new HashIntSet(1, 2);
for (Player $member : lastAttacker.getPlayerGroup())
_dropPlayers.add($member.getObjectId());
_dropTimeOwner = System.currentTimeMillis() + Config.NONOWNER_ITEM_PICKUP_DELAY + (fromNpc != null && fromNpc.isRaid() ? 285000 : 0);
}
// Init the dropped L2ItemInstance and add it in the world as a visible object at the position where mob was last
dropMe(dropper, pos);
// Add drop to auto destroy item task
if (isHerb())
ItemsAutoDestroy.getInstance().addHerb(this);
else if (Config.AUTODESTROY_ITEM_AFTER > 0 && !isCursed() && _attachment == null)
ItemsAutoDestroy.getInstance().addItem(this, Config.AUTODESTROY_ITEM_AFTER * 1000L);
}
/**
* Бросает вещь на землю туда, где ее можно поднять
* @param dropper
* @param dropPos
*/
public void dropToTheGround(Creature dropper, Location dropPos)
{
if (GeoEngine.canMoveToCoord(dropper.getX(), dropper.getY(), dropper.getZ(), dropPos.x, dropPos.y, dropPos.z, dropper.getGeoIndex()))
dropMe(dropper, dropPos);
else
dropMe(dropper, dropper.getLoc());
}
/**
* Бросает вещь на землю из инвентаря туда, где ее можно поднять
* @param dropper
* @param dropPos
*/
public void dropToTheGround(Playable dropper, Location dropPos)
{
setLocation(ItemLocation.VOID);
if (getJdbcState().isPersisted())
{
setJdbcState(JdbcEntityState.UPDATED);
update();
}
if (GeoEngine.canMoveToCoord(dropper.getX(), dropper.getY(), dropper.getZ(), dropPos.x, dropPos.y, dropPos.z, dropper.getGeoIndex()))
dropMe(dropper, dropPos);
else
dropMe(dropper, dropper.getLoc());
// Add drop to auto destroy item task from player items.
if (Config.AUTODESTROY_PLAYER_ITEM_AFTER > 0 && _attachment == null)
ItemsAutoDestroy.getInstance().addItem(this, Config.AUTODESTROY_PLAYER_ITEM_AFTER * 1000L);
}
/**
* Init a dropped L2ItemInstance and add it in the world as a visible object.<BR><BR>
*
* <B><U> Actions</U> :</B><BR><BR>
* <li>Set the x,y,z position of the L2ItemInstance dropped and update its _worldregion </li>
* <li>Add the L2ItemInstance dropped to _visibleObjects of its L2WorldRegion</li>
* <li>Add the L2ItemInstance dropped in the world as a <B>visible</B> object</li><BR><BR>
*
* <FONT COLOR=#FF0000><B> <U>Caution</U> : This method DOESN'T ADD the object to _allObjects of L2World </B></FONT><BR><BR>
*
* <B><U> Assert </U> :</B><BR><BR>
* <li> this instanceof L2ItemInstance</li>
* <li> _worldRegion == null <I>(L2Object is invisible at the beginning)</I></li><BR><BR>
*
* <B><U> Example of use </U> :</B><BR><BR>
* <li> Drop item</li>
* <li> Call Pet</li><BR>
*
* @param dropper Char that dropped item
* @param loc drop coordinates
*/
public void dropMe(Creature dropper, Location loc)
{
if (dropper != null)
setReflection(dropper.getReflection());
spawnMe0(loc, dropper);
if (isHerb())
{
ItemsAutoDestroy.getInstance().addHerb(this);
}
else if ((Config.AUTODESTROY_ITEM_AFTER > 0) && (!isCursed()))
{
ItemsAutoDestroy.getInstance().addItem(this, 100000L);
}
}
public final void pickupMe()
{
decayMe();
setReflection(ReflectionManager.DEFAULT);
}
public ItemClass getItemClass()
{
return template.getItemClass();
}
/**
* Возвращает защиту от элемента.
* @param element
* @return значение защиты
*/
private int getDefence(Element element)
{
return isArmor() ? getAttributeElementValue(element, true) : 0;
}
/**
* Возвращает защиту от элемента: огонь.
* @return значение защиты
*/
public int getDefenceFire()
{
return getDefence(Element.FIRE);
}
/**
* Возвращает защиту от элемента: вода.
* @return значение защиты
*/
public int getDefenceWater()
{
return getDefence(Element.WATER);
}
/**
* Возвращает защиту от элемента: воздух.
* @return значение защиты
*/
public int getDefenceWind()
{
return getDefence(Element.WIND);
}
/**
* Возвращает защиту от элемента: земля.
* @return значение защиты
*/
public int getDefenceEarth()
{
return getDefence(Element.EARTH);
}
/**
* Возвращает защиту от элемента: свет.
* @return значение защиты
*/
public int getDefenceHoly()
{
return getDefence(Element.HOLY);
}
/**
* Возвращает защиту от элемента: тьма.
* @return значение защиты
*/
public int getDefenceUnholy()
{
return getDefence(Element.UNHOLY);
}
/**
* Возвращает значение элемента.
* @param element
* @param withBase
* @return
*/
public int getAttributeElementValue(Element element, boolean withBase)
{
return attrs.getValue(element) + (withBase ? template.getBaseAttributeValue(element) : 0);
}
/**
* Возвращает элемент атрибуции предмета.<br>
* @return
*/
public Element getAttributeElement()
{
return attrs.getElement();
}
public int getAttributeElementValue()
{
return attrs.getValue();
}
public Element getAttackElement()
{
Element element = isWeapon() ? getAttributeElement() : Element.NONE;
if (element == Element.NONE)
for (Element e : Element.VALUES)
if (template.getBaseAttributeValue(e) > 0)
return e;
return element;
}
public int getAttackElementValue()
{
return isWeapon() ? getAttributeElementValue(getAttackElement(), true) : 0;
}
/**
* Устанавливает элемент атрибуции предмета.<br>
* Element (0 - Fire, 1 - Water, 2 - Wind, 3 - Earth, 4 - Holy, 5 - Dark, -1 - None)
* @param element элемент
* @param value
*/
public void setAttributeElement(Element element, int value)
{
attrs.setValue(element, value);
}
/**
* Проверяет, является ли данный инстанс предмета хербом
* @return true если предмет является хербом
*/
public boolean isHerb()
{
if (getTemplate().isHerb())
return true;
return false;
}
public Grade getCrystalType()
{
return template.getCrystalType();
}
@Override
public String getName()
{
return getTemplate().getName();
}
@Override
public void save()
{
_itemsDAO.save(this);
}
@Override
public void update()
{
_itemsDAO.update(this);
}
@Override
public void delete()
{
_itemsDAO.delete(this);
}
@Override
public List<L2GameServerPacket> addPacketList(Player forPlayer, Creature dropper)
{
L2GameServerPacket packet = null;
if (dropper != null)
packet = new DropItem(this, dropper.getObjectId());
else
packet = new SpawnItem(this);
return Collections.singletonList(packet);
}
/**
* Returns the item in String format
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(getTemplate().getItemId());
sb.append(" ");
if (getEnchantLevel() > 0)
{
sb.append("+");
sb.append(getEnchantLevel());
sb.append(" ");
}
sb.append(getTemplate().getName());
if (!getTemplate().getAdditionalName().isEmpty())
{
sb.append(" ");
sb.append("\\").append(getTemplate().getAdditionalName()).append("\\");
}
sb.append(" ");
sb.append("(");
sb.append(getCount());
sb.append(")");
sb.append("[");
sb.append(getObjectId());
sb.append("]");
return sb.toString();
}
@Override
public void setJdbcState(JdbcEntityState state)
{
_state = state;
}
@Override
public JdbcEntityState getJdbcState()
{
return _state;
}
@Override
public boolean isItem()
{
return true;
}
public ItemAttachment getAttachment()
{
return _attachment;
}
public void setAttachment(ItemAttachment attachment)
{
ItemAttachment old = _attachment;
_attachment = attachment;
if (_attachment != null)
_attachment.setItem(this);
if (old != null)
old.setItem(null);
}
public int getAgathionEnergy()
{
return _agathionEnergy;
}
public void setAgathionEnergy(int agathionEnergy)
{
_agathionEnergy = agathionEnergy;
}
public int[] getEnchantOptions()
{
return _enchantOptions;
}
public IntSet getDropPlayers()
{
return _dropPlayers;
}
/**
* sending item stat like pAtk or mDef
* @param stat
* @return
*/
public double getStatFunc(Stats stat)
{
for (FuncTemplate func : template.getAttachedFuncs())
if (func._stat == stat)
return func._value;
return 0.0;
}
/**
* @return
*/
public int getVisualItemId()
{
return visualItemId;
}
public void setVisualItemId(int visualItemId)
{
this.visualItemId = visualItemId;
}
public int getAugmentationMineralId()
{
return _augmentationId;
}
public void setAugmentation(int mineralId, int[] augmentations)
{
_augmentationId = mineralId;
_augmentations = augmentations;
}
public int[] getAugmentations()
{
return _augmentations;
}
}
| 29,784 | 0.698128 | 0.691268 | 1,352 | 20.4571 | 23.710649 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.561391 | false | false |
0
|
b3e3bfaac92e7124e2ec45aa4ba6046c01398ba8
| 36,825,049,605,178 |
de98daad19846833d7d509f09ac2bba15538d8da
|
/src/main/java/de/maxhenkel/miningdimension/Main.java
|
6e1923247eac7e3f599758fb84fa5b85f86b5b80
|
[] |
no_license
|
metzen227/advanced-mining-dimension
|
https://github.com/metzen227/advanced-mining-dimension
|
e10192daa8d40aefe4749095f97a079ffd631caa
|
b1ecff3ad884c10479accb1dfad9b0ac5e9cd643
|
refs/heads/master
| 2022-12-02T09:51:20.595000 | 2020-08-19T16:20:26 | 2020-08-19T16:20:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.maxhenkel.miningdimension;
import de.maxhenkel.corelib.CommonRegistry;
import de.maxhenkel.corelib.config.DynamicConfig;
import de.maxhenkel.miningdimension.block.ModBlocks;
import de.maxhenkel.miningdimension.config.MobConfig;
import de.maxhenkel.miningdimension.config.OreConfig;
import de.maxhenkel.miningdimension.config.ServerConfig;
import de.maxhenkel.miningdimension.dimension.CanyonWorldCarver;
import de.maxhenkel.miningdimension.dimension.CaveWorldCarver;
import de.maxhenkel.miningdimension.dimension.ChunkGeneratorMining;
import de.maxhenkel.miningdimension.dimension.MiningBiome;
import de.maxhenkel.miningdimension.tileentity.TileentityTeleporter;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.carver.WorldCarver;
import net.minecraft.world.gen.feature.ProbabilityConfig;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(Main.MODID)
public class Main {
public static final String MODID = "mining_dimension";
public static final Logger LOGGER = LogManager.getLogger(MODID);
public static CaveWorldCarver CAVE_CARVER;
public static CanyonWorldCarver CANYON_CARVER;
public static TileEntityType<TileentityTeleporter> TELEPORTER_TILEENTITY;
public static MiningBiome MINING_BIOME;
public static final RegistryKey<World> MINING_DIMENSION = RegistryKey.func_240903_a_(Registry.field_239699_ae_, new ResourceLocation(Main.MODID, "mining_dimension"));
public static ServerConfig SERVER_CONFIG;
public static OreConfig ORE_CONFIG;
public static MobConfig MOB_CONFIG;
public Main() {
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(Item.class, this::registerItems);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(Block.class, this::registerBlocks);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(TileEntityType.class, this::registerTileEntities);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(Biome.class, this::registerBiomes);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(WorldCarver.class, this::registerCarver);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
SERVER_CONFIG = CommonRegistry.registerConfig(ModConfig.Type.SERVER, ServerConfig.class, true);
ORE_CONFIG = CommonRegistry.registerDynamicConfig(DynamicConfig.DynamicConfigType.SERVER, MODID, "ores", OreConfig.class);
MOB_CONFIG = CommonRegistry.registerDynamicConfig(DynamicConfig.DynamicConfigType.SERVER, MODID, "mobs", MobConfig.class);
Registry.register(Registry.field_239690_aB_, new ResourceLocation(Main.MODID, "mining"), ChunkGeneratorMining.CODEC);
Registry.register(Registry.field_239690_aB_, new ResourceLocation(Main.MODID, "mining"), ChunkGeneratorMining.CODEC);
}
@SubscribeEvent
public void commonSetup(FMLCommonSetupEvent event) {
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void registerItems(RegistryEvent.Register<Item> event) {
event.getRegistry().registerAll(
ModBlocks.TELEPORTER.toItem()
);
}
@SubscribeEvent
public void registerBlocks(RegistryEvent.Register<Block> event) {
event.getRegistry().registerAll(
ModBlocks.TELEPORTER
);
}
@SubscribeEvent
public void registerTileEntities(RegistryEvent.Register<TileEntityType<?>> event) {
TELEPORTER_TILEENTITY = TileEntityType.Builder.create(TileentityTeleporter::new, ModBlocks.TELEPORTER).build(null);
TELEPORTER_TILEENTITY.setRegistryName(new ResourceLocation(MODID, "teleporter"));
event.getRegistry().register(TELEPORTER_TILEENTITY);
}
@SubscribeEvent
public void registerBiomes(RegistryEvent.Register<Biome> event) {
MINING_BIOME = new MiningBiome();
MINING_BIOME.setRegistryName(new ResourceLocation(Main.MODID, "mining_biome"));
event.getRegistry().register(MINING_BIOME);
}
@SubscribeEvent
public void registerCarver(RegistryEvent.Register<WorldCarver<?>> event) {
CAVE_CARVER = new CaveWorldCarver(ProbabilityConfig.field_236576_b_, 255);
CAVE_CARVER.setRegistryName(new ResourceLocation(Main.MODID, "mining_carver"));
event.getRegistry().register(CAVE_CARVER);
CANYON_CARVER = new CanyonWorldCarver(ProbabilityConfig.field_236576_b_);
CANYON_CARVER.setRegistryName(new ResourceLocation(Main.MODID, "canyon_carver"));
event.getRegistry().register(CANYON_CARVER);
}
}
|
UTF-8
|
Java
| 5,292 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package de.maxhenkel.miningdimension;
import de.maxhenkel.corelib.CommonRegistry;
import de.maxhenkel.corelib.config.DynamicConfig;
import de.maxhenkel.miningdimension.block.ModBlocks;
import de.maxhenkel.miningdimension.config.MobConfig;
import de.maxhenkel.miningdimension.config.OreConfig;
import de.maxhenkel.miningdimension.config.ServerConfig;
import de.maxhenkel.miningdimension.dimension.CanyonWorldCarver;
import de.maxhenkel.miningdimension.dimension.CaveWorldCarver;
import de.maxhenkel.miningdimension.dimension.ChunkGeneratorMining;
import de.maxhenkel.miningdimension.dimension.MiningBiome;
import de.maxhenkel.miningdimension.tileentity.TileentityTeleporter;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.carver.WorldCarver;
import net.minecraft.world.gen.feature.ProbabilityConfig;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(Main.MODID)
public class Main {
public static final String MODID = "mining_dimension";
public static final Logger LOGGER = LogManager.getLogger(MODID);
public static CaveWorldCarver CAVE_CARVER;
public static CanyonWorldCarver CANYON_CARVER;
public static TileEntityType<TileentityTeleporter> TELEPORTER_TILEENTITY;
public static MiningBiome MINING_BIOME;
public static final RegistryKey<World> MINING_DIMENSION = RegistryKey.func_240903_a_(Registry.field_239699_ae_, new ResourceLocation(Main.MODID, "mining_dimension"));
public static ServerConfig SERVER_CONFIG;
public static OreConfig ORE_CONFIG;
public static MobConfig MOB_CONFIG;
public Main() {
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(Item.class, this::registerItems);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(Block.class, this::registerBlocks);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(TileEntityType.class, this::registerTileEntities);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(Biome.class, this::registerBiomes);
FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(WorldCarver.class, this::registerCarver);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
SERVER_CONFIG = CommonRegistry.registerConfig(ModConfig.Type.SERVER, ServerConfig.class, true);
ORE_CONFIG = CommonRegistry.registerDynamicConfig(DynamicConfig.DynamicConfigType.SERVER, MODID, "ores", OreConfig.class);
MOB_CONFIG = CommonRegistry.registerDynamicConfig(DynamicConfig.DynamicConfigType.SERVER, MODID, "mobs", MobConfig.class);
Registry.register(Registry.field_239690_aB_, new ResourceLocation(Main.MODID, "mining"), ChunkGeneratorMining.CODEC);
Registry.register(Registry.field_239690_aB_, new ResourceLocation(Main.MODID, "mining"), ChunkGeneratorMining.CODEC);
}
@SubscribeEvent
public void commonSetup(FMLCommonSetupEvent event) {
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void registerItems(RegistryEvent.Register<Item> event) {
event.getRegistry().registerAll(
ModBlocks.TELEPORTER.toItem()
);
}
@SubscribeEvent
public void registerBlocks(RegistryEvent.Register<Block> event) {
event.getRegistry().registerAll(
ModBlocks.TELEPORTER
);
}
@SubscribeEvent
public void registerTileEntities(RegistryEvent.Register<TileEntityType<?>> event) {
TELEPORTER_TILEENTITY = TileEntityType.Builder.create(TileentityTeleporter::new, ModBlocks.TELEPORTER).build(null);
TELEPORTER_TILEENTITY.setRegistryName(new ResourceLocation(MODID, "teleporter"));
event.getRegistry().register(TELEPORTER_TILEENTITY);
}
@SubscribeEvent
public void registerBiomes(RegistryEvent.Register<Biome> event) {
MINING_BIOME = new MiningBiome();
MINING_BIOME.setRegistryName(new ResourceLocation(Main.MODID, "mining_biome"));
event.getRegistry().register(MINING_BIOME);
}
@SubscribeEvent
public void registerCarver(RegistryEvent.Register<WorldCarver<?>> event) {
CAVE_CARVER = new CaveWorldCarver(ProbabilityConfig.field_236576_b_, 255);
CAVE_CARVER.setRegistryName(new ResourceLocation(Main.MODID, "mining_carver"));
event.getRegistry().register(CAVE_CARVER);
CANYON_CARVER = new CanyonWorldCarver(ProbabilityConfig.field_236576_b_);
CANYON_CARVER.setRegistryName(new ResourceLocation(Main.MODID, "canyon_carver"));
event.getRegistry().register(CANYON_CARVER);
}
}
| 5,292 | 0.775321 | 0.767574 | 111 | 46.684685 | 37.353432 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846847 | false | false |
0
|
5f039e0c0365a1137b3ac31ee613131f91a4c122
| 16,930,761,122,601 |
3a6d8f0f565a00bae6c0cb35cfaf84fcfc8fff66
|
/lab3/Flik/FlikTest.java
|
4eea590779fc39c902a033282bd0228dc4f5c263
|
[] |
no_license
|
datlife/skeleton-sp18
|
https://github.com/datlife/skeleton-sp18
|
3b7f0ac4005c5fcf1c470cb4b6f0ce31f2bcfe79
|
4932daf9d400d61316def7274af2576148b16293
|
refs/heads/master
| 2020-04-17T05:30:54.151000 | 2019-01-18T00:43:01 | 2019-01-18T00:43:01 | 166,282,752 | 0 | 1 | null | true | 2019-01-17T19:20:27 | 2019-01-17T19:20:26 | 2019-01-16T19:17:58 | 2019-01-01T21:28:50 | 3,516 | 0 | 0 | 0 | null | false | null |
import static org.junit.Assert.*;
import org.junit.Test;
public class FlikTest {
/**
* Test if two number is the same
*/
@Test
public void testIsSameNumber() {
assertTrue(Flik.isSameNumber(1, 1));
assertTrue(Flik.isSameNumber(255, 255));
assertTrue(Flik.isSameNumber(128, 128));
}
}
|
UTF-8
|
Java
| 336 |
java
|
FlikTest.java
|
Java
|
[] | null |
[] |
import static org.junit.Assert.*;
import org.junit.Test;
public class FlikTest {
/**
* Test if two number is the same
*/
@Test
public void testIsSameNumber() {
assertTrue(Flik.isSameNumber(1, 1));
assertTrue(Flik.isSameNumber(255, 255));
assertTrue(Flik.isSameNumber(128, 128));
}
}
| 336 | 0.622024 | 0.580357 | 16 | 20 | 17.881556 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
bde4a19bf8d61b6fa91b9ef3fe22c9c9355dbd5a
| 3,375,844,359,697 |
7ca76e699dc0d1e33f645d8990e8736dd8ec9bc9
|
/vn_post/src/main/java/vn_post/mapper/RoleMapper.java
|
d93fd4a84ec08ff8b9beb366ba3a8b96f8e561f8
|
[] |
no_license
|
son98hn/vn_post
|
https://github.com/son98hn/vn_post
|
6f47f256cd77af88b129376f3cd846671a617946
|
2fde4b32615547f3dc321e0d6fb6259fd3f262bc
|
refs/heads/master
| 2023-06-05T19:58:10.373000 | 2021-06-17T13:11:00 | 2021-06-17T13:11:00 | 368,373,881 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package vn_post.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import vn_post.model.RoleModel;
public class RoleMapper implements RowMapper<RoleModel> {
@Override
public RoleModel mapRow(ResultSet resultSet) {
try {
RoleModel role = new RoleModel();
role.setId(resultSet.getLong("id"));
role.setCode(resultSet.getString("code"));
role.setName(resultSet.getString("name"));
return role;
} catch (SQLException e) {
return null;
}
}
}
|
UTF-8
|
Java
| 480 |
java
|
RoleMapper.java
|
Java
|
[] | null |
[] |
package vn_post.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import vn_post.model.RoleModel;
public class RoleMapper implements RowMapper<RoleModel> {
@Override
public RoleModel mapRow(ResultSet resultSet) {
try {
RoleModel role = new RoleModel();
role.setId(resultSet.getLong("id"));
role.setCode(resultSet.getString("code"));
role.setName(resultSet.getString("name"));
return role;
} catch (SQLException e) {
return null;
}
}
}
| 480 | 0.722917 | 0.722917 | 21 | 21.857143 | 17.857334 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.761905 | false | false |
0
|
1e68b0e70a6ffe4eeafb55c4ebf1207a8dc54b37
| 37,194,416,784,512 |
4f1392b7c53a901758b16e24c0de3de3502bc3cb
|
/src/main/java/hbec/app/hospital/service/impl/AskService.java
|
d07af08cd42e027c8709c32fbf4e37653b3fabb9
|
[] |
no_license
|
cw2030/falconiter01
|
https://github.com/cw2030/falconiter01
|
c99aeba84c4bf3af2781486e29deb2207ee497e2
|
6623e63b1330c909ba0dcf9a197d56e5dd7362ec
|
refs/heads/master
| 2021-04-12T02:46:09.779000 | 2018-03-20T11:05:47 | 2018-03-20T11:05:47 | 125,826,668 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package hbec.app.hospital.service.impl;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.xy.platform.commons.annotations.Inject;
import com.xy.platform.commons.exceptions.DbServiceException;
import com.xy.platform.commons.services.IDbService;
import com.xy.platform.commons.utils.Strings;
import hbec.app.hospital.domain.Ask;
import hbec.app.hospital.domain.PayRefundResult;
import hbec.app.hospital.service.IAskService;
public class AskService implements IAskService {
@Inject
private IDbService dbService;
private static Logger logger = LoggerFactory.getLogger("AskService");
@Override
public int save(Ask ask) {
try{
return dbService.insert("ask.insert", ask);
}catch(DbServiceException e){
logger.error("", e.getMessage());
}catch(Exception e){
logger.error("", e);
}
return 0;
}
@Override
public Ask get(long askId) {
// TODO Auto-generated method stub
return null;
}
@Override
public int saveOrder(String askId, String orderNo, int payAmt) {
try{
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("askId", askId);
paramMap.put("orderNo", orderNo);
paramMap.put("orderAmt", payAmt*100);
logger.info("[Order]pay order : {}", paramMap);
return dbService.insert("order.insert", paramMap);
}catch(DbServiceException e){
logger.error("", e.getMessage());
}catch(Exception e){
logger.error("", e);
}
return 0;
}
@Override
public int refund(String askId) {
try{
Map<String,Object> map = dbService.select("order.selectPayStatus", askId);
if(map != null && map.size() == 1){
String refund_order_no = (String)map.get("refund_order_no");
if(Strings.isEmpty(refund_order_no)){
}else{
logger.warn("[Refund]askId:{} is already refund:{}",askId,refund_order_no);
return 0;
}
logger.info("[Refund]askId");
}
RefundService refund = new RefundService();
String orderNo = (String)map.get("order_no");
String refundOrderNo = "R" + System.nanoTime();
int totalAmt = (Integer)map.get("order_amt");
PayRefundResult refundResult = refund.refund(orderNo, "", refundOrderNo, Integer.toString(totalAmt)
, Integer.toString(totalAmt));
if("SUCCESS".equalsIgnoreCase(refundResult.getReturnCode())){
logger.info("[Refund]refund success: ",JSON.toJSONString(refundResult));
return 1;
}
}catch(DbServiceException e){
logger.error("", e.getMessage());
}catch(Exception e){
logger.error("", e);
}
return 0;
}
@Override
public int saveRealOrder(String out_trade_no) {
try{
int askId = dbService.select("ask.getAskId", out_trade_no);
Map<String,Object> param = Maps.newHashMap();
param.put("askId",askId);
return dbService.insert("ask.insertRealOrder", param);
}catch(Exception e){
logger.error("", e);
}
return 0;
}
}
|
UTF-8
|
Java
| 2,952 |
java
|
AskService.java
|
Java
|
[] | null |
[] |
package hbec.app.hospital.service.impl;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.xy.platform.commons.annotations.Inject;
import com.xy.platform.commons.exceptions.DbServiceException;
import com.xy.platform.commons.services.IDbService;
import com.xy.platform.commons.utils.Strings;
import hbec.app.hospital.domain.Ask;
import hbec.app.hospital.domain.PayRefundResult;
import hbec.app.hospital.service.IAskService;
public class AskService implements IAskService {
@Inject
private IDbService dbService;
private static Logger logger = LoggerFactory.getLogger("AskService");
@Override
public int save(Ask ask) {
try{
return dbService.insert("ask.insert", ask);
}catch(DbServiceException e){
logger.error("", e.getMessage());
}catch(Exception e){
logger.error("", e);
}
return 0;
}
@Override
public Ask get(long askId) {
// TODO Auto-generated method stub
return null;
}
@Override
public int saveOrder(String askId, String orderNo, int payAmt) {
try{
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("askId", askId);
paramMap.put("orderNo", orderNo);
paramMap.put("orderAmt", payAmt*100);
logger.info("[Order]pay order : {}", paramMap);
return dbService.insert("order.insert", paramMap);
}catch(DbServiceException e){
logger.error("", e.getMessage());
}catch(Exception e){
logger.error("", e);
}
return 0;
}
@Override
public int refund(String askId) {
try{
Map<String,Object> map = dbService.select("order.selectPayStatus", askId);
if(map != null && map.size() == 1){
String refund_order_no = (String)map.get("refund_order_no");
if(Strings.isEmpty(refund_order_no)){
}else{
logger.warn("[Refund]askId:{} is already refund:{}",askId,refund_order_no);
return 0;
}
logger.info("[Refund]askId");
}
RefundService refund = new RefundService();
String orderNo = (String)map.get("order_no");
String refundOrderNo = "R" + System.nanoTime();
int totalAmt = (Integer)map.get("order_amt");
PayRefundResult refundResult = refund.refund(orderNo, "", refundOrderNo, Integer.toString(totalAmt)
, Integer.toString(totalAmt));
if("SUCCESS".equalsIgnoreCase(refundResult.getReturnCode())){
logger.info("[Refund]refund success: ",JSON.toJSONString(refundResult));
return 1;
}
}catch(DbServiceException e){
logger.error("", e.getMessage());
}catch(Exception e){
logger.error("", e);
}
return 0;
}
@Override
public int saveRealOrder(String out_trade_no) {
try{
int askId = dbService.select("ask.getAskId", out_trade_no);
Map<String,Object> param = Maps.newHashMap();
param.put("askId",askId);
return dbService.insert("ask.insertRealOrder", param);
}catch(Exception e){
logger.error("", e);
}
return 0;
}
}
| 2,952 | 0.695799 | 0.691734 | 110 | 25.836363 | 22.658142 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.527273 | false | false |
0
|
4718c4ff0988a0127bec485f9eab83c4d62189b8
| 37,194,416,785,291 |
ff72eacb53e5fa100c84ab323838b4e0a1881dee
|
/jps-plugin/src/com/eiffel/jps/EiffelTargetType.java
|
271fefd95cee4eac96519df70ab32e69ca6f22b3
|
[
"MIT"
] |
permissive
|
ionagamed/eiffel-idea
|
https://github.com/ionagamed/eiffel-idea
|
37da8ce647708363c5708e1c88c0277af328f3e3
|
bd3945c8637a57b8a9e5ed02d0d724e684c5ab53
|
refs/heads/master
| 2021-09-04T03:44:01.830000 | 2018-01-11T21:30:09 | 2018-01-11T21:30:09 | 103,184,447 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.eiffel.jps;
import com.eiffel.jps.model.JpsEiffelModuleType;
import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.builders.BuildTargetLoader;
import org.jetbrains.jps.builders.ModuleBasedBuildTargetType;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsModel;
import org.jetbrains.jps.model.module.JpsTypedModule;
import java.util.ArrayList;
import java.util.List;
public class EiffelTargetType extends ModuleBasedBuildTargetType<EiffelTarget> {
public static final EiffelTargetType PRODUCTION = new EiffelTargetType("eiffel-production");
protected EiffelTargetType(String typeId) {
super(typeId);
}
@NotNull
@Override
public List<EiffelTarget> computeAllTargets(@NotNull JpsModel model) {
List<EiffelTarget> targets = new ArrayList<>();
for (JpsTypedModule module : model.getProject().getModules(JpsEiffelModuleType.getInstance())) {
targets.add(new EiffelTarget(this, module));
}
return targets;
}
@NotNull
@Override
public BuildTargetLoader<EiffelTarget> createLoader(@NotNull JpsModel model) {
return new BuildTargetLoader<EiffelTarget>() {
@Nullable
@Override
public EiffelTarget createTarget(@NotNull String targetId) {
for (JpsTypedModule module : model.getProject().getModules(JpsEiffelModuleType.getInstance())) {
if (module.getName().equals(targetId)) {
return new EiffelTarget(EiffelTargetType.this, module);
}
}
return null;
}
};
}
}
|
UTF-8
|
Java
| 1,773 |
java
|
EiffelTargetType.java
|
Java
|
[] | null |
[] |
package com.eiffel.jps;
import com.eiffel.jps.model.JpsEiffelModuleType;
import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.builders.BuildTargetLoader;
import org.jetbrains.jps.builders.ModuleBasedBuildTargetType;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsModel;
import org.jetbrains.jps.model.module.JpsTypedModule;
import java.util.ArrayList;
import java.util.List;
public class EiffelTargetType extends ModuleBasedBuildTargetType<EiffelTarget> {
public static final EiffelTargetType PRODUCTION = new EiffelTargetType("eiffel-production");
protected EiffelTargetType(String typeId) {
super(typeId);
}
@NotNull
@Override
public List<EiffelTarget> computeAllTargets(@NotNull JpsModel model) {
List<EiffelTarget> targets = new ArrayList<>();
for (JpsTypedModule module : model.getProject().getModules(JpsEiffelModuleType.getInstance())) {
targets.add(new EiffelTarget(this, module));
}
return targets;
}
@NotNull
@Override
public BuildTargetLoader<EiffelTarget> createLoader(@NotNull JpsModel model) {
return new BuildTargetLoader<EiffelTarget>() {
@Nullable
@Override
public EiffelTarget createTarget(@NotNull String targetId) {
for (JpsTypedModule module : model.getProject().getModules(JpsEiffelModuleType.getInstance())) {
if (module.getName().equals(targetId)) {
return new EiffelTarget(EiffelTargetType.this, module);
}
}
return null;
}
};
}
}
| 1,773 | 0.688663 | 0.688663 | 49 | 35.183674 | 29.945988 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44898 | false | false |
0
|
c4ba5f93dc0155f6ce96c92ba0279829583fe9f0
| 1,786,706,442,296 |
adbc08836d71efe291cff0d31d1b45f2a0c61b6a
|
/oscm-billing-unittests/javasrc-it/org/oscm/billingservice/business/calculation/share/SharesCalculatorBeanCutOffDayIT.java
|
f4d35358e6afdb9710afdd940e14e7beb1d2fef7
|
[
"Apache-2.0",
"EPL-1.0",
"BSD-3-Clause",
"W3C",
"LGPL-3.0-only",
"CPL-1.0",
"CDDL-1.1",
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-or-later",
"CDDL-1.0",
"Apache-1.1",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"W3C-19980720",
"LGPL-2.1-only",
"PostgreSQL"
] |
permissive
|
servicecatalog/development
|
https://github.com/servicecatalog/development
|
6f43905f4ee7a8e32926df0c3aeac26a096b5982
|
c8e4ab513993fc635c97dc5d2639c09a84a64b31
|
refs/heads/master
| 2021-05-24T03:22:18.823000 | 2020-10-20T07:43:14 | 2020-10-20T07:43:14 | 43,540,339 | 57 | 41 |
Apache-2.0
| false | 2020-10-20T07:43:15 | 2015-10-02T07:20:22 | 2020-02-21T21:48:02 | 2020-10-20T07:43:14 | 82,615 | 38 | 27 | 117 |
Java
| false | false |
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
*
* Creation Date: 29.08.2012
*
*
*******************************************************************************/
package org.oscm.billingservice.business.calculation.share;
import static org.oscm.test.matchers.JavaMatchers.hasOneItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Callable;
import javax.persistence.Query;
import javax.xml.xpath.XPathExpressionException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.oscm.billingservice.business.model.suppliershare.OfferingType;
import org.oscm.billingservice.dao.BillingDataRetrievalServiceBean;
import org.oscm.billingservice.dao.SharesDataRetrievalServiceBean;
import org.oscm.converter.XMLConverter;
import org.oscm.dataservice.bean.DataServiceBean;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.BillingSharesResult;
import org.oscm.domobjects.Marketplace;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.Product;
import org.oscm.domobjects.Subscription;
import org.oscm.interceptor.DateFactory;
import org.oscm.test.EJBTestBase;
import org.oscm.test.data.BillingResults;
import org.oscm.test.data.CatalogEntries;
import org.oscm.test.data.Marketplaces;
import org.oscm.test.data.Organizations;
import org.oscm.test.data.Products;
import org.oscm.test.data.Subscriptions;
import org.oscm.test.ejb.TestContainer;
import org.oscm.internal.types.enumtypes.BillingSharesResultType;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
/**
* Integration test for the share calculations with cut-off day
*
* @author stavreva
*/
public class SharesCalculatorBeanCutOffDayIT extends EJBTestBase {
private static final long DAY_MILLIS = 86400000L;
private static final long PERIOD_START = getStartMonth(
System.currentTimeMillis(), 1);
private static final long PERIOD_END = getEndMonth(
System.currentTimeMillis(), 1);
private static final long PERIOD_START_NO_RESULTS = getStartMonth(
System.currentTimeMillis(), 2);
private static final long PERIOD_END_NO_RESULTS = getEndMonth(
System.currentTimeMillis(), 2);
private static final int NUM_BILLING_RESULTS = 10;
private static final BigDecimal NET_REVENUE = BigDecimal.valueOf(50);
private static final BigDecimal GROSS_REVENUE = BigDecimal.valueOf(23.4);
private static final BigDecimal REVENUE_SHARE_PERCENT = BigDecimal.TEN;
private static final BigDecimal REVENUE_SHARE = BigDecimal.valueOf(5);
private static final BigDecimal MP_REVENUE_SHARE = BigDecimal.valueOf(1);
private static final BigDecimal MP_BROKER_REVENUE_SHARE = BigDecimal.ONE;
private static final BigDecimal MP_RESELLER_REVENUE_SHARE = BigDecimal.ONE;
private static final List<String> SupplierResult_RevenueShareDetails_DIRECT = Arrays
.asList(null, null, null, null, "0.50", "1.00", "50.00", "49.50");
private static final List<String> SupplierResult_RevenueShareDetails_BROKER = Arrays
.asList("5.00", "10.00", null, null, "0.50", "1.00", "50.00",
"44.50");
private static final List<String> SupplierResult_RevenueShareDetails_RESELLER = Arrays
.asList(null, null, "5.00", "10.00", "0.50", "1.00", "50.00",
"44.50");
private static final List<String> SupplierResult_RevenuePerMarketplace = Arrays
.asList("1385.00", "50.00", "50.00", "15.00", "1500.00");
private static final List<String> MarketplaceOwnerResult_RevenueShareDetails_DIRECT = Arrays
.asList("50.00", "1.00", "0.50", "0.00", "0.00", "0.50", "49.50",
"0.00", "0.00", "0.00");
private static final List<String> MarketplaceOwnerResult_RevenueShareDetails_BROKER = Arrays
.asList("50.00", "1.00", "0.50", "0.00", "0.00", "0.50", "44.50",
"10.00", "5.00", "5.00");
private static final List<String> MarketplaceOwnerResult_RevenueShareDetails_RESELLER = Arrays
.asList("50.00", "1.00", "0.50", "0.00", "0.00", "0.50", "44.50",
"10.00", "5.00", "5.00");
private DataService ds;
private Organization supplier;
private Organization customer;
private Organization broker;
private Organization reseller;
private Marketplace mp;
private Product product;
private SharesCalculatorLocal calculator;
private long transactionTime;
@Override
protected void setup(TestContainer container) throws Exception {
container.login("1");
container.addBean(new DataServiceBean());
ds = container.get(DataService.class);
container.addBean(new SharesDataRetrievalServiceBean());
container.addBean(new BillingDataRetrievalServiceBean());
container.addBean(new SharesCalculatorBean());
calculator = container.get(SharesCalculatorLocal.class);
givenTransactionTime();
}
@Test
public void performBrokerSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performBrokerSharesCalculationRun(PERIOD_START, PERIOD_END);
// then
String xmlAsString = loadResultXML(broker,
BillingSharesResultType.BROKER, PERIOD_START, PERIOD_END);
verify_ResaleOrganizationResult(xmlAsString, supplier, broker,
OrganizationRoleType.BROKER);
verifyTransactionTimeSet();
}
@Test
public void performBrokerSharesCalculationRun_Empty() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performBrokerSharesCalculationRun(PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(broker.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.BROKER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(broker,
BillingSharesResultType.BROKER, PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.BROKER));
}
@Test
public void performResellerSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator
.performResellerSharesCalculationRun(PERIOD_START, PERIOD_END);
// then
String xmlAsString = loadResultXML(reseller,
BillingSharesResultType.RESELLER, PERIOD_START, PERIOD_END);
verify_ResaleOrganizationResult(xmlAsString, supplier, reseller,
OrganizationRoleType.RESELLER);
}
@Test
public void performResellerSharesCalculationRun_Empty() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performResellerSharesCalculationRun(PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(reseller.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.RESELLER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(reseller,
BillingSharesResultType.RESELLER, PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.RESELLER));
}
@Test
public void performSupplierSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator
.performSupplierSharesCalculationRun(PERIOD_START, PERIOD_END);
// then
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.SUPPLIER, PERIOD_START, PERIOD_END);
verify_SupplierResult(xmlAsString);
}
@Test
public void performSupplierSharesCalculationRun_Empty() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performSupplierSharesCalculationRun(PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(supplier.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.SUPPLIER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.SUPPLIER, PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.SUPPLIER));
}
@Test
public void performMarketplacesSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performMarketplacesSharesCalculationRun(PERIOD_START,
PERIOD_END);
// then
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.MARKETPLACE_OWNER, PERIOD_START,
PERIOD_END);
verify_MarketplaceOwnerResult(xmlAsString);
}
@Test
public void performMarketplacesSharesCalculationRun_Empty()
throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performMarketplacesSharesCalculationRun(
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(supplier.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.MARKETPLACE_OWNER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.MARKETPLACE_OWNER,
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.MARKETPLACE_OWNER));
}
private void createSupplierProductAndSubscriptions(
final int numBillingResults) throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
supplier = Organizations.createOrganization(ds, "supplierId",
OrganizationRoleType.SUPPLIER,
OrganizationRoleType.MARKETPLACE_OWNER);
customer = Organizations.createOrganization(ds, "customerId",
OrganizationRoleType.CUSTOMER);
Organization customer1 = Organizations.createOrganization(ds,
"customerId1", OrganizationRoleType.CUSTOMER);
mp = Marketplaces.createGlobalMarketplace(supplier, "mp_"
+ supplier.getOrganizationId(), ds, MP_REVENUE_SHARE,
MP_BROKER_REVENUE_SHARE, MP_RESELLER_REVENUE_SHARE);
int num = numBillingResults;
for (int i = 0; i < num; i++) {
long billingPeriodStart = PERIOD_START - i * DAY_MILLIS;
long billingPeriodEnd = PERIOD_END - i * DAY_MILLIS;
int cutOffDay = getCutOffDay(billingPeriodStart);
if (cutOffDay > 28) {
num++;
continue;
}
product = Products.createProduct(supplier, "techProd",
true, "product_supplier_" + i, "priceModelId_" + i,
ds);
CatalogEntries.create(ds, mp, product);
Subscription sub = Subscriptions.createSubscription(ds,
customer.getOrganizationId(), product, mp,
cutOffDay);
BillingResults.createBillingResult(ds, sub,
supplier.getKey(), supplier.getKey(),
billingPeriodStart, billingPeriodEnd, NET_REVENUE,
GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\""
+ NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
}
Subscription sub = Subscriptions.createSubscription(ds,
customer1.getOrganizationId(), product, mp, 1);
BillingResults.createBillingResult(ds, sub, supplier.getKey(),
supplier.getKey(),
getStartMonth(System.currentTimeMillis(), 3),
getEndMonth(System.currentTimeMillis(), 3),
NET_REVENUE, GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\"" + NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
return null;
}
});
}
private void givenBillingResult() throws Exception {
createSupplierProductAndSubscriptions(NUM_BILLING_RESULTS);
createBrokerProductAndSubscriptions(NUM_BILLING_RESULTS);
createResellerProductAndSubscriptions(NUM_BILLING_RESULTS);
}
private void givenTransactionTime() {
transactionTime = DateFactory.getInstance().getTransactionTime();
}
private void verifyTransactionTimeSet() {
assertEquals(Boolean.FALSE, Boolean.valueOf(transactionTime == 0));
assertEquals("Transaction time not set.", Boolean.FALSE,
Boolean.valueOf(transactionTime == DateFactory.getInstance()
.getTransactionTime()));
}
@SuppressWarnings({ "unchecked", "boxing" })
private List<BillingSharesResult> loadSharesResult(final long orgKey,
final long fromDate, final long toDate,
final BillingSharesResultType type) throws Exception {
return runTX(new Callable<List<BillingSharesResult>>() {
@Override
public List<BillingSharesResult> call() {
Query query = ds
.createNamedQuery("BillingSharesResult.getSharesResultForOrganization");
query.setParameter("orgKey", orgKey);
query.setParameter("resultType", type);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<BillingSharesResult> result = query.getResultList();
return result;
}
});
}
private void createBrokerProductAndSubscriptions(final int numBillingResults)
throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
broker = Organizations.createOrganization(ds,
OrganizationRoleType.BROKER.name(),
OrganizationRoleType.BROKER);
int num = numBillingResults;
for (int i = 0; i < num; i++) {
long billingPeriodStart = PERIOD_START - i * DAY_MILLIS;
long billingPeriodEnd = PERIOD_END - i * DAY_MILLIS;
int cutOffDay = getCutOffDay(billingPeriodStart);
if (cutOffDay > 28) {
num++;
continue;
}
Product resaleCopy = Products.createProductResaleCopy(
product, broker, ds);
resaleCopy.setProductId("resaleProd_" + i
+ OrganizationRoleType.BROKER.name());
// publish to marketplace
CatalogEntries.createWithBrokerShare(ds, mp, resaleCopy,
REVENUE_SHARE_PERCENT);
// subscribe to resale copy
Subscription sub = Subscriptions.createSubscription(ds,
customer.getOrganizationId(), resaleCopy, mp,
cutOffDay);
BillingResults.createBillingResult(ds, sub,
broker.getKey(), broker.getKey(),
billingPeriodStart, billingPeriodEnd, NET_REVENUE,
GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\""
+ NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
}
return null;
}
});
}
private void createResellerProductAndSubscriptions(
final int numBillingResults) throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
reseller = Organizations.createOrganization(ds,
OrganizationRoleType.RESELLER.name(),
OrganizationRoleType.RESELLER);
int num = numBillingResults;
for (int i = 0; i < num; i++) {
long billingPeriodStart = PERIOD_START - i * DAY_MILLIS;
long billingPeriodEnd = PERIOD_END - i * DAY_MILLIS;
int cutOffDay = getCutOffDay(billingPeriodStart);
if (cutOffDay > 28) {
num++;
continue;
}
Product resaleCopy = Products.createProductResaleCopy(
product, reseller, ds);
resaleCopy.setProductId("resaleProd_" + i
+ OrganizationRoleType.RESELLER.name());
// publish to marketplace
CatalogEntries.createWithResellerShare(ds, mp, resaleCopy,
REVENUE_SHARE_PERCENT);
// subscribe to resale copy
Subscription sub = Subscriptions.createSubscription(ds,
customer.getOrganizationId(), resaleCopy, mp,
cutOffDay);
BillingResults.createBillingResult(ds, sub,
reseller.getKey(), reseller.getKey(),
billingPeriodStart, billingPeriodEnd, NET_REVENUE,
GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\""
+ NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
}
return null;
}
});
}
private void verify_ResaleOrganizationResult(String xmlAsString,
Organization supplier, Organization org, OrganizationRoleType role)
throws Exception {
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
String roleString = getRoleString(role);
OfferingType offerType = getOfferingType(role);
assertNotNull(roleString);
assertNotNull(offerType);
verify_RootNode(xml, org, roleString);
verify_Period(xml, roleString);
verify_Currency(xml, roleString);
verify_Supplier(xml, supplier, roleString);
verify_ResaleResult_Service(xml, NUM_BILLING_RESULTS, roleString);
verify_ServiceRevenue(xml, roleString);
verify_ResaleOrganization_RevenuePerSupplier(xml, roleString);
verify_ResaleOrganization_Revenue(xml, roleString);
}
private void verify_SupplierResult(String xmlAsString) throws Exception {
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
String roleString = getRoleString(OrganizationRoleType.SUPPLIER);
verify_RootNode(xml, supplier, roleString);
verify_Period(xml, roleString);
verify_Currency(xml, roleString);
verify_Marketplace(xml, mp, roleString);
verify_SupplierResult_Service(xml, null, OfferingType.DIRECT,
roleString);
verify_SupplierResult_Service(xml, broker, OfferingType.BROKER,
roleString);
verify_SupplierResult_Service(xml, reseller, OfferingType.RESELLER,
roleString);
}
private void verify_MarketplaceOwnerResult(String xmlAsString)
throws Exception {
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
String roleString = getRoleString(OrganizationRoleType.MARKETPLACE_OWNER);
verify_RootNode(xml, supplier, roleString);
verify_Period(xml, roleString);
verify_Currency(xml, roleString);
verify_Marketplace(xml, mp, roleString);
verify_MarketplaceOwnerResult_Service(xml, null, OfferingType.DIRECT,
roleString);
verify_MarketplaceOwnerResult_Service(xml, broker, OfferingType.BROKER,
roleString);
verify_MarketplaceOwnerResult_Service(xml, reseller,
OfferingType.RESELLER, roleString);
verify_RevenuesOverAllMarketplaces(xml);
}
private void verify_RootNode(Document xml, Organization org,
String roleString) throws XPathExpressionException {
Node rootNode = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult");
assertEquals(org.getKey(),
XMLConverter.getLongAttValue(rootNode, "organizationKey"));
assertEquals(org.getOrganizationId(),
XMLConverter.getStringAttValue(rootNode, "organizationId"));
}
private void verify_Period(Document xml, String roleString)
throws XPathExpressionException {
Node period = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Period");
assertEquals(PERIOD_START,
XMLConverter.getLongAttValue(period, "startDate"));
assertEquals(PERIOD_END,
XMLConverter.getLongAttValue(period, "endDate"));
}
private void verify_Currency(Document xml, String roleString)
throws XPathExpressionException {
Node currency = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Currency");
assertEquals("EUR", XMLConverter.getStringAttValue(currency, "id"));
}
private void verify_Empty(Document xml, String roleString)
throws XPathExpressionException {
NodeList currency = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString + "RevenueShareResult/Currency");
assertEquals(0, currency.getLength());
}
private void verify_Supplier(Document xml, Organization supplier,
String roleString) throws XPathExpressionException {
Node organizationData = XMLConverter.getNodeByXPath(xml, "/"
+ roleString
+ "RevenueShareResult/Currency/Supplier/OrganizationData");
assertEquals(supplier.getKey(),
XMLConverter.getLongAttValue(organizationData, "key"));
}
private void verify_ResaleOrganization(Node service, Organization resaleOrg) {
String model = XMLConverter.getStringAttValue(service, "model");
String resaleRole = null;
if (OfferingType.BROKER.name().equals(model)) {
resaleRole = "Broker";
} else if (OfferingType.RESELLER.name().equals(model)) {
resaleRole = "Reseller";
}
assertNotNull(resaleRole);
Node org = XMLConverter.getLastChildNode(service, resaleRole);
Node organizationData = XMLConverter.getLastChildNode(org,
"OrganizationData");
assertEquals(resaleOrg.getKey(),
XMLConverter.getLongAttValue(organizationData, "key"));
}
private void verify_ServiceRevenue(Document xml, String roleString)
throws XPathExpressionException {
Node serviceRevenue = XMLConverter
.getNodeByXPath(
xml,
"/"
+ roleString
+ "RevenueShareResult/Currency/Supplier/Service/ServiceRevenue");
assertEquals(
REVENUE_SHARE.intValue() + ".00",
XMLConverter.getStringAttValue(serviceRevenue,
roleString.toLowerCase() + "Revenue"));
assertEquals(
REVENUE_SHARE_PERCENT.intValue() + ".00",
XMLConverter.getStringAttValue(serviceRevenue,
roleString.toLowerCase() + "RevenueSharePercentage"));
assertEquals(REVENUE_SHARE.intValue() * NUM_BILLING_RESULTS + ".00",
XMLConverter.getStringAttValue(serviceRevenue, "totalAmount"));
}
private void verify_SupplierResult_RevenueShareDetails(Node service) {
String model = XMLConverter.getStringAttValue(service, "model");
List<String> expected = new ArrayList<String>();
if (OfferingType.DIRECT.name().equals(model)) {
expected = SupplierResult_RevenueShareDetails_DIRECT;
} else if (OfferingType.BROKER.name().equals(model)) {
expected = SupplierResult_RevenueShareDetails_BROKER;
} else if (OfferingType.RESELLER.name().equals(model)) {
expected = SupplierResult_RevenueShareDetails_RESELLER;
}
assertEquals(8, expected.size());
Node revenueShareDetails = XMLConverter.getLastChildNode(service,
"RevenueShareDetails");
assertEquals(expected.get(0), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenue"));
assertEquals(expected.get(1), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenueSharePercentage"));
assertEquals(expected.get(2), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenue"));
assertEquals(expected.get(3), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenueSharePercentage"));
assertEquals(expected.get(4), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenue"));
assertEquals(expected.get(5), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenueSharePercentage"));
assertEquals(expected.get(6), XMLConverter.getStringAttValue(
revenueShareDetails, "serviceRevenue"));
assertEquals(expected.get(7), XMLConverter.getStringAttValue(
revenueShareDetails, "amountForSupplier"));
}
private void verify_MarketplaceOwnerResult_RevenueShareDetails(
Node service, OfferingType type) {
String model = XMLConverter.getStringAttValue(service, "model");
List<String> expected = new ArrayList<String>();
if (OfferingType.DIRECT.name().equals(model)) {
expected = MarketplaceOwnerResult_RevenueShareDetails_DIRECT;
} else if (OfferingType.BROKER.name().equals(model)) {
expected = MarketplaceOwnerResult_RevenueShareDetails_BROKER;
} else if (OfferingType.RESELLER.name().equals(model)) {
expected = MarketplaceOwnerResult_RevenueShareDetails_RESELLER;
}
assertEquals(NUM_BILLING_RESULTS, expected.size());
Node revenueShareDetails = XMLConverter.getLastChildNode(service,
"RevenueShareDetails");
assertEquals(expected.get(0), XMLConverter.getStringAttValue(
revenueShareDetails, "serviceRevenue"));
assertEquals(expected.get(1), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenueSharePercentage"));
assertEquals(expected.get(2), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenue"));
assertEquals(expected.get(6), XMLConverter.getStringAttValue(
revenueShareDetails, "amountForSupplier"));
if (OfferingType.BROKER.equals(type)) {
assertEquals(expected.get(7), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenueSharePercentage"));
assertEquals(expected.get(8), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenue"));
} else if (OfferingType.RESELLER.equals(type)) {
assertEquals(expected.get(7), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenueSharePercentage"));
assertEquals(expected.get(8), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenue"));
}
}
private void verify_ResaleOrganization_RevenuePerSupplier(Document xml,
String roleString) throws XPathExpressionException {
Node resaleRevenuePerSupplier = XMLConverter.getNodeByXPath(xml, "/"
+ roleString + "RevenueShareResult/Currency/Supplier/"
+ roleString + "RevenuePerSupplier");
assertEquals(REVENUE_SHARE.intValue() * NUM_BILLING_RESULTS + ".00",
XMLConverter.getStringAttValue(resaleRevenuePerSupplier,
"amount"));
}
private void verify_ResaleOrganization_Revenue(Document xml,
String roleString) throws XPathExpressionException {
Node revenue = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Currency/" + roleString + "Revenue");
assertEquals(REVENUE_SHARE.intValue() * NUM_BILLING_RESULTS + ".00",
XMLConverter.getStringAttValue(revenue, "amount"));
}
private void verify_Marketplace(Document xml, Marketplace mp,
String roleString) throws XPathExpressionException {
Node marketplace = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Currency/Marketplace");
assertEquals(mp.getMarketplaceId(),
XMLConverter.getStringAttValue(marketplace, "id"));
if (roleString.equals("Supplier")) {
verify_SupplierResult_MarketplaceRevenue(marketplace);
} else {
Node revenue = XMLConverter.getLastChildNode(marketplace,
"RevenuesPerMarketplace");
verify_RevenuesPerMarketplace_Suppliers(revenue);
verify_RevenuesPerMarketplace_Brokers(revenue);
verify_RevenuesPerMarketplace_Resellers(revenue);
}
}
private void verify_RevenuesPerMarketplace_Suppliers(Node revenue) {
Node suppliers = XMLConverter.getLastChildNode(revenue, "Suppliers");
Node org = XMLConverter.getLastChildNode(suppliers, "Organization");
assertEquals(supplier.getOrganizationId(),
XMLConverter.getStringAttValue(org, "identifier"));
assertEquals("1385.00", XMLConverter.getStringAttValue(org, "amount"));
}
private void verify_RevenuesPerMarketplace_Brokers(Node revenue) {
Node brokers = XMLConverter.getLastChildNode(revenue, "Brokers");
Node org = XMLConverter.getLastChildNode(brokers, "Organization");
assertEquals(broker.getOrganizationId(),
XMLConverter.getStringAttValue(org, "identifier"));
assertEquals("50.00", XMLConverter.getStringAttValue(org, "amount"));
}
private void verify_RevenuesPerMarketplace_Resellers(Node revenue) {
Node resellers = XMLConverter.getLastChildNode(revenue, "Resellers");
Node org = XMLConverter.getLastChildNode(resellers, "Organization");
assertEquals(reseller.getOrganizationId(),
XMLConverter.getStringAttValue(org, "identifier"));
assertEquals("50.00", XMLConverter.getStringAttValue(org, "amount"));
}
private void verify_RevenuesOverAllMarketplaces(Document xml)
throws XPathExpressionException {
Node allMarketplaces = XMLConverter
.getNodeByXPath(xml,
"/MarketplaceOwnerRevenueShareResult/Currency/RevenuesOverAllMarketplaces");
verify_RevenuesPerMarketplace_Suppliers(allMarketplaces);
verify_RevenuesPerMarketplace_Brokers(allMarketplaces);
verify_RevenuesPerMarketplace_Resellers(allMarketplaces);
}
private void verify_SupplierResult_MarketplaceRevenue(Node mp) {
Node revenuePerMp = XMLConverter.getLastChildNode(mp,
"RevenuePerMarketplace");
assertEquals(SupplierResult_RevenuePerMarketplace.get(0),
XMLConverter.getStringAttValue(revenuePerMp, "overallRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(1),
XMLConverter.getStringAttValue(revenuePerMp, "brokerRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(2),
XMLConverter.getStringAttValue(revenuePerMp, "resellerRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(3),
XMLConverter.getStringAttValue(revenuePerMp,
"marketplaceRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(4),
XMLConverter.getStringAttValue(revenuePerMp, "serviceRevenue"));
}
private void verify_ResaleResult_Service(Document xml, int numServices,
String roleString) throws XPathExpressionException {
NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString + "RevenueShareResult/Currency/Supplier/Service");
assertEquals(numServices, services.getLength());
}
private void verify_SupplierResult_Service(Document xml,
Organization resaleOrg, OfferingType type, String roleString)
throws XPathExpressionException {
NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString
+ "RevenueShareResult/Currency/Marketplace/Service");
for (int i = 0; i < services.getLength(); i++) {
String model = XMLConverter.getStringAttValue(services.item(i),
"model");
if (type.name().equals(model)) {
verify_SupplierResult_RevenueShareDetails(services.item(i));
if (resaleOrg != null) {
verify_ResaleOrganization(services.item(i), resaleOrg);
}
}
}
}
private void verify_MarketplaceOwnerResult_Service(Document xml,
Organization resaleOrg, OfferingType type, String roleString)
throws XPathExpressionException {
NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString
+ "RevenueShareResult/Currency/Marketplace/Service");
for (int i = 0; i < services.getLength(); i++) {
String model = XMLConverter.getStringAttValue(services.item(i),
"model");
if (type.name().equals(model)) {
verify_MarketplaceOwnerResult_RevenueShareDetails(
services.item(i), type);
if (resaleOrg != null) {
verify_ResaleOrganization(services.item(i), resaleOrg);
}
}
}
}
private String loadResultXML(Organization org,
BillingSharesResultType role, long startPeriod, long endPeriod)
throws Exception {
List<BillingSharesResult> result = loadSharesResult(org.getKey(),
startPeriod, endPeriod, role);
String xmlAsString = result.get(0).getResultXML();
System.out.println(xmlAsString);
return xmlAsString;
}
private String getRoleString(OrganizationRoleType role) {
if (OrganizationRoleType.BROKER.equals(role)) {
return "Broker";
}
if (OrganizationRoleType.RESELLER.equals(role)) {
return "Reseller";
}
if (OrganizationRoleType.SUPPLIER.equals(role)) {
return "Supplier";
}
if (OrganizationRoleType.MARKETPLACE_OWNER.equals(role)) {
return "MarketplaceOwner";
}
return null;
}
private OfferingType getOfferingType(OrganizationRoleType role) {
if (OrganizationRoleType.BROKER.equals(role)) {
return OfferingType.BROKER;
}
if (OrganizationRoleType.RESELLER.equals(role)) {
return OfferingType.RESELLER;
}
if (OrganizationRoleType.SUPPLIER.equals(role)) {
return OfferingType.DIRECT;
}
return null;
}
private static long getStartMonth(long baseTime, int numMonths) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(baseTime);
cal.add(Calendar.MONTH, numMonths);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
private static long getEndMonth(long baseTime, int numMonths) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getStartMonth(baseTime, numMonths));
cal.add(Calendar.MONTH, 1);
return cal.getTimeInMillis();
}
private int getCutOffDay(long baseTime) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(baseTime);
return cal.get(Calendar.DAY_OF_MONTH);
}
}
|
UTF-8
|
Java
| 39,723 |
java
|
SharesCalculatorBeanCutOffDayIT.java
|
Java
|
[
{
"context": "share calculations with cut-off day\n * \n * @author stavreva\n */\npublic class SharesCalculatorBeanCutOffDayIT ",
"end": 2529,
"score": 0.9969953894615173,
"start": 2521,
"tag": "USERNAME",
"value": "stavreva"
}
] | null |
[] |
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
*
* Creation Date: 29.08.2012
*
*
*******************************************************************************/
package org.oscm.billingservice.business.calculation.share;
import static org.oscm.test.matchers.JavaMatchers.hasOneItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Callable;
import javax.persistence.Query;
import javax.xml.xpath.XPathExpressionException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.oscm.billingservice.business.model.suppliershare.OfferingType;
import org.oscm.billingservice.dao.BillingDataRetrievalServiceBean;
import org.oscm.billingservice.dao.SharesDataRetrievalServiceBean;
import org.oscm.converter.XMLConverter;
import org.oscm.dataservice.bean.DataServiceBean;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.BillingSharesResult;
import org.oscm.domobjects.Marketplace;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.Product;
import org.oscm.domobjects.Subscription;
import org.oscm.interceptor.DateFactory;
import org.oscm.test.EJBTestBase;
import org.oscm.test.data.BillingResults;
import org.oscm.test.data.CatalogEntries;
import org.oscm.test.data.Marketplaces;
import org.oscm.test.data.Organizations;
import org.oscm.test.data.Products;
import org.oscm.test.data.Subscriptions;
import org.oscm.test.ejb.TestContainer;
import org.oscm.internal.types.enumtypes.BillingSharesResultType;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
/**
* Integration test for the share calculations with cut-off day
*
* @author stavreva
*/
public class SharesCalculatorBeanCutOffDayIT extends EJBTestBase {
private static final long DAY_MILLIS = 86400000L;
private static final long PERIOD_START = getStartMonth(
System.currentTimeMillis(), 1);
private static final long PERIOD_END = getEndMonth(
System.currentTimeMillis(), 1);
private static final long PERIOD_START_NO_RESULTS = getStartMonth(
System.currentTimeMillis(), 2);
private static final long PERIOD_END_NO_RESULTS = getEndMonth(
System.currentTimeMillis(), 2);
private static final int NUM_BILLING_RESULTS = 10;
private static final BigDecimal NET_REVENUE = BigDecimal.valueOf(50);
private static final BigDecimal GROSS_REVENUE = BigDecimal.valueOf(23.4);
private static final BigDecimal REVENUE_SHARE_PERCENT = BigDecimal.TEN;
private static final BigDecimal REVENUE_SHARE = BigDecimal.valueOf(5);
private static final BigDecimal MP_REVENUE_SHARE = BigDecimal.valueOf(1);
private static final BigDecimal MP_BROKER_REVENUE_SHARE = BigDecimal.ONE;
private static final BigDecimal MP_RESELLER_REVENUE_SHARE = BigDecimal.ONE;
private static final List<String> SupplierResult_RevenueShareDetails_DIRECT = Arrays
.asList(null, null, null, null, "0.50", "1.00", "50.00", "49.50");
private static final List<String> SupplierResult_RevenueShareDetails_BROKER = Arrays
.asList("5.00", "10.00", null, null, "0.50", "1.00", "50.00",
"44.50");
private static final List<String> SupplierResult_RevenueShareDetails_RESELLER = Arrays
.asList(null, null, "5.00", "10.00", "0.50", "1.00", "50.00",
"44.50");
private static final List<String> SupplierResult_RevenuePerMarketplace = Arrays
.asList("1385.00", "50.00", "50.00", "15.00", "1500.00");
private static final List<String> MarketplaceOwnerResult_RevenueShareDetails_DIRECT = Arrays
.asList("50.00", "1.00", "0.50", "0.00", "0.00", "0.50", "49.50",
"0.00", "0.00", "0.00");
private static final List<String> MarketplaceOwnerResult_RevenueShareDetails_BROKER = Arrays
.asList("50.00", "1.00", "0.50", "0.00", "0.00", "0.50", "44.50",
"10.00", "5.00", "5.00");
private static final List<String> MarketplaceOwnerResult_RevenueShareDetails_RESELLER = Arrays
.asList("50.00", "1.00", "0.50", "0.00", "0.00", "0.50", "44.50",
"10.00", "5.00", "5.00");
private DataService ds;
private Organization supplier;
private Organization customer;
private Organization broker;
private Organization reseller;
private Marketplace mp;
private Product product;
private SharesCalculatorLocal calculator;
private long transactionTime;
@Override
protected void setup(TestContainer container) throws Exception {
container.login("1");
container.addBean(new DataServiceBean());
ds = container.get(DataService.class);
container.addBean(new SharesDataRetrievalServiceBean());
container.addBean(new BillingDataRetrievalServiceBean());
container.addBean(new SharesCalculatorBean());
calculator = container.get(SharesCalculatorLocal.class);
givenTransactionTime();
}
@Test
public void performBrokerSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performBrokerSharesCalculationRun(PERIOD_START, PERIOD_END);
// then
String xmlAsString = loadResultXML(broker,
BillingSharesResultType.BROKER, PERIOD_START, PERIOD_END);
verify_ResaleOrganizationResult(xmlAsString, supplier, broker,
OrganizationRoleType.BROKER);
verifyTransactionTimeSet();
}
@Test
public void performBrokerSharesCalculationRun_Empty() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performBrokerSharesCalculationRun(PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(broker.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.BROKER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(broker,
BillingSharesResultType.BROKER, PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.BROKER));
}
@Test
public void performResellerSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator
.performResellerSharesCalculationRun(PERIOD_START, PERIOD_END);
// then
String xmlAsString = loadResultXML(reseller,
BillingSharesResultType.RESELLER, PERIOD_START, PERIOD_END);
verify_ResaleOrganizationResult(xmlAsString, supplier, reseller,
OrganizationRoleType.RESELLER);
}
@Test
public void performResellerSharesCalculationRun_Empty() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performResellerSharesCalculationRun(PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(reseller.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.RESELLER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(reseller,
BillingSharesResultType.RESELLER, PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.RESELLER));
}
@Test
public void performSupplierSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator
.performSupplierSharesCalculationRun(PERIOD_START, PERIOD_END);
// then
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.SUPPLIER, PERIOD_START, PERIOD_END);
verify_SupplierResult(xmlAsString);
}
@Test
public void performSupplierSharesCalculationRun_Empty() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performSupplierSharesCalculationRun(PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(supplier.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.SUPPLIER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.SUPPLIER, PERIOD_START_NO_RESULTS,
PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.SUPPLIER));
}
@Test
public void performMarketplacesSharesCalculationRun() throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performMarketplacesSharesCalculationRun(PERIOD_START,
PERIOD_END);
// then
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.MARKETPLACE_OWNER, PERIOD_START,
PERIOD_END);
verify_MarketplaceOwnerResult(xmlAsString);
}
@Test
public void performMarketplacesSharesCalculationRun_Empty()
throws Exception {
// given a billing results for products of vendors that are published
// and subscribed
givenBillingResult();
// when
calculator.performMarketplacesSharesCalculationRun(
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS);
// then
List<BillingSharesResult> result = loadSharesResult(supplier.getKey(),
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS,
BillingSharesResultType.MARKETPLACE_OWNER);
assertThat(result, hasOneItem());
String xmlAsString = loadResultXML(supplier,
BillingSharesResultType.MARKETPLACE_OWNER,
PERIOD_START_NO_RESULTS, PERIOD_END_NO_RESULTS);
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
verify_Empty(xml, getRoleString(OrganizationRoleType.MARKETPLACE_OWNER));
}
private void createSupplierProductAndSubscriptions(
final int numBillingResults) throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
supplier = Organizations.createOrganization(ds, "supplierId",
OrganizationRoleType.SUPPLIER,
OrganizationRoleType.MARKETPLACE_OWNER);
customer = Organizations.createOrganization(ds, "customerId",
OrganizationRoleType.CUSTOMER);
Organization customer1 = Organizations.createOrganization(ds,
"customerId1", OrganizationRoleType.CUSTOMER);
mp = Marketplaces.createGlobalMarketplace(supplier, "mp_"
+ supplier.getOrganizationId(), ds, MP_REVENUE_SHARE,
MP_BROKER_REVENUE_SHARE, MP_RESELLER_REVENUE_SHARE);
int num = numBillingResults;
for (int i = 0; i < num; i++) {
long billingPeriodStart = PERIOD_START - i * DAY_MILLIS;
long billingPeriodEnd = PERIOD_END - i * DAY_MILLIS;
int cutOffDay = getCutOffDay(billingPeriodStart);
if (cutOffDay > 28) {
num++;
continue;
}
product = Products.createProduct(supplier, "techProd",
true, "product_supplier_" + i, "priceModelId_" + i,
ds);
CatalogEntries.create(ds, mp, product);
Subscription sub = Subscriptions.createSubscription(ds,
customer.getOrganizationId(), product, mp,
cutOffDay);
BillingResults.createBillingResult(ds, sub,
supplier.getKey(), supplier.getKey(),
billingPeriodStart, billingPeriodEnd, NET_REVENUE,
GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\""
+ NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
}
Subscription sub = Subscriptions.createSubscription(ds,
customer1.getOrganizationId(), product, mp, 1);
BillingResults.createBillingResult(ds, sub, supplier.getKey(),
supplier.getKey(),
getStartMonth(System.currentTimeMillis(), 3),
getEndMonth(System.currentTimeMillis(), 3),
NET_REVENUE, GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\"" + NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
return null;
}
});
}
private void givenBillingResult() throws Exception {
createSupplierProductAndSubscriptions(NUM_BILLING_RESULTS);
createBrokerProductAndSubscriptions(NUM_BILLING_RESULTS);
createResellerProductAndSubscriptions(NUM_BILLING_RESULTS);
}
private void givenTransactionTime() {
transactionTime = DateFactory.getInstance().getTransactionTime();
}
private void verifyTransactionTimeSet() {
assertEquals(Boolean.FALSE, Boolean.valueOf(transactionTime == 0));
assertEquals("Transaction time not set.", Boolean.FALSE,
Boolean.valueOf(transactionTime == DateFactory.getInstance()
.getTransactionTime()));
}
@SuppressWarnings({ "unchecked", "boxing" })
private List<BillingSharesResult> loadSharesResult(final long orgKey,
final long fromDate, final long toDate,
final BillingSharesResultType type) throws Exception {
return runTX(new Callable<List<BillingSharesResult>>() {
@Override
public List<BillingSharesResult> call() {
Query query = ds
.createNamedQuery("BillingSharesResult.getSharesResultForOrganization");
query.setParameter("orgKey", orgKey);
query.setParameter("resultType", type);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<BillingSharesResult> result = query.getResultList();
return result;
}
});
}
private void createBrokerProductAndSubscriptions(final int numBillingResults)
throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
broker = Organizations.createOrganization(ds,
OrganizationRoleType.BROKER.name(),
OrganizationRoleType.BROKER);
int num = numBillingResults;
for (int i = 0; i < num; i++) {
long billingPeriodStart = PERIOD_START - i * DAY_MILLIS;
long billingPeriodEnd = PERIOD_END - i * DAY_MILLIS;
int cutOffDay = getCutOffDay(billingPeriodStart);
if (cutOffDay > 28) {
num++;
continue;
}
Product resaleCopy = Products.createProductResaleCopy(
product, broker, ds);
resaleCopy.setProductId("resaleProd_" + i
+ OrganizationRoleType.BROKER.name());
// publish to marketplace
CatalogEntries.createWithBrokerShare(ds, mp, resaleCopy,
REVENUE_SHARE_PERCENT);
// subscribe to resale copy
Subscription sub = Subscriptions.createSubscription(ds,
customer.getOrganizationId(), resaleCopy, mp,
cutOffDay);
BillingResults.createBillingResult(ds, sub,
broker.getKey(), broker.getKey(),
billingPeriodStart, billingPeriodEnd, NET_REVENUE,
GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\""
+ NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
}
return null;
}
});
}
private void createResellerProductAndSubscriptions(
final int numBillingResults) throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
reseller = Organizations.createOrganization(ds,
OrganizationRoleType.RESELLER.name(),
OrganizationRoleType.RESELLER);
int num = numBillingResults;
for (int i = 0; i < num; i++) {
long billingPeriodStart = PERIOD_START - i * DAY_MILLIS;
long billingPeriodEnd = PERIOD_END - i * DAY_MILLIS;
int cutOffDay = getCutOffDay(billingPeriodStart);
if (cutOffDay > 28) {
num++;
continue;
}
Product resaleCopy = Products.createProductResaleCopy(
product, reseller, ds);
resaleCopy.setProductId("resaleProd_" + i
+ OrganizationRoleType.RESELLER.name());
// publish to marketplace
CatalogEntries.createWithResellerShare(ds, mp, resaleCopy,
REVENUE_SHARE_PERCENT);
// subscribe to resale copy
Subscription sub = Subscriptions.createSubscription(ds,
customer.getOrganizationId(), resaleCopy, mp,
cutOffDay);
BillingResults.createBillingResult(ds, sub,
reseller.getKey(), reseller.getKey(),
billingPeriodStart, billingPeriodEnd, NET_REVENUE,
GROSS_REVENUE, "<PriceModel id=\""
+ sub.getPriceModel().getKey()
+ "\"><PriceModelCosts amount=\""
+ NET_REVENUE
+ "\"></PriceModelCosts></PriceModel>");
}
return null;
}
});
}
private void verify_ResaleOrganizationResult(String xmlAsString,
Organization supplier, Organization org, OrganizationRoleType role)
throws Exception {
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
String roleString = getRoleString(role);
OfferingType offerType = getOfferingType(role);
assertNotNull(roleString);
assertNotNull(offerType);
verify_RootNode(xml, org, roleString);
verify_Period(xml, roleString);
verify_Currency(xml, roleString);
verify_Supplier(xml, supplier, roleString);
verify_ResaleResult_Service(xml, NUM_BILLING_RESULTS, roleString);
verify_ServiceRevenue(xml, roleString);
verify_ResaleOrganization_RevenuePerSupplier(xml, roleString);
verify_ResaleOrganization_Revenue(xml, roleString);
}
private void verify_SupplierResult(String xmlAsString) throws Exception {
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
String roleString = getRoleString(OrganizationRoleType.SUPPLIER);
verify_RootNode(xml, supplier, roleString);
verify_Period(xml, roleString);
verify_Currency(xml, roleString);
verify_Marketplace(xml, mp, roleString);
verify_SupplierResult_Service(xml, null, OfferingType.DIRECT,
roleString);
verify_SupplierResult_Service(xml, broker, OfferingType.BROKER,
roleString);
verify_SupplierResult_Service(xml, reseller, OfferingType.RESELLER,
roleString);
}
private void verify_MarketplaceOwnerResult(String xmlAsString)
throws Exception {
Document xml = XMLConverter.convertToDocument(xmlAsString, false);
String roleString = getRoleString(OrganizationRoleType.MARKETPLACE_OWNER);
verify_RootNode(xml, supplier, roleString);
verify_Period(xml, roleString);
verify_Currency(xml, roleString);
verify_Marketplace(xml, mp, roleString);
verify_MarketplaceOwnerResult_Service(xml, null, OfferingType.DIRECT,
roleString);
verify_MarketplaceOwnerResult_Service(xml, broker, OfferingType.BROKER,
roleString);
verify_MarketplaceOwnerResult_Service(xml, reseller,
OfferingType.RESELLER, roleString);
verify_RevenuesOverAllMarketplaces(xml);
}
private void verify_RootNode(Document xml, Organization org,
String roleString) throws XPathExpressionException {
Node rootNode = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult");
assertEquals(org.getKey(),
XMLConverter.getLongAttValue(rootNode, "organizationKey"));
assertEquals(org.getOrganizationId(),
XMLConverter.getStringAttValue(rootNode, "organizationId"));
}
private void verify_Period(Document xml, String roleString)
throws XPathExpressionException {
Node period = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Period");
assertEquals(PERIOD_START,
XMLConverter.getLongAttValue(period, "startDate"));
assertEquals(PERIOD_END,
XMLConverter.getLongAttValue(period, "endDate"));
}
private void verify_Currency(Document xml, String roleString)
throws XPathExpressionException {
Node currency = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Currency");
assertEquals("EUR", XMLConverter.getStringAttValue(currency, "id"));
}
private void verify_Empty(Document xml, String roleString)
throws XPathExpressionException {
NodeList currency = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString + "RevenueShareResult/Currency");
assertEquals(0, currency.getLength());
}
private void verify_Supplier(Document xml, Organization supplier,
String roleString) throws XPathExpressionException {
Node organizationData = XMLConverter.getNodeByXPath(xml, "/"
+ roleString
+ "RevenueShareResult/Currency/Supplier/OrganizationData");
assertEquals(supplier.getKey(),
XMLConverter.getLongAttValue(organizationData, "key"));
}
private void verify_ResaleOrganization(Node service, Organization resaleOrg) {
String model = XMLConverter.getStringAttValue(service, "model");
String resaleRole = null;
if (OfferingType.BROKER.name().equals(model)) {
resaleRole = "Broker";
} else if (OfferingType.RESELLER.name().equals(model)) {
resaleRole = "Reseller";
}
assertNotNull(resaleRole);
Node org = XMLConverter.getLastChildNode(service, resaleRole);
Node organizationData = XMLConverter.getLastChildNode(org,
"OrganizationData");
assertEquals(resaleOrg.getKey(),
XMLConverter.getLongAttValue(organizationData, "key"));
}
private void verify_ServiceRevenue(Document xml, String roleString)
throws XPathExpressionException {
Node serviceRevenue = XMLConverter
.getNodeByXPath(
xml,
"/"
+ roleString
+ "RevenueShareResult/Currency/Supplier/Service/ServiceRevenue");
assertEquals(
REVENUE_SHARE.intValue() + ".00",
XMLConverter.getStringAttValue(serviceRevenue,
roleString.toLowerCase() + "Revenue"));
assertEquals(
REVENUE_SHARE_PERCENT.intValue() + ".00",
XMLConverter.getStringAttValue(serviceRevenue,
roleString.toLowerCase() + "RevenueSharePercentage"));
assertEquals(REVENUE_SHARE.intValue() * NUM_BILLING_RESULTS + ".00",
XMLConverter.getStringAttValue(serviceRevenue, "totalAmount"));
}
private void verify_SupplierResult_RevenueShareDetails(Node service) {
String model = XMLConverter.getStringAttValue(service, "model");
List<String> expected = new ArrayList<String>();
if (OfferingType.DIRECT.name().equals(model)) {
expected = SupplierResult_RevenueShareDetails_DIRECT;
} else if (OfferingType.BROKER.name().equals(model)) {
expected = SupplierResult_RevenueShareDetails_BROKER;
} else if (OfferingType.RESELLER.name().equals(model)) {
expected = SupplierResult_RevenueShareDetails_RESELLER;
}
assertEquals(8, expected.size());
Node revenueShareDetails = XMLConverter.getLastChildNode(service,
"RevenueShareDetails");
assertEquals(expected.get(0), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenue"));
assertEquals(expected.get(1), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenueSharePercentage"));
assertEquals(expected.get(2), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenue"));
assertEquals(expected.get(3), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenueSharePercentage"));
assertEquals(expected.get(4), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenue"));
assertEquals(expected.get(5), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenueSharePercentage"));
assertEquals(expected.get(6), XMLConverter.getStringAttValue(
revenueShareDetails, "serviceRevenue"));
assertEquals(expected.get(7), XMLConverter.getStringAttValue(
revenueShareDetails, "amountForSupplier"));
}
private void verify_MarketplaceOwnerResult_RevenueShareDetails(
Node service, OfferingType type) {
String model = XMLConverter.getStringAttValue(service, "model");
List<String> expected = new ArrayList<String>();
if (OfferingType.DIRECT.name().equals(model)) {
expected = MarketplaceOwnerResult_RevenueShareDetails_DIRECT;
} else if (OfferingType.BROKER.name().equals(model)) {
expected = MarketplaceOwnerResult_RevenueShareDetails_BROKER;
} else if (OfferingType.RESELLER.name().equals(model)) {
expected = MarketplaceOwnerResult_RevenueShareDetails_RESELLER;
}
assertEquals(NUM_BILLING_RESULTS, expected.size());
Node revenueShareDetails = XMLConverter.getLastChildNode(service,
"RevenueShareDetails");
assertEquals(expected.get(0), XMLConverter.getStringAttValue(
revenueShareDetails, "serviceRevenue"));
assertEquals(expected.get(1), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenueSharePercentage"));
assertEquals(expected.get(2), XMLConverter.getStringAttValue(
revenueShareDetails, "marketplaceRevenue"));
assertEquals(expected.get(6), XMLConverter.getStringAttValue(
revenueShareDetails, "amountForSupplier"));
if (OfferingType.BROKER.equals(type)) {
assertEquals(expected.get(7), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenueSharePercentage"));
assertEquals(expected.get(8), XMLConverter.getStringAttValue(
revenueShareDetails, "brokerRevenue"));
} else if (OfferingType.RESELLER.equals(type)) {
assertEquals(expected.get(7), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenueSharePercentage"));
assertEquals(expected.get(8), XMLConverter.getStringAttValue(
revenueShareDetails, "resellerRevenue"));
}
}
private void verify_ResaleOrganization_RevenuePerSupplier(Document xml,
String roleString) throws XPathExpressionException {
Node resaleRevenuePerSupplier = XMLConverter.getNodeByXPath(xml, "/"
+ roleString + "RevenueShareResult/Currency/Supplier/"
+ roleString + "RevenuePerSupplier");
assertEquals(REVENUE_SHARE.intValue() * NUM_BILLING_RESULTS + ".00",
XMLConverter.getStringAttValue(resaleRevenuePerSupplier,
"amount"));
}
private void verify_ResaleOrganization_Revenue(Document xml,
String roleString) throws XPathExpressionException {
Node revenue = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Currency/" + roleString + "Revenue");
assertEquals(REVENUE_SHARE.intValue() * NUM_BILLING_RESULTS + ".00",
XMLConverter.getStringAttValue(revenue, "amount"));
}
private void verify_Marketplace(Document xml, Marketplace mp,
String roleString) throws XPathExpressionException {
Node marketplace = XMLConverter.getNodeByXPath(xml, "/" + roleString
+ "RevenueShareResult/Currency/Marketplace");
assertEquals(mp.getMarketplaceId(),
XMLConverter.getStringAttValue(marketplace, "id"));
if (roleString.equals("Supplier")) {
verify_SupplierResult_MarketplaceRevenue(marketplace);
} else {
Node revenue = XMLConverter.getLastChildNode(marketplace,
"RevenuesPerMarketplace");
verify_RevenuesPerMarketplace_Suppliers(revenue);
verify_RevenuesPerMarketplace_Brokers(revenue);
verify_RevenuesPerMarketplace_Resellers(revenue);
}
}
private void verify_RevenuesPerMarketplace_Suppliers(Node revenue) {
Node suppliers = XMLConverter.getLastChildNode(revenue, "Suppliers");
Node org = XMLConverter.getLastChildNode(suppliers, "Organization");
assertEquals(supplier.getOrganizationId(),
XMLConverter.getStringAttValue(org, "identifier"));
assertEquals("1385.00", XMLConverter.getStringAttValue(org, "amount"));
}
private void verify_RevenuesPerMarketplace_Brokers(Node revenue) {
Node brokers = XMLConverter.getLastChildNode(revenue, "Brokers");
Node org = XMLConverter.getLastChildNode(brokers, "Organization");
assertEquals(broker.getOrganizationId(),
XMLConverter.getStringAttValue(org, "identifier"));
assertEquals("50.00", XMLConverter.getStringAttValue(org, "amount"));
}
private void verify_RevenuesPerMarketplace_Resellers(Node revenue) {
Node resellers = XMLConverter.getLastChildNode(revenue, "Resellers");
Node org = XMLConverter.getLastChildNode(resellers, "Organization");
assertEquals(reseller.getOrganizationId(),
XMLConverter.getStringAttValue(org, "identifier"));
assertEquals("50.00", XMLConverter.getStringAttValue(org, "amount"));
}
private void verify_RevenuesOverAllMarketplaces(Document xml)
throws XPathExpressionException {
Node allMarketplaces = XMLConverter
.getNodeByXPath(xml,
"/MarketplaceOwnerRevenueShareResult/Currency/RevenuesOverAllMarketplaces");
verify_RevenuesPerMarketplace_Suppliers(allMarketplaces);
verify_RevenuesPerMarketplace_Brokers(allMarketplaces);
verify_RevenuesPerMarketplace_Resellers(allMarketplaces);
}
private void verify_SupplierResult_MarketplaceRevenue(Node mp) {
Node revenuePerMp = XMLConverter.getLastChildNode(mp,
"RevenuePerMarketplace");
assertEquals(SupplierResult_RevenuePerMarketplace.get(0),
XMLConverter.getStringAttValue(revenuePerMp, "overallRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(1),
XMLConverter.getStringAttValue(revenuePerMp, "brokerRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(2),
XMLConverter.getStringAttValue(revenuePerMp, "resellerRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(3),
XMLConverter.getStringAttValue(revenuePerMp,
"marketplaceRevenue"));
assertEquals(SupplierResult_RevenuePerMarketplace.get(4),
XMLConverter.getStringAttValue(revenuePerMp, "serviceRevenue"));
}
private void verify_ResaleResult_Service(Document xml, int numServices,
String roleString) throws XPathExpressionException {
NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString + "RevenueShareResult/Currency/Supplier/Service");
assertEquals(numServices, services.getLength());
}
private void verify_SupplierResult_Service(Document xml,
Organization resaleOrg, OfferingType type, String roleString)
throws XPathExpressionException {
NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString
+ "RevenueShareResult/Currency/Marketplace/Service");
for (int i = 0; i < services.getLength(); i++) {
String model = XMLConverter.getStringAttValue(services.item(i),
"model");
if (type.name().equals(model)) {
verify_SupplierResult_RevenueShareDetails(services.item(i));
if (resaleOrg != null) {
verify_ResaleOrganization(services.item(i), resaleOrg);
}
}
}
}
private void verify_MarketplaceOwnerResult_Service(Document xml,
Organization resaleOrg, OfferingType type, String roleString)
throws XPathExpressionException {
NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
+ roleString
+ "RevenueShareResult/Currency/Marketplace/Service");
for (int i = 0; i < services.getLength(); i++) {
String model = XMLConverter.getStringAttValue(services.item(i),
"model");
if (type.name().equals(model)) {
verify_MarketplaceOwnerResult_RevenueShareDetails(
services.item(i), type);
if (resaleOrg != null) {
verify_ResaleOrganization(services.item(i), resaleOrg);
}
}
}
}
private String loadResultXML(Organization org,
BillingSharesResultType role, long startPeriod, long endPeriod)
throws Exception {
List<BillingSharesResult> result = loadSharesResult(org.getKey(),
startPeriod, endPeriod, role);
String xmlAsString = result.get(0).getResultXML();
System.out.println(xmlAsString);
return xmlAsString;
}
private String getRoleString(OrganizationRoleType role) {
if (OrganizationRoleType.BROKER.equals(role)) {
return "Broker";
}
if (OrganizationRoleType.RESELLER.equals(role)) {
return "Reseller";
}
if (OrganizationRoleType.SUPPLIER.equals(role)) {
return "Supplier";
}
if (OrganizationRoleType.MARKETPLACE_OWNER.equals(role)) {
return "MarketplaceOwner";
}
return null;
}
private OfferingType getOfferingType(OrganizationRoleType role) {
if (OrganizationRoleType.BROKER.equals(role)) {
return OfferingType.BROKER;
}
if (OrganizationRoleType.RESELLER.equals(role)) {
return OfferingType.RESELLER;
}
if (OrganizationRoleType.SUPPLIER.equals(role)) {
return OfferingType.DIRECT;
}
return null;
}
private static long getStartMonth(long baseTime, int numMonths) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(baseTime);
cal.add(Calendar.MONTH, numMonths);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
private static long getEndMonth(long baseTime, int numMonths) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getStartMonth(baseTime, numMonths));
cal.add(Calendar.MONTH, 1);
return cal.getTimeInMillis();
}
private int getCutOffDay(long baseTime) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(baseTime);
return cal.get(Calendar.DAY_OF_MONTH);
}
}
| 39,723 | 0.615739 | 0.608514 | 904 | 42.941372 | 28.16803 | 132 | false | false | 0 | 0 | 0 | 0 | 72 | 0.001813 | 0.844027 | false | false |
0
|
39a73e46255e34a9ad55624f90e32c9cbf6ea3c0
| 27,556,510,208,150 |
5eb21c560f664aa3179acf16fc2c2a3a89aa4097
|
/src/main/java/com/example/demo/util/StrUtil.java
|
63e7ddb2c55cc0492f5d1e7f13b33a048545bb5b
|
[
"Apache-2.0"
] |
permissive
|
cjqCN/springboot-demo
|
https://github.com/cjqCN/springboot-demo
|
f8f7aa2715839f865a096781aa56a604c274ef84
|
c2775750886453fba9516ca853912100a01fa7cd
|
refs/heads/master
| 2021-01-24T10:26:11.593000 | 2018-07-02T01:58:52 | 2018-07-02T01:58:52 | 123,051,726 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.demo.util;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import javax.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Collator;
import java.util.*;
import java.util.regex.Pattern;
public class StrUtil extends org.apache.commons.lang3.StringUtils {
public static void main(String[] args) {
System.out.println(stringToBase64StringByGuava("hello world"));
System.out.println(base64StringToSourceStringByGuava(stringToBase64StringByCodec("hello world")));
System.out.println(checkIsEmail("123@122.com"));
}
/**
* 检查字符串是否为空。null、“” 是空字符
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @return reference
*/
public static String checkNotEmpty(final String reference) {
return checkNotEmpty(reference, "参数为NULL");
}
/**
* 检查字符串是否为空。null、“” 是空字符
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @param errorMessage 异常信息
* @return reference
*/
public static String checkNotEmpty(final String reference, @Nullable Object errorMessage) {
if (isEmpty(reference)) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* 检查字符串是否为NULL
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @return reference
*/
public static String checkNotNull(final String reference) {
return checkNotNull(reference, "参数为NULL");
}
/**
* 检查字符串是否为NULL
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @param errorMessage 异常信息
* @return reference
*/
public static String checkNotNull(final String reference, @Nullable Object errorMessage) {
if (null == reference) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
//=================================================================================================
/**
* 编码
*
* @param text 需要编码的内容
* @param charsetEncoding 指定编码
* @return
* @throws UnsupportedEncodingException
*/
public static String encodeURL(final String text, String charsetEncoding) {
if (isBlank(text)) {
return null;
}
if (isBlank(charsetEncoding)) {
charsetEncoding = "UTF-8";
}
try {
return URLEncoder.encode(text, charsetEncoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解码
*
* @param text 需要解码的内容
* @param charsetEncoding 指定编码
* @return
* @throws UnsupportedEncodingException
*/
public static String decodeURL(final String text, String charsetEncoding) {
if (isBlank(text)) {
return null;
}
if (isBlank(charsetEncoding)) {
charsetEncoding = "UTF-8";
}
try {
return URLDecoder.decode(text, charsetEncoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
//==============================================================================================================
/**
* 检查是否以指定字符开头
*
* @param string
* @param prefixString
* @return
*/
public static boolean checkStartsWithString(final String string, final String prefixString) {
if (isBlank(string) || isBlank(prefixString)) {
return false;
}
return string.startsWith(prefixString);
}
/**
* 检查是否以指定字符结尾
*
* @param string
* @param suffixString
* @return
*/
public static boolean checkEndsWithString(final String string, final String suffixString) {
if (isBlank(string) || isBlank(suffixString)) {
return false;
}
return string.endsWith(suffixString);
}
/**
* 检查是否包含指定字符
*
* @param string
* @param containsString 被包含字符
* @return
*/
public static boolean checkContainsString(final String string, final String containsString) {
if (isBlank(string) || isBlank(containsString)) {
return false;
}
return string.contains(containsString);
}
//===========================================================================================================
/**
* 字符串匹配
*
* @param regex
* @param str
* @return
*/
public static boolean stringMatching(final String regex, final String str) {
if (isBlank(regex) || isBlank(str)) {
return false;
}
return Pattern.matches(regex, str);
}
/**
* 检查字符串是否包含汉字
*
* @param string
* @return
*/
public static boolean checkIsIncludeChineseCharacter(final String string) {
final String regex = "[\\u4e00-\\u9fa5]";
return stringMatching(regex, string);
}
/**
* 检查字符串是否包含字母
*
* @param string
* @return
*/
public static boolean checkIsIncludeEnglishLetters(final String string) {
final String regex = "[A-Za-z]+";
return stringMatching(regex, string);
}
/**
* 检查字符串是否包含数字
*
* @param string
* @return
*/
public static boolean checkIsIncludeNumber(final String string) {
final String regex = "[0-9]+";
return stringMatching(regex, string);
}
/**
* 检查字符串是否是字母和数字组成(可以是全部数字/字母或是两种混合)
*
* @param string
* @return
*/
public static boolean checkIsNumberAndLetter(final String string) {
final String regex = "[A-Za-z0-9]+";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合邮箱规则
*
* @param string
* @return
*/
public static boolean checkIsEmail(final String string) {
final String regex = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\" +
".)" +
"+[\\w](?:[\\w-]*[\\w])?";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合手机规则
*
* @param string
* @return
*/
public static boolean checkIsMobile(final String string) {
final String regex = "1(\\d{10})";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合身份证规则(由于目前国内15位的身份证已经越来少了,所以忽略不算)
*
* @param string
* @return
*/
public static boolean checkIsIdCard(final String string) {
final String regex = "(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合身份证是否符合成年人18岁规则
*
* @param string
* @return
*/
public static boolean checkIsIdCardAndExceed18(final String string) {
if (checkIsIdCard(string)) {
Calendar calendar = Calendar.getInstance();
Integer birthYear = Integer.parseInt(string.substring(6, 10));
Integer newYear = calendar.get(Calendar.YEAR);
if ((newYear - birthYear) >= 18) {
return true;
}
}
return false;
}
/**
* 检查字符串是否符合固定电话规则
*
* @param string
* @return
*/
public static boolean checkIsTelephone(final String string) {
final String regex = "\\d{1,}-\\d{1,}-?\\d*";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合邮政编码规则
*
* @param string
* @return
*/
public static boolean checkIsPostCode(final String string) {
final String regex = "[1-9]\\d{5}";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合IP地址规则
*
* @param string
* @return true符合要求
*/
public static boolean checkIsIpV4(final String string) {
final String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1," +
"2})?))";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合URL地址规则(必须包含http开头)
*
* @param string
* @return true符合要求
*/
public static boolean checkIsUrl(final String string) {
final String regex = "(http(s)?)://((w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?" +
"(&" +
".+=.*)?)?";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合URL地址规则(不必须包含http开头)
*
* @param string
* @return true符合要求
*/
public static boolean checkIsUrlCanNoIncludeHttp(final String string) {
final String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=" +
".*)?)?";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合QQ号规则
*
* @param string
* @return true符合要求
*/
public static boolean checkIsQQNum(final String string) {
final String regex = "[1-9][0-9]{4,11}";
return stringMatching(regex, string);
}
/**
* 检查字符串是否含有HTML标签
*
* @param string
* @return true包含html标签
*/
public static boolean checkIsIncludeHtml(final String string) {
final String regex = "<(\\S*?)[^>]*>.*?</\\1>|<.*? />";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合正整数规则
*
* @param string
* @return
*/
public static boolean checkIsPositiveInteger(final String string) {
final String regex = "[1-9]\\d*";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合整数规则(可以正负)
*
* @param string
* @return
*/
public static boolean checkIsInteger(final String string) {
final String regex = "-?[1-9]\\d*";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合正浮点数规则
*
* @param string
* @return
*/
public static boolean checkIsPositiveFloat(final String string) {
final String regex = "[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*";
return stringMatching(regex, string);
}
/**
* 把一个字符串通过特定字符,拆分成一个 Iterable
*
* @param separator 根据此间隔符拆分
* @param stringContent 被拆分的字符串
* 被拆分的字符串如果有空字符会被过滤;
* 元素前后有空格会把空格去掉
* @return
*/
public static Iterable<String> splitStringToIterableByGuava(final char separator, final String stringContent) {
if (isNotBlank(stringContent)) {
return Splitter.on(separator).trimResults().omitEmptyStrings().split(stringContent);
}
return null;
}
/**
* 把一个map数据通过特定字符,拼接成一个字符串
*
* @param keyValueSeparator map的key=value的间隔符
* @param elementSeparator map元素之间的间隔符
* @param map map的key或是value都不能有null,不然会报错
* 如果有null,要转成指定字符串是多加个一个useForNull("")方法即可
* @return
*/
public static String joinStringFromMapByGuava(final String keyValueSeparator, final char elementSeparator, Map
map) {
if (map != null) {
return Joiner.on(elementSeparator).withKeyValueSeparator(keyValueSeparator).join(map);
}
return null;
}
/**
* 把一个list数据通过特定字符,拼接成一个字符串
*
* @param separator 拼接间隔字符
* @param list 被拼接数据
* 会跳过null,但是空字符不会被跳过
* @return
*/
public static String joinStringFromListByGuava(final char separator, final List list) {
if (list != null && list.size() > 0) {
return Joiner.on(separator).skipNulls().join(list);
}
return null;
}
/**
* 把字符串编码为 MD5 字符串(通过Google guava)
*
* @return
*/
public static String stringToMD5StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.md5().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把 byte 类型的信息 md5 成 byte 类型信息
*
* @param context
* @return
*/
private static byte[] byteToMD5Byte(byte[] context) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md.digest(context);
}
/**
* 把字符串编码为 sha1 字符串(通过Google guava)
*
* @return
*/
public static String stringToSha1StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.sha1().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把字符串编码为 sha256 字符串(通过Google guava)
*
* @return
*/
public static String stringToSha256StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.sha256().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把字符串编码为 sha512 字符串(通过Google guava)
*
* @return
*/
public static String stringToSha512StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.sha512().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把字符串编码为base16进制字符串(通过Google guava)
*
* @return
*/
public static String stringToBase16StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return BaseEncoding.base16().encode(sourceString.getBytes());
}
return null;
}
/**
* 把base16字符串解码为源字符串(通过Google guava)
*
* @return
*/
public static String base16StringToSourceStringByGuava(final String base16String) {
if (isNotBlank(base16String)) {
return new String(BaseEncoding.base16().decode(base16String));
}
return null;
}
/**
* 把字符串编码为base32进制字符串(通过Google guava)
*
* @return
*/
public static String stringToBase32StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return BaseEncoding.base32().encode(sourceString.getBytes());
}
return null;
}
/**
* 把base32字符串解码为源字符串(通过Google guava)
*
* @return
*/
public static String base32StringToSourceStringByGuava(final String base32String) {
if (isNotBlank(base32String)) {
return new String(BaseEncoding.base32().decode(base32String));
}
return null;
}
/**
* 把字符串编码为base64进制字符串(通过Google guava)
* 这种 base64 出来的结果会带等号,比如:aHR0cDovL3d3dy5Zb3VNZWVrLmNvbT9zZGZhPTIzMjE0JmRkZD0zMw==
*
* @return
*/
public static String stringToBase64StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return BaseEncoding.base64().encode(sourceString.getBytes());
}
return null;
}
/**
* 把字符串编码为base64进制字符串(通过 commons codec)
* 这种 base64 出来的结果不会带等号,推荐使用,比如:aHR0cDovL3d3dy5Zb3VNZWVrLmNvbT9zZGZhPTIzMjE0JmRkZD0zMw
*
* @return
*/
public static String stringToBase64StringByCodec(final String sourceString) {
if (isNotBlank(sourceString)) {
return Base64.encodeBase64URLSafeString(sourceString.getBytes());
}
return null;
}
/**
* 把字节编码为base64进制字符串(通过Google guava)
*
* @return
*/
public static String byteToBase64StringByGuava(final byte[] bytes) {
if (null != bytes) {
return BaseEncoding.base64().encode(bytes);
}
return null;
}
/**
* 把base64字符串解码为源字符串(通过Google guava)
*
* @return
*/
public static String base64StringToSourceStringByGuava(final String base64String) {
if (isNotBlank(base64String)) {
return new String(BaseEncoding.base64().decode(base64String));
}
return null;
}
/**
* 把base64字符串解码为源字符串(通过 commons codec) (推荐)
*
* @return
* @throws IllegalArgumentException
*/
public static String base64StringToSourceStringByCodec(final String base64String) {
if (isNotBlank(base64String)) {
return new String(Base64.decodeBase64(base64String));
}
return null;
}
/**
* 把base64字符串解码为源字符串数组(通过Google guava)
*
* @return
* @throws IllegalArgumentException
*/
public static byte[] base64StringToSourceByteByGuava(final String base64String) {
if (isNotBlank(base64String)) {
return BaseEncoding.base64().decode(base64String);
}
return null;
}
//============================================================================================================
private final static String[] hexDigits = {
"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F"};
/**
* 转换字节数组为16进制字串
*
* @param b 字节数组
* @return 16进制字串
*/
public static String byteArrayToHexString(final byte[] b) {
StringBuilder resultSb = new StringBuilder();
for (byte temp : b) {
resultSb.append(byteToHexString(temp));
}
return resultSb.toString();
}
/**
* 转换字符串为16进制字串
*
* @param bString 字符串
* @return 16进制字串
*/
public static String stringToHexString(final String bString) {
byte[] b = bString.getBytes();
StringBuilder resultSb = new StringBuilder();
for (byte temp : b) {
resultSb.append(byteToHexString(temp));
}
return resultSb.toString();
}
private static String byteToHexString(final byte b) {
int n = b;
if (n < 0) {
n = 256 + n;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
/**
* 获取 URL 后缀
* 比如:"/template/abc/login.jsp",得到的结果是:.jsp
*
* @param url
* @return
*/
public static String getUrlSuffix(final String url) {
if (isNotBlank(url)) {
return substring(url, indexOf(url, "."), url.length());
}
return null;
}
/**
* 把带有指定分隔符的字符串转换成Long类型的List
*
* @param ids
* @param separatorChars
* @return
*/
public static List<Long> stringToLongListByIds(final String ids, final String separatorChars) {
if (isNotBlank(ids) && isNotBlank(separatorChars)) {
String[] splitArray = split(ids, separatorChars);
List<Long> idsByLong = new ArrayList<Long>();
for (String temp : splitArray) {
//校验是否其下还有未删除的子节点
Long idByLong = Long.valueOf(temp);
idsByLong.add(idByLong);
}
return idsByLong;
}
return null;
}
/**
* 驼峰命名法工具
*
* @return toCamelCase(hello_world) == "helloWorld"
*/
public static String toCamelCase(String s) {
final char SEPARATOR = '_';
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 驼峰命名法工具
*
* @return toCapitalizeCamelCase(hello_world) == "HelloWorld"
*/
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
return null;
}
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/**
* 驼峰命名法工具
*
* @return toUnderScoreCase(helloWorld) = "hello_world"
*/
public static String toUnderScoreCase(String s) {
final char SEPARATOR = '_';
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 判断文件 contentType 是否是图片的格式
* 使用方法:
* <p>
* MultipartFile picFileInfo;
* String contentType = picFileInfo.getContentType();
*
* @param contentType
* @return
*/
public static Boolean judgePictureFormat(String contentType) {
if (isBlank(contentType)) {
return false;
}
return contentType.equalsIgnoreCase("image/png") || contentType.equalsIgnoreCase("image/jpeg") || contentType
.equalsIgnoreCase("image/jpg") || contentType.equalsIgnoreCase("image/gif");
}
/**
* 根据中文首字母排序
*
* @param stringList
* @return
*/
public static List sortChineseStringList(List<String> stringList) {
if (stringList.size() == 0) {
return null;
}
//把list转换成数组
String[] arrStrings = stringList.toArray(new String[stringList.size()]);
// Collator 类是用来执行区分语言环境的 String 比较的,这里选择使用CHINA
Comparator comparator = Collator.getInstance(Locale.CHINA);
// 使根据指定比较器产生的顺序对指定对象数组进行排序。
Arrays.sort(arrStrings, comparator);
//把数组转换成List(不过Arrays.asList()方法返回的List不能add对象,因为该方法的实现是使用参数引用的数组的大小来new的一个ArrayList,会报异常:java.lang
// .UnsupportedOperationException)
return Arrays.asList(arrStrings);
}
/**
* 拼接字符串,把多个字符串拼接成一个字符串
*
* @param separator 拼接符,可以为空字符,但是不能为空格
* @param rest 需要拼接的字符串内容
* @return
*/
public static String joinString(String separator, Object... rest) {
if (isBlank(separator)) {
separator = "";
}
return Joiner.on(separator).skipNulls().join(rest);
}
/**
* 把字符串转换成 List(通过 Guava)
*
* @param separator
* @param target
* @return
*/
public static List<String> stringToList(String separator, String target) {
return Splitter.on(separator).trimResults().splitToList(target);
}
/**
* 把 List 转换成字符串
*
* @param separator
* @param target
* @return
*/
public static String listToString(String separator, List target) {
return Joiner.on(separator).skipNulls().join(target);
}
/**
* 把字符串转换成 Map
*
* @param separator
* @param keyValueSeparator
* @param target 需要转换的字符串,建议有类似这样的格式:"John=first,Adam=second";
* @return
*/
public static Map<String, String> stringToMap(String separator, String keyValueSeparator, String target) {
return Splitter.on(separator).withKeyValueSeparator(keyValueSeparator).split(target);
}
/**
* 把 Map 转换成字符串
*
* @param separator
* @param keyValueSeparator
* @param target
* @return
*/
public static String mapToString(String separator, String keyValueSeparator, Map target) {
//key和value不能有null
return Joiner.on(separator).withKeyValueSeparator(keyValueSeparator).join(target);
}
/**
* 寻找两个字符串之间共同的前缀,也就是从一个位置开始算
* eg:
* <p>
* String param1 = ",13,2,3,4,5,6,";
* String param2 = ",134,222,3,44,5,666,";
* String result = StrUtils.findCommonPrefix(param1, param2);
* 结果为:,13
*
* @param param1
* @param param2
* @return
*/
public static String findCommonPrefix(String param1, String param2) {
return Strings.commonPrefix(param1, param2);
}
/**
* 寻找两个字符串之间共同的后缀
* eg:
* <p>
* String param1 = ",13,2,3,4,5,6,";
* String param2 = ",134,222,3,44,5,666,";
* String result = StrUtils.findCommonSuffix(param1, param2);
* 结果为:6,
*
* @param param1
* @param param2
* @return
*/
public static String findCommonSuffix(String param1, String param2) {
return Strings.commonSuffix(param1, param2);
}
}
|
UTF-8
|
Java
| 24,221 |
java
|
StrUtil.java
|
Java
|
[
{
"context": "llo world\")));\n\t\tSystem.out.println(checkIsEmail(\"123@122.com\"));\n\t}\n\n\n\t/**\n\t * 检查字符串是否为空。null、“” 是空字符\n\t * 如果为空",
"end": 929,
"score": 0.9960607886314392,
"start": 918,
"tag": "EMAIL",
"value": "123@122.com"
},
{
"context": "4进制字符串(通过Google guava)\n\t * 这种 base64 出来的结果会带等号,比如:aHR0cDovL3d3dy5Zb3VNZWVrLmNvbT9zZGZhPTIzMjE0JmRkZD0zMw==\n\t *\n\t * @return\n\t */\n\tpublic static String string",
"end": 13241,
"score": 0.9508714079856873,
"start": 13185,
"tag": "KEY",
"value": "aHR0cDovL3d3dy5Zb3VNZWVrLmNvbT9zZGZhPTIzMjE0JmRkZD0zMw=="
},
{
"context": "过 commons codec)\n\t * 这种 base64 出来的结果不会带等号,推荐使用,比如:aHR0cDovL3d3dy5Zb3VNZWVrLmNvbT9zZGZhPTIzMjE0JmRkZD0zMw\n\t *\n\t * @return\n\t */\n\tpublic static String string",
"end": 13597,
"score": 0.9898332953453064,
"start": 13543,
"tag": "KEY",
"value": "aHR0cDovL3d3dy5Zb3VNZWVrLmNvbT9zZGZhPTIzMjE0JmRkZD0zMw"
},
{
"context": "\t * @param target 需要转换的字符串,建议有类似这样的格式:\"John=first,Adam=second\";\n\t * @return\n\t */\n\tpublic stat",
"end": 20339,
"score": 0.9993003010749817,
"start": 20335,
"tag": "NAME",
"value": "John"
},
{
"context": "target 需要转换的字符串,建议有类似这样的格式:\"John=first,Adam=second\";\n\t * @return\n\t */\n\tpublic static Map<Stri",
"end": 20350,
"score": 0.9995871186256409,
"start": 20346,
"tag": "NAME",
"value": "Adam"
}
] | null |
[] |
package com.example.demo.util;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import javax.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Collator;
import java.util.*;
import java.util.regex.Pattern;
public class StrUtil extends org.apache.commons.lang3.StringUtils {
public static void main(String[] args) {
System.out.println(stringToBase64StringByGuava("hello world"));
System.out.println(base64StringToSourceStringByGuava(stringToBase64StringByCodec("hello world")));
System.out.println(checkIsEmail("<EMAIL>"));
}
/**
* 检查字符串是否为空。null、“” 是空字符
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @return reference
*/
public static String checkNotEmpty(final String reference) {
return checkNotEmpty(reference, "参数为NULL");
}
/**
* 检查字符串是否为空。null、“” 是空字符
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @param errorMessage 异常信息
* @return reference
*/
public static String checkNotEmpty(final String reference, @Nullable Object errorMessage) {
if (isEmpty(reference)) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* 检查字符串是否为NULL
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @return reference
*/
public static String checkNotNull(final String reference) {
return checkNotNull(reference, "参数为NULL");
}
/**
* 检查字符串是否为NULL
* 如果为空则抛出NullPointerException异常
*
* @param reference
* @param errorMessage 异常信息
* @return reference
*/
public static String checkNotNull(final String reference, @Nullable Object errorMessage) {
if (null == reference) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
//=================================================================================================
/**
* 编码
*
* @param text 需要编码的内容
* @param charsetEncoding 指定编码
* @return
* @throws UnsupportedEncodingException
*/
public static String encodeURL(final String text, String charsetEncoding) {
if (isBlank(text)) {
return null;
}
if (isBlank(charsetEncoding)) {
charsetEncoding = "UTF-8";
}
try {
return URLEncoder.encode(text, charsetEncoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解码
*
* @param text 需要解码的内容
* @param charsetEncoding 指定编码
* @return
* @throws UnsupportedEncodingException
*/
public static String decodeURL(final String text, String charsetEncoding) {
if (isBlank(text)) {
return null;
}
if (isBlank(charsetEncoding)) {
charsetEncoding = "UTF-8";
}
try {
return URLDecoder.decode(text, charsetEncoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
//==============================================================================================================
/**
* 检查是否以指定字符开头
*
* @param string
* @param prefixString
* @return
*/
public static boolean checkStartsWithString(final String string, final String prefixString) {
if (isBlank(string) || isBlank(prefixString)) {
return false;
}
return string.startsWith(prefixString);
}
/**
* 检查是否以指定字符结尾
*
* @param string
* @param suffixString
* @return
*/
public static boolean checkEndsWithString(final String string, final String suffixString) {
if (isBlank(string) || isBlank(suffixString)) {
return false;
}
return string.endsWith(suffixString);
}
/**
* 检查是否包含指定字符
*
* @param string
* @param containsString 被包含字符
* @return
*/
public static boolean checkContainsString(final String string, final String containsString) {
if (isBlank(string) || isBlank(containsString)) {
return false;
}
return string.contains(containsString);
}
//===========================================================================================================
/**
* 字符串匹配
*
* @param regex
* @param str
* @return
*/
public static boolean stringMatching(final String regex, final String str) {
if (isBlank(regex) || isBlank(str)) {
return false;
}
return Pattern.matches(regex, str);
}
/**
* 检查字符串是否包含汉字
*
* @param string
* @return
*/
public static boolean checkIsIncludeChineseCharacter(final String string) {
final String regex = "[\\u4e00-\\u9fa5]";
return stringMatching(regex, string);
}
/**
* 检查字符串是否包含字母
*
* @param string
* @return
*/
public static boolean checkIsIncludeEnglishLetters(final String string) {
final String regex = "[A-Za-z]+";
return stringMatching(regex, string);
}
/**
* 检查字符串是否包含数字
*
* @param string
* @return
*/
public static boolean checkIsIncludeNumber(final String string) {
final String regex = "[0-9]+";
return stringMatching(regex, string);
}
/**
* 检查字符串是否是字母和数字组成(可以是全部数字/字母或是两种混合)
*
* @param string
* @return
*/
public static boolean checkIsNumberAndLetter(final String string) {
final String regex = "[A-Za-z0-9]+";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合邮箱规则
*
* @param string
* @return
*/
public static boolean checkIsEmail(final String string) {
final String regex = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\" +
".)" +
"+[\\w](?:[\\w-]*[\\w])?";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合手机规则
*
* @param string
* @return
*/
public static boolean checkIsMobile(final String string) {
final String regex = "1(\\d{10})";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合身份证规则(由于目前国内15位的身份证已经越来少了,所以忽略不算)
*
* @param string
* @return
*/
public static boolean checkIsIdCard(final String string) {
final String regex = "(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合身份证是否符合成年人18岁规则
*
* @param string
* @return
*/
public static boolean checkIsIdCardAndExceed18(final String string) {
if (checkIsIdCard(string)) {
Calendar calendar = Calendar.getInstance();
Integer birthYear = Integer.parseInt(string.substring(6, 10));
Integer newYear = calendar.get(Calendar.YEAR);
if ((newYear - birthYear) >= 18) {
return true;
}
}
return false;
}
/**
* 检查字符串是否符合固定电话规则
*
* @param string
* @return
*/
public static boolean checkIsTelephone(final String string) {
final String regex = "\\d{1,}-\\d{1,}-?\\d*";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合邮政编码规则
*
* @param string
* @return
*/
public static boolean checkIsPostCode(final String string) {
final String regex = "[1-9]\\d{5}";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合IP地址规则
*
* @param string
* @return true符合要求
*/
public static boolean checkIsIpV4(final String string) {
final String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1," +
"2})?))";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合URL地址规则(必须包含http开头)
*
* @param string
* @return true符合要求
*/
public static boolean checkIsUrl(final String string) {
final String regex = "(http(s)?)://((w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?" +
"(&" +
".+=.*)?)?";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合URL地址规则(不必须包含http开头)
*
* @param string
* @return true符合要求
*/
public static boolean checkIsUrlCanNoIncludeHttp(final String string) {
final String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=" +
".*)?)?";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合QQ号规则
*
* @param string
* @return true符合要求
*/
public static boolean checkIsQQNum(final String string) {
final String regex = "[1-9][0-9]{4,11}";
return stringMatching(regex, string);
}
/**
* 检查字符串是否含有HTML标签
*
* @param string
* @return true包含html标签
*/
public static boolean checkIsIncludeHtml(final String string) {
final String regex = "<(\\S*?)[^>]*>.*?</\\1>|<.*? />";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合正整数规则
*
* @param string
* @return
*/
public static boolean checkIsPositiveInteger(final String string) {
final String regex = "[1-9]\\d*";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合整数规则(可以正负)
*
* @param string
* @return
*/
public static boolean checkIsInteger(final String string) {
final String regex = "-?[1-9]\\d*";
return stringMatching(regex, string);
}
/**
* 检查字符串是否符合正浮点数规则
*
* @param string
* @return
*/
public static boolean checkIsPositiveFloat(final String string) {
final String regex = "[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*";
return stringMatching(regex, string);
}
/**
* 把一个字符串通过特定字符,拆分成一个 Iterable
*
* @param separator 根据此间隔符拆分
* @param stringContent 被拆分的字符串
* 被拆分的字符串如果有空字符会被过滤;
* 元素前后有空格会把空格去掉
* @return
*/
public static Iterable<String> splitStringToIterableByGuava(final char separator, final String stringContent) {
if (isNotBlank(stringContent)) {
return Splitter.on(separator).trimResults().omitEmptyStrings().split(stringContent);
}
return null;
}
/**
* 把一个map数据通过特定字符,拼接成一个字符串
*
* @param keyValueSeparator map的key=value的间隔符
* @param elementSeparator map元素之间的间隔符
* @param map map的key或是value都不能有null,不然会报错
* 如果有null,要转成指定字符串是多加个一个useForNull("")方法即可
* @return
*/
public static String joinStringFromMapByGuava(final String keyValueSeparator, final char elementSeparator, Map
map) {
if (map != null) {
return Joiner.on(elementSeparator).withKeyValueSeparator(keyValueSeparator).join(map);
}
return null;
}
/**
* 把一个list数据通过特定字符,拼接成一个字符串
*
* @param separator 拼接间隔字符
* @param list 被拼接数据
* 会跳过null,但是空字符不会被跳过
* @return
*/
public static String joinStringFromListByGuava(final char separator, final List list) {
if (list != null && list.size() > 0) {
return Joiner.on(separator).skipNulls().join(list);
}
return null;
}
/**
* 把字符串编码为 MD5 字符串(通过Google guava)
*
* @return
*/
public static String stringToMD5StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.md5().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把 byte 类型的信息 md5 成 byte 类型信息
*
* @param context
* @return
*/
private static byte[] byteToMD5Byte(byte[] context) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md.digest(context);
}
/**
* 把字符串编码为 sha1 字符串(通过Google guava)
*
* @return
*/
public static String stringToSha1StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.sha1().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把字符串编码为 sha256 字符串(通过Google guava)
*
* @return
*/
public static String stringToSha256StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.sha256().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把字符串编码为 sha512 字符串(通过Google guava)
*
* @return
*/
public static String stringToSha512StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return Hashing.sha512().hashString(sourceString, Charset.forName(Charsets.UTF_8.toString())).toString();
}
return null;
}
/**
* 把字符串编码为base16进制字符串(通过Google guava)
*
* @return
*/
public static String stringToBase16StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return BaseEncoding.base16().encode(sourceString.getBytes());
}
return null;
}
/**
* 把base16字符串解码为源字符串(通过Google guava)
*
* @return
*/
public static String base16StringToSourceStringByGuava(final String base16String) {
if (isNotBlank(base16String)) {
return new String(BaseEncoding.base16().decode(base16String));
}
return null;
}
/**
* 把字符串编码为base32进制字符串(通过Google guava)
*
* @return
*/
public static String stringToBase32StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return BaseEncoding.base32().encode(sourceString.getBytes());
}
return null;
}
/**
* 把base32字符串解码为源字符串(通过Google guava)
*
* @return
*/
public static String base32StringToSourceStringByGuava(final String base32String) {
if (isNotBlank(base32String)) {
return new String(BaseEncoding.base32().decode(base32String));
}
return null;
}
/**
* 把字符串编码为base64进制字符串(通过Google guava)
* 这种 base64 出来的结果会带等号,比如:<KEY>
*
* @return
*/
public static String stringToBase64StringByGuava(final String sourceString) {
if (isNotBlank(sourceString)) {
return BaseEncoding.base64().encode(sourceString.getBytes());
}
return null;
}
/**
* 把字符串编码为base64进制字符串(通过 commons codec)
* 这种 base64 出来的结果不会带等号,推荐使用,比如:<KEY>
*
* @return
*/
public static String stringToBase64StringByCodec(final String sourceString) {
if (isNotBlank(sourceString)) {
return Base64.encodeBase64URLSafeString(sourceString.getBytes());
}
return null;
}
/**
* 把字节编码为base64进制字符串(通过Google guava)
*
* @return
*/
public static String byteToBase64StringByGuava(final byte[] bytes) {
if (null != bytes) {
return BaseEncoding.base64().encode(bytes);
}
return null;
}
/**
* 把base64字符串解码为源字符串(通过Google guava)
*
* @return
*/
public static String base64StringToSourceStringByGuava(final String base64String) {
if (isNotBlank(base64String)) {
return new String(BaseEncoding.base64().decode(base64String));
}
return null;
}
/**
* 把base64字符串解码为源字符串(通过 commons codec) (推荐)
*
* @return
* @throws IllegalArgumentException
*/
public static String base64StringToSourceStringByCodec(final String base64String) {
if (isNotBlank(base64String)) {
return new String(Base64.decodeBase64(base64String));
}
return null;
}
/**
* 把base64字符串解码为源字符串数组(通过Google guava)
*
* @return
* @throws IllegalArgumentException
*/
public static byte[] base64StringToSourceByteByGuava(final String base64String) {
if (isNotBlank(base64String)) {
return BaseEncoding.base64().decode(base64String);
}
return null;
}
//============================================================================================================
private final static String[] hexDigits = {
"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F"};
/**
* 转换字节数组为16进制字串
*
* @param b 字节数组
* @return 16进制字串
*/
public static String byteArrayToHexString(final byte[] b) {
StringBuilder resultSb = new StringBuilder();
for (byte temp : b) {
resultSb.append(byteToHexString(temp));
}
return resultSb.toString();
}
/**
* 转换字符串为16进制字串
*
* @param bString 字符串
* @return 16进制字串
*/
public static String stringToHexString(final String bString) {
byte[] b = bString.getBytes();
StringBuilder resultSb = new StringBuilder();
for (byte temp : b) {
resultSb.append(byteToHexString(temp));
}
return resultSb.toString();
}
private static String byteToHexString(final byte b) {
int n = b;
if (n < 0) {
n = 256 + n;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
/**
* 获取 URL 后缀
* 比如:"/template/abc/login.jsp",得到的结果是:.jsp
*
* @param url
* @return
*/
public static String getUrlSuffix(final String url) {
if (isNotBlank(url)) {
return substring(url, indexOf(url, "."), url.length());
}
return null;
}
/**
* 把带有指定分隔符的字符串转换成Long类型的List
*
* @param ids
* @param separatorChars
* @return
*/
public static List<Long> stringToLongListByIds(final String ids, final String separatorChars) {
if (isNotBlank(ids) && isNotBlank(separatorChars)) {
String[] splitArray = split(ids, separatorChars);
List<Long> idsByLong = new ArrayList<Long>();
for (String temp : splitArray) {
//校验是否其下还有未删除的子节点
Long idByLong = Long.valueOf(temp);
idsByLong.add(idByLong);
}
return idsByLong;
}
return null;
}
/**
* 驼峰命名法工具
*
* @return toCamelCase(hello_world) == "helloWorld"
*/
public static String toCamelCase(String s) {
final char SEPARATOR = '_';
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 驼峰命名法工具
*
* @return toCapitalizeCamelCase(hello_world) == "HelloWorld"
*/
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
return null;
}
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/**
* 驼峰命名法工具
*
* @return toUnderScoreCase(helloWorld) = "hello_world"
*/
public static String toUnderScoreCase(String s) {
final char SEPARATOR = '_';
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 判断文件 contentType 是否是图片的格式
* 使用方法:
* <p>
* MultipartFile picFileInfo;
* String contentType = picFileInfo.getContentType();
*
* @param contentType
* @return
*/
public static Boolean judgePictureFormat(String contentType) {
if (isBlank(contentType)) {
return false;
}
return contentType.equalsIgnoreCase("image/png") || contentType.equalsIgnoreCase("image/jpeg") || contentType
.equalsIgnoreCase("image/jpg") || contentType.equalsIgnoreCase("image/gif");
}
/**
* 根据中文首字母排序
*
* @param stringList
* @return
*/
public static List sortChineseStringList(List<String> stringList) {
if (stringList.size() == 0) {
return null;
}
//把list转换成数组
String[] arrStrings = stringList.toArray(new String[stringList.size()]);
// Collator 类是用来执行区分语言环境的 String 比较的,这里选择使用CHINA
Comparator comparator = Collator.getInstance(Locale.CHINA);
// 使根据指定比较器产生的顺序对指定对象数组进行排序。
Arrays.sort(arrStrings, comparator);
//把数组转换成List(不过Arrays.asList()方法返回的List不能add对象,因为该方法的实现是使用参数引用的数组的大小来new的一个ArrayList,会报异常:java.lang
// .UnsupportedOperationException)
return Arrays.asList(arrStrings);
}
/**
* 拼接字符串,把多个字符串拼接成一个字符串
*
* @param separator 拼接符,可以为空字符,但是不能为空格
* @param rest 需要拼接的字符串内容
* @return
*/
public static String joinString(String separator, Object... rest) {
if (isBlank(separator)) {
separator = "";
}
return Joiner.on(separator).skipNulls().join(rest);
}
/**
* 把字符串转换成 List(通过 Guava)
*
* @param separator
* @param target
* @return
*/
public static List<String> stringToList(String separator, String target) {
return Splitter.on(separator).trimResults().splitToList(target);
}
/**
* 把 List 转换成字符串
*
* @param separator
* @param target
* @return
*/
public static String listToString(String separator, List target) {
return Joiner.on(separator).skipNulls().join(target);
}
/**
* 把字符串转换成 Map
*
* @param separator
* @param keyValueSeparator
* @param target 需要转换的字符串,建议有类似这样的格式:"John=first,Adam=second";
* @return
*/
public static Map<String, String> stringToMap(String separator, String keyValueSeparator, String target) {
return Splitter.on(separator).withKeyValueSeparator(keyValueSeparator).split(target);
}
/**
* 把 Map 转换成字符串
*
* @param separator
* @param keyValueSeparator
* @param target
* @return
*/
public static String mapToString(String separator, String keyValueSeparator, Map target) {
//key和value不能有null
return Joiner.on(separator).withKeyValueSeparator(keyValueSeparator).join(target);
}
/**
* 寻找两个字符串之间共同的前缀,也就是从一个位置开始算
* eg:
* <p>
* String param1 = ",13,2,3,4,5,6,";
* String param2 = ",134,222,3,44,5,666,";
* String result = StrUtils.findCommonPrefix(param1, param2);
* 结果为:,13
*
* @param param1
* @param param2
* @return
*/
public static String findCommonPrefix(String param1, String param2) {
return Strings.commonPrefix(param1, param2);
}
/**
* 寻找两个字符串之间共同的后缀
* eg:
* <p>
* String param1 = ",13,2,3,4,5,6,";
* String param2 = ",134,222,3,44,5,666,";
* String result = StrUtils.findCommonSuffix(param1, param2);
* 结果为:6,
*
* @param param1
* @param param2
* @return
*/
public static String findCommonSuffix(String param1, String param2) {
return Strings.commonSuffix(param1, param2);
}
}
| 24,117 | 0.650136 | 0.634391 | 961 | 21.5359 | 24.954256 | 113 | false | false | 0 | 0 | 0 | 0 | 114 | 0.020224 | 1.635796 | false | false |
0
|
157031fa8c71db92468b106c3b3ef4d323385c20
| 27,556,510,207,459 |
e5f3a8a8f2aca58d6b13f5655fb04d6bb547a714
|
/src/main/java/com/cdk/carbuy/dao/OrderDAO.java
|
7c91d1000e0141e79a862baab1da453537c44e4b
|
[] |
no_license
|
anithashok1910/CaseStudy-car-buy
|
https://github.com/anithashok1910/CaseStudy-car-buy
|
c29c122d71da1a116bd7eade49a4985f74d79742
|
bce6f2b90f2406b95e830a010d282551ce8fd828
|
refs/heads/master
| 2020-04-24T05:20:12.298000 | 2016-09-09T09:00:28 | 2016-09-09T09:00:28 | 67,688,719 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cdk.carbuy.dao;
import com.cdk.carbuy.dto.Order;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* Created by guptah on 9/1/2016.
*/
@Component
public class OrderDAO {
@Autowired
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public Order addOrder(Order order) {
com.cdk.carbuy.domain.Order domainOrder = new com.cdk.carbuy.domain.Order(order);
hibernateTemplate.save(domainOrder);
order = new Order(domainOrder);
return order;
}
}
|
UTF-8
|
Java
| 993 |
java
|
OrderDAO.java
|
Java
|
[
{
"context": "ion;\nimport java.io.FileReader;\n\n/**\n * Created by guptah on 9/1/2016.\n */\n@Component\npublic class OrderDAO",
"end": 397,
"score": 0.9996786713600159,
"start": 391,
"tag": "USERNAME",
"value": "guptah"
}
] | null |
[] |
package com.cdk.carbuy.dao;
import com.cdk.carbuy.dto.Order;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* Created by guptah on 9/1/2016.
*/
@Component
public class OrderDAO {
@Autowired
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public Order addOrder(Order order) {
com.cdk.carbuy.domain.Order domainOrder = new com.cdk.carbuy.domain.Order(order);
hibernateTemplate.save(domainOrder);
order = new Order(domainOrder);
return order;
}
}
| 993 | 0.748238 | 0.741188 | 37 | 25.837837 | 23.917101 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432432 | false | false |
0
|
e464f643246a62a984a17530abaa666f2787a3d8
| 3,169,685,878,832 |
224e6cd990e439176cc148dcbcef8a2f3c1d6fb2
|
/src/main/java/ml/jmoodle/authentications/MoodleAuthentication.java
|
dd4f1143af4ee0ab3ae9b1fbd9895871e7deb8ec
|
[
"MIT"
] |
permissive
|
tuliomn/jMoodle
|
https://github.com/tuliomn/jMoodle
|
2ae261b45a2da35539f00f42e9b67c438fee6340
|
7ddd4540858d3e37a0732634a2e610cb2c084b81
|
refs/heads/master
| 2018-03-25T15:48:09.948000 | 2016-08-29T17:48:16 | 2016-08-29T17:48:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ml.jmoodle.authentications;
/**
* Interface for Moodle WS authentication methods
*
*
* @author Carlos Alexandre S. da Fonseca
* @copyrigth © 2016 Carlos Alexandre S. da Fonseca
* @license https://opensource.org/licenses/MIT - MIT License
*
*/
public interface MoodleAuthentication {
/**
* Get the authentication string
* @return Authentication String
*/
String getAuthentication();
}
|
UTF-8
|
Java
| 413 |
java
|
MoodleAuthentication.java
|
Java
|
[
{
"context": "oodle WS authentication methods\n * \n * \n * @author Carlos Alexandre S. da Fonseca\n * @copyrigth © 2016 Carlos Alexandre S. da Fonse",
"end": 141,
"score": 0.9998846054077148,
"start": 111,
"tag": "NAME",
"value": "Carlos Alexandre S. da Fonseca"
},
{
"context": "arlos Alexandre S. da Fonseca\n * @copyrigth © 2016 Carlos Alexandre S. da Fonseca\n * @license https://opensource.org/licenses/MIT -",
"end": 193,
"score": 0.9998821020126343,
"start": 163,
"tag": "NAME",
"value": "Carlos Alexandre S. da Fonseca"
}
] | null |
[] |
package ml.jmoodle.authentications;
/**
* Interface for Moodle WS authentication methods
*
*
* @author <NAME>
* @copyrigth © 2016 <NAME>
* @license https://opensource.org/licenses/MIT - MIT License
*
*/
public interface MoodleAuthentication {
/**
* Get the authentication string
* @return Authentication String
*/
String getAuthentication();
}
| 365 | 0.720874 | 0.711165 | 19 | 20.68421 | 20.591394 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false |
0
|
eb9ac0c407925eeac597dbeaf7517478fc0913b0
| 11,579,231,876,396 |
36a6cf3869191757466c617719b405d1b0a17db6
|
/src/test/java/com/lionxxw/seckill/service/SeckillServiceTest.java
|
616d7926d3caef91cfa4157c4d89b1190cdc1c46
|
[] |
no_license
|
fimi2008/seckill
|
https://github.com/fimi2008/seckill
|
e0773f6b9bc688e7fa7f307a32462fa26d0a3c30
|
2cc13cb0cde6fa431a15f9c479c5755ecfed3df2
|
refs/heads/master
| 2021-01-21T10:19:09.975000 | 2018-11-26T06:01:13 | 2018-11-26T06:01:13 | 83,403,589 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lionxxw.seckill.service;
import com.lionxxw.seckill.dto.Exposer;
import com.lionxxw.seckill.dto.SeckillExecution;
import com.lionxxw.seckill.entity.Seckill;
import com.lionxxw.seckill.exception.RepeatKillException;
import com.lionxxw.seckill.exception.SeckillCloseException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* @author lionxxw
* @version 1.0.0
* @description 接口集成测试类
* @package com.lionxxw.seckill.service
* @project seckill
* @date 2017/3/1 9:48
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml"})
public class SeckillServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private SeckillService seckillService;
@Test
public void getSeckillList() throws Exception {
List<Seckill> seckillList = seckillService.getSeckillList();
logger.info("seckillList={}", seckillList);
}
@Test
public void getById() throws Exception {
Long id = 1000L;
Seckill seckill = seckillService.getById(id);
logger.info("seckill={}", seckill);
}
/**
* 测试整个秒杀业务逻辑
* @throws Exception
*/
@Test
public void testSeckillLogic() throws Exception {
Long id = 1000L;
Exposer exposer = seckillService.exportSeckillUrl(id);
if (exposer.getExposed()) {
logger.info("exposer={}", exposer);
String userPhone = "18721472364";
String md5 = exposer.getMd5();
SeckillExecution seckillExecution = null;
try {
seckillExecution = seckillService.executeSeckill(id, userPhone, md5);
logger.info("seckillExecution={}", seckillExecution);
} catch (SeckillCloseException e) {
logger.error(e.getMessage());
} catch (RepeatKillException e) {
logger.error(e.getMessage());
}
} else {
// 秒杀未开始
logger.warn("exposer={}", exposer);
}
}
/**
* 测试存储过程
*/
@Test
public void testExecuteSeckillByProcedure(){
Long id = 1001L;
Exposer exposer = seckillService.exportSeckillUrl(id);
if (exposer.getExposed()) {
logger.info("exposer={}", exposer);
String userPhone = "18721472364";
String md5 = exposer.getMd5();
SeckillExecution seckillExecution = null;
try {
seckillExecution = seckillService.executeSeckillByProcedure(id, userPhone, md5);
logger.info("seckillExecution={}", seckillExecution);
} catch (SeckillCloseException e) {
logger.error(e.getMessage());
} catch (RepeatKillException e) {
logger.error(e.getMessage());
}
} else {
// 秒杀未开始
logger.warn("exposer={}", exposer);
}
}
}
|
UTF-8
|
Java
| 3,332 |
java
|
SeckillServiceTest.java
|
Java
|
[
{
"context": "assRunner;\n\nimport java.util.List;\n\n/**\n * @author lionxxw\n * @version 1.0.0\n * @description 接口集成测试类\n * @pac",
"end": 645,
"score": 0.9996693134307861,
"start": 638,
"tag": "USERNAME",
"value": "lionxxw"
}
] | null |
[] |
package com.lionxxw.seckill.service;
import com.lionxxw.seckill.dto.Exposer;
import com.lionxxw.seckill.dto.SeckillExecution;
import com.lionxxw.seckill.entity.Seckill;
import com.lionxxw.seckill.exception.RepeatKillException;
import com.lionxxw.seckill.exception.SeckillCloseException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* @author lionxxw
* @version 1.0.0
* @description 接口集成测试类
* @package com.lionxxw.seckill.service
* @project seckill
* @date 2017/3/1 9:48
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml"})
public class SeckillServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private SeckillService seckillService;
@Test
public void getSeckillList() throws Exception {
List<Seckill> seckillList = seckillService.getSeckillList();
logger.info("seckillList={}", seckillList);
}
@Test
public void getById() throws Exception {
Long id = 1000L;
Seckill seckill = seckillService.getById(id);
logger.info("seckill={}", seckill);
}
/**
* 测试整个秒杀业务逻辑
* @throws Exception
*/
@Test
public void testSeckillLogic() throws Exception {
Long id = 1000L;
Exposer exposer = seckillService.exportSeckillUrl(id);
if (exposer.getExposed()) {
logger.info("exposer={}", exposer);
String userPhone = "18721472364";
String md5 = exposer.getMd5();
SeckillExecution seckillExecution = null;
try {
seckillExecution = seckillService.executeSeckill(id, userPhone, md5);
logger.info("seckillExecution={}", seckillExecution);
} catch (SeckillCloseException e) {
logger.error(e.getMessage());
} catch (RepeatKillException e) {
logger.error(e.getMessage());
}
} else {
// 秒杀未开始
logger.warn("exposer={}", exposer);
}
}
/**
* 测试存储过程
*/
@Test
public void testExecuteSeckillByProcedure(){
Long id = 1001L;
Exposer exposer = seckillService.exportSeckillUrl(id);
if (exposer.getExposed()) {
logger.info("exposer={}", exposer);
String userPhone = "18721472364";
String md5 = exposer.getMd5();
SeckillExecution seckillExecution = null;
try {
seckillExecution = seckillService.executeSeckillByProcedure(id, userPhone, md5);
logger.info("seckillExecution={}", seckillExecution);
} catch (SeckillCloseException e) {
logger.error(e.getMessage());
} catch (RepeatKillException e) {
logger.error(e.getMessage());
}
} else {
// 秒杀未开始
logger.warn("exposer={}", exposer);
}
}
}
| 3,332 | 0.63319 | 0.615738 | 100 | 31.67 | 23.364098 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.56 | false | false |
0
|
f8cc46ae8c70eec893fe26f92d43ce83db65a178
| 11,879,879,588,213 |
cb0ba5bfa61576bd679eb1b60e53a30c488e4f86
|
/src/ncu/im3069/Group23/controllers/RequirementController.java
|
d7ce12415260518b4d5db3583d57a17c0c5ceeb0
|
[] |
no_license
|
cyihsu/ncuim-sa-final-project
|
https://github.com/cyihsu/ncuim-sa-final-project
|
70d78d91be275a24767abb36d2b66df5afc0ec47
|
736aca82124862e6ff88b34c45ad07e0e67066bc
|
refs/heads/master
| 2020-10-01T18:09:11.394000 | 2020-01-06T04:37:26 | 2020-01-06T04:37:26 | 227,595,205 | 0 | 0 | null | false | 2020-01-02T14:02:22 | 2019-12-12T11:53:08 | 2019-12-12T12:35:41 | 2020-01-02T14:02:21 | 5,638 | 0 | 0 | 0 |
Java
| false | false |
package ncu.im3069.Group23.controllers;
import java.text.*;
import java.util.*;
import javax.annotation.security.*;
import javax.persistence.NoResultException;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import org.hibernate.*;
import org.hibernate.query.Query;
import ncu.im3069.Group23.models.ResponseContent;
import ncu.im3069.Group23.models.TimeRequirement;
import ncu.im3069.Group23.utils.HibernateUtils;
@Path("/schedule")
public class RequirementController {
SessionFactory sf = HibernateUtils.getSessionFactory();
Session session = sf.getCurrentSession();
Transaction tx = null;
/*
* Transform date String to the Date Object
*/
public Date transformDateString(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC+8"));
Date tmpDate = null;
try {
tmpDate = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return tmpDate;
}
/*
* deleteRequirement()
* Delete specific requirement
*/
@RolesAllowed("ADMIN")
@DELETE
@Path("/date/{date}/{time}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteRequirement(@PathParam("date") String date, @PathParam("time") int time)
{
// Flag for the transaction status;
Boolean success = false;
try {
// Parsing date string
Date tmpDate = transformDateString(date);
// Get the transaction instance and begin the transaction.
tx = session.getTransaction();
tx.begin();
// Querying specific date and time
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.tokenDate = :date and t.tokenTime = :time")
.setParameter("date", tmpDate)
.setParameter("time", time);
TimeRequirement tmpTR = query.getSingleResult();
// Remove all TimeAvailables and the TimeRequirement itself
tmpTR.getAvailableWorkforce().forEach(worker -> session.remove(worker));
session.remove(tmpTR);
tx.commit();
success = true;
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "removed successfully", null)).build();
} else {
return Response.status(Status.BAD_REQUEST).entity(new ResponseContent(400, "bad request", null)).build();
}
}
/*
* patchRequirement()
* Patch specific requirement
*/
@RolesAllowed("ADMIN")
@PATCH
@Path("/date/{date}/{time}")
@Produces(MediaType.APPLICATION_JSON)
public Response patchRequirement(@PathParam("date") String date, @PathParam("time") int time,
@FormParam("workforce") int workforce)
{
// Flag for the transaction status;
Boolean success = false;
// Only if the workforce parameter > 0 will execute the following procedure.
if(workforce > 0) {
try {
// Parsing date string
Date tmpDate = transformDateString(date);
// Get the transaction instance and begin the transaction.
tx = session.getTransaction();
tx.begin();
// Querying specific date and time
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.tokenDate = :date and t.tokenTime = :time")
.setParameter("date", tmpDate)
.setParameter("time", time);
TimeRequirement tmpTR = query.getSingleResult();
// Adjust the requirement and commit current transaction
tmpTR.setWorkforceRequirements(workforce);
session.save(tmpTR);
tx.commit();
success = true;
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "patched successfully", null)).build();
} else {
return Response.status(Status.BAD_REQUEST).entity(new ResponseContent(400, "bad request", null)).build();
}
}
/*
* addRequirement()
* Add specific requirement
*/
@RolesAllowed("ADMIN")
@POST
@Path("/date/add")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response addRequirement(@FormParam("date") String date,
@FormParam("time") int time,
@FormParam("workforce") int workforce)
{
// Flag for the transaction status;
Boolean success = false;
// Begin the TimeRequirement creation.
try {
// Parsing date string
Date tmpDate = transformDateString(date);
// Get the transaction instance and begin the transaction.
tx = session.getTransaction();
tx.begin();
// Querying if specific date and time exists.
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.tokenDate = :date and t.tokenTime = :time")
.setParameter("date", tmpDate)
.setParameter("time", time);
// Check if there's no such result
// or the current transaction will be rolling back
TimeRequirement tmpTR = null;
try {
tmpTR = query.getSingleResult();
tx.rollback();
} catch(NoResultException e) {
// If there's no duplicated results
tmpTR = new TimeRequirement(tmpDate, time, workforce);
session.save(tmpTR);
tx.commit();
success = true;
} catch(Exception e) {
System.out.println(e);
tx.rollback();
} finally {
// Close the current session.
session.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "created successfully", null)).build();
} else {
return Response.status(Status.BAD_REQUEST).entity(new ResponseContent(400, "bad request", null)).build();
}
}
@RolesAllowed({"ADMIN", "USER"})
@GET
@Path("/year/{year}")
@Produces(MediaType.APPLICATION_JSON)
public Response getWeeklyRequirement(@PathParam("year") int year, @QueryParam("week") int week)
{
// Flag for the transaction status;
Boolean success = false;
// Variables for the returning values;
List<TimeRequirement> requirements = null;
try {
// Find specific week of the year
session.beginTransaction();
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.week = :week and t.year = :year")
.setParameter("week", week)
.setParameter("year", year);
requirements = query.list();
if (!requirements.isEmpty()) {
success = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "success", requirements)).build();
} else {
return Response.status(Status.NO_CONTENT).entity(new ResponseContent(203, "no results", null)).build();
}
}
@RolesAllowed({"ADMIN", "USER"})
@GET
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllRequirement()
{
// Flag for the transaction status;
Boolean success = false;
// Variables for the returning values;
List<TimeRequirement> requirements = null;
try {
// Find specific week of the year
session.beginTransaction();
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t");
requirements = query.list();
if (!requirements.isEmpty()) {
success = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "success", requirements)).build();
} else {
return Response.status(Status.NO_CONTENT).entity(new ResponseContent(203, "no results", null)).build();
}
}
/*
* OPTIONS METHODS ARE MAKING FOR THE CORS POLICY!
*/
@PermitAll
@OPTIONS
@Path("/year/{id}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionWeek()
{
return Response.status(200).build();
}
@PermitAll
@OPTIONS
@Path("/date/{date}/{time}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionDate()
{
return Response.status(200).build();
}
@PermitAll
@OPTIONS
@Path("/date/add")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionDateAdd()
{
return Response.status(200).build();
}
@PermitAll
@OPTIONS
@Path("/all")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionGetAll()
{
return Response.status(200).build();
}
}
|
UTF-8
|
Java
| 8,901 |
java
|
RequirementController.java
|
Java
|
[] | null |
[] |
package ncu.im3069.Group23.controllers;
import java.text.*;
import java.util.*;
import javax.annotation.security.*;
import javax.persistence.NoResultException;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import org.hibernate.*;
import org.hibernate.query.Query;
import ncu.im3069.Group23.models.ResponseContent;
import ncu.im3069.Group23.models.TimeRequirement;
import ncu.im3069.Group23.utils.HibernateUtils;
@Path("/schedule")
public class RequirementController {
SessionFactory sf = HibernateUtils.getSessionFactory();
Session session = sf.getCurrentSession();
Transaction tx = null;
/*
* Transform date String to the Date Object
*/
public Date transformDateString(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC+8"));
Date tmpDate = null;
try {
tmpDate = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return tmpDate;
}
/*
* deleteRequirement()
* Delete specific requirement
*/
@RolesAllowed("ADMIN")
@DELETE
@Path("/date/{date}/{time}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteRequirement(@PathParam("date") String date, @PathParam("time") int time)
{
// Flag for the transaction status;
Boolean success = false;
try {
// Parsing date string
Date tmpDate = transformDateString(date);
// Get the transaction instance and begin the transaction.
tx = session.getTransaction();
tx.begin();
// Querying specific date and time
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.tokenDate = :date and t.tokenTime = :time")
.setParameter("date", tmpDate)
.setParameter("time", time);
TimeRequirement tmpTR = query.getSingleResult();
// Remove all TimeAvailables and the TimeRequirement itself
tmpTR.getAvailableWorkforce().forEach(worker -> session.remove(worker));
session.remove(tmpTR);
tx.commit();
success = true;
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "removed successfully", null)).build();
} else {
return Response.status(Status.BAD_REQUEST).entity(new ResponseContent(400, "bad request", null)).build();
}
}
/*
* patchRequirement()
* Patch specific requirement
*/
@RolesAllowed("ADMIN")
@PATCH
@Path("/date/{date}/{time}")
@Produces(MediaType.APPLICATION_JSON)
public Response patchRequirement(@PathParam("date") String date, @PathParam("time") int time,
@FormParam("workforce") int workforce)
{
// Flag for the transaction status;
Boolean success = false;
// Only if the workforce parameter > 0 will execute the following procedure.
if(workforce > 0) {
try {
// Parsing date string
Date tmpDate = transformDateString(date);
// Get the transaction instance and begin the transaction.
tx = session.getTransaction();
tx.begin();
// Querying specific date and time
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.tokenDate = :date and t.tokenTime = :time")
.setParameter("date", tmpDate)
.setParameter("time", time);
TimeRequirement tmpTR = query.getSingleResult();
// Adjust the requirement and commit current transaction
tmpTR.setWorkforceRequirements(workforce);
session.save(tmpTR);
tx.commit();
success = true;
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "patched successfully", null)).build();
} else {
return Response.status(Status.BAD_REQUEST).entity(new ResponseContent(400, "bad request", null)).build();
}
}
/*
* addRequirement()
* Add specific requirement
*/
@RolesAllowed("ADMIN")
@POST
@Path("/date/add")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response addRequirement(@FormParam("date") String date,
@FormParam("time") int time,
@FormParam("workforce") int workforce)
{
// Flag for the transaction status;
Boolean success = false;
// Begin the TimeRequirement creation.
try {
// Parsing date string
Date tmpDate = transformDateString(date);
// Get the transaction instance and begin the transaction.
tx = session.getTransaction();
tx.begin();
// Querying if specific date and time exists.
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.tokenDate = :date and t.tokenTime = :time")
.setParameter("date", tmpDate)
.setParameter("time", time);
// Check if there's no such result
// or the current transaction will be rolling back
TimeRequirement tmpTR = null;
try {
tmpTR = query.getSingleResult();
tx.rollback();
} catch(NoResultException e) {
// If there's no duplicated results
tmpTR = new TimeRequirement(tmpDate, time, workforce);
session.save(tmpTR);
tx.commit();
success = true;
} catch(Exception e) {
System.out.println(e);
tx.rollback();
} finally {
// Close the current session.
session.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "created successfully", null)).build();
} else {
return Response.status(Status.BAD_REQUEST).entity(new ResponseContent(400, "bad request", null)).build();
}
}
@RolesAllowed({"ADMIN", "USER"})
@GET
@Path("/year/{year}")
@Produces(MediaType.APPLICATION_JSON)
public Response getWeeklyRequirement(@PathParam("year") int year, @QueryParam("week") int week)
{
// Flag for the transaction status;
Boolean success = false;
// Variables for the returning values;
List<TimeRequirement> requirements = null;
try {
// Find specific week of the year
session.beginTransaction();
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t where t.week = :week and t.year = :year")
.setParameter("week", week)
.setParameter("year", year);
requirements = query.list();
if (!requirements.isEmpty()) {
success = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "success", requirements)).build();
} else {
return Response.status(Status.NO_CONTENT).entity(new ResponseContent(203, "no results", null)).build();
}
}
@RolesAllowed({"ADMIN", "USER"})
@GET
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllRequirement()
{
// Flag for the transaction status;
Boolean success = false;
// Variables for the returning values;
List<TimeRequirement> requirements = null;
try {
// Find specific week of the year
session.beginTransaction();
@SuppressWarnings("unchecked")
Query<TimeRequirement> query = session.createQuery("from TimeRequirement t");
requirements = query.list();
if (!requirements.isEmpty()) {
success = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the current session.
session.close();
}
// Returning the results.
if(success) {
return Response.status(200).entity(new ResponseContent(200, "success", requirements)).build();
} else {
return Response.status(Status.NO_CONTENT).entity(new ResponseContent(203, "no results", null)).build();
}
}
/*
* OPTIONS METHODS ARE MAKING FOR THE CORS POLICY!
*/
@PermitAll
@OPTIONS
@Path("/year/{id}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionWeek()
{
return Response.status(200).build();
}
@PermitAll
@OPTIONS
@Path("/date/{date}/{time}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionDate()
{
return Response.status(200).build();
}
@PermitAll
@OPTIONS
@Path("/date/add")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionDateAdd()
{
return Response.status(200).build();
}
@PermitAll
@OPTIONS
@Path("/all")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response optionGetAll()
{
return Response.status(200).build();
}
}
| 8,901 | 0.691495 | 0.682058 | 322 | 26.642857 | 25.564552 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.52795 | false | false |
0
|
0bfe310585390658013f48ad69f8ea935ee86387
| 3,178,275,827,498 |
e67e002ae02c8d47b37a410f7caffd6053222767
|
/src/com/kyle/service/CoreService.java
|
1c306e510d2a856d3df9272ac6d25ebdac043a56
|
[] |
no_license
|
zhangjinde/weixin
|
https://github.com/zhangjinde/weixin
|
232ad9152e7073bedc69a07433aadd348b4b978d
|
19ad63478166a301c6a762c9dfdf02f0aa2a8b7d
|
refs/heads/master
| 2021-01-19T21:58:22.104000 | 2017-03-03T05:04:14 | 2017-03-03T05:04:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kyle.service;
import com.kyle.message_resp.*;
import com.kyle.util.FacePlusPlusUtil;
import com.kyle.util.MessageUtil;
import com.kyle.util.MysqlUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created by Java on 2016/10/9.
* 邏輯處理,就是你想怎麽將請求消息進行處理就怎麽處理,按照你的意願返回
*/
public class CoreService {
public static String processRequest(HttpServletRequest request){
String respXML=null;
TextMessage tm=new TextMessage(); //想要返回返回的文本對象
//解析请求
try {
HashMap<String,String> requestMap= MessageUtil.parseXml(request);
String fromUserName=requestMap.get("FromUserName");
String toUserName=requestMap.get("ToUserName");
String msgType=requestMap.get("MsgType");
tm.setFromUserName(toUserName);
tm.setToUserName(fromUserName);
tm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
tm.setCreateTime(new Date().getTime());
if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)){
//tm.setContent("您发送的是文本消息");
//将文本保存到BAE数据库
String content=requestMap.get("Content");
//MysqlUtil.saveTextMessage(request,fromUserName,content);
//tm.setContent("BAE MYSQL 已存");
if(content.equals("歌曲")){
Music music=new Music();
music.setTitle("boom boom pow");
music.setDescription("Black Eyed Pea");
music.setMusicUrl("http://kyleweixin.duapp.com/weixin_war/music/boom_boom_pow.mp3");
music.setHQMusicUrl("http://kyleweixin.duapp.com/weixin_war/music/boom_boom_pow.mp3");
MusicMessage mm=new MusicMessage();
mm.setFromUserName(toUserName);
mm.setToUserName(fromUserName);
mm.setCreateTime(new Date().getTime());
mm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_MUSIC);
mm.setMusic(music);
respXML=MessageUtil.messageToXML(mm);
}
else if("2048".equals(content)){
Article article=new Article();
article.setTitle("挑战2048");
article.setDescription("这张图是假的。By the way. 反正我是没到过2048 :)");
article.setPicUrl("http://kyleweixin.duapp.com/weixin_war/image/2048.jpg");
article.setUrl("http://kyleweixin.duapp.com/weixin_war/2048/index.html");
List<Article> articles=new ArrayList<>();
articles.add(article);
NewsMessage nm=new NewsMessage();
nm.setFromUserName(toUserName);
nm.setToUserName(fromUserName);
nm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
nm.setCreateTime(new Date().getTime());
nm.setArticleCount(articles.size());
nm.setArticles(articles);
respXML=MessageUtil.messageToXML(nm);
}else{
tm.setContent("您发送的是文本消息," +
"" +
"" +
"试着发送“2048”看看。");
respXML=MessageUtil.messageToXML(tm);
}
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)){
String imageUrl=requestMap.get("PicUrl");
String result=FacePlusPlusUtil.detectFace(imageUrl);
if(result!=null){
tm.setContent(FacePlusPlusUtil.detectFace(imageUrl));
}else{
tm.setContent("无法识别图片,请换一张。");
}
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)){
tm.setContent("您发送的是视频消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)){
tm.setContent("您发送的是语音消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)){
tm.setContent("您发送的是链接消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)){
tm.setContent("您发送的是地址消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)){
String eventType=requestMap.get("Event");
if(eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)){
tm.setContent("Boom! Boom! Boom!欢迎关注!看到这条消息的人三天内必有好事发生!");
respXML=MessageUtil.messageToXML(tm);
}else if( eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)){
}
}
} catch (Exception e) {
e.printStackTrace();
}
return respXML; //再将tm对象转成xml格式
}
}
|
UTF-8
|
Java
| 5,545 |
java
|
CoreService.java
|
Java
|
[
{
"context": "HashMap;\nimport java.util.List;\n\n/**\n * Created by Java on 2016/10/9.\n * 邏輯處理,就是你想怎麽將請求消息進行處理就怎麽處理,按照你的意願",
"end": 336,
"score": 0.9955761432647705,
"start": 332,
"tag": "USERNAME",
"value": "Java"
},
{
"context": "Message();\n mm.setFromUserName(toUserName);\n mm.setToUserName(fromUserNa",
"end": 1908,
"score": 0.9994021654129028,
"start": 1898,
"tag": "USERNAME",
"value": "toUserName"
},
{
"context": "toUserName);\n mm.setToUserName(fromUserName);\n mm.setCreateTime(new Date()",
"end": 1960,
"score": 0.9991481304168701,
"start": 1948,
"tag": "USERNAME",
"value": "fromUserName"
},
{
"context": "Message();\n nm.setFromUserName(toUserName);\n nm.setToUserName(fromUserNa",
"end": 2842,
"score": 0.9996042251586914,
"start": 2832,
"tag": "USERNAME",
"value": "toUserName"
},
{
"context": "toUserName);\n nm.setToUserName(fromUserName);\n nm.setMsgType(MessageUtil.R",
"end": 2894,
"score": 0.9995275735855103,
"start": 2882,
"tag": "USERNAME",
"value": "fromUserName"
}
] | null |
[] |
package com.kyle.service;
import com.kyle.message_resp.*;
import com.kyle.util.FacePlusPlusUtil;
import com.kyle.util.MessageUtil;
import com.kyle.util.MysqlUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created by Java on 2016/10/9.
* 邏輯處理,就是你想怎麽將請求消息進行處理就怎麽處理,按照你的意願返回
*/
public class CoreService {
public static String processRequest(HttpServletRequest request){
String respXML=null;
TextMessage tm=new TextMessage(); //想要返回返回的文本對象
//解析请求
try {
HashMap<String,String> requestMap= MessageUtil.parseXml(request);
String fromUserName=requestMap.get("FromUserName");
String toUserName=requestMap.get("ToUserName");
String msgType=requestMap.get("MsgType");
tm.setFromUserName(toUserName);
tm.setToUserName(fromUserName);
tm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
tm.setCreateTime(new Date().getTime());
if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)){
//tm.setContent("您发送的是文本消息");
//将文本保存到BAE数据库
String content=requestMap.get("Content");
//MysqlUtil.saveTextMessage(request,fromUserName,content);
//tm.setContent("BAE MYSQL 已存");
if(content.equals("歌曲")){
Music music=new Music();
music.setTitle("boom boom pow");
music.setDescription("Black Eyed Pea");
music.setMusicUrl("http://kyleweixin.duapp.com/weixin_war/music/boom_boom_pow.mp3");
music.setHQMusicUrl("http://kyleweixin.duapp.com/weixin_war/music/boom_boom_pow.mp3");
MusicMessage mm=new MusicMessage();
mm.setFromUserName(toUserName);
mm.setToUserName(fromUserName);
mm.setCreateTime(new Date().getTime());
mm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_MUSIC);
mm.setMusic(music);
respXML=MessageUtil.messageToXML(mm);
}
else if("2048".equals(content)){
Article article=new Article();
article.setTitle("挑战2048");
article.setDescription("这张图是假的。By the way. 反正我是没到过2048 :)");
article.setPicUrl("http://kyleweixin.duapp.com/weixin_war/image/2048.jpg");
article.setUrl("http://kyleweixin.duapp.com/weixin_war/2048/index.html");
List<Article> articles=new ArrayList<>();
articles.add(article);
NewsMessage nm=new NewsMessage();
nm.setFromUserName(toUserName);
nm.setToUserName(fromUserName);
nm.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
nm.setCreateTime(new Date().getTime());
nm.setArticleCount(articles.size());
nm.setArticles(articles);
respXML=MessageUtil.messageToXML(nm);
}else{
tm.setContent("您发送的是文本消息," +
"" +
"" +
"试着发送“2048”看看。");
respXML=MessageUtil.messageToXML(tm);
}
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)){
String imageUrl=requestMap.get("PicUrl");
String result=FacePlusPlusUtil.detectFace(imageUrl);
if(result!=null){
tm.setContent(FacePlusPlusUtil.detectFace(imageUrl));
}else{
tm.setContent("无法识别图片,请换一张。");
}
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)){
tm.setContent("您发送的是视频消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)){
tm.setContent("您发送的是语音消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)){
tm.setContent("您发送的是链接消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)){
tm.setContent("您发送的是地址消息");
respXML=MessageUtil.messageToXML(tm);
}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)){
String eventType=requestMap.get("Event");
if(eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)){
tm.setContent("Boom! Boom! Boom!欢迎关注!看到这条消息的人三天内必有好事发生!");
respXML=MessageUtil.messageToXML(tm);
}else if( eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)){
}
}
} catch (Exception e) {
e.printStackTrace();
}
return respXML; //再将tm对象转成xml格式
}
}
| 5,545 | 0.56 | 0.553623 | 122 | 41.418034 | 25.842791 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606557 | false | false |
0
|
2f1b07c5c4cdb0596aa0fd05d4037577638f9466
| 32,719,060,876,038 |
320f31665b7fa7022358930c345050557ec2f2d7
|
/proiect/src/CenterAlign.java
|
ca91d46f69a73b874759a2eadcc815a186a57f6a
|
[] |
no_license
|
robertmuraru/Muraru-Alexa-Robert_IR_SP
|
https://github.com/robertmuraru/Muraru-Alexa-Robert_IR_SP
|
6deba1ad11d0adddea86a43c4ca7e2f17469e462
|
8ca1b6513253f85923982eeae6825665911f3007
|
refs/heads/master
| 2021-05-11T18:04:07.789000 | 2018-01-17T09:39:41 | 2018-01-17T09:39:41 | 117,814,700 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class CenterAlign implements AlignStrategy {
public void print(String text) {
System.out.print("***" + text + "***");
}
}
|
UTF-8
|
Java
| 136 |
java
|
CenterAlign.java
|
Java
|
[] | null |
[] |
public class CenterAlign implements AlignStrategy {
public void print(String text) {
System.out.print("***" + text + "***");
}
}
| 136 | 0.647059 | 0.647059 | 6 | 21.5 | 20.830666 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
0
|
0ea48fabadac4d88aca5d67ce38cc35364e72f6e
| 19,000,935,341,342 |
f184f6c7101c40a08d80d49d38f883c55b2453c7
|
/Source/monopolycards/ui/test/PlayerInfoTest.java
|
1e34cfb3625033344cd193eb86d7600a57ab0e5b
|
[] |
no_license
|
theKidOfArcrania/Monopoly-Cards
|
https://github.com/theKidOfArcrania/Monopoly-Cards
|
6156de5530fd56537f3ddfa539c4786ea45cc548
|
9ba0480bf0d196b283cd6d4ffa897ec46d4dd5e7
|
refs/heads/master
| 2021-01-01T19:39:32.143000 | 2017-02-02T19:26:47 | 2017-02-02T19:26:47 | 40,675,463 | 1 | 1 | null | false | 2015-08-21T20:08:57 | 2015-08-13T18:35:33 | 2015-08-21T14:31:33 | 2015-08-21T20:08:57 | 15,336 | 0 | 0 | 0 |
Java
| null | null |
package monopolycards.ui.test;
import java.awt.Dimension;
import java.awt.DisplayMode;
import javafx.animation.Animation.Status;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.InnerShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import static java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment;
public class PlayerInfoTest extends Application {
private static final double ANCHOR = 10.0;
//test
public static void main(String[] args) {
launch(args);
}
private final PerspectiveCamera cameraView = new PerspectiveCamera();
private final DisplayMode defaultMode = getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDisplayMode();
private final Dimension displayRes = new Dimension(defaultMode.getWidth(), defaultMode.getHeight());
public final double dispWidth = displayRes.getWidth();
public final double dispHeight = displayRes.getHeight();
public double wRatio = dispWidth/1600;
public double hRatio = dispHeight/900;
//user variables
private SimpleIntegerProperty moneyValue;
private SimpleStringProperty playerName;
private final SimpleDoubleProperty alph;
private SimpleIntegerProperty setNumber;
private final Timeline solid = new Timeline();
public PlayerInfoTest() {
alph = new SimpleDoubleProperty(.4);
}
public ImageView createScrew(Effect g)
{
Image turnoff = new Image((PlayerInfoTest.class.getResource("screw.png").toExternalForm()));
ImageView lightoff = new ImageView();
lightoff.setImage(turnoff);
lightoff.setFitHeight(15);
lightoff.setFitWidth(15);
lightoff.setPreserveRatio(true);
lightoff.setSmooth(true);
lightoff.setCache(true);
lightoff.setEffect(g);
return lightoff;
}
@Override
public void start(Stage primaryStage) throws Exception {
init(primaryStage);
}
public void trans(boolean status){
if (solid.getStatus() == Status.RUNNING) {
return;
}
if (status) {
solid.playFromStart();
} else {
solid.setRate(-1);
solid.jumpTo("end");
solid.play();
}
}
private void init(Stage primaryStage) {
primaryStage.initStyle(StageStyle.TRANSPARENT);
AnchorPane root = new AnchorPane();
InnerShadow smallShade = new InnerShadow();
smallShade.setRadius(2.0);
InnerShadow mediumShade = new InnerShadow();
mediumShade.setRadius(3.0);
InnerShadow largeShade = new InnerShadow();
mediumShade.setRadius(5.0);
InnerShadow greenShade = new InnerShadow();
greenShade.setRadius(2);
greenShade.setColor(Color.DARKGREEN.darker());
DropShadow out = new DropShadow();
out.setRadius(2.0);
Text name = new Text("MyUsername");
//name.textProperty().bind(playerName);
name.setFill(Color.GRAY);
name.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Bold.otf").toExternalForm(), 24));
AnchorPane.setTopAnchor(name, 15.0);
AnchorPane.setLeftAnchor(name,80.0);
name.setEffect(smallShade);
Text money = new Text("Money:");
money.setFill(Color.GREEN.brighter());
money.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(money, 85.0);
AnchorPane.setLeftAnchor(money, 15.0);
money.setEffect(greenShade);
Text moneyDisplay = new Text("$1000M");
//moneyDisplay.textProperty().bind(new SimpleStringProperty(moneyValue.getValue()+""));
moneyDisplay.setFill(Color.GRAY);
moneyDisplay.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(moneyDisplay, 85.0);
AnchorPane.setLeftAnchor(moneyDisplay, 85.0);
moneyDisplay.setEffect(smallShade);
Text properties = new Text("Full Set Count:");
properties.setFill(Color.GREEN.brighter());
properties.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(properties, 112.0);
AnchorPane.setLeftAnchor(properties, 15.0);
properties.setEffect(greenShade);
Text setDisplay = new Text("0 Sets");
//setDisplay.textProperty().bind(new SimpleStringProperty(setNumber.getValue()+""));
setDisplay.setFill(Color.GRAY);
setDisplay.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(setDisplay, 112.0);
AnchorPane.setLeftAnchor(setDisplay, 150.0);
setDisplay.setEffect(smallShade);
Image profileImage = new Image((PlayerInfoTest.class.getResource("blank-profile.jpg").toExternalForm()));
ImageView profileView = new ImageView();
profileView.setImage(profileImage);
profileView.setFitHeight(60);
profileView.setFitWidth(60);
profileView.setSmooth(true);
profileView.setCache(true);
profileView.setEffect(smallShade);
AnchorPane.setTopAnchor(profileView, 15.0);
AnchorPane.setLeftAnchor(profileView, 10.0);
//moneypic
/*Image moneyPic = new Image((PlayerInfoTest.class.getResource("Dollar Sign.png").toExternalForm()));
ImageView moneyView = new ImageView();
moneyView.setImage(moneyPic);
moneyView.setFitHeight(20);
moneyView.setFitWidth(20);
moneyView.setPreserveRatio(true);
moneyView.setSmooth(true);
moneyView.setCache(true);
AnchorPane.setTopAnchor(moneyView, 65.0);
AnchorPane.setLeftAnchor(moneyView, 90.0);
moneyView.setEffect(shader);
//fullsets pic
Image cardPic = new Image((PlayerInfoTest.class.getResource("fullset.png").toExternalForm()));
ImageView cardView = new ImageView();
cardView.setImage(cardPic);
cardView.setFitHeight(50);
cardView.setFitWidth(50);
cardView.setPreserveRatio(true);
cardView.setSmooth(true);
cardView.setCache(true);
cardView.setEffect(shader);
AnchorPane.setTopAnchor(cardView, 85.0);
AnchorPane.setLeftAnchor(cardView, 15.0);*/
Scene scene = new Scene(root, dispWidth/5.5, dispHeight/6);
scene.setFill(Color.color(.85, .85, .85,.4));
ImageView nut1 = createScrew(out);
AnchorPane.setTopAnchor(nut1, 0.0);
AnchorPane.setLeftAnchor(nut1, 0.0);
ImageView nut2 = createScrew(out);
AnchorPane.setTopAnchor(nut2, 0.0);
AnchorPane.setLeftAnchor(nut2, scene.getWidth()-21);
ImageView nut3 = createScrew(out);
AnchorPane.setTopAnchor(nut3, scene.getHeight()-20);
AnchorPane.setLeftAnchor(nut3, 0.0);
ImageView nut4 = createScrew(out);
AnchorPane.setTopAnchor(nut4, scene.getHeight()-20);
AnchorPane.setLeftAnchor(nut4, scene.getWidth()-21);
Rectangle panel = new Rectangle(scene.getWidth()-100, 25);
panel.setArcHeight(5.0);
panel.setArcWidth(5.0);
AnchorPane.setTopAnchor(panel, 50.0);
AnchorPane.setLeftAnchor(panel,80.0);
panel.setFill(Color.DARKGRAY.darker().darker());
panel.setEffect(largeShade);
Text playerRank = new Text("Rank:");
playerRank.setFill(Color.WHITE);
playerRank.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 10));
AnchorPane.setTopAnchor(playerRank, 57.0);
AnchorPane.setLeftAnchor(playerRank,85.0);
playerRank.setEffect(out);
Text playerGames = new Text("Games:");
playerGames.setFill(Color.WHITE);
playerGames.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 10));
AnchorPane.setTopAnchor(playerGames, 57.0);
AnchorPane.setRightAnchor(playerGames,50.0);
playerGames.setEffect(out);
root.getChildren().addAll(name, properties, money, moneyDisplay, setDisplay, profileView, nut1
,nut2, nut3,nut4, panel, playerRank, playerGames);
root.opacityProperty().bind(alph);
scene.setOnMouseEntered(e->trans(true));
scene.setOnMouseExited(e->trans(false));
//white background
AnchorPane secLayout = new AnchorPane();
Stage secondStage = new Stage();
secondStage.initStyle(StageStyle.TRANSPARENT);
secondStage.setScene(new Scene(secLayout, dispWidth,dispHeight));
//secondStage.show();
root.setId("ROOTNODE");
scene.getStylesheets().add("/monopolycards/ui/test/border.css");
primaryStage.setX(dispWidth/2-scene.getWidth()/2);
primaryStage.setY(0);
primaryStage.setScene(scene);
scene.setCamera(cameraView);
primaryStage.show();
// Timeline
//start
solid.getKeyFrames()
.add(new KeyFrame(Duration.ZERO, new KeyValue(alph, .4),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,.4))));
solid.getKeyFrames()
.add(new KeyFrame(Duration.seconds(.05), new KeyValue(alph, .6),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,.6))));
solid.getKeyFrames()
.add(new KeyFrame(Duration.seconds(.1), new KeyValue(alph, .8),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,.8))));
solid.getKeyFrames()
.add(new KeyFrame(Duration.seconds(.15), new KeyValue(alph, 1.0),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,1.0))));
}
}
|
UTF-8
|
Java
| 9,464 |
java
|
PlayerInfoTest.java
|
Java
|
[
{
"context": ";\n\t\tout.setRadius(2.0);\n\n\n\t\tText name = new Text(\"MyUsername\");\n\t\t//name.textProperty().bind(playerName);\n\t\tna",
"end": 3268,
"score": 0.9995445013046265,
"start": 3258,
"tag": "USERNAME",
"value": "MyUsername"
}
] | null |
[] |
package monopolycards.ui.test;
import java.awt.Dimension;
import java.awt.DisplayMode;
import javafx.animation.Animation.Status;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.InnerShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import static java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment;
public class PlayerInfoTest extends Application {
private static final double ANCHOR = 10.0;
//test
public static void main(String[] args) {
launch(args);
}
private final PerspectiveCamera cameraView = new PerspectiveCamera();
private final DisplayMode defaultMode = getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDisplayMode();
private final Dimension displayRes = new Dimension(defaultMode.getWidth(), defaultMode.getHeight());
public final double dispWidth = displayRes.getWidth();
public final double dispHeight = displayRes.getHeight();
public double wRatio = dispWidth/1600;
public double hRatio = dispHeight/900;
//user variables
private SimpleIntegerProperty moneyValue;
private SimpleStringProperty playerName;
private final SimpleDoubleProperty alph;
private SimpleIntegerProperty setNumber;
private final Timeline solid = new Timeline();
public PlayerInfoTest() {
alph = new SimpleDoubleProperty(.4);
}
public ImageView createScrew(Effect g)
{
Image turnoff = new Image((PlayerInfoTest.class.getResource("screw.png").toExternalForm()));
ImageView lightoff = new ImageView();
lightoff.setImage(turnoff);
lightoff.setFitHeight(15);
lightoff.setFitWidth(15);
lightoff.setPreserveRatio(true);
lightoff.setSmooth(true);
lightoff.setCache(true);
lightoff.setEffect(g);
return lightoff;
}
@Override
public void start(Stage primaryStage) throws Exception {
init(primaryStage);
}
public void trans(boolean status){
if (solid.getStatus() == Status.RUNNING) {
return;
}
if (status) {
solid.playFromStart();
} else {
solid.setRate(-1);
solid.jumpTo("end");
solid.play();
}
}
private void init(Stage primaryStage) {
primaryStage.initStyle(StageStyle.TRANSPARENT);
AnchorPane root = new AnchorPane();
InnerShadow smallShade = new InnerShadow();
smallShade.setRadius(2.0);
InnerShadow mediumShade = new InnerShadow();
mediumShade.setRadius(3.0);
InnerShadow largeShade = new InnerShadow();
mediumShade.setRadius(5.0);
InnerShadow greenShade = new InnerShadow();
greenShade.setRadius(2);
greenShade.setColor(Color.DARKGREEN.darker());
DropShadow out = new DropShadow();
out.setRadius(2.0);
Text name = new Text("MyUsername");
//name.textProperty().bind(playerName);
name.setFill(Color.GRAY);
name.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Bold.otf").toExternalForm(), 24));
AnchorPane.setTopAnchor(name, 15.0);
AnchorPane.setLeftAnchor(name,80.0);
name.setEffect(smallShade);
Text money = new Text("Money:");
money.setFill(Color.GREEN.brighter());
money.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(money, 85.0);
AnchorPane.setLeftAnchor(money, 15.0);
money.setEffect(greenShade);
Text moneyDisplay = new Text("$1000M");
//moneyDisplay.textProperty().bind(new SimpleStringProperty(moneyValue.getValue()+""));
moneyDisplay.setFill(Color.GRAY);
moneyDisplay.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(moneyDisplay, 85.0);
AnchorPane.setLeftAnchor(moneyDisplay, 85.0);
moneyDisplay.setEffect(smallShade);
Text properties = new Text("Full Set Count:");
properties.setFill(Color.GREEN.brighter());
properties.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(properties, 112.0);
AnchorPane.setLeftAnchor(properties, 15.0);
properties.setEffect(greenShade);
Text setDisplay = new Text("0 Sets");
//setDisplay.textProperty().bind(new SimpleStringProperty(setNumber.getValue()+""));
setDisplay.setFill(Color.GRAY);
setDisplay.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 16));
AnchorPane.setTopAnchor(setDisplay, 112.0);
AnchorPane.setLeftAnchor(setDisplay, 150.0);
setDisplay.setEffect(smallShade);
Image profileImage = new Image((PlayerInfoTest.class.getResource("blank-profile.jpg").toExternalForm()));
ImageView profileView = new ImageView();
profileView.setImage(profileImage);
profileView.setFitHeight(60);
profileView.setFitWidth(60);
profileView.setSmooth(true);
profileView.setCache(true);
profileView.setEffect(smallShade);
AnchorPane.setTopAnchor(profileView, 15.0);
AnchorPane.setLeftAnchor(profileView, 10.0);
//moneypic
/*Image moneyPic = new Image((PlayerInfoTest.class.getResource("Dollar Sign.png").toExternalForm()));
ImageView moneyView = new ImageView();
moneyView.setImage(moneyPic);
moneyView.setFitHeight(20);
moneyView.setFitWidth(20);
moneyView.setPreserveRatio(true);
moneyView.setSmooth(true);
moneyView.setCache(true);
AnchorPane.setTopAnchor(moneyView, 65.0);
AnchorPane.setLeftAnchor(moneyView, 90.0);
moneyView.setEffect(shader);
//fullsets pic
Image cardPic = new Image((PlayerInfoTest.class.getResource("fullset.png").toExternalForm()));
ImageView cardView = new ImageView();
cardView.setImage(cardPic);
cardView.setFitHeight(50);
cardView.setFitWidth(50);
cardView.setPreserveRatio(true);
cardView.setSmooth(true);
cardView.setCache(true);
cardView.setEffect(shader);
AnchorPane.setTopAnchor(cardView, 85.0);
AnchorPane.setLeftAnchor(cardView, 15.0);*/
Scene scene = new Scene(root, dispWidth/5.5, dispHeight/6);
scene.setFill(Color.color(.85, .85, .85,.4));
ImageView nut1 = createScrew(out);
AnchorPane.setTopAnchor(nut1, 0.0);
AnchorPane.setLeftAnchor(nut1, 0.0);
ImageView nut2 = createScrew(out);
AnchorPane.setTopAnchor(nut2, 0.0);
AnchorPane.setLeftAnchor(nut2, scene.getWidth()-21);
ImageView nut3 = createScrew(out);
AnchorPane.setTopAnchor(nut3, scene.getHeight()-20);
AnchorPane.setLeftAnchor(nut3, 0.0);
ImageView nut4 = createScrew(out);
AnchorPane.setTopAnchor(nut4, scene.getHeight()-20);
AnchorPane.setLeftAnchor(nut4, scene.getWidth()-21);
Rectangle panel = new Rectangle(scene.getWidth()-100, 25);
panel.setArcHeight(5.0);
panel.setArcWidth(5.0);
AnchorPane.setTopAnchor(panel, 50.0);
AnchorPane.setLeftAnchor(panel,80.0);
panel.setFill(Color.DARKGRAY.darker().darker());
panel.setEffect(largeShade);
Text playerRank = new Text("Rank:");
playerRank.setFill(Color.WHITE);
playerRank.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 10));
AnchorPane.setTopAnchor(playerRank, 57.0);
AnchorPane.setLeftAnchor(playerRank,85.0);
playerRank.setEffect(out);
Text playerGames = new Text("Games:");
playerGames.setFill(Color.WHITE);
playerGames.setFont(Font.loadFont(PlayerInfoTest.class.getResource("Xolonium-Regular.otf").toExternalForm(), 10));
AnchorPane.setTopAnchor(playerGames, 57.0);
AnchorPane.setRightAnchor(playerGames,50.0);
playerGames.setEffect(out);
root.getChildren().addAll(name, properties, money, moneyDisplay, setDisplay, profileView, nut1
,nut2, nut3,nut4, panel, playerRank, playerGames);
root.opacityProperty().bind(alph);
scene.setOnMouseEntered(e->trans(true));
scene.setOnMouseExited(e->trans(false));
//white background
AnchorPane secLayout = new AnchorPane();
Stage secondStage = new Stage();
secondStage.initStyle(StageStyle.TRANSPARENT);
secondStage.setScene(new Scene(secLayout, dispWidth,dispHeight));
//secondStage.show();
root.setId("ROOTNODE");
scene.getStylesheets().add("/monopolycards/ui/test/border.css");
primaryStage.setX(dispWidth/2-scene.getWidth()/2);
primaryStage.setY(0);
primaryStage.setScene(scene);
scene.setCamera(cameraView);
primaryStage.show();
// Timeline
//start
solid.getKeyFrames()
.add(new KeyFrame(Duration.ZERO, new KeyValue(alph, .4),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,.4))));
solid.getKeyFrames()
.add(new KeyFrame(Duration.seconds(.05), new KeyValue(alph, .6),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,.6))));
solid.getKeyFrames()
.add(new KeyFrame(Duration.seconds(.1), new KeyValue(alph, .8),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,.8))));
solid.getKeyFrames()
.add(new KeyFrame(Duration.seconds(.15), new KeyValue(alph, 1.0),
new KeyValue(scene.fillProperty(), Color.color(.85, .85, .85,1.0))));
}
}
| 9,464 | 0.749049 | 0.726014 | 282 | 32.560284 | 25.935509 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.241135 | false | false |
0
|
77c40502eaf3d01a6b17b3ef9a307f6fe263f6c0
| 5,557,687,702,035 |
5bce7ceba3ae5ce9b750c98211c6ed8439611cbb
|
/src/server/src/model/SettingsData.java
|
a78fd45e20e9f28884523e8468b4918c67905ca6
|
[] |
no_license
|
MiniCodeMonkey/Willys-Jukebox
|
https://github.com/MiniCodeMonkey/Willys-Jukebox
|
55f17e74280449a9b9f63f642e9a7ee5fbe4852d
|
aa657115b757f7b3e9f3f81f2308fd8583d86bf1
|
refs/heads/master
| 2021-01-19T00:12:41.518000 | 2015-01-07T04:20:09 | 2015-01-07T04:20:09 | 28,898,018 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package model;
import db.daf.DAFException;
import db.daf.impl.SettingsDAF;
import db.daf.interfaces.ISettingsDAF;
public class SettingsData implements ISettingsData
{
private static SettingsData instance = null;
private ISettingsDAF settingsDAF = null;
/**
* Contructor that initiates all settings
*/
protected SettingsData()
{
settingsDAF = new SettingsDAF();
try
{
if (settingsDAF.getSettingsCount() <= 0)
{
setDefaultSettings();
}
}
catch (DAFException e)
{
setDefaultSettings();
}
}
public void setDefaultSettings()
{
this.set("crossFadingEnabled","false");
this.set("crossFadeSeconds", "4");
this.set("protectWithPasswordEnabled", "false");
this.set("password", "");
this.set("playlistManagerEnabled","false");
this.set("queueSize", "7");
this.set("artistThrottling", "1");
this.set("songFrequency", "15");
this.set("artistFrequency", "10");
}
/**
* gets the instance
* @return instance
*/
public static SettingsData getInstance()
{
if (instance == null)
{
instance = new SettingsData();
}
return instance;
}
public void set(String name, String value){
try
{
settingsDAF.setSetting(name, value);
}
catch (DAFException e)
{
e.printStackTrace();
}
}
public String get(String name)
{
try
{
return settingsDAF.getSetting(name);
}
catch (DAFException e)
{
e.printStackTrace();
}
return "";
}
}
|
UTF-8
|
Java
| 1,442 |
java
|
SettingsData.java
|
Java
|
[] | null |
[] |
package model;
import db.daf.DAFException;
import db.daf.impl.SettingsDAF;
import db.daf.interfaces.ISettingsDAF;
public class SettingsData implements ISettingsData
{
private static SettingsData instance = null;
private ISettingsDAF settingsDAF = null;
/**
* Contructor that initiates all settings
*/
protected SettingsData()
{
settingsDAF = new SettingsDAF();
try
{
if (settingsDAF.getSettingsCount() <= 0)
{
setDefaultSettings();
}
}
catch (DAFException e)
{
setDefaultSettings();
}
}
public void setDefaultSettings()
{
this.set("crossFadingEnabled","false");
this.set("crossFadeSeconds", "4");
this.set("protectWithPasswordEnabled", "false");
this.set("password", "");
this.set("playlistManagerEnabled","false");
this.set("queueSize", "7");
this.set("artistThrottling", "1");
this.set("songFrequency", "15");
this.set("artistFrequency", "10");
}
/**
* gets the instance
* @return instance
*/
public static SettingsData getInstance()
{
if (instance == null)
{
instance = new SettingsData();
}
return instance;
}
public void set(String name, String value){
try
{
settingsDAF.setSetting(name, value);
}
catch (DAFException e)
{
e.printStackTrace();
}
}
public String get(String name)
{
try
{
return settingsDAF.getSetting(name);
}
catch (DAFException e)
{
e.printStackTrace();
}
return "";
}
}
| 1,442 | 0.658114 | 0.652566 | 85 | 15.964705 | 16.110243 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.964706 | false | false |
0
|
2412b8e8f020501464ce4c08d34ea81e0b997dc4
| 11,819,750,027,450 |
4468800dd72174adada7c612b4343b9be4898a6d
|
/java01/src/step08/Test07_4.java
|
6fbaf1c01e4c970d5d5cfc44848278b0baf8da55
|
[] |
no_license
|
sharryhong/java93-hs
|
https://github.com/sharryhong/java93-hs
|
be793ea5d1e692c62939b001eba9d7a314f42be1
|
ec73dbe0669d26073ec0fd7e7db99548c466cee9
|
refs/heads/master
| 2021-01-23T04:34:06.551000 | 2017-06-23T09:13:33 | 2017-06-23T09:13:33 | 86,209,572 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/* 컬렉션(Collection) 클래스 : java.util.HashSet
* => 저장하려는 객체에 대해 hashCode()를 호출하여, 그 리턴 값을 가지고 저장할 위치(인덱스)를 계산 */
package step08;
import java.sql.Date;
import java.util.HashSet;
import java.util.Iterator;
public class Test07_4 {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add(new String("홍길동"));
set.add(new String("임꺽정"));
set.add(new String("유관순"));
set.add(new String("윤봉길"));
set.add(new String("안중근"));
set.add(new String("김구"));
set.add(new String("김구"));
/* new String("김구") 로 하면.. 인스턴스 주소가 다르다고 배웠다. 그럼에도 불구하고 중복되지 않는다!
* Why?
* => Set은 객체(의 주소)를 저장할 때, 그 객체에 대해 hashCode()메서드를 호출한 후, 그 리턴 값으로 위치를 계산한다.
* 그런데 String class는 같은 값을 갖는 경우, 같은 hash value를 리턴하도록 hashCode()를 오버라이딩하였다.
*/
System.out.println(new String("김구").hashCode());
System.out.println(new String("김구").hashCode());
System.out.println(new String("김구").hashCode()); // 모두 같은 값
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
|
UTF-8
|
Java
| 1,450 |
java
|
Test07_4.java
|
Java
|
[] | null |
[] |
/* 컬렉션(Collection) 클래스 : java.util.HashSet
* => 저장하려는 객체에 대해 hashCode()를 호출하여, 그 리턴 값을 가지고 저장할 위치(인덱스)를 계산 */
package step08;
import java.sql.Date;
import java.util.HashSet;
import java.util.Iterator;
public class Test07_4 {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add(new String("홍길동"));
set.add(new String("임꺽정"));
set.add(new String("유관순"));
set.add(new String("윤봉길"));
set.add(new String("안중근"));
set.add(new String("김구"));
set.add(new String("김구"));
/* new String("김구") 로 하면.. 인스턴스 주소가 다르다고 배웠다. 그럼에도 불구하고 중복되지 않는다!
* Why?
* => Set은 객체(의 주소)를 저장할 때, 그 객체에 대해 hashCode()메서드를 호출한 후, 그 리턴 값으로 위치를 계산한다.
* 그런데 String class는 같은 값을 갖는 경우, 같은 hash value를 리턴하도록 hashCode()를 오버라이딩하였다.
*/
System.out.println(new String("김구").hashCode());
System.out.println(new String("김구").hashCode());
System.out.println(new String("김구").hashCode()); // 모두 같은 값
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
| 1,450 | 0.609206 | 0.604693 | 38 | 28.157894 | 23.209034 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.552632 | false | false |
0
|
1dd69030bfedd68dc907bf7a71983cec09ce3b43
| 22,033,182,252,626 |
01becdd9c3418b33e02590b33bcbd97a822fa377
|
/src/Observer/Boss.java
|
9cd352e6a42260618e44ad9380bd1658bc3c73a5
|
[] |
no_license
|
JafetDS/Trabajo_Extraclase2_DatosI_1semestre_2020
|
https://github.com/JafetDS/Trabajo_Extraclase2_DatosI_1semestre_2020
|
16344ccff426beaa075617bb9a7f00f1393de82a
|
8220f9e6b535ed7e013dea6be045df1e79054854
|
refs/heads/master
| 2021-03-25T01:49:44.986000 | 2020-03-25T18:45:53 | 2020-03-25T18:45:53 | 247,579,827 | 0 | 0 | null | false | 2020-03-25T18:45:54 | 2020-03-16T01:00:25 | 2020-03-16T22:22:01 | 2020-03-25T18:45:54 | 309 | 0 | 0 | 0 |
HTML
| false | false |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Observer;
/**
*
* @author Kennet
*/
public class Boss {
private Employe empleado;
/**
*
* @param empleado es el objeto que vamos a observar
*/
// public Boss(Employe empleado){
// this.empleado = empleado;
// this.empleado.setBoss(this);
// }
public Boss(Employe empleado){
this.empleado = empleado;
empleado.setBoss(this);
}
public void Notify() {
if(empleado.isWorking()){
System.out.println("I´m working");
}else{
System.out.println("I´m nott working");
}
}
}
|
UTF-8
|
Java
| 795 |
java
|
Boss.java
|
Java
|
[
{
"context": "e editor.\n */\npackage Observer;\n\n/**\n *\n * @author Kennet\n */\npublic class Boss {\n private Employe em",
"end": 225,
"score": 0.8546298742294312,
"start": 222,
"tag": "NAME",
"value": "Ken"
},
{
"context": "itor.\n */\npackage Observer;\n\n/**\n *\n * @author Kennet\n */\npublic class Boss {\n private Employe emple",
"end": 228,
"score": 0.8467479944229126,
"start": 225,
"tag": "USERNAME",
"value": "net"
}
] | 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 Observer;
/**
*
* @author Kennet
*/
public class Boss {
private Employe empleado;
/**
*
* @param empleado es el objeto que vamos a observar
*/
// public Boss(Employe empleado){
// this.empleado = empleado;
// this.empleado.setBoss(this);
// }
public Boss(Employe empleado){
this.empleado = empleado;
empleado.setBoss(this);
}
public void Notify() {
if(empleado.isWorking()){
System.out.println("I´m working");
}else{
System.out.println("I´m nott working");
}
}
}
| 795 | 0.587642 | 0.587642 | 38 | 19.868422 | 19.913195 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.289474 | false | false |
0
|
a26585a71fcb2bb2faf453c1e5d4dac85cd00e7a
| 6,743,098,657,650 |
c4c7f3b6dec38705ff85d9f2f5eec4261ceeead0
|
/Raspcast/api/src/main/java/be/krivi/ucll/da/raspcast/api/filter/JWTSecured.java
|
2989d20016c811ba489e5252d108df5fffc1a285
|
[] |
no_license
|
Qrivi/UCLL-DA
|
https://github.com/Qrivi/UCLL-DA
|
fd6488cd25b7509716d52a664a6da3a2f05dfb8a
|
79e78ee14a9137b4b65660a5b9f6215d302fd2c4
|
refs/heads/master
| 2021-01-13T07:53:00.780000 | 2016-12-18T23:41:28 | 2016-12-18T23:41:28 | 68,927,031 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package be.krivi.ucll.da.raspcast.api.filter;
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@NameBinding
@Retention( RUNTIME )
@Target( {TYPE, METHOD} )
public @interface JWTSecured{
}
|
UTF-8
|
Java
| 416 |
java
|
JWTSecured.java
|
Java
|
[] | null |
[] |
package be.krivi.ucll.da.raspcast.api.filter;
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@NameBinding
@Retention( RUNTIME )
@Target( {TYPE, METHOD} )
public @interface JWTSecured{
}
| 416 | 0.8125 | 0.8125 | 15 | 26.799999 | 20.057251 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false |
0
|
fd6a9f9eff7f41519d4ea02ca203ae2d979eea1f
| 412,316,888,790 |
7ae2c9cbae47072bf0853af67b8ad36dbd0823cd
|
/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/filter/DataProviderFilter.java
|
246ec30b9870591d2a5c5c9de1f3def6112f7d21
|
[
"Apache-2.0",
"CC-BY-4.0"
] |
permissive
|
mach6/SeLion
|
https://github.com/mach6/SeLion
|
e4e5dbaa33bf26128b1b35bd979aaf9ff6c75e09
|
b74585a5c65911068febd71f4fa19d5ba2a73f4e
|
refs/heads/develop
| 2022-05-13T10:52:43.603000 | 2022-03-24T06:31:16 | 2022-03-24T06:31:16 | 24,708,086 | 6 | 0 |
Apache-2.0
| true | 2022-03-24T06:31:17 | 2014-10-02T05:57:34 | 2022-03-24T06:30:17 | 2022-03-24T06:31:16 | 6,935 | 2 | 0 | 4 |
Java
| false | false |
/*-------------------------------------------------------------------------------------------------------------------*\
| Copyright (C) 2015 PayPal |
| |
| Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance |
| with the License. |
| |
| You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, software distributed under the License is distributed |
| on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for |
| the specific language governing permissions and limitations under the License. |
\*-------------------------------------------------------------------------------------------------------------------*/
package com.paypal.selion.platform.dataprovider.filter;
/**
* This Interface provides the facility to provide the custom filtering logic based on the needs. user can create the
* custom filter class by implementing this filter and invoke the filter based methods to apply the filter. <br>
* <br>
* Example dataproviderfilter:
*
* <pre>
* public class SimpleIndexInclusionDataProviderFilter implements IDataProviderFilter {
*
* @Override
* public Object[][] filter(Object[][] data, String... args) {
* // filtering logic here
* return filteredData;
* }
*
* }
* </pre>
*/
public interface DataProviderFilter {
/**
* This function identifies whether the given object falls in the injected filter criteria.
*
* @param data
* Object the object to be filtered.
* @return boolean - true if object falls in the filter criteria.
*/
boolean filter(Object data);
}
|
UTF-8
|
Java
| 2,641 |
java
|
DataProviderFilter.java
|
Java
|
[] | null |
[] |
/*-------------------------------------------------------------------------------------------------------------------*\
| Copyright (C) 2015 PayPal |
| |
| Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance |
| with the License. |
| |
| You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, software distributed under the License is distributed |
| on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for |
| the specific language governing permissions and limitations under the License. |
\*-------------------------------------------------------------------------------------------------------------------*/
package com.paypal.selion.platform.dataprovider.filter;
/**
* This Interface provides the facility to provide the custom filtering logic based on the needs. user can create the
* custom filter class by implementing this filter and invoke the filter based methods to apply the filter. <br>
* <br>
* Example dataproviderfilter:
*
* <pre>
* public class SimpleIndexInclusionDataProviderFilter implements IDataProviderFilter {
*
* @Override
* public Object[][] filter(Object[][] data, String... args) {
* // filtering logic here
* return filteredData;
* }
*
* }
* </pre>
*/
public interface DataProviderFilter {
/**
* This function identifies whether the given object falls in the injected filter criteria.
*
* @param data
* Object the object to be filtered.
* @return boolean - true if object falls in the filter criteria.
*/
boolean filter(Object data);
}
| 2,641 | 0.408936 | 0.404771 | 47 | 55.19149 | 50.381371 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723404 | false | false |
0
|
0eabc3a38a6a1e39630d401ca88963458a1eb313
| 7,808,250,567,887 |
38ab080e4df324ddbff102f9862f5848907dac69
|
/stockmanager/src/main/java/com/usr/csdm/stockmanager/common/db/DBUtil.java
|
b9c7d42831c4591d68fe35f95b4aad83023c2f02
|
[] |
no_license
|
gcsdm/stock_manager
|
https://github.com/gcsdm/stock_manager
|
3ff6c52396cb9f8f6e1a610f38d6106e71682db3
|
e2a763f9bcca54eff9d8f53fe23dbb7f9bc795b5
|
refs/heads/master
| 2021-01-10T11:17:06.494000 | 2016-01-24T05:07:23 | 2016-01-24T05:10:04 | 44,109,153 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: DBUtil.java
package com.usr.csdm.stockmanager.common.db;
import java.sql.*;
import java.util.Hashtable;
import javax.naming.*;
import javax.sql.DataSource;
public class DBUtil
{
private DBUtil()
{
}
public static Connection getMySQLConnection(String database, String userName, String pwd)
{
return getMySQLConnection("localhost", 3306, database, userName, pwd, "utf-8");
}
public static Connection getMySQLConnection(String host, String database, String userName, String pwd)
{
return getMySQLConnection(host, 3306, database, userName, pwd, "utf-8");
}
public static Connection getMySQLConnection(String host, int port, String database, String userName, String pwd)
{
return getMySQLConnection(host, port, database, userName, pwd, "utf-8");
}
public static Connection getMySQLConnection(String host, int port, String database, String userName, String pwd, String characterEncoding)
{
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection((new StringBuilder("jdbc:mysql://")).append(host).append(":").append(port).append("/").append(database).append("?useUnicode=true&characterEncoding=").append(characterEncoding).toString(), userName, pwd);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return conn;
}
private static synchronized void addDataSource(String dataSourceName)
throws NamingException
{
if(!htDataSource.containsKey(dataSourceName))
{
InitialContext ic = new InitialContext();
Context context = (Context)ic.lookup("java:/comp/env");
htDataSource.put(dataSourceName, (DataSource)context.lookup(dataSourceName));
}
}
public static void setAutoCommit(Connection conn, boolean isAutoCommit)
{
try
{
conn.setAutoCommit(isAutoCommit);
}
catch(Exception exception) { }
}
public static void commit(Connection conn)
{
try
{
conn.commit();
}
catch(Exception exception) { }
setAutoCommit(conn, true);
}
public static void rollback(Connection conn)
{
try
{
conn.rollback();
}
catch(Exception exception) { }
setAutoCommit(conn, true);
}
public static Connection getConnection(String dataSourceName)
throws Exception
{
if(!htDataSource.contains(dataSourceName))
addDataSource(dataSourceName);
return ((DataSource)htDataSource.get(dataSourceName)).getConnection();
}
public static void close(Connection obj)
{
if(obj != null)
{
try
{
if(!obj.getAutoCommit())
obj.setAutoCommit(true);
}
catch(Exception exception) { }
try
{
obj.close();
}
catch(Exception exception1) { }
}
}
public static void close(ResultSet obj)
{
if(obj != null)
try
{
obj.close();
}
catch(Exception exception) { }
}
public static void close(PreparedStatement obj)
{
if(obj != null)
try
{
obj.close();
}
catch(Exception exception) { }
}
private static Hashtable htDataSource = new Hashtable();
}
|
UTF-8
|
Java
| 3,895 |
java
|
DBUtil.java
|
Java
|
[
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\r\n// Jad home page: http://www.kpdus.com/jad.html",
"end": 61,
"score": 0.9996394515037537,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null |
[] |
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: DBUtil.java
package com.usr.csdm.stockmanager.common.db;
import java.sql.*;
import java.util.Hashtable;
import javax.naming.*;
import javax.sql.DataSource;
public class DBUtil
{
private DBUtil()
{
}
public static Connection getMySQLConnection(String database, String userName, String pwd)
{
return getMySQLConnection("localhost", 3306, database, userName, pwd, "utf-8");
}
public static Connection getMySQLConnection(String host, String database, String userName, String pwd)
{
return getMySQLConnection(host, 3306, database, userName, pwd, "utf-8");
}
public static Connection getMySQLConnection(String host, int port, String database, String userName, String pwd)
{
return getMySQLConnection(host, port, database, userName, pwd, "utf-8");
}
public static Connection getMySQLConnection(String host, int port, String database, String userName, String pwd, String characterEncoding)
{
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection((new StringBuilder("jdbc:mysql://")).append(host).append(":").append(port).append("/").append(database).append("?useUnicode=true&characterEncoding=").append(characterEncoding).toString(), userName, pwd);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return conn;
}
private static synchronized void addDataSource(String dataSourceName)
throws NamingException
{
if(!htDataSource.containsKey(dataSourceName))
{
InitialContext ic = new InitialContext();
Context context = (Context)ic.lookup("java:/comp/env");
htDataSource.put(dataSourceName, (DataSource)context.lookup(dataSourceName));
}
}
public static void setAutoCommit(Connection conn, boolean isAutoCommit)
{
try
{
conn.setAutoCommit(isAutoCommit);
}
catch(Exception exception) { }
}
public static void commit(Connection conn)
{
try
{
conn.commit();
}
catch(Exception exception) { }
setAutoCommit(conn, true);
}
public static void rollback(Connection conn)
{
try
{
conn.rollback();
}
catch(Exception exception) { }
setAutoCommit(conn, true);
}
public static Connection getConnection(String dataSourceName)
throws Exception
{
if(!htDataSource.contains(dataSourceName))
addDataSource(dataSourceName);
return ((DataSource)htDataSource.get(dataSourceName)).getConnection();
}
public static void close(Connection obj)
{
if(obj != null)
{
try
{
if(!obj.getAutoCommit())
obj.setAutoCommit(true);
}
catch(Exception exception) { }
try
{
obj.close();
}
catch(Exception exception1) { }
}
}
public static void close(ResultSet obj)
{
if(obj != null)
try
{
obj.close();
}
catch(Exception exception) { }
}
public static void close(PreparedStatement obj)
{
if(obj != null)
try
{
obj.close();
}
catch(Exception exception) { }
}
private static Hashtable htDataSource = new Hashtable();
}
| 3,885 | 0.565854 | 0.560719 | 138 | 26.224638 | 32.92746 | 250 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false |
0
|
0b452d2c43e9fdea036e6ca692f0f658eb7e3b54
| 16,037,407,944,379 |
750e169703bcec290abd6e4b3221e88a54bd9ee8
|
/example/src/main/java/com/fastcode/example/application/core/casehistory/dto/UpdateCaseHistoryOutput.java
|
c55e09431ee779ee64fea5a91aedacec2fce640d
|
[] |
no_license
|
fastcode-inc/case-mgmt
|
https://github.com/fastcode-inc/case-mgmt
|
150833791a666b4b5d4d58a81dec3ec488277a8e
|
859a46cacb94fe0f986d5a0d0f49d41b59187421
|
refs/heads/master
| 2023-08-14T15:57:03.594000 | 2021-10-12T18:19:50 | 2021-10-12T18:19:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fastcode.example.application.core.casehistory.dto;
import java.time.*;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UpdateCaseHistoryOutput {
private Long caseHistoryId;
private String message;
private OffsetTime timestamp;
private Long caseId;
private Long casesDescriptiveField;
}
|
UTF-8
|
Java
| 346 |
java
|
UpdateCaseHistoryOutput.java
|
Java
|
[] | null |
[] |
package com.fastcode.example.application.core.casehistory.dto;
import java.time.*;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UpdateCaseHistoryOutput {
private Long caseHistoryId;
private String message;
private OffsetTime timestamp;
private Long caseId;
private Long casesDescriptiveField;
}
| 346 | 0.777457 | 0.777457 | 16 | 20.625 | 17.138681 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false |
0
|
dd89a0b36aa1468e2ced0e10cf944dd523d5803f
| 16,037,407,948,217 |
7450e68d1b58035a892ee4b6e83848eb10aa4d99
|
/app/src/main/java/com/example/seminarhall/LogIn/MainActivity.java
|
f45ef4226075b67be30a43444e1507018b4fd48f
|
[] |
no_license
|
shubhamB25/Seminar-Hall-Reservation
|
https://github.com/shubhamB25/Seminar-Hall-Reservation
|
d6b999df26947f65d769d7ff8a94b57f5bb0a158
|
42f30707338bb3a10ff5741be79b6d5a260f9b9a
|
refs/heads/master
| 2023-06-15T18:04:04.495000 | 2021-07-10T06:25:32 | 2021-07-10T06:25:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.seminarhall.LogIn;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.seminarhall.R;
import com.example.seminarhall.homePage.UserDetails;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "MainActivity";
private Button Continue;
private FirebaseAuth mAuth;
TextView newUserTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setUPNotification();
newUserTextView = findViewById(R.id.TextRegister);
mAuth = FirebaseAuth.getInstance();
newUserTextView.setText(Html.fromHtml(newUserTextView.getText().toString()));
newUserTextView.setVisibility(View.VISIBLE);
newUserTextView.setOnClickListener(this);
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Intent intent = new Intent(MainActivity.this, UserDetails.class);
startActivity(intent);
}
Continue = findViewById(R.id.button);
Continue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SignIn.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
});
}
@Override
public void onClick(View v) {
int i = newUserTextView.getId();
if (i == R.id.TextRegister) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
}
}
|
UTF-8
|
Java
| 2,047 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.example.seminarhall.LogIn;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.seminarhall.R;
import com.example.seminarhall.homePage.UserDetails;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "MainActivity";
private Button Continue;
private FirebaseAuth mAuth;
TextView newUserTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setUPNotification();
newUserTextView = findViewById(R.id.TextRegister);
mAuth = FirebaseAuth.getInstance();
newUserTextView.setText(Html.fromHtml(newUserTextView.getText().toString()));
newUserTextView.setVisibility(View.VISIBLE);
newUserTextView.setOnClickListener(this);
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Intent intent = new Intent(MainActivity.this, UserDetails.class);
startActivity(intent);
}
Continue = findViewById(R.id.button);
Continue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SignIn.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
});
}
@Override
public void onClick(View v) {
int i = newUserTextView.getId();
if (i == R.id.TextRegister) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
}
}
| 2,047 | 0.679531 | 0.679531 | 69 | 28.652174 | 25.032631 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false |
0
|
862298323d61b9e90784b00cff9ba773c5c906c5
| 23,484,881,237,449 |
f716634ea97b91bf19ab246dd2f4fde87478379d
|
/src/main/java/com/qa/student/rest/ScreenService.java
|
2527775cfb7c25ba99b63f6da61ffc1ae5b5c2a4
|
[] |
no_license
|
scrappy1987/Team1
|
https://github.com/scrappy1987/Team1
|
467e15577150f262d127e3efc344783c21b91ff4
|
b1cdc7f7c6955348d283ebbdc7ef797bde48a12e
|
refs/heads/master
| 2021-05-01T02:20:54.412000 | 2017-02-03T14:36:44 | 2017-02-03T14:36:44 | 79,910,600 | 0 | 0 | null | false | 2017-02-03T14:36:44 | 2017-01-24T12:43:01 | 2017-01-24T12:45:31 | 2017-02-03T14:36:44 | 218 | 0 | 0 | 1 |
Java
| null | null |
package com.qa.student.rest;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.jboss.logging.Logger;
import com.google.gson.Gson;
import com.qa.student.model.Screen;
public class ScreenService {
private static final Logger SCREENLOGGER = Logger.getLogger(Screen.class);
@Inject
private EntityManager em;
@Inject
private Gson gsonParser;
public void createScreen(String jsonString){
Screen screen = gsonParser.fromJson(jsonString, Screen.class);
this.createScreen(screen);
}
public void createScreen(Screen screen){
Screen checker = em.find(Screen.class, screen);
if(checker != null){
SCREENLOGGER.info("Screen not added, already exists");
} else {
em.persist(screen);
SCREENLOGGER.info("Screen added successfully");
}
}
public Screen getScreen(long id){
Screen screen = em.find(Screen.class,id);
if(screen == null){
SCREENLOGGER.info("Screen of given id doesn't exists");
return null;
}
else {
return screen;
}
}
@SuppressWarnings("unchecked")
public List<Screen> getScreenAll(){
Query query = em.createQuery("SELECT s FROM Screen s");
if(query == null){
SCREENLOGGER.info("No Screens exist");
return null;
} else {
List<Screen> resultList = query.getResultList();
return resultList;
}
}
public void removeScreen(String jsonString){
Screen screen = gsonParser.fromJson(jsonString, Screen.class);
removeScreen(screen);
}
public void removeScreen(Screen screen){
Screen checker = em.find(Screen.class, screen);
if(checker == null){
SCREENLOGGER.info("Screen doesn't exist");
} else {
em.remove(screen);
SCREENLOGGER.info("Screen removed successfully");
}
}
public void updateScreen(String jsonString){
Screen screen = gsonParser.fromJson(jsonString, Screen.class);
updateScreen(screen);
}
public void updateScreen(Screen screen){
Screen checker = em.find(Screen.class, screen);
if(checker == null){
SCREENLOGGER.info("Screen doesn't exist");
} else {
em.merge(screen);
SCREENLOGGER.info("Screen updated successfully");
}
}
}
|
UTF-8
|
Java
| 2,249 |
java
|
ScreenService.java
|
Java
|
[] | null |
[] |
package com.qa.student.rest;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.jboss.logging.Logger;
import com.google.gson.Gson;
import com.qa.student.model.Screen;
public class ScreenService {
private static final Logger SCREENLOGGER = Logger.getLogger(Screen.class);
@Inject
private EntityManager em;
@Inject
private Gson gsonParser;
public void createScreen(String jsonString){
Screen screen = gsonParser.fromJson(jsonString, Screen.class);
this.createScreen(screen);
}
public void createScreen(Screen screen){
Screen checker = em.find(Screen.class, screen);
if(checker != null){
SCREENLOGGER.info("Screen not added, already exists");
} else {
em.persist(screen);
SCREENLOGGER.info("Screen added successfully");
}
}
public Screen getScreen(long id){
Screen screen = em.find(Screen.class,id);
if(screen == null){
SCREENLOGGER.info("Screen of given id doesn't exists");
return null;
}
else {
return screen;
}
}
@SuppressWarnings("unchecked")
public List<Screen> getScreenAll(){
Query query = em.createQuery("SELECT s FROM Screen s");
if(query == null){
SCREENLOGGER.info("No Screens exist");
return null;
} else {
List<Screen> resultList = query.getResultList();
return resultList;
}
}
public void removeScreen(String jsonString){
Screen screen = gsonParser.fromJson(jsonString, Screen.class);
removeScreen(screen);
}
public void removeScreen(Screen screen){
Screen checker = em.find(Screen.class, screen);
if(checker == null){
SCREENLOGGER.info("Screen doesn't exist");
} else {
em.remove(screen);
SCREENLOGGER.info("Screen removed successfully");
}
}
public void updateScreen(String jsonString){
Screen screen = gsonParser.fromJson(jsonString, Screen.class);
updateScreen(screen);
}
public void updateScreen(Screen screen){
Screen checker = em.find(Screen.class, screen);
if(checker == null){
SCREENLOGGER.info("Screen doesn't exist");
} else {
em.merge(screen);
SCREENLOGGER.info("Screen updated successfully");
}
}
}
| 2,249 | 0.687417 | 0.687417 | 91 | 22.714285 | 20.320122 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.989011 | false | false |
0
|
b702a6041b86a05f6ac46da5fd4a24a4c8c389fd
| 10,934,986,782,821 |
99b4a1303345ecb8dd2547dac2c783bf979dbad0
|
/src/main/java/com/hs/entity/FrontRole.java
|
8ec7e4ae66d9f11b4a6babb96c7f0d40cf1befb8
|
[] |
no_license
|
YuChengHup/Hs-The-flower-shoping
|
https://github.com/YuChengHup/Hs-The-flower-shoping
|
e32f39fbe992a6cec0937f84a359a6fb419245fd
|
ff8767bba63e23d014c1b65d2c416d1a0d31fb06
|
refs/heads/master
| 2023-09-02T12:19:00.554000 | 2021-11-09T02:54:06 | 2021-11-09T02:54:06 | 420,320,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hs.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FrontRole {
private Integer pageSize;
private String comName;
private Integer comVolume;
private String priceDesc;
private String priceAsc;
private Integer sizId;
private Integer sorId;
}
|
UTF-8
|
Java
| 389 |
java
|
FrontRole.java
|
Java
|
[] | null |
[] |
package com.hs.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FrontRole {
private Integer pageSize;
private String comName;
private Integer comVolume;
private String priceDesc;
private String priceAsc;
private Integer sizId;
private Integer sorId;
}
| 389 | 0.766067 | 0.766067 | 21 | 17.523809 | 12.427385 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false |
0
|
45116bdcf26b12db107eeaf2515ff69118298160
| 19,920,058,385,235 |
6d1d8fffa895fb5daf11f7edbd07f81bb26ed121
|
/service/src/main/java/com/rensm/audit/service/mq/config/MQAutoConfiguration.java
|
856dc39bcb7c71be6423767e3ce9e7c632d55037
|
[] |
no_license
|
pianotrain/micro_service
|
https://github.com/pianotrain/micro_service
|
7e1db2723eb20765c888b433d9e4daf62d322142
|
1af534ced14d913e71870328499e3ef24503fefa
|
refs/heads/master
| 2020-03-27T02:27:44.128000 | 2018-08-23T03:17:19 | 2018-08-23T03:17:19 | 145,791,925 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.rensm.audit.service.mq.config;
/**
* Created by DELL on 2018/8/14.
*/
public class MQAutoConfiguration {
public MQAutoConfiguration() {
}
}
|
UTF-8
|
Java
| 163 |
java
|
MQAutoConfiguration.java
|
Java
|
[
{
"context": ".rensm.audit.service.mq.config;\n\n/**\n * Created by DELL on 2018/8/14.\n */\npublic class MQAutoConfiguratio",
"end": 66,
"score": 0.9992382526397705,
"start": 62,
"tag": "USERNAME",
"value": "DELL"
}
] | null |
[] |
package com.rensm.audit.service.mq.config;
/**
* Created by DELL on 2018/8/14.
*/
public class MQAutoConfiguration {
public MQAutoConfiguration() {
}
}
| 163 | 0.687117 | 0.644172 | 9 | 17.111111 | 16.69627 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | false | false |
0
|
acb28a2d009d3b0507536e5f887ff81bf024ea87
| 18,769,007,100,658 |
211f4d054af55616c5c5eaf95e1c1772f7987e6a
|
/pinyougou-interface/src/main/java/com/pinyougou/service/TypeTemplateService.java
|
67dcd4e1941e3981af8465682df19cbd92755106
|
[] |
no_license
|
coding4happiness/pinyougou
|
https://github.com/coding4happiness/pinyougou
|
158daa0d257ce3ef169aadb33e791e31485d75f4
|
46f27063a95fe271c96d37ced68eb8799abaad77
|
refs/heads/master
| 2020-05-05T07:29:23.709000 | 2019-04-06T12:12:32 | 2019-04-06T12:12:35 | 179,426,937 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pinyougou.service;
import com.pinyougou.common.pojo.PageResult;
import com.pinyougou.pojo.TypeTemplate;
import java.util.List;
import java.util.Map;
public interface TypeTemplateService {
PageResult findByPage(TypeTemplate typeTemplate, Integer page, Integer rows);
void save(TypeTemplate typeTemplate);
void update(TypeTemplate typeTemplate);
void deleteById(Long[] ids);
TypeTemplate findTypeTemplate(Long typeId);
List<Map<String,Object>> findAllByIdAndName();
}
|
UTF-8
|
Java
| 511 |
java
|
TypeTemplateService.java
|
Java
|
[] | null |
[] |
package com.pinyougou.service;
import com.pinyougou.common.pojo.PageResult;
import com.pinyougou.pojo.TypeTemplate;
import java.util.List;
import java.util.Map;
public interface TypeTemplateService {
PageResult findByPage(TypeTemplate typeTemplate, Integer page, Integer rows);
void save(TypeTemplate typeTemplate);
void update(TypeTemplate typeTemplate);
void deleteById(Long[] ids);
TypeTemplate findTypeTemplate(Long typeId);
List<Map<String,Object>> findAllByIdAndName();
}
| 511 | 0.772994 | 0.772994 | 22 | 22.227272 | 23.043303 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false |
0
|
220e217bcadd1924035ce89d25049993b642a37e
| 13,426,067,770,002 |
a205936864332316bd12ae37777cd695b53b8598
|
/profiles/2-spring-profiles-example/src/main/java/org/spring/boot/examples/profiles/service/SmtpMailSender.java
|
617c6714c4292469831ce2d78003a7c5d125435d
|
[] |
no_license
|
amdouni-mohamed-ali/spring-boot-examples
|
https://github.com/amdouni-mohamed-ali/spring-boot-examples
|
a3dc5bb4096d1ddef3310f313c1ea667952ff1cc
|
8e35f4f64f3a962afe83dd991cbdb28fe51e1ef3
|
refs/heads/master
| 2020-05-09T14:51:34.323000 | 2020-02-27T16:21:23 | 2020-02-27T16:21:23 | 181,209,859 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.spring.boot.examples.profiles.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("production")
public class SmtpMailSender implements MailSender {
/*
* this is a static logger
*/
private final static Logger LOGGER = LoggerFactory.getLogger(SmtpMailSender.class);
@Override
public void send(String to, String object, String message) {
LOGGER.info("Sending an SMTP mail ...");
LOGGER.info("to : {} , object : {}", to, object);
LOGGER.info("message : {}", message);
LOGGER.info("operation terminated successfully.");
}
}
|
UTF-8
|
Java
| 732 |
java
|
SmtpMailSender.java
|
Java
|
[] | null |
[] |
package org.spring.boot.examples.profiles.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("production")
public class SmtpMailSender implements MailSender {
/*
* this is a static logger
*/
private final static Logger LOGGER = LoggerFactory.getLogger(SmtpMailSender.class);
@Override
public void send(String to, String object, String message) {
LOGGER.info("Sending an SMTP mail ...");
LOGGER.info("to : {} , object : {}", to, object);
LOGGER.info("message : {}", message);
LOGGER.info("operation terminated successfully.");
}
}
| 732 | 0.698087 | 0.695355 | 25 | 28.280001 | 25.306948 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64 | false | false |
0
|
48c2c406a9ce173ac89e4d05611d852f93bc72ec
| 25,280,177,519,653 |
a2d9f50738956a066dcb41850baf60a3166ece93
|
/src/Company.java
|
0d1cb87ed94b577d078e9e9726f9c1226d570182
|
[] |
no_license
|
vallerboy/AkademiaFirma
|
https://github.com/vallerboy/AkademiaFirma
|
e7a51ecf843800fe7ed10cdcc907d44944c129d1
|
fdbc4dc0d15274b2fbaadddfeddd9e38af11b596
|
refs/heads/master
| 2021-01-01T15:44:06.355000 | 2017-07-19T08:00:03 | 2017-07-19T08:00:03 | 97,689,498 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lenovo on 18.07.2017.
*/
public class Company {
List<Menager> menagerList = new ArrayList<>();
public static void main(String[] args) {
}
public Company() {
for (Menager menager : menagerList) {
for(Worker worker : menager.getWorkerList()){
for(Worker.Registry registry : worker.getRegistryList()){
System.out.println("Opis tasku: " + registry.getMessage());
System.out.println("Czas trwania: " + registry.getTaskTime());
}
}
}
}
}
|
UTF-8
|
Java
| 649 |
java
|
Company.java
|
Java
|
[
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Lenovo on 18.07.2017.\n */\npublic class Company {\n Lis",
"end": 76,
"score": 0.9555339813232422,
"start": 70,
"tag": "USERNAME",
"value": "Lenovo"
}
] | null |
[] |
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lenovo on 18.07.2017.
*/
public class Company {
List<Menager> menagerList = new ArrayList<>();
public static void main(String[] args) {
}
public Company() {
for (Menager menager : menagerList) {
for(Worker worker : menager.getWorkerList()){
for(Worker.Registry registry : worker.getRegistryList()){
System.out.println("Opis tasku: " + registry.getMessage());
System.out.println("Czas trwania: " + registry.getTaskTime());
}
}
}
}
}
| 649 | 0.553159 | 0.540832 | 25 | 24.959999 | 26.536737 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
0
|
202686805e3843c410c8c8a39b31a41c69434135
| 33,217,277,114,505 |
5c53356618e4d6d422fa59993cfe220dba4620cd
|
/src/main/java/edu/drexel/TrainDemo/controllers/itinerary/ItineraryController.java
|
ee685ef6ebcdafebf260cee6c11b5272170dcb7c
|
[] |
no_license
|
UjiMani/SE577_SEPTA
|
https://github.com/UjiMani/SE577_SEPTA
|
00472e550acfb1271fe3bc264be85b786b67c84f
|
db904b0d744b30f88e80bb51c306b25295083c97
|
refs/heads/master
| 2022-04-08T14:44:56.670000 | 2020-03-21T03:35:45 | 2020-03-21T03:35:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.drexel.TrainDemo.controllers.itinerary;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import edu.drexel.TrainDemo.entities.itinerary.Route;
import edu.drexel.TrainDemo.entities.itinerary.Stop;
import edu.drexel.TrainDemo.model.Itinerary.Itinerary;
import edu.drexel.TrainDemo.model.Itinerary.RouteInfo;
import edu.drexel.TrainDemo.service.itinerary.ItineraryService;
@RestController
@RequestMapping("/itinerary/*")
public class ItineraryController {
@Autowired
private ItineraryService itineraryService;
@GetMapping("/")
public String getItenaries() {
List<Itinerary> itineraries = itineraryService.getItineraries();
System.out.println(itineraries);
return itineraries.get(0).getAgency().toString();
}
@PostMapping("/addStop.html")
public String addStop(@RequestBody Stop stop,HttpServletRequest request, HttpServletResponse response) {
return itineraryService.addStop(stop).getId();
}
@GetMapping("/routeInfo")
public List<Route> getRouteInfo(){
return itineraryService.getRouteInfo();
}
@GetMapping("/tripsInfo")
public List<RouteInfo> getTripInfo(){
return itineraryService.getTripInfo();
}
}
|
UTF-8
|
Java
| 1,594 |
java
|
ItineraryController.java
|
Java
|
[] | null |
[] |
package edu.drexel.TrainDemo.controllers.itinerary;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import edu.drexel.TrainDemo.entities.itinerary.Route;
import edu.drexel.TrainDemo.entities.itinerary.Stop;
import edu.drexel.TrainDemo.model.Itinerary.Itinerary;
import edu.drexel.TrainDemo.model.Itinerary.RouteInfo;
import edu.drexel.TrainDemo.service.itinerary.ItineraryService;
@RestController
@RequestMapping("/itinerary/*")
public class ItineraryController {
@Autowired
private ItineraryService itineraryService;
@GetMapping("/")
public String getItenaries() {
List<Itinerary> itineraries = itineraryService.getItineraries();
System.out.println(itineraries);
return itineraries.get(0).getAgency().toString();
}
@PostMapping("/addStop.html")
public String addStop(@RequestBody Stop stop,HttpServletRequest request, HttpServletResponse response) {
return itineraryService.addStop(stop).getId();
}
@GetMapping("/routeInfo")
public List<Route> getRouteInfo(){
return itineraryService.getRouteInfo();
}
@GetMapping("/tripsInfo")
public List<RouteInfo> getTripInfo(){
return itineraryService.getTripInfo();
}
}
| 1,594 | 0.806148 | 0.805521 | 53 | 29.075472 | 25.633005 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.09434 | false | false |
0
|
8a26766fe02929f625fb1b3dd64414f1c8f0d152
| 1,279,900,280,343 |
fe9f4cae529b8f127cab8fc3380e86cd84ec0c4c
|
/library/src/main/java/com/gatebuzz/rapidapi/rx/FailedCallException.java
|
f1ce9e4e684bf055739bcc3bb6a2c1ef23c4f417
|
[
"Apache-2.0"
] |
permissive
|
waffle-iron/RxRapidApi
|
https://github.com/waffle-iron/RxRapidApi
|
1a5725825da4c2cdd9bbe4994507788d816515d2
|
c0f57eed3630e5f7711613b7c5fec49a68e2c4b0
|
refs/heads/master
| 2020-06-14T22:57:28.608000 | 2016-12-02T14:09:15 | 2016-12-02T14:09:15 | 75,401,028 | 0 | 0 | null | true | 2016-12-02T14:09:14 | 2016-12-02T14:09:13 | 2016-12-01T21:45:50 | 2016-12-02T14:01:27 | 162 | 0 | 0 | 0 | null | null | null |
package com.gatebuzz.rapidapi.rx;
import android.support.annotation.Keep;
import java.util.Map;
@Keep
public class FailedCallException extends Throwable {
private Map<String, Object> response;
public FailedCallException(Map<String, Object> response) {
this.response = response;
}
public Map<String, Object> getResponse() {
return response;
}
}
|
UTF-8
|
Java
| 385 |
java
|
FailedCallException.java
|
Java
|
[] | null |
[] |
package com.gatebuzz.rapidapi.rx;
import android.support.annotation.Keep;
import java.util.Map;
@Keep
public class FailedCallException extends Throwable {
private Map<String, Object> response;
public FailedCallException(Map<String, Object> response) {
this.response = response;
}
public Map<String, Object> getResponse() {
return response;
}
}
| 385 | 0.709091 | 0.709091 | 18 | 20.388889 | 20.621292 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
753138f7fd9553589963eb76d8c7e5b5ce9df82e
| 13,280,038,903,044 |
e3fbf300cd2fb07840f7204b8ec97e8cf9141b9f
|
/passport/passport-coupon/src/main/java/cn/globalph/coupon/dao/CouponAttributeDao.java
|
162f9d0fc64b22dade5e97af7ac6e98991af0ec2
|
[] |
no_license
|
ynial/nongph
|
https://github.com/ynial/nongph
|
0af2b6b60956b9e77f60eb369c339db5e86b2699
|
4f4c2a640a2832ff447073107988652993f2d88c
|
refs/heads/master
| 2019-07-09T03:19:00.279000 | 2016-01-20T12:35:09 | 2016-01-20T12:35:09 | 58,435,964 | 2 | 0 | null | false | 2019-10-18T13:57:45 | 2016-05-10T06:36:09 | 2016-11-22T08:16:32 | 2019-10-18T13:57:41 | 19,033 | 2 | 0 | 2 |
Java
| false | false |
package cn.globalph.coupon.dao;
public interface CouponAttributeDao {
}
|
UTF-8
|
Java
| 74 |
java
|
CouponAttributeDao.java
|
Java
|
[] | null |
[] |
package cn.globalph.coupon.dao;
public interface CouponAttributeDao {
}
| 74 | 0.797297 | 0.797297 | 5 | 13.8 | 16.606024 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
0
|
572c8c4cb22582041d881bf91180f4996a8d8bb6
| 18,227,841,231,884 |
5725bd8869f1638363ac1bee8e53dd92fecd7a4d
|
/siscae/src/main/java/pe/edu/unmsm/fisi/siscae/service/impl/reporte/ReporteEstadisticaInfraccionesService.java
|
8c104d3c25d525e0e528e748eacb820260900c80
|
[] |
no_license
|
CrisDC/SISCAE
|
https://github.com/CrisDC/SISCAE
|
cc331295e37834a528a3628a005c6b965611f2a0
|
8fa750e41473f72a939528ce05406d294ae99491
|
refs/heads/master
| 2023-04-10T05:54:33.870000 | 2020-01-15T22:01:44 | 2020-01-15T22:01:44 | 362,678,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pe.edu.unmsm.fisi.siscae.service.impl.reporte;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pe.edu.unmsm.fisi.siscae.mapper.IReporteEstadisticaInfraccionesMapper;
import pe.edu.unmsm.fisi.siscae.model.consulta.ConsultaInfracciones;
import pe.edu.unmsm.fisi.siscae.model.criterio.ReporteEstadisticaInfraccionesCriterioBusqueda;
import pe.edu.unmsm.fisi.siscae.model.reporte.resumen.ReporteEstadisticaInfraccionesPorEjeX;
import pe.edu.unmsm.fisi.siscae.model.reporte.resumen.ReporteInfraccionesPorEjeXSegmentado;
import pe.edu.unmsm.fisi.siscae.service.IReporteEstadisticaInfraccionesService;
@Service
public class ReporteEstadisticaInfraccionesService implements IReporteEstadisticaInfraccionesService {
private @Autowired IReporteEstadisticaInfraccionesMapper reporteEstadisticaInfraccionesMapper;
/*
@Override
public List<ReporteEstadisticaInfracciones> buscarTodos() {
return reporteEstadisticaInfraccionesMapper.buscarTodos();
}
@Override
public List<ReporteEstadisticaInfracciones> buscarPorCriterio(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorCriterio(criterioBusqueda);
}*/
@Override
public List<ReporteEstadisticaInfraccionesPorEjeX> buscarPorPeriodoSinSegementar(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorPeriodoSinSegementar(criterioBusqueda);
}
@Override
public List<ReporteEstadisticaInfraccionesPorEjeX> buscarPorCriterio(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorCriterio(criterioBusqueda);
}
@Override
public List<ReporteInfraccionesPorEjeXSegmentado> buscarPorPeriodoSegmentado(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorPeriodoSegmentado(criterioBusqueda);
}
@Override
public List<ReporteEstadisticaInfraccionesPorEjeX> buscarPorEjeXSinSegmentar(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorEjeXSinSegmentar(criterioBusqueda);
}
@Override
public List<ReporteInfraccionesPorEjeXSegmentado> buscarPorEjeXSegmentado(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorEjeXSegmentado(criterioBusqueda);
}
@Override
public List<ConsultaInfracciones> buscarPorNumeroDocumento(ConsultaInfracciones criterioBusqueda) {
//esto tambien
return reporteEstadisticaInfraccionesMapper.buscarPorNumeroDocumento(criterioBusqueda);
}
}
|
UTF-8
|
Java
| 2,850 |
java
|
ReporteEstadisticaInfraccionesService.java
|
Java
|
[] | null |
[] |
package pe.edu.unmsm.fisi.siscae.service.impl.reporte;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pe.edu.unmsm.fisi.siscae.mapper.IReporteEstadisticaInfraccionesMapper;
import pe.edu.unmsm.fisi.siscae.model.consulta.ConsultaInfracciones;
import pe.edu.unmsm.fisi.siscae.model.criterio.ReporteEstadisticaInfraccionesCriterioBusqueda;
import pe.edu.unmsm.fisi.siscae.model.reporte.resumen.ReporteEstadisticaInfraccionesPorEjeX;
import pe.edu.unmsm.fisi.siscae.model.reporte.resumen.ReporteInfraccionesPorEjeXSegmentado;
import pe.edu.unmsm.fisi.siscae.service.IReporteEstadisticaInfraccionesService;
@Service
public class ReporteEstadisticaInfraccionesService implements IReporteEstadisticaInfraccionesService {
private @Autowired IReporteEstadisticaInfraccionesMapper reporteEstadisticaInfraccionesMapper;
/*
@Override
public List<ReporteEstadisticaInfracciones> buscarTodos() {
return reporteEstadisticaInfraccionesMapper.buscarTodos();
}
@Override
public List<ReporteEstadisticaInfracciones> buscarPorCriterio(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorCriterio(criterioBusqueda);
}*/
@Override
public List<ReporteEstadisticaInfraccionesPorEjeX> buscarPorPeriodoSinSegementar(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorPeriodoSinSegementar(criterioBusqueda);
}
@Override
public List<ReporteEstadisticaInfraccionesPorEjeX> buscarPorCriterio(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorCriterio(criterioBusqueda);
}
@Override
public List<ReporteInfraccionesPorEjeXSegmentado> buscarPorPeriodoSegmentado(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorPeriodoSegmentado(criterioBusqueda);
}
@Override
public List<ReporteEstadisticaInfraccionesPorEjeX> buscarPorEjeXSinSegmentar(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorEjeXSinSegmentar(criterioBusqueda);
}
@Override
public List<ReporteInfraccionesPorEjeXSegmentado> buscarPorEjeXSegmentado(
ReporteEstadisticaInfraccionesCriterioBusqueda criterioBusqueda) {
return reporteEstadisticaInfraccionesMapper.buscarPorEjeXSegmentado(criterioBusqueda);
}
@Override
public List<ConsultaInfracciones> buscarPorNumeroDocumento(ConsultaInfracciones criterioBusqueda) {
//esto tambien
return reporteEstadisticaInfraccionesMapper.buscarPorNumeroDocumento(criterioBusqueda);
}
}
| 2,850 | 0.847719 | 0.847719 | 70 | 38.685715 | 38.033272 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.185714 | false | false |
0
|
98551eda8a3b6f0c98f7f0e5f3ebd09329c23975
| 24,369,644,460,193 |
174a0df65d5a550215f5528684c6b52cd784e14a
|
/test/ResultTest.java
|
daf2ce19cf9286c992da67bbfa2191a69b1ce79e
|
[] |
no_license
|
wyjwl/GuessNumber
|
https://github.com/wyjwl/GuessNumber
|
9c01c211b618ae2184fd2dcfcd48268117d84b1e
|
c5af3a315f420ac7d7fdb5679ae78b8c7ea65fb6
|
refs/heads/master
| 2021-01-10T01:17:40.372000 | 2016-01-14T04:01:02 | 2016-01-14T04:01:02 | 49,621,246 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import com.company.ReturnResult;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
/**
* Created by lenovo on 2015/12/26.
*/
public class ResultTest {
@Test
public void should_equals_0A0B() {
assertEquals(new ReturnResult().getResult("1234", "5678"), "0A0B");
}
@Test
public void should_equals_4A0B() {
assertEquals(new ReturnResult().getResult("1234", "1234"), "4A0B");
}
@Test
public void should_equals_2A2B(){
assertEquals(new ReturnResult().getResult("1234", "1243"), "2A2B");
}
}
|
UTF-8
|
Java
| 628 |
java
|
ResultTest.java
|
Java
|
[
{
"context": ".framework.Assert.assertEquals;\n\n/**\n * Created by lenovo on 2015/12/26.\n */\npublic class ResultTest {\n ",
"end": 186,
"score": 0.9995195865631104,
"start": 180,
"tag": "USERNAME",
"value": "lenovo"
}
] | null |
[] |
import com.company.ReturnResult;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
/**
* Created by lenovo on 2015/12/26.
*/
public class ResultTest {
@Test
public void should_equals_0A0B() {
assertEquals(new ReturnResult().getResult("1234", "5678"), "0A0B");
}
@Test
public void should_equals_4A0B() {
assertEquals(new ReturnResult().getResult("1234", "1234"), "4A0B");
}
@Test
public void should_equals_2A2B(){
assertEquals(new ReturnResult().getResult("1234", "1243"), "2A2B");
}
}
| 628 | 0.659236 | 0.589172 | 25 | 24.120001 | 24.889067 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false |
0
|
7438ed9fc16fc68f201b3e3188f7141007332a46
| 8,126,078,129,822 |
17a988215c219afb94f65096754bef1595a24849
|
/src/test/java/com/selenium/template/tests/LeftSideMenuCustomerTest.java
|
2f54cf762212e6531d20296253803e1faf0a9aa1
|
[] |
no_license
|
AlexandruZainea/EPOCA-Selenium
|
https://github.com/AlexandruZainea/EPOCA-Selenium
|
468e8990f4b069ff0a79722886d71631863ba48c
|
b6bc88f6b392065aff02e50a9bd32c04feaba5ee
|
refs/heads/master
| 2020-03-12T22:11:54.640000 | 2018-06-04T06:55:58 | 2018-06-04T06:55:58 | 130,842,812 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.selenium.template.tests;
import com.selenium.template.DriverBase;
import com.selenium.template.automationFramework.TestData;
import com.selenium.template.pageObjects.frontend.FELeftMenu;
import com.selenium.template.pageObjects.frontend.FELoginPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Wait;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
public class LeftSideMenuCustomerTest extends DriverBase {
private static final Logger log = Logger.getLogger(APScheduledProcessesTests.class);
private static Wait<WebDriver> wait;
private static DesiredCapabilities capabillities;
// @BeforeClass
// public void setup() throws Exception {
// capabillities = DesiredCapabilities.chrome();
//
// driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabillities);
//
// capabillities.setBrowserName("chrome");
//
// wait = new WebDriverWait(driver, 6000);
//
// }
@Test(groups = "Test")
public void customerSearch () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (TestData.password);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickSearch();
Assert.assertEquals(driver.getCurrentUrl(), TestData.search);
driver.quit();
}
@Test(groups = "Test")
public void specialCommission () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (TestData.password);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickSpecialCommission();
Assert.assertEquals(driver.getCurrentUrl(), TestData.specialCommission);
driver.quit();
}
@Test(groups = "Test")
public void vat () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername(TestData.username);
feLoginPage.inputPassword(TestData.password);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickVAT();
Assert.assertEquals(driver.getCurrentUrl(), TestData.vat);
driver.quit();
}
@Test(groups = "Test")
public void exchangeRate () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (TestData.password);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickExchangeRate();
Assert.assertEquals(driver.getCurrentUrl(), TestData.exchangeRate);
driver.quit();
}
@Test(groups = "Test")
public void bulkCreditLimit () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (TestData.password);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickBulkCreditLimit();
Assert.assertEquals(driver.getCurrentUrl(), TestData.bulkCreditLimit);
driver.quit();
}
@Test(groups = "Test")
public void setupCreditLimit () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (TestData.password);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickSetupCreditLimit();
Assert.assertEquals(driver.getCurrentUrl(), TestData.setupCreditLimit);
driver.quit();
}
}
|
UTF-8
|
Java
| 6,626 |
java
|
LeftSideMenuCustomerTest.java
|
Java
|
[
{
"context": ");\r\n\r\n feLoginPage.inputUsername (TestData.username);\r\n feLoginPage.inputPassword (TestData.pa",
"end": 2414,
"score": 0.788414478302002,
"start": 2406,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ta.username);\r\n feLoginPage.inputPassword (TestData.password);\r\n feLoginPage.signIn();\r\n\r\n FELef",
"end": 2470,
"score": 0.9949964880943298,
"start": 2453,
"tag": "PASSWORD",
"value": "TestData.password"
},
{
"context": "age(driver);\r\n\r\n feLoginPage.inputUsername(TestData.username);\r\n feLoginPage.inputPassword(Tes",
"end": 3304,
"score": 0.5833141207695007,
"start": 3296,
"tag": "USERNAME",
"value": "TestData"
},
{
"context": "r);\r\n\r\n feLoginPage.inputUsername(TestData.username);\r\n feLoginPage.inputPassword(TestData.pas",
"end": 3313,
"score": 0.8672963380813599,
"start": 3305,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ata.username);\r\n feLoginPage.inputPassword(TestData.password);\r\n feLoginPage.signIn();\r\n\r\n FELef",
"end": 3368,
"score": 0.995225191116333,
"start": 3351,
"tag": "PASSWORD",
"value": "TestData.password"
},
{
"context": "river);\r\n\r\n feLoginPage.inputUsername (TestData.username);\r\n feLoginPage.inputPassword (TestDat",
"end": 4221,
"score": 0.9522681832313538,
"start": 4204,
"tag": "USERNAME",
"value": "TestData.username"
},
{
"context": "sername);\r\n feLoginPage.inputPassword (TestData.password);\r\n feLoginPage.signIn();\r\n\r\n ",
"end": 4281,
"score": 0.9988059997558594,
"start": 4264,
"tag": "PASSWORD",
"value": "TestData.password"
},
{
"context": "ge(driver);\r\n\r\n feLoginPage.inputUsername (TestData.username);\r\n feLoginPage.inputPassword (TestData.pa",
"end": 5171,
"score": 0.9899627566337585,
"start": 5154,
"tag": "USERNAME",
"value": "TestData.username"
},
{
"context": "ta.username);\r\n feLoginPage.inputPassword (TestData.password);\r\n feLoginPage.signIn();\r\n\r\n FELef",
"end": 5227,
"score": 0.9992195963859558,
"start": 5210,
"tag": "PASSWORD",
"value": "TestData.password"
},
{
"context": "ge(driver);\r\n\r\n feLoginPage.inputUsername (TestData.username);\r\n feLoginPage.inputPassword (TestData.pa",
"end": 6043,
"score": 0.8997685313224792,
"start": 6026,
"tag": "USERNAME",
"value": "TestData.username"
},
{
"context": "ta.username);\r\n feLoginPage.inputPassword (TestData.password);\r\n feLoginPage.signIn();\r\n\r\n FELef",
"end": 6099,
"score": 0.998919665813446,
"start": 6082,
"tag": "PASSWORD",
"value": "TestData.password"
}
] | null |
[] |
package com.selenium.template.tests;
import com.selenium.template.DriverBase;
import com.selenium.template.automationFramework.TestData;
import com.selenium.template.pageObjects.frontend.FELeftMenu;
import com.selenium.template.pageObjects.frontend.FELoginPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Wait;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.log4testng.Logger;
public class LeftSideMenuCustomerTest extends DriverBase {
private static final Logger log = Logger.getLogger(APScheduledProcessesTests.class);
private static Wait<WebDriver> wait;
private static DesiredCapabilities capabillities;
// @BeforeClass
// public void setup() throws Exception {
// capabillities = DesiredCapabilities.chrome();
//
// driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabillities);
//
// capabillities.setBrowserName("chrome");
//
// wait = new WebDriverWait(driver, 6000);
//
// }
@Test(groups = "Test")
public void customerSearch () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (TestData.password);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickSearch();
Assert.assertEquals(driver.getCurrentUrl(), TestData.search);
driver.quit();
}
@Test(groups = "Test")
public void specialCommission () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (<PASSWORD>);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickSpecialCommission();
Assert.assertEquals(driver.getCurrentUrl(), TestData.specialCommission);
driver.quit();
}
@Test(groups = "Test")
public void vat () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername(TestData.username);
feLoginPage.inputPassword(<PASSWORD>);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickVAT();
Assert.assertEquals(driver.getCurrentUrl(), TestData.vat);
driver.quit();
}
@Test(groups = "Test")
public void exchangeRate () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (<PASSWORD>);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickExchangeRate();
Assert.assertEquals(driver.getCurrentUrl(), TestData.exchangeRate);
driver.quit();
}
@Test(groups = "Test")
public void bulkCreditLimit () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (<PASSWORD>);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickBulkCreditLimit();
Assert.assertEquals(driver.getCurrentUrl(), TestData.bulkCreditLimit);
driver.quit();
}
@Test(groups = "Test")
public void setupCreditLimit () throws Exception {
WebDriver driver = getDriver();
// driver.manage().window().maximize();
driver.get(TestData.search);
FELoginPage feLoginPage = new FELoginPage(driver);
feLoginPage.inputUsername (TestData.username);
feLoginPage.inputPassword (<PASSWORD>);
feLoginPage.signIn();
FELeftMenu feLeftMenu = new FELeftMenu(driver);
feLeftMenu.clickCustomer();
WebElement search = driver.findElement(By.cssSelector("#customer > ul.nav.nav-pills.nav-stacked.null > li:nth-of-type(1) > a"));
if (!search.isDisplayed()) {
feLeftMenu.clickCustomer();
}
feLeftMenu.clickSetupCreditLimit();
Assert.assertEquals(driver.getCurrentUrl(), TestData.setupCreditLimit);
driver.quit();
}
}
| 6,591 | 0.633112 | 0.630848 | 204 | 30.470589 | 30.138798 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544118 | false | false |
0
|
fa5683e631206c36bf6f253b36be7f8b9672dd2a
| 12,635,793,803,565 |
c62717b03b3c04b779900d009eab54348936d067
|
/guli-microservice-sysuser/src/main/java/com/guli/sysuser/entity/Sysuser.java
|
24650a4fd2aebf8ee64eb650a072488956d63a9c
|
[] |
no_license
|
cuvee233/guli
|
https://github.com/cuvee233/guli
|
bdd2ffb7949a52cf8e43f06be0b1c73df90f93b6
|
e0eac68362e802d01737ce7cf31d4c764ccb9ec8
|
refs/heads/master
| 2022-07-10T13:45:36.352000 | 2019-08-12T02:26:55 | 2019-08-12T02:26:55 | 200,234,339 | 1 | 1 | null | false | 2022-05-20T21:04:24 | 2019-08-02T12:53:25 | 2019-08-20T06:00:29 | 2022-05-20T21:04:24 | 83 | 0 | 0 | 5 |
Java
| false | false |
package com.guli.sysuser.entity;
import lombok.Data;
/**
* @author helen
* @since 2019/3/2
*/
@Data
public class Sysuser {
private String id;
private String username;
private String password;
}
|
UTF-8
|
Java
| 203 |
java
|
Sysuser.java
|
Java
|
[
{
"context": "suser.entity;\n\nimport lombok.Data;\n\n/**\n * @author helen\n * @since 2019/3/2\n */\n@Data\npublic class Sysuser",
"end": 75,
"score": 0.9996377229690552,
"start": 70,
"tag": "USERNAME",
"value": "helen"
}
] | null |
[] |
package com.guli.sysuser.entity;
import lombok.Data;
/**
* @author helen
* @since 2019/3/2
*/
@Data
public class Sysuser {
private String id;
private String username;
private String password;
}
| 203 | 0.70936 | 0.679803 | 15 | 12.533334 | 10.794237 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false |
0
|
56cb15f3cbcb95e43f32095a6bc35a0a8082e115
| 13,726,715,493,845 |
2f5fe456f8a85db0dfd69faa26c2e561e7613cf3
|
/src/main/java/com/ual/blog/service/impl/UserServiceImpl.java
|
a5a08a31d43ead6975076c1ca42f1d53d9efe621
|
[] |
no_license
|
Uarealoser/blog
|
https://github.com/Uarealoser/blog
|
6bc1ebdf87349e8a1053f557a3803070c56e7876
|
a05c62f0e865b6b93d3e7e32dd9644d75d20e488
|
refs/heads/master
| 2022-06-08T06:27:02.056000 | 2020-10-29T08:24:42 | 2020-10-29T08:24:42 | 225,748,467 | 1 | 0 | null | false | 2022-05-20T21:17:31 | 2019-12-04T01:03:06 | 2020-10-29T08:24:45 | 2022-05-20T21:17:30 | 84 | 0 | 0 | 2 |
Java
| false | false |
package com.ual.blog.service.impl;
import com.ual.blog.Mapper.BaseMapper;
import com.ual.blog.Mapper.UserMapper;
import com.ual.blog.model.User;
import com.ual.blog.service.UserService;
import com.ual.blog.web.exception.GlobalException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @ClassName UserServiceImpl
* @Description TODO
* @Author ual
*/
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findByUsername(String username) throws GlobalException {
return this.userMapper.getByUsername(username);
}
@Override
public void updatePwd(String username, String oldpwd, String newpwd) throws GlobalException {
User user=this.findByUsername(username);
if(user==null){
throw new GlobalException(403,"用户不存在");
}
if(!user.getPassword().equals(DigestUtils.md5Hex(oldpwd))){
throw new GlobalException(403,"未输入正确的旧密码");
}
User tmp=new User();
tmp.setId(user.getId());
tmp.setPassword(DigestUtils.md5Hex(newpwd));
this.userMapper.updateByPrimaryKeySelective(tmp);
}
@Override
public BaseMapper<User> getBaseMapper() {
return this.userMapper;
}
}
|
UTF-8
|
Java
| 1,404 |
java
|
UserServiceImpl.java
|
Java
|
[
{
"context": "e UserServiceImpl\n * @Description TODO\n * @Author ual\n */\npublic class UserServiceImpl extends BaseServ",
"end": 423,
"score": 0.9883745908737183,
"start": 420,
"tag": "USERNAME",
"value": "ual"
}
] | null |
[] |
package com.ual.blog.service.impl;
import com.ual.blog.Mapper.BaseMapper;
import com.ual.blog.Mapper.UserMapper;
import com.ual.blog.model.User;
import com.ual.blog.service.UserService;
import com.ual.blog.web.exception.GlobalException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @ClassName UserServiceImpl
* @Description TODO
* @Author ual
*/
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findByUsername(String username) throws GlobalException {
return this.userMapper.getByUsername(username);
}
@Override
public void updatePwd(String username, String oldpwd, String newpwd) throws GlobalException {
User user=this.findByUsername(username);
if(user==null){
throw new GlobalException(403,"用户不存在");
}
if(!user.getPassword().equals(DigestUtils.md5Hex(oldpwd))){
throw new GlobalException(403,"未输入正确的旧密码");
}
User tmp=new User();
tmp.setId(user.getId());
tmp.setPassword(DigestUtils.md5Hex(newpwd));
this.userMapper.updateByPrimaryKeySelective(tmp);
}
@Override
public BaseMapper<User> getBaseMapper() {
return this.userMapper;
}
}
| 1,404 | 0.707122 | 0.701308 | 46 | 28.913044 | 25.043289 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false |
0
|
1000347df643cba9b5a5dcdab8e7a2f99d88ca5f
| 19,129,784,350,981 |
f0087b99eba30d13921e7cf9baf700e8fc32aed5
|
/evens.java
|
97700e2a866832245ed9935876a88b1a4e89b082
|
[] |
no_license
|
nikhil336/assign2
|
https://github.com/nikhil336/assign2
|
b488b9037bed1714f766294cac9505c3561c42ca
|
06280b7497a8a2b8fb0d3f35da3506e36d30cd84
|
refs/heads/master
| 2020-03-26T22:02:42.014000 | 2018-08-20T15:08:35 | 2018-08-20T15:08:35 | 145,427,099 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
class evens
{
public static void main(String args[])
{
Scanner kb=new Scanner(System.in);
System.out.print("Enter no:");
int n;
n=kb.nextInt();
System.out.println("output: ");
for(int i=1;i<=n;i++)
{
if(i%2==0)
{
System.out.print(i+" ");
}
}
}
}
|
UTF-8
|
Java
| 271 |
java
|
evens.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
class evens
{
public static void main(String args[])
{
Scanner kb=new Scanner(System.in);
System.out.print("Enter no:");
int n;
n=kb.nextInt();
System.out.println("output: ");
for(int i=1;i<=n;i++)
{
if(i%2==0)
{
System.out.print(i+" ");
}
}
}
}
| 271 | 0.649446 | 0.638376 | 19 | 13.315789 | 13.026502 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false |
0
|
3adaacdca5d2e33377d2ccbba738cb6371c3c021
| 22,574,348,127,792 |
33a60f53cee83923f0a2b154e9d8da5071317987
|
/app/src/main/java/com/example/comer/myproject/Activity/ThirdNewsRepeat.java
|
5546d7cc0880b629761cffc9d4b13439ff0647b7
|
[] |
no_license
|
CBaldemir/webservice-project
|
https://github.com/CBaldemir/webservice-project
|
9a08d1652c0a41cb0c394f3d81f8c962bfc77a5f
|
5ff849b8dd4f882adf48545d627ca166ac0ba49b
|
refs/heads/master
| 2021-01-25T00:48:56.220000 | 2017-06-18T15:23:31 | 2017-06-18T15:23:31 | 94,695,285 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.comer.myproject.Activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.comer.myproject.R;
import com.google.android.gms.common.api.GoogleApiClient;
public class ThirdNewsRepeat extends Activity {
private TextView textview;
private TextView textview1;
private TextView textview2;
private TextView textview3;
private TextView textview4;
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdnewsrepeat);
textview = (TextView) findViewById(R.id.text1);
textview1 = (TextView) findViewById(R.id.text2);
textview2 = (TextView) findViewById(R.id.text3);
textview3 = (TextView) findViewById(R.id.text4);
textview4 = (TextView) findViewById(R.id.text5);
textview.setText("To" + " " + "19" + " " + "İçin, e, e doğru anlamlarına gelir");
textview1.setText("The" + " " + "18" + " " + "Belgeli tanımlılık anlamına gelir.");
textview2.setText("A" + " " + "15" + " " + "Bir anlamına gelir.");
textview3.setText("Of" + " " + "13" + " " + "Nin, in, den anlamına gelir.");
textview4.setText("In" + " " + "11" + " " + "İçinde anlamına gelir.");
}
}
|
UTF-8
|
Java
| 1,374 |
java
|
ThirdNewsRepeat.java
|
Java
|
[] | null |
[] |
package com.example.comer.myproject.Activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.comer.myproject.R;
import com.google.android.gms.common.api.GoogleApiClient;
public class ThirdNewsRepeat extends Activity {
private TextView textview;
private TextView textview1;
private TextView textview2;
private TextView textview3;
private TextView textview4;
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdnewsrepeat);
textview = (TextView) findViewById(R.id.text1);
textview1 = (TextView) findViewById(R.id.text2);
textview2 = (TextView) findViewById(R.id.text3);
textview3 = (TextView) findViewById(R.id.text4);
textview4 = (TextView) findViewById(R.id.text5);
textview.setText("To" + " " + "19" + " " + "İçin, e, e doğru anlamlarına gelir");
textview1.setText("The" + " " + "18" + " " + "Belgeli tanımlılık anlamına gelir.");
textview2.setText("A" + " " + "15" + " " + "Bir anlamına gelir.");
textview3.setText("Of" + " " + "13" + " " + "Nin, in, den anlamına gelir.");
textview4.setText("In" + " " + "11" + " " + "İçinde anlamına gelir.");
}
}
| 1,374 | 0.657605 | 0.637766 | 38 | 34.763157 | 27.737904 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736842 | false | false |
0
|
eebbbe1380727763d155065714028fa7508ddbaf
| 30,906,584,675,795 |
2e360ad1620b76ff17c2a846865a8b3cdd9b948c
|
/tcp/src/main/java/com/mkleo/tcp/Sender.java
|
40ce23025ef1143f84f4b1b94b13c318189cfa7c
|
[] |
no_license
|
Mkleo-github/MkLibraryStore
|
https://github.com/Mkleo-github/MkLibraryStore
|
d3e0ea0d3e7dbc7eacfedcbabb2c160f98d98426
|
41bc779b710ebed9e0d315c8e3fcee27ef96dc67
|
refs/heads/master
| 2021-03-28T20:21:17.183000 | 2020-06-18T07:23:18 | 2020-06-18T07:23:18 | 247,891,683 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mkleo.tcp;
import java.lang.ref.WeakReference;
/**
* @说明:
* @作者: Wang HengJin
* @日期: 2018/12/7 11:53 星期五
*/
public abstract class Sender {
private WeakReference<IClient.Internal> mClientRefrence;
public Sender() {
}
void bindClient(IClient.Internal client) {
mClientRefrence = new WeakReference<>(client);
}
/**
* 是否允许发送
*
* @return
*/
protected boolean isPrepare() {
return null != mClientRefrence && null != mClientRefrence.get();
}
/**
* 发送
*
* @param text
*/
protected void send(String text) {
if (isPrepare())
mClientRefrence.get().sendMessage(text);
}
}
|
UTF-8
|
Java
| 739 |
java
|
Sender.java
|
Java
|
[
{
"context": " java.lang.ref.WeakReference;\n\n/**\n * @说明:\n * @作者: Wang HengJin\n * @日期: 2018/12/7 11:53 星期五\n */\npublic abstract c",
"end": 93,
"score": 0.9998309016227722,
"start": 81,
"tag": "NAME",
"value": "Wang HengJin"
}
] | null |
[] |
package com.mkleo.tcp;
import java.lang.ref.WeakReference;
/**
* @说明:
* @作者: <NAME>
* @日期: 2018/12/7 11:53 星期五
*/
public abstract class Sender {
private WeakReference<IClient.Internal> mClientRefrence;
public Sender() {
}
void bindClient(IClient.Internal client) {
mClientRefrence = new WeakReference<>(client);
}
/**
* 是否允许发送
*
* @return
*/
protected boolean isPrepare() {
return null != mClientRefrence && null != mClientRefrence.get();
}
/**
* 发送
*
* @param text
*/
protected void send(String text) {
if (isPrepare())
mClientRefrence.get().sendMessage(text);
}
}
| 733 | 0.57305 | 0.557447 | 41 | 16.195122 | 18.738535 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.146341 | false | false |
0
|
8bfb38960986a319db1adb4bf6495769dc7e63ba
| 11,639,361,388,790 |
530fe1b3a654543334d5a9afbb2ea46b8544d6b0
|
/Week-12/Day2/src/Generacio.java
|
0b4240f1ee6944bbd885961b10cc06f68e76af31
|
[] |
no_license
|
greenfox-zerda-raptors/PappBeata
|
https://github.com/greenfox-zerda-raptors/PappBeata
|
d58ea959f8588172df5ae9994a552a6af5bb7283
|
3a67b8eedeb7e1b0ff723429ea4faa5350fa8d80
|
refs/heads/master
| 2021-01-12T18:19:16.649000 | 2017-05-06T07:55:19 | 2017-05-06T07:55:19 | 71,363,242 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Generacio {
private Cell[][] cells;
public Generacio(String[][] input) {
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
if (input[i][j].equals(".")) {
cells[i][j] = new Cell(false);
}
cells[i][j] = new Cell(true);
}
}
cells = input;
}
public Generacio createNextGeneracio() {
int[][] countedNeighbours = listAliveNeighbours();
return null;
}
public int[][] listAliveNeighbours() {
int aliveNeighbours = 0;
int[][] output = new int[cells.length][cells[0].length];
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
output[i][j] = cells[i][j].countAliveNeighbours();
}
}
return null;
}
public int countAliveNeighbours() {
return 0;
}
public boolean equals(Object o) {
return alive == ((Cell) o.alive);
}
}
|
UTF-8
|
Java
| 1,068 |
java
|
Generacio.java
|
Java
|
[] | null |
[] |
public class Generacio {
private Cell[][] cells;
public Generacio(String[][] input) {
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
if (input[i][j].equals(".")) {
cells[i][j] = new Cell(false);
}
cells[i][j] = new Cell(true);
}
}
cells = input;
}
public Generacio createNextGeneracio() {
int[][] countedNeighbours = listAliveNeighbours();
return null;
}
public int[][] listAliveNeighbours() {
int aliveNeighbours = 0;
int[][] output = new int[cells.length][cells[0].length];
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
output[i][j] = cells[i][j].countAliveNeighbours();
}
}
return null;
}
public int countAliveNeighbours() {
return 0;
}
public boolean equals(Object o) {
return alive == ((Cell) o.alive);
}
}
| 1,068 | 0.473783 | 0.467228 | 40 | 25.674999 | 20.877485 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
a0718e69ffbc11b9f7c01f50258a97d2a4d30b2c
| 25,769,803,797,746 |
caa64876e9a42a8720dcbaf28edd1da6828a70c4
|
/io/netty/util/NetUtil.java
|
95959de2adb9648ee5d710848d0814022d8d3921
|
[] |
no_license
|
linouxis9/mc-dev-1.10.2
|
https://github.com/linouxis9/mc-dev-1.10.2
|
488bb40d6823a1a78e752de350ca7270ac689240
|
ba3498c936b28fd4bdfa2fb74e97e85f13d8a1a4
|
refs/heads/master
| 2016-09-22T12:49:41.289000 | 2016-07-03T16:32:17 | 2016-07-03T16:32:17 | 62,504,260 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.netty.util;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.StringTokenizer;
public final class NetUtil {
public static final Inet4Address LOCALHOST4;
public static final Inet6Address LOCALHOST6;
public static final InetAddress LOCALHOST;
public static final NetworkInterface LOOPBACK_IF;
public static final int SOMAXCONN;
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NetUtil.class);
public static byte[] createByteArrayFromIpAddressString(String s) {
StringTokenizer stringtokenizer;
if (isValidIpV4Address(s)) {
stringtokenizer = new StringTokenizer(s, ".");
byte[] abyte = new byte[4];
for (int i = 0; i < 4; ++i) {
String s1 = stringtokenizer.nextToken();
int j = Integer.parseInt(s1);
abyte[i] = (byte) j;
}
return abyte;
} else if (!isValidIpV6Address(s)) {
return null;
} else {
if (s.charAt(0) == 91) {
s = s.substring(1, s.length() - 1);
}
stringtokenizer = new StringTokenizer(s, ":.", true);
ArrayList arraylist = new ArrayList();
ArrayList arraylist1 = new ArrayList();
String s2 = "";
String s3 = "";
int k = -1;
while (stringtokenizer.hasMoreTokens()) {
s3 = s2;
s2 = stringtokenizer.nextToken();
if (":".equals(s2)) {
if (":".equals(s3)) {
k = arraylist.size();
} else if (!s3.isEmpty()) {
arraylist.add(s3);
}
} else if (".".equals(s2)) {
arraylist1.add(s3);
}
}
if (":".equals(s3)) {
if (":".equals(s2)) {
k = arraylist.size();
} else {
arraylist.add(s2);
}
} else if (".".equals(s3)) {
arraylist1.add(s2);
}
int l = 8;
if (!arraylist1.isEmpty()) {
l -= 2;
}
int i1;
if (k != -1) {
int j1 = l - arraylist.size();
for (i1 = 0; i1 < j1; ++i1) {
arraylist.add(k, "0");
}
}
byte[] abyte1 = new byte[16];
for (i1 = 0; i1 < arraylist.size(); ++i1) {
convertToBytes((String) arraylist.get(i1), abyte1, i1 * 2);
}
for (i1 = 0; i1 < arraylist1.size(); ++i1) {
abyte1[i1 + 12] = (byte) (Integer.parseInt((String) arraylist1.get(i1)) & 255);
}
return abyte1;
}
}
private static void convertToBytes(String s, byte[] abyte, int i) {
int j = s.length();
int k = 0;
abyte[i] = 0;
abyte[i + 1] = 0;
int l;
if (j > 3) {
l = getIntValue(s.charAt(k++));
abyte[i] = (byte) (abyte[i] | l << 4);
}
if (j > 2) {
l = getIntValue(s.charAt(k++));
abyte[i] = (byte) (abyte[i] | l);
}
if (j > 1) {
l = getIntValue(s.charAt(k++));
abyte[i + 1] = (byte) (abyte[i + 1] | l << 4);
}
l = getIntValue(s.charAt(k));
abyte[i + 1] = (byte) (abyte[i + 1] | l & 15);
}
static int getIntValue(char c0) {
switch (c0) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
c0 = Character.toLowerCase(c0);
switch (c0) {
case 'a':
return 10;
case 'b':
return 11;
case 'c':
return 12;
case 'd':
return 13;
case 'e':
return 14;
case 'f':
return 15;
default:
return 0;
}
}
}
public static boolean isValidIpV6Address(String s) {
int i = s.length();
boolean flag = false;
int j = 0;
int k = 0;
int l = 0;
StringBuilder stringbuilder = new StringBuilder();
char c0 = 0;
byte b0 = 0;
if (i < 2) {
return false;
} else {
for (int i1 = 0; i1 < i; ++i1) {
char c1 = c0;
c0 = s.charAt(i1);
switch (c0) {
case '%':
if (j == 0) {
return false;
}
++l;
if (i1 + 1 >= i) {
return false;
}
try {
if (Integer.parseInt(s.substring(i1 + 1)) < 0) {
return false;
}
break;
} catch (NumberFormatException numberformatexception) {
return false;
}
case '.':
++k;
if (k > 3) {
return false;
}
if (!isValidIp4Word(stringbuilder.toString())) {
return false;
}
if (j != 6 && !flag) {
return false;
}
if (j == 7 && s.charAt(b0) != 58 && s.charAt(1 + b0) != 58) {
return false;
}
stringbuilder.delete(0, stringbuilder.length());
break;
case ':':
if (i1 == b0 && (s.length() <= i1 || s.charAt(i1 + 1) != 58)) {
return false;
}
++j;
if (j > 7) {
return false;
}
if (k > 0) {
return false;
}
if (c1 == 58) {
if (flag) {
return false;
}
flag = true;
}
stringbuilder.delete(0, stringbuilder.length());
break;
case '[':
if (i1 != 0) {
return false;
}
if (s.charAt(i - 1) != 93) {
return false;
}
b0 = 1;
if (i < 4) {
return false;
}
break;
case ']':
if (i1 != i - 1) {
return false;
}
if (s.charAt(0) != 91) {
return false;
}
break;
default:
if (l == 0) {
if (stringbuilder != null && stringbuilder.length() > 3) {
return false;
}
if (!isValidHexChar(c0)) {
return false;
}
}
stringbuilder.append(c0);
}
}
if (k > 0) {
if (k != 3 || !isValidIp4Word(stringbuilder.toString()) || j >= 7) {
return false;
}
} else {
if (j != 7 && !flag) {
return false;
}
if (l == 0 && stringbuilder.length() == 0 && s.charAt(i - 1 - b0) == 58 && s.charAt(i - 2 - b0) != 58) {
return false;
}
}
return true;
}
}
public static boolean isValidIp4Word(String s) {
if (s.length() >= 1 && s.length() <= 3) {
for (int i = 0; i < s.length(); ++i) {
char c0 = s.charAt(i);
if (c0 < 48 || c0 > 57) {
return false;
}
}
return Integer.parseInt(s) <= 255;
} else {
return false;
}
}
static boolean isValidHexChar(char c0) {
return c0 >= 48 && c0 <= 57 || c0 >= 65 && c0 <= 70 || c0 >= 97 && c0 <= 102;
}
public static boolean isValidIpV4Address(String s) {
int i = 0;
int j = s.length();
if (j > 15) {
return false;
} else {
StringBuilder stringbuilder = new StringBuilder();
for (int k = 0; k < j; ++k) {
char c0 = s.charAt(k);
if (c0 == 46) {
++i;
if (i > 3) {
return false;
}
if (stringbuilder.length() == 0) {
return false;
}
if (Integer.parseInt(stringbuilder.toString()) > 255) {
return false;
}
stringbuilder.delete(0, stringbuilder.length());
} else {
if (!Character.isDigit(c0)) {
return false;
}
if (stringbuilder.length() > 2) {
return false;
}
stringbuilder.append(c0);
}
}
if (stringbuilder.length() != 0 && Integer.parseInt(stringbuilder.toString()) <= 255) {
return i == 3;
} else {
return false;
}
}
}
private NetUtil() {}
static {
byte[] abyte = new byte[] { (byte) 127, (byte) 0, (byte) 0, (byte) 1};
byte[] abyte1 = new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 1};
Inet4Address inet4address = null;
try {
inet4address = (Inet4Address) InetAddress.getByAddress(abyte);
} catch (Exception exception) {
PlatformDependent.throwException(exception);
}
LOCALHOST4 = inet4address;
Inet6Address inet6address = null;
try {
inet6address = (Inet6Address) InetAddress.getByAddress(abyte1);
} catch (Exception exception1) {
PlatformDependent.throwException(exception1);
}
LOCALHOST6 = inet6address;
ArrayList arraylist = new ArrayList();
try {
Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkinterface = (NetworkInterface) enumeration.nextElement();
if (networkinterface.getInetAddresses().hasMoreElements()) {
arraylist.add(networkinterface);
}
}
} catch (SocketException socketexception) {
NetUtil.logger.warn("Failed to retrieve the list of available network interfaces", (Throwable) socketexception);
}
NetworkInterface networkinterface1 = null;
Object object = null;
Iterator iterator = arraylist.iterator();
NetworkInterface networkinterface2;
Enumeration enumeration1;
label424:
while (iterator.hasNext()) {
networkinterface2 = (NetworkInterface) iterator.next();
enumeration1 = networkinterface2.getInetAddresses();
while (enumeration1.hasMoreElements()) {
InetAddress inetaddress = (InetAddress) enumeration1.nextElement();
if (inetaddress.isLoopbackAddress()) {
networkinterface1 = networkinterface2;
object = inetaddress;
break label424;
}
}
}
if (networkinterface1 == null) {
try {
iterator = arraylist.iterator();
while (iterator.hasNext()) {
networkinterface2 = (NetworkInterface) iterator.next();
if (networkinterface2.isLoopback()) {
enumeration1 = networkinterface2.getInetAddresses();
if (enumeration1.hasMoreElements()) {
networkinterface1 = networkinterface2;
object = (InetAddress) enumeration1.nextElement();
break;
}
}
}
if (networkinterface1 == null) {
NetUtil.logger.warn("Failed to find the loopback interface");
}
} catch (SocketException socketexception1) {
NetUtil.logger.warn("Failed to find the loopback interface", (Throwable) socketexception1);
}
}
if (networkinterface1 != null) {
NetUtil.logger.debug("Loopback interface: {} ({}, {})", new Object[] { networkinterface1.getName(), networkinterface1.getDisplayName(), ((InetAddress) object).getHostAddress()});
} else if (object == null) {
try {
if (NetworkInterface.getByInetAddress(NetUtil.LOCALHOST6) != null) {
NetUtil.logger.debug("Using hard-coded IPv6 localhost address: {}", (Object) inet6address);
object = inet6address;
}
} catch (Exception exception2) {
;
} finally {
if (object == null) {
NetUtil.logger.debug("Using hard-coded IPv4 localhost address: {}", (Object) inet4address);
object = inet4address;
}
}
}
LOOPBACK_IF = networkinterface1;
LOCALHOST = (InetAddress) object;
int i = PlatformDependent.isWindows() ? 200 : 128;
File file = new File("/proc/sys/net/core/somaxconn");
if (file.exists()) {
BufferedReader bufferedreader = null;
try {
bufferedreader = new BufferedReader(new FileReader(file));
i = Integer.parseInt(bufferedreader.readLine());
if (NetUtil.logger.isDebugEnabled()) {
NetUtil.logger.debug("{}: {}", file, Integer.valueOf(i));
}
} catch (Exception exception3) {
NetUtil.logger.debug("Failed to get SOMAXCONN from: {}", file, exception3);
} finally {
if (bufferedreader != null) {
try {
bufferedreader.close();
} catch (Exception exception4) {
;
}
}
}
} else if (NetUtil.logger.isDebugEnabled()) {
NetUtil.logger.debug("{}: {} (non-existent)", file, Integer.valueOf(i));
}
SOMAXCONN = i;
}
}
|
UTF-8
|
Java
| 16,104 |
java
|
NetUtil.java
|
Java
|
[] | null |
[] |
package io.netty.util;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.StringTokenizer;
public final class NetUtil {
public static final Inet4Address LOCALHOST4;
public static final Inet6Address LOCALHOST6;
public static final InetAddress LOCALHOST;
public static final NetworkInterface LOOPBACK_IF;
public static final int SOMAXCONN;
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NetUtil.class);
public static byte[] createByteArrayFromIpAddressString(String s) {
StringTokenizer stringtokenizer;
if (isValidIpV4Address(s)) {
stringtokenizer = new StringTokenizer(s, ".");
byte[] abyte = new byte[4];
for (int i = 0; i < 4; ++i) {
String s1 = stringtokenizer.nextToken();
int j = Integer.parseInt(s1);
abyte[i] = (byte) j;
}
return abyte;
} else if (!isValidIpV6Address(s)) {
return null;
} else {
if (s.charAt(0) == 91) {
s = s.substring(1, s.length() - 1);
}
stringtokenizer = new StringTokenizer(s, ":.", true);
ArrayList arraylist = new ArrayList();
ArrayList arraylist1 = new ArrayList();
String s2 = "";
String s3 = "";
int k = -1;
while (stringtokenizer.hasMoreTokens()) {
s3 = s2;
s2 = stringtokenizer.nextToken();
if (":".equals(s2)) {
if (":".equals(s3)) {
k = arraylist.size();
} else if (!s3.isEmpty()) {
arraylist.add(s3);
}
} else if (".".equals(s2)) {
arraylist1.add(s3);
}
}
if (":".equals(s3)) {
if (":".equals(s2)) {
k = arraylist.size();
} else {
arraylist.add(s2);
}
} else if (".".equals(s3)) {
arraylist1.add(s2);
}
int l = 8;
if (!arraylist1.isEmpty()) {
l -= 2;
}
int i1;
if (k != -1) {
int j1 = l - arraylist.size();
for (i1 = 0; i1 < j1; ++i1) {
arraylist.add(k, "0");
}
}
byte[] abyte1 = new byte[16];
for (i1 = 0; i1 < arraylist.size(); ++i1) {
convertToBytes((String) arraylist.get(i1), abyte1, i1 * 2);
}
for (i1 = 0; i1 < arraylist1.size(); ++i1) {
abyte1[i1 + 12] = (byte) (Integer.parseInt((String) arraylist1.get(i1)) & 255);
}
return abyte1;
}
}
private static void convertToBytes(String s, byte[] abyte, int i) {
int j = s.length();
int k = 0;
abyte[i] = 0;
abyte[i + 1] = 0;
int l;
if (j > 3) {
l = getIntValue(s.charAt(k++));
abyte[i] = (byte) (abyte[i] | l << 4);
}
if (j > 2) {
l = getIntValue(s.charAt(k++));
abyte[i] = (byte) (abyte[i] | l);
}
if (j > 1) {
l = getIntValue(s.charAt(k++));
abyte[i + 1] = (byte) (abyte[i + 1] | l << 4);
}
l = getIntValue(s.charAt(k));
abyte[i + 1] = (byte) (abyte[i + 1] | l & 15);
}
static int getIntValue(char c0) {
switch (c0) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
c0 = Character.toLowerCase(c0);
switch (c0) {
case 'a':
return 10;
case 'b':
return 11;
case 'c':
return 12;
case 'd':
return 13;
case 'e':
return 14;
case 'f':
return 15;
default:
return 0;
}
}
}
public static boolean isValidIpV6Address(String s) {
int i = s.length();
boolean flag = false;
int j = 0;
int k = 0;
int l = 0;
StringBuilder stringbuilder = new StringBuilder();
char c0 = 0;
byte b0 = 0;
if (i < 2) {
return false;
} else {
for (int i1 = 0; i1 < i; ++i1) {
char c1 = c0;
c0 = s.charAt(i1);
switch (c0) {
case '%':
if (j == 0) {
return false;
}
++l;
if (i1 + 1 >= i) {
return false;
}
try {
if (Integer.parseInt(s.substring(i1 + 1)) < 0) {
return false;
}
break;
} catch (NumberFormatException numberformatexception) {
return false;
}
case '.':
++k;
if (k > 3) {
return false;
}
if (!isValidIp4Word(stringbuilder.toString())) {
return false;
}
if (j != 6 && !flag) {
return false;
}
if (j == 7 && s.charAt(b0) != 58 && s.charAt(1 + b0) != 58) {
return false;
}
stringbuilder.delete(0, stringbuilder.length());
break;
case ':':
if (i1 == b0 && (s.length() <= i1 || s.charAt(i1 + 1) != 58)) {
return false;
}
++j;
if (j > 7) {
return false;
}
if (k > 0) {
return false;
}
if (c1 == 58) {
if (flag) {
return false;
}
flag = true;
}
stringbuilder.delete(0, stringbuilder.length());
break;
case '[':
if (i1 != 0) {
return false;
}
if (s.charAt(i - 1) != 93) {
return false;
}
b0 = 1;
if (i < 4) {
return false;
}
break;
case ']':
if (i1 != i - 1) {
return false;
}
if (s.charAt(0) != 91) {
return false;
}
break;
default:
if (l == 0) {
if (stringbuilder != null && stringbuilder.length() > 3) {
return false;
}
if (!isValidHexChar(c0)) {
return false;
}
}
stringbuilder.append(c0);
}
}
if (k > 0) {
if (k != 3 || !isValidIp4Word(stringbuilder.toString()) || j >= 7) {
return false;
}
} else {
if (j != 7 && !flag) {
return false;
}
if (l == 0 && stringbuilder.length() == 0 && s.charAt(i - 1 - b0) == 58 && s.charAt(i - 2 - b0) != 58) {
return false;
}
}
return true;
}
}
public static boolean isValidIp4Word(String s) {
if (s.length() >= 1 && s.length() <= 3) {
for (int i = 0; i < s.length(); ++i) {
char c0 = s.charAt(i);
if (c0 < 48 || c0 > 57) {
return false;
}
}
return Integer.parseInt(s) <= 255;
} else {
return false;
}
}
static boolean isValidHexChar(char c0) {
return c0 >= 48 && c0 <= 57 || c0 >= 65 && c0 <= 70 || c0 >= 97 && c0 <= 102;
}
public static boolean isValidIpV4Address(String s) {
int i = 0;
int j = s.length();
if (j > 15) {
return false;
} else {
StringBuilder stringbuilder = new StringBuilder();
for (int k = 0; k < j; ++k) {
char c0 = s.charAt(k);
if (c0 == 46) {
++i;
if (i > 3) {
return false;
}
if (stringbuilder.length() == 0) {
return false;
}
if (Integer.parseInt(stringbuilder.toString()) > 255) {
return false;
}
stringbuilder.delete(0, stringbuilder.length());
} else {
if (!Character.isDigit(c0)) {
return false;
}
if (stringbuilder.length() > 2) {
return false;
}
stringbuilder.append(c0);
}
}
if (stringbuilder.length() != 0 && Integer.parseInt(stringbuilder.toString()) <= 255) {
return i == 3;
} else {
return false;
}
}
}
private NetUtil() {}
static {
byte[] abyte = new byte[] { (byte) 127, (byte) 0, (byte) 0, (byte) 1};
byte[] abyte1 = new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 1};
Inet4Address inet4address = null;
try {
inet4address = (Inet4Address) InetAddress.getByAddress(abyte);
} catch (Exception exception) {
PlatformDependent.throwException(exception);
}
LOCALHOST4 = inet4address;
Inet6Address inet6address = null;
try {
inet6address = (Inet6Address) InetAddress.getByAddress(abyte1);
} catch (Exception exception1) {
PlatformDependent.throwException(exception1);
}
LOCALHOST6 = inet6address;
ArrayList arraylist = new ArrayList();
try {
Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkinterface = (NetworkInterface) enumeration.nextElement();
if (networkinterface.getInetAddresses().hasMoreElements()) {
arraylist.add(networkinterface);
}
}
} catch (SocketException socketexception) {
NetUtil.logger.warn("Failed to retrieve the list of available network interfaces", (Throwable) socketexception);
}
NetworkInterface networkinterface1 = null;
Object object = null;
Iterator iterator = arraylist.iterator();
NetworkInterface networkinterface2;
Enumeration enumeration1;
label424:
while (iterator.hasNext()) {
networkinterface2 = (NetworkInterface) iterator.next();
enumeration1 = networkinterface2.getInetAddresses();
while (enumeration1.hasMoreElements()) {
InetAddress inetaddress = (InetAddress) enumeration1.nextElement();
if (inetaddress.isLoopbackAddress()) {
networkinterface1 = networkinterface2;
object = inetaddress;
break label424;
}
}
}
if (networkinterface1 == null) {
try {
iterator = arraylist.iterator();
while (iterator.hasNext()) {
networkinterface2 = (NetworkInterface) iterator.next();
if (networkinterface2.isLoopback()) {
enumeration1 = networkinterface2.getInetAddresses();
if (enumeration1.hasMoreElements()) {
networkinterface1 = networkinterface2;
object = (InetAddress) enumeration1.nextElement();
break;
}
}
}
if (networkinterface1 == null) {
NetUtil.logger.warn("Failed to find the loopback interface");
}
} catch (SocketException socketexception1) {
NetUtil.logger.warn("Failed to find the loopback interface", (Throwable) socketexception1);
}
}
if (networkinterface1 != null) {
NetUtil.logger.debug("Loopback interface: {} ({}, {})", new Object[] { networkinterface1.getName(), networkinterface1.getDisplayName(), ((InetAddress) object).getHostAddress()});
} else if (object == null) {
try {
if (NetworkInterface.getByInetAddress(NetUtil.LOCALHOST6) != null) {
NetUtil.logger.debug("Using hard-coded IPv6 localhost address: {}", (Object) inet6address);
object = inet6address;
}
} catch (Exception exception2) {
;
} finally {
if (object == null) {
NetUtil.logger.debug("Using hard-coded IPv4 localhost address: {}", (Object) inet4address);
object = inet4address;
}
}
}
LOOPBACK_IF = networkinterface1;
LOCALHOST = (InetAddress) object;
int i = PlatformDependent.isWindows() ? 200 : 128;
File file = new File("/proc/sys/net/core/somaxconn");
if (file.exists()) {
BufferedReader bufferedreader = null;
try {
bufferedreader = new BufferedReader(new FileReader(file));
i = Integer.parseInt(bufferedreader.readLine());
if (NetUtil.logger.isDebugEnabled()) {
NetUtil.logger.debug("{}: {}", file, Integer.valueOf(i));
}
} catch (Exception exception3) {
NetUtil.logger.debug("Failed to get SOMAXCONN from: {}", file, exception3);
} finally {
if (bufferedreader != null) {
try {
bufferedreader.close();
} catch (Exception exception4) {
;
}
}
}
} else if (NetUtil.logger.isDebugEnabled()) {
NetUtil.logger.debug("{}: {} (non-existent)", file, Integer.valueOf(i));
}
SOMAXCONN = i;
}
}
| 16,104 | 0.419709 | 0.397727 | 543 | 28.657459 | 25.370779 | 197 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513812 | false | false |
0
|
dc9ba32fbb61e1f3ee1a89c7c77b63db88e16374
| 2,705,829,424,079 |
274d2c4ccb3045b1b9736f3340420b87b5df2308
|
/app/src/main/java/com/example/two_dimentioncodedemo/Activity/Fragment3.java
|
e8b387be5e8bd04bc7cd88eb897d6dd61ff36690
|
[] |
no_license
|
seventeenxsq/Rubbish_Classify
|
https://github.com/seventeenxsq/Rubbish_Classify
|
f8fe4dd0fcf98f62e1a601cc42545676644a1238
|
59fb450eaf3dc38349495b455bf6580b906ec0b0
|
refs/heads/master
| 2020-12-11T11:29:03.819000 | 2020-04-14T15:09:04 | 2020-04-14T15:09:04 | 233,836,255 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.two_dimentioncodedemo.Activity;
import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.two_dimentioncodedemo.R;
/**
* A simple {@link Fragment} subclass.
*/
public class Fragment3 extends Fragment {
private ImageView iv1,iv2,iv3,iv4;
private Button btndati;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main3, container, false);
initview(view);
Animation();
return view;
}
private void Animation(){
ObjectAnimator animator1 = ObjectAnimator.ofFloat(iv1, "translationY", 0f, 40f,0f);
animator1.setDuration(4000);
animator1.setRepeatCount(-1);//设置一直重复
animator1.start();
ObjectAnimator animator2 = ObjectAnimator.ofFloat(iv2, "translationY", 0f, -40f,0f);
animator2.setDuration(4000);
animator2.setRepeatCount(-1);//设置一直重复
animator2.start();
ObjectAnimator animator3 = ObjectAnimator.ofFloat(iv3, "translationY", 0f, 40f,0f);
animator3.setDuration(3000);
animator3.setRepeatCount(-1);//设置一直重复
animator3.start();
ObjectAnimator animator4 = ObjectAnimator.ofFloat(iv4, "translationY", 0f, -40f,0f);
animator4.setDuration(3000);
animator4.setRepeatCount(-1);//设置一直重复
animator4.start();
}
private void initview(View view){
iv1=view.findViewById(R.id.brownround3);
iv2=view.findViewById(R.id.blueround3);
iv3=view.findViewById(R.id.redround3);
iv4=view.findViewById(R.id.greenround3);
btndati=view.findViewById(R.id.btn_dati);
btndati.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
vibrator.vibrate(40);
Intent intent=new Intent(getActivity(),DatiGameActivity.class);
startActivity(intent);
getActivity().finish();
}
});
}
}
|
UTF-8
|
Java
| 2,542 |
java
|
Fragment3.java
|
Java
|
[] | null |
[] |
package com.example.two_dimentioncodedemo.Activity;
import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.two_dimentioncodedemo.R;
/**
* A simple {@link Fragment} subclass.
*/
public class Fragment3 extends Fragment {
private ImageView iv1,iv2,iv3,iv4;
private Button btndati;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main3, container, false);
initview(view);
Animation();
return view;
}
private void Animation(){
ObjectAnimator animator1 = ObjectAnimator.ofFloat(iv1, "translationY", 0f, 40f,0f);
animator1.setDuration(4000);
animator1.setRepeatCount(-1);//设置一直重复
animator1.start();
ObjectAnimator animator2 = ObjectAnimator.ofFloat(iv2, "translationY", 0f, -40f,0f);
animator2.setDuration(4000);
animator2.setRepeatCount(-1);//设置一直重复
animator2.start();
ObjectAnimator animator3 = ObjectAnimator.ofFloat(iv3, "translationY", 0f, 40f,0f);
animator3.setDuration(3000);
animator3.setRepeatCount(-1);//设置一直重复
animator3.start();
ObjectAnimator animator4 = ObjectAnimator.ofFloat(iv4, "translationY", 0f, -40f,0f);
animator4.setDuration(3000);
animator4.setRepeatCount(-1);//设置一直重复
animator4.start();
}
private void initview(View view){
iv1=view.findViewById(R.id.brownround3);
iv2=view.findViewById(R.id.blueround3);
iv3=view.findViewById(R.id.redround3);
iv4=view.findViewById(R.id.greenround3);
btndati=view.findViewById(R.id.btn_dati);
btndati.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
vibrator.vibrate(40);
Intent intent=new Intent(getActivity(),DatiGameActivity.class);
startActivity(intent);
getActivity().finish();
}
});
}
}
| 2,542 | 0.676423 | 0.647153 | 74 | 32.702702 | 26.384235 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.959459 | false | false |
0
|
1bc59cad3aa35b5e617c32e1a77cba6870a15b56
| 23,373,212,048,927 |
43f0ee726d3f65b2fb77eb80a3473ae646d17d02
|
/core/src/io/piotrjastrzebski/playground/box2dtest/lights/SimpleRayLight.java
|
3bbe99683a3693f5b6554e851be1c3b4872b1f00
|
[] |
no_license
|
piotr-j/libgdxplayground
|
https://github.com/piotr-j/libgdxplayground
|
a4280a672152d5a059a6828d9f56c1eab840a45e
|
db30e4c6b6c5f6476e8ce0794a40c9276e3e2e2b
|
refs/heads/master
| 2023-01-22T20:56:28.570000 | 2023-01-19T19:58:44 | 2023-01-19T19:58:44 | 37,018,024 | 41 | 8 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.piotrjastrzebski.playground.box2dtest.lights;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.RayCastCallback;
import com.badlogic.gdx.physics.box2d.World;
/**
* Created by PiotrJ on 18/09/15.
*/
public class SimpleRayLight implements RayCastCallback, Light {
private Vector2 pos = new Vector2();
private World world;
int rays = 360;
float radius = 1;
float[] xs = new float[rays];
float[] ys = new float[rays];
float[] fs = new float[rays];
public SimpleRayLight (float x, float y, float radius, World world) {
pos.set(x, y);
this.radius = radius;
this.world = world;
}
public SimpleRayLight setRadius (float radius) {
this.radius = radius;
return this;
}
public SimpleRayLight setPos (float x, float y) {
this.pos.set(x, y);
return this;
}
Vector2 target = new Vector2();
int rayId;
public void fixedUpdate() {
for (int i = 0; i < rays; i++) {
rayId = i;
target.set(radius, 0).setAngleDeg(i);
target.add(pos);
xs[rayId] = target.x;
ys[rayId] = target.y;
fs[rayId] = 1;
world.rayCast(this, pos, target);
}
}
@Override public float reportRayFixture (Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
xs[rayId] = point.x;
ys[rayId] = point.y;
fs[rayId] = fraction;
return fraction;
}
public void draw(ShapeRenderer renderer) {
renderer.setColor(Color.RED);
renderer.circle(pos.x, pos.y, 0.05f, 8);
renderer.circle(pos.x, pos.y, radius, 32);
renderer.setColor(Color.CYAN);
for (int i = 0; i < rays; i++) {
// renderer.line(pos.x, pos.y, pos.x+ xs[i], pos.y + ys[i]);
renderer.line(pos.x, pos.y, xs[i], ys[i]);
}
}
@Override public void draw (PolygonSpriteBatch batch) {
}
}
|
UTF-8
|
Java
| 1,928 |
java
|
SimpleRayLight.java
|
Java
|
[
{
"context": "package io.piotrjastrzebski.playground.box2dtest.lights;\n\nimport com.ba",
"end": 21,
"score": 0.6212727427482605,
"start": 18,
"tag": "USERNAME",
"value": "str"
},
{
"context": "logic.gdx.physics.box2d.World;\n\n\n/**\n * Created by PiotrJ on 18/09/15.\n */\npublic class SimpleRayLight impl",
"end": 422,
"score": 0.9967018365859985,
"start": 416,
"tag": "USERNAME",
"value": "PiotrJ"
}
] | null |
[] |
package io.piotrjastrzebski.playground.box2dtest.lights;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.RayCastCallback;
import com.badlogic.gdx.physics.box2d.World;
/**
* Created by PiotrJ on 18/09/15.
*/
public class SimpleRayLight implements RayCastCallback, Light {
private Vector2 pos = new Vector2();
private World world;
int rays = 360;
float radius = 1;
float[] xs = new float[rays];
float[] ys = new float[rays];
float[] fs = new float[rays];
public SimpleRayLight (float x, float y, float radius, World world) {
pos.set(x, y);
this.radius = radius;
this.world = world;
}
public SimpleRayLight setRadius (float radius) {
this.radius = radius;
return this;
}
public SimpleRayLight setPos (float x, float y) {
this.pos.set(x, y);
return this;
}
Vector2 target = new Vector2();
int rayId;
public void fixedUpdate() {
for (int i = 0; i < rays; i++) {
rayId = i;
target.set(radius, 0).setAngleDeg(i);
target.add(pos);
xs[rayId] = target.x;
ys[rayId] = target.y;
fs[rayId] = 1;
world.rayCast(this, pos, target);
}
}
@Override public float reportRayFixture (Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
xs[rayId] = point.x;
ys[rayId] = point.y;
fs[rayId] = fraction;
return fraction;
}
public void draw(ShapeRenderer renderer) {
renderer.setColor(Color.RED);
renderer.circle(pos.x, pos.y, 0.05f, 8);
renderer.circle(pos.x, pos.y, radius, 32);
renderer.setColor(Color.CYAN);
for (int i = 0; i < rays; i++) {
// renderer.line(pos.x, pos.y, pos.x+ xs[i], pos.y + ys[i]);
renderer.line(pos.x, pos.y, xs[i], ys[i]);
}
}
@Override public void draw (PolygonSpriteBatch batch) {
}
}
| 1,928 | 0.688278 | 0.671681 | 76 | 24.368422 | 21.625912 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.078947 | false | false |
0
|
800859f6fd95a55c11ba2c450632fba73a256fae
| 6,227,702,605,250 |
0d98e84c2cc3b702ed30030b98f71a46f638bf56
|
/src/main/java/structuralpattern/decoratorpattern/BasicCar/Car.java
|
7d9cd8c131f602eafccefd8d4f93ae8c4f4e286d
|
[] |
no_license
|
rsun07/Design_Pattern
|
https://github.com/rsun07/Design_Pattern
|
1cf55c063588b94871714387276481b4168ee17b
|
48a301b9e8f176a0ee836d8f43f47d40c398fb2b
|
refs/heads/master
| 2023-04-01T22:45:45.787000 | 2019-07-23T20:06:22 | 2019-07-23T20:06:22 | 124,569,614 | 0 | 0 | null | false | 2021-03-31T19:06:25 | 2018-03-09T17:03:30 | 2019-07-23T20:06:24 | 2021-03-31T19:06:22 | 121 | 0 | 0 | 2 |
Java
| false | false |
package structuralpattern.decoratorpattern.BasicCar;
public abstract class Car {
String description;
public abstract int price();
public String getDescription() {
return "This is a car";
};
}
|
UTF-8
|
Java
| 220 |
java
|
Car.java
|
Java
|
[] | null |
[] |
package structuralpattern.decoratorpattern.BasicCar;
public abstract class Car {
String description;
public abstract int price();
public String getDescription() {
return "This is a car";
};
}
| 220 | 0.686364 | 0.686364 | 12 | 17.333334 | 17.499207 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false |
0
|
74890fc71292f59ec7dff05d1cb62da747885c93
| 32,057,635,922,907 |
c5326e2ae655ddbdc5ce15021d91f4554068ae61
|
/src/com/trax/tools/TableAdapter.java
|
6061ab06252b0dc6bd072c4a8beb1066636b0300
|
[] |
no_license
|
drogeek/Trax
|
https://github.com/drogeek/Trax
|
60d66f384d12649ff40a36322cbb97de55fdc4b6
|
38b7fee7d9e8214c11ac2d383ac600ac52b8e6f9
|
refs/heads/master
| 2021-08-11T17:31:44.054000 | 2017-11-14T00:50:24 | 2017-11-14T00:50:24 | 110,620,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.trax.tools;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import java.util.*;
/**
* Created by unautre on 03/12/14.
*/
public abstract class TableAdapter<K, V> extends BaseAdapter implements Observer {
private List<K> lookup;
private ObservableTable<K, V> table;
protected Context context;
public TableAdapter(ObservableTable<K, V> table){
this.table = table;
this.lookup = Arrays.asList((K[])table.keySet().toArray());
table.addObserver(this);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getCount() {
return lookup.size();
}
@Override
public Object getItem(int position) {
return getNativeItem(position);
}
public V getNativeItem(int position){
V ret = table.get(lookup.get(position));
assert ret != null;
return ret;
}
@Override
public void update(Observable observable, Object data){
/* on rafraichit la table de correspondance */
this.lookup = Arrays.asList((K[])table.keySet().toArray());
notifyDataSetChanged();
}
}
|
UTF-8
|
Java
| 1,303 |
java
|
TableAdapter.java
|
Java
|
[
{
"context": "seAdapter;\n\nimport java.util.*;\n\n/**\n * Created by unautre on 03/12/14.\n */\npublic abstract class TableAdapt",
"end": 257,
"score": 0.9996193051338196,
"start": 250,
"tag": "USERNAME",
"value": "unautre"
}
] | null |
[] |
package com.trax.tools;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import java.util.*;
/**
* Created by unautre on 03/12/14.
*/
public abstract class TableAdapter<K, V> extends BaseAdapter implements Observer {
private List<K> lookup;
private ObservableTable<K, V> table;
protected Context context;
public TableAdapter(ObservableTable<K, V> table){
this.table = table;
this.lookup = Arrays.asList((K[])table.keySet().toArray());
table.addObserver(this);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getCount() {
return lookup.size();
}
@Override
public Object getItem(int position) {
return getNativeItem(position);
}
public V getNativeItem(int position){
V ret = table.get(lookup.get(position));
assert ret != null;
return ret;
}
@Override
public void update(Observable observable, Object data){
/* on rafraichit la table de correspondance */
this.lookup = Arrays.asList((K[])table.keySet().toArray());
notifyDataSetChanged();
}
}
| 1,303 | 0.656946 | 0.652341 | 54 | 23.129629 | 20.367044 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false |
0
|
a85fe0f130afc0a71a0bb2b6576ce18e9c5fc305
| 28,346,784,170,852 |
eded31167b89eb1e533c9ddc59179baa72e55eb4
|
/Heap.java
|
8044092c777716db2021886af0439b7cebcf67e0
|
[] |
no_license
|
mohdryz/Heapz
|
https://github.com/mohdryz/Heapz
|
49d9b3c8a99fd8f307c9abf038ec62c0f0ca0055
|
68fb741de8484cdd19e059d9e0a76d99c41aba99
|
refs/heads/master
| 2020-05-25T23:12:19.806000 | 2019-05-23T20:32:32 | 2019-05-23T20:32:32 | 188,030,307 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.lang.Math;
class Heap{
private Node head;
private int size;
public Heap(){
this.head = null;
this.size = 0;
}
public void createHeap(int[] a){
for(int i=0;i<a.length;i++){
Node curr = new Node(a[i],i);
insertLast(curr);
}
}
public void insertAtLeft(Node parent, Node x){
parent.setLeft(x);
if(x!=null)
x.setParent(parent);
}
public void insertAtRight(Node parent, Node x){
parent.setRight(x);
if(x!=null)
x.setParent(parent);
}
public void insertLast(Node x){
if(this.size==0 && x!=null){
this.head = x;
this.size = 1;
return;
}
Node parent = nodeAt((size+1)/2);
if((size+1)%2==0)
insertAtLeft(parent, x);
else
insertAtRight(parent, x);
this.size = this.size+1;
bubbleUp(x);
}
public Node nodeAt(int n){
if(n>size)
throw new RuntimeException("Invalid Index");
if(n==0)
return null;
if(n==1)
return head;
Node x = nodeAt(n/2);
return (n%2==0) ? x.getLeft() : x.getRight();
}
public void bubbleUp(Node x){
while(!x.equals(head) && (x.getParent().getValue() > x.getValue())){
Node parent = x.getParent();
Node grandParent = parent.getParent();
if(grandParent != null){
if(grandParent.getLeft().equals(parent))
insertAtLeft(grandParent, x);
else if(grandParent.getRight().equals(parent))
insertAtRight(grandParent, x);
}
if(parent.getLeft().equals(x)){
Node temp = parent.getRight();
insertAtRight(parent, x.getRight());
insertAtRight(x, temp);
insertAtLeft(parent, x.getLeft());
insertAtLeft(x, parent);
}
else if(parent.getRight().equals(x)){
Node temp = parent.getLeft();
insertAtLeft(parent, x.getLeft());
insertAtLeft(x, temp);
insertAtRight(parent, x.getRight());
insertAtRight(x, parent);
}
if(parent.equals(head)){
this.head = x;
x.setParent(null);
}
}
}
public Node extractMin(){
Node x = head;
if(x.getLeft()==null && x.getRight()==null){
this.head = null;
this.size = 0;
return x;
}
Node last = findLast();
Node lastNodeParent = last.getParent();
if(lastNodeParent.getLeft().equals(last))
insertAtLeft(lastNodeParent, null);
else if(lastNodeParent.getRight().equals(last))
insertAtRight(lastNodeParent, null);
insertAtLeft(last, x.getLeft());
insertAtRight(last, x.getRight());
last.setParent(null);
x.setLeft(null);
x.setRight(null);
x.setParent(null);
this.head = last;
this.size = this.size-1;
sinkDown(last);
return x;
}
public void sinkDown(Node x){
boolean heapPropertyMissedFlag = true;
while(x!=null && heapPropertyMissedFlag){
Node left = x.getLeft();
Node right = x.getRight();
Node parent = x.getParent();
heapPropertyMissedFlag = false;
if(left!=null && right!=null){
if((left.getValue() < right.getValue()) && (left.getValue() < x.getValue())){
heapPropertyMissedFlag = true;
Node temp = left.getRight();
insertAtRight(left, x.getRight());
insertAtRight(x, temp);
insertAtLeft(x, left.getLeft());
insertAtLeft(left, x);
if(parent!=null){
if(parent.getLeft().equals(x))
insertAtLeft(parent, left);
else if(parent.getRight().equals(x))
insertAtRight(parent, left);
}
if(head.equals(x)){
this.head = left;
left.setParent(null);
}
}
else if((left.getValue() >= right.getValue()) && (right.getValue() < x.getValue())){
heapPropertyMissedFlag = true;
Node temp = right.getLeft();
insertAtLeft(right, x.getLeft());
insertAtLeft(x, temp);
insertAtRight(x, right.getRight());
insertAtRight(right, x);
if(parent!=null){
if(parent.getLeft().equals(x))
insertAtLeft(parent, right);
else if(parent.getRight().equals(x))
insertAtRight(parent, right);
}
if(head.equals(x)){
this.head = right;
right.setParent(null);
}
}
}
if(right==null && left==null)
break;
if(right==null && (left.getValue() < x.getValue())){
heapPropertyMissedFlag = true;
Node temp = left.getRight();
insertAtRight(left, x.getRight());
insertAtRight(x, temp);
insertAtLeft(x, left.getLeft());
insertAtLeft(left, x);
if(parent!=null){
if(parent.getLeft().equals(x))
insertAtLeft(parent, left);
else if(parent.getRight().equals(x))
insertAtRight(parent, left);
}
if(head.equals(x)){
this.head = left;
left.setParent(null);
}
}
}
}
public int getSize(){return this.size;}
public Node getHead(){return this.head;}
public Node findLast(){ return nodeAt(size); }
}
|
UTF-8
|
Java
| 6,264 |
java
|
Heap.java
|
Java
|
[] | null |
[] |
import java.lang.Math;
class Heap{
private Node head;
private int size;
public Heap(){
this.head = null;
this.size = 0;
}
public void createHeap(int[] a){
for(int i=0;i<a.length;i++){
Node curr = new Node(a[i],i);
insertLast(curr);
}
}
public void insertAtLeft(Node parent, Node x){
parent.setLeft(x);
if(x!=null)
x.setParent(parent);
}
public void insertAtRight(Node parent, Node x){
parent.setRight(x);
if(x!=null)
x.setParent(parent);
}
public void insertLast(Node x){
if(this.size==0 && x!=null){
this.head = x;
this.size = 1;
return;
}
Node parent = nodeAt((size+1)/2);
if((size+1)%2==0)
insertAtLeft(parent, x);
else
insertAtRight(parent, x);
this.size = this.size+1;
bubbleUp(x);
}
public Node nodeAt(int n){
if(n>size)
throw new RuntimeException("Invalid Index");
if(n==0)
return null;
if(n==1)
return head;
Node x = nodeAt(n/2);
return (n%2==0) ? x.getLeft() : x.getRight();
}
public void bubbleUp(Node x){
while(!x.equals(head) && (x.getParent().getValue() > x.getValue())){
Node parent = x.getParent();
Node grandParent = parent.getParent();
if(grandParent != null){
if(grandParent.getLeft().equals(parent))
insertAtLeft(grandParent, x);
else if(grandParent.getRight().equals(parent))
insertAtRight(grandParent, x);
}
if(parent.getLeft().equals(x)){
Node temp = parent.getRight();
insertAtRight(parent, x.getRight());
insertAtRight(x, temp);
insertAtLeft(parent, x.getLeft());
insertAtLeft(x, parent);
}
else if(parent.getRight().equals(x)){
Node temp = parent.getLeft();
insertAtLeft(parent, x.getLeft());
insertAtLeft(x, temp);
insertAtRight(parent, x.getRight());
insertAtRight(x, parent);
}
if(parent.equals(head)){
this.head = x;
x.setParent(null);
}
}
}
public Node extractMin(){
Node x = head;
if(x.getLeft()==null && x.getRight()==null){
this.head = null;
this.size = 0;
return x;
}
Node last = findLast();
Node lastNodeParent = last.getParent();
if(lastNodeParent.getLeft().equals(last))
insertAtLeft(lastNodeParent, null);
else if(lastNodeParent.getRight().equals(last))
insertAtRight(lastNodeParent, null);
insertAtLeft(last, x.getLeft());
insertAtRight(last, x.getRight());
last.setParent(null);
x.setLeft(null);
x.setRight(null);
x.setParent(null);
this.head = last;
this.size = this.size-1;
sinkDown(last);
return x;
}
public void sinkDown(Node x){
boolean heapPropertyMissedFlag = true;
while(x!=null && heapPropertyMissedFlag){
Node left = x.getLeft();
Node right = x.getRight();
Node parent = x.getParent();
heapPropertyMissedFlag = false;
if(left!=null && right!=null){
if((left.getValue() < right.getValue()) && (left.getValue() < x.getValue())){
heapPropertyMissedFlag = true;
Node temp = left.getRight();
insertAtRight(left, x.getRight());
insertAtRight(x, temp);
insertAtLeft(x, left.getLeft());
insertAtLeft(left, x);
if(parent!=null){
if(parent.getLeft().equals(x))
insertAtLeft(parent, left);
else if(parent.getRight().equals(x))
insertAtRight(parent, left);
}
if(head.equals(x)){
this.head = left;
left.setParent(null);
}
}
else if((left.getValue() >= right.getValue()) && (right.getValue() < x.getValue())){
heapPropertyMissedFlag = true;
Node temp = right.getLeft();
insertAtLeft(right, x.getLeft());
insertAtLeft(x, temp);
insertAtRight(x, right.getRight());
insertAtRight(right, x);
if(parent!=null){
if(parent.getLeft().equals(x))
insertAtLeft(parent, right);
else if(parent.getRight().equals(x))
insertAtRight(parent, right);
}
if(head.equals(x)){
this.head = right;
right.setParent(null);
}
}
}
if(right==null && left==null)
break;
if(right==null && (left.getValue() < x.getValue())){
heapPropertyMissedFlag = true;
Node temp = left.getRight();
insertAtRight(left, x.getRight());
insertAtRight(x, temp);
insertAtLeft(x, left.getLeft());
insertAtLeft(left, x);
if(parent!=null){
if(parent.getLeft().equals(x))
insertAtLeft(parent, left);
else if(parent.getRight().equals(x))
insertAtRight(parent, left);
}
if(head.equals(x)){
this.head = left;
left.setParent(null);
}
}
}
}
public int getSize(){return this.size;}
public Node getHead(){return this.head;}
public Node findLast(){ return nodeAt(size); }
}
| 6,264 | 0.458493 | 0.455779 | 187 | 32.502674 | 18.681219 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false |
0
|
48f5265adde02b35441dd19ac53c6c5f340df51a
| 2,705,829,416,598 |
6c9a1852426ce7b255a5a05433a66806a927c5d3
|
/ch03/src/ch03/OperatorEx34.java
|
07235c3e0b0a00d3574452659076fbb5efddb26f
|
[] |
no_license
|
LEEWOODO/work_java
|
https://github.com/LEEWOODO/work_java
|
f26eee2b6b20508c0bd17500cdbf327cdd188a49
|
c66024bd09bb5daf4e17b163e41ea2432b92a6e7
|
refs/heads/master
| 2020-03-18T03:43:36.400000 | 2018-06-30T05:21:44 | 2018-06-30T05:21:44 | 134,252,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ch03;
public class OperatorEx34 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=0;
i=i+3;
System.out.println(" i :"+i);
i=0;
i+=3;
System.out.println(" i :"+i);
i=0;
i=i-3;
System.out.println(" i :"+i);
i=0;
i-=3;
System.out.println(" i :"+i);
i=1;
i*=3;
System.out.println(" i :"+i);
i=30;
i/=3;
System.out.println(" i :"+i);
}
}
|
UTF-8
|
Java
| 449 |
java
|
OperatorEx34.java
|
Java
|
[] | null |
[] |
package ch03;
public class OperatorEx34 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=0;
i=i+3;
System.out.println(" i :"+i);
i=0;
i+=3;
System.out.println(" i :"+i);
i=0;
i=i-3;
System.out.println(" i :"+i);
i=0;
i-=3;
System.out.println(" i :"+i);
i=1;
i*=3;
System.out.println(" i :"+i);
i=30;
i/=3;
System.out.println(" i :"+i);
}
}
| 449 | 0.510022 | 0.47216 | 28 | 14.035714 | 13.026024 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.178571 | false | false |
0
|
31cb45734aca186bb2afbc16a649c8ac13486122
| 28,071,906,257,221 |
2186e9547154ff5dd2e57a9197f8952accb96942
|
/app/src/main/java/com/longhan/huang/homeinter/ui/acticity/SplashActivity.java
|
aacf3a014ae0ef93e8928074defc217df069becc
|
[] |
no_license
|
kar98kar/homeinter_and
|
https://github.com/kar98kar/homeinter_and
|
1179f994c328b1e39e30fee85d77d40b158b3566
|
d2c309272afcf4be71ea9bf706246b1bbbf3e065
|
refs/heads/master
| 2021-06-19T03:09:17.628000 | 2016-09-11T14:46:03 | 2016-09-11T14:46:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.longhan.huang.homeinter.ui.acticity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.concurrent.TimeUnit;
import com.longhan.huang.homeinter.R;
import com.longhan.huang.homeinter.service.LocationService;
import com.longhan.huang.homeinter.service.MonitorService;
import com.longhan.huang.homeinter.utls.Tools;
import rx.Observable;
import rx.Subscription;
public class SplashActivity extends Activity {
//@Bind(R.id.splash_view)
// ImageView splashView;
Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
//ButterKnife.bind(this);
init();
}
protected void init() {
// Glide.with(this)
// .load(R.drawable.splash_view)
// .crossFade()
// .into(splashView);
if (!Tools.getServerState(this, LocationService.HomeInterServicePackName)) {
startService(new Intent(this, LocationService.class));
}
if (!Tools.getServerState(this, MonitorService.MonitorServicePackName)) {
startService(new Intent(this, MonitorService.class));
}
subscription = Observable.timer(1, TimeUnit.SECONDS).subscribe(i -> {
startActivity(new Intent(this, MainActivity.class));
finish();
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription.isUnsubscribed()){
subscription.unsubscribe();
}
// ButterKnife.unbind(this);
}
}
|
UTF-8
|
Java
| 1,682 |
java
|
SplashActivity.java
|
Java
|
[] | null |
[] |
package com.longhan.huang.homeinter.ui.acticity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.concurrent.TimeUnit;
import com.longhan.huang.homeinter.R;
import com.longhan.huang.homeinter.service.LocationService;
import com.longhan.huang.homeinter.service.MonitorService;
import com.longhan.huang.homeinter.utls.Tools;
import rx.Observable;
import rx.Subscription;
public class SplashActivity extends Activity {
//@Bind(R.id.splash_view)
// ImageView splashView;
Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
//ButterKnife.bind(this);
init();
}
protected void init() {
// Glide.with(this)
// .load(R.drawable.splash_view)
// .crossFade()
// .into(splashView);
if (!Tools.getServerState(this, LocationService.HomeInterServicePackName)) {
startService(new Intent(this, LocationService.class));
}
if (!Tools.getServerState(this, MonitorService.MonitorServicePackName)) {
startService(new Intent(this, MonitorService.class));
}
subscription = Observable.timer(1, TimeUnit.SECONDS).subscribe(i -> {
startActivity(new Intent(this, MainActivity.class));
finish();
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription.isUnsubscribed()){
subscription.unsubscribe();
}
// ButterKnife.unbind(this);
}
}
| 1,682 | 0.656956 | 0.656361 | 59 | 27.508474 | 23.171705 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.542373 | false | false |
0
|
cf2cd18329690f85857ef9d96608129e2e9944cf
| 18,459,769,456,187 |
87fcfaef8247183bbb8032565645c5a0bd080e2f
|
/app/src/main/java/com/Sparsh/easymanpower/MainUI/Comments.java
|
eab9652b85727293cdc323084dda2a8c38dbb672
|
[] |
no_license
|
spur-s/Diss.e-Commerce
|
https://github.com/spur-s/Diss.e-Commerce
|
5839a47d07cb1d0baa85896ccc879af1784d1fc6
|
6730b0cb370dba6177867abae27f39b6c221f12c
|
refs/heads/main
| 2022-12-28T09:55:07.556000 | 2020-10-14T15:23:39 | 2020-10-14T15:23:39 | 304,055,707 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kishor_bhattarai.easymanpower.MainUI;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kishor_bhattarai.easymanpower.Interfaces.ManpowerInterface;
import com.kishor_bhattarai.easymanpower.R;
import com.kishor_bhattarai.easymanpower.models.Review;
import com.kishor_bhattarai.easymanpower.models.ReviewResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Comments extends AppCompatActivity {
public EditText review, rating, itemname;
Button Review;
private String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
review = findViewById(R.id.review);
rating = findViewById(R.id.ratin);
// Review = findViewById(R.id.btnreview1);
itemname = findViewById(R.id.namee);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
id = bundle.getString("id");
}
Toast.makeText(this, "Id : " + id, Toast.LENGTH_SHORT).show();
Review.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addReview();
}
});
}
private void addReview() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:3000/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ManpowerInterface bookApi = retrofit.create(ManpowerInterface.class);
String r = review.getText().toString();
String ratin = rating.getText().toString();
String itemnam = itemname.getText().toString();
com.kishor_bhattarai.easymanpower.models.Review review = new Review(Integer.parseInt(r), ratin, itemnam);
Call<ReviewResponse> call = bookApi.postReview(review);
call.enqueue(new Callback<ReviewResponse>() {
@Override
public void onResponse(Call<ReviewResponse> call, Response<ReviewResponse> response) {
if (response.isSuccessful()) {
Toast.makeText(Comments.this, "Done:" + response.code(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), com.kishor_bhattarai.easymanpower.MainUI.ViewReviews.class));
return;
}
ReviewResponse review = response.body();
// for (ReviewResponse reviews : review) {
String str = "";
str += "Rating:" + review.getRating() + "/n";
str += "reviews:" + review.getReview() + "/n";
str += "itemname:" + review.getitemname() + "/n";
Toast.makeText(Comments.this, "Review " + str, Toast.LENGTH_SHORT).show();
// }
}
@Override
public void onFailure(Call<ReviewResponse> call, Throwable t) {
Toast.makeText(Comments.this, "Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
|
UTF-8
|
Java
| 3,414 |
java
|
Comments.java
|
Java
|
[
{
"context": "er.Interfaces.ManpowerInterface;\nimport com.kishor_bhattarai.easymanpower.R;\nimport com.kishor_bhatta",
"end": 364,
"score": 0.506798505783081,
"start": 364,
"tag": "USERNAME",
"value": ""
},
{
"context": "trofit.Builder()\n .baseUrl(\"http://10.0.2.2:3000/\")\n .addConverterFactory(Gson",
"end": 1679,
"score": 0.963175892829895,
"start": 1671,
"tag": "IP_ADDRESS",
"value": "10.0.2.2"
}
] | null |
[] |
package com.kishor_bhattarai.easymanpower.MainUI;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kishor_bhattarai.easymanpower.Interfaces.ManpowerInterface;
import com.kishor_bhattarai.easymanpower.R;
import com.kishor_bhattarai.easymanpower.models.Review;
import com.kishor_bhattarai.easymanpower.models.ReviewResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Comments extends AppCompatActivity {
public EditText review, rating, itemname;
Button Review;
private String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
review = findViewById(R.id.review);
rating = findViewById(R.id.ratin);
// Review = findViewById(R.id.btnreview1);
itemname = findViewById(R.id.namee);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
id = bundle.getString("id");
}
Toast.makeText(this, "Id : " + id, Toast.LENGTH_SHORT).show();
Review.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addReview();
}
});
}
private void addReview() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:3000/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ManpowerInterface bookApi = retrofit.create(ManpowerInterface.class);
String r = review.getText().toString();
String ratin = rating.getText().toString();
String itemnam = itemname.getText().toString();
com.kishor_bhattarai.easymanpower.models.Review review = new Review(Integer.parseInt(r), ratin, itemnam);
Call<ReviewResponse> call = bookApi.postReview(review);
call.enqueue(new Callback<ReviewResponse>() {
@Override
public void onResponse(Call<ReviewResponse> call, Response<ReviewResponse> response) {
if (response.isSuccessful()) {
Toast.makeText(Comments.this, "Done:" + response.code(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), com.kishor_bhattarai.easymanpower.MainUI.ViewReviews.class));
return;
}
ReviewResponse review = response.body();
// for (ReviewResponse reviews : review) {
String str = "";
str += "Rating:" + review.getRating() + "/n";
str += "reviews:" + review.getReview() + "/n";
str += "itemname:" + review.getitemname() + "/n";
Toast.makeText(Comments.this, "Review " + str, Toast.LENGTH_SHORT).show();
// }
}
@Override
public void onFailure(Call<ReviewResponse> call, Throwable t) {
Toast.makeText(Comments.this, "Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
| 3,414 | 0.623609 | 0.619215 | 104 | 31.817308 | 29.547474 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false |
0
|
8cc7fb0bb0af168a1b8d98635d18f4589b777e40
| 32,469,952,774,465 |
9c99132280e82f663bf5c8d51ae7d295247e365d
|
/src/test/java/logintoapp/loginTestSteps.java
|
e455de39064c3683feb933e68745867514dc84de
|
[] |
no_license
|
PiotrKoziel/TestingTheApps
|
https://github.com/PiotrKoziel/TestingTheApps
|
c24c04847d639e6b2c483c5f7a47a77f2b65c15f
|
bd35dfa3d7c2ddc24a2a5567f28259e7503a63b4
|
refs/heads/master
| 2023-01-20T06:05:04.069000 | 2020-11-27T18:05:07 | 2020-11-27T18:05:07 | 302,064,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package logintoapp;
import cucumber.api.java.en.*;
import org.junit.Assert;
public class loginTestSteps {
private userLogsIn userlogsin;
private String username;
private String password;
@Given("^user is on the login page$")
public void userIsOnTheLogInPage() {
userlogsin = new userLogsIn();
}
@And("^user clicks login button$")
public void userClicksLoginButton() {
System.out.println("user clicks login button");
}
@And("^user with username (.*) and password (.*) is listed in database$")
public void userIsListedInDatabase(String name, String pass) {
userlogsin.SetUserInDataBase(name, pass);
}
@When("^user enters username (.*) and password (.*)$")
public void userEntersUserNameAndPassword$(String name, String pass) {
System.out.println("user enters username: "+ name + " and password: " + pass);
this.username = name;
this.password = pass;
userlogsin.logIn(name, pass);
}
@Then("^user logs in to home page$")
public void userLogsInToHomePage() {
Assert.assertTrue(userlogsin.isLoggedOn());
}
@And("^user sees successful log in message$")
public void userSeesSuccessfulLogInMessage() {
Assert.assertTrue(userlogsin.getMessage().equals("user is logged in"));
}
@But("^log in data is incorrect$")
public void logInDataIsIncorrect() {
String databaseUsername = userlogsin.getCurrentUsername();
String databasePassword = userlogsin.getCurrentPassword();
Assert.assertFalse(username.equals(databaseUsername) && password.equals(databasePassword));
}
@Then("^user is not forwarded to home page$")
public void userIsNotForwardedToHomePage() {
Assert.assertFalse(userlogsin.isLoggedOn());
}
@And("^user sees unsuccessful log in message$")
public void userSeesUnsuccessfulLogInMessage() {
Assert.assertTrue(userlogsin.getMessage().equals("user is not logged in"));
}
}
|
UTF-8
|
Java
| 2,019 |
java
|
loginTestSteps.java
|
Java
|
[
{
"context": "\" and password: \" + pass);\n this.username = name;\n this.password = pass;\n userlogsin",
"end": 932,
"score": 0.9975913763046265,
"start": 928,
"tag": "USERNAME",
"value": "name"
},
{
"context": " this.username = name;\n this.password = pass;\n userlogsin.logIn(name, pass);\n }\n\n ",
"end": 962,
"score": 0.9991998076438904,
"start": 958,
"tag": "PASSWORD",
"value": "pass"
}
] | null |
[] |
package logintoapp;
import cucumber.api.java.en.*;
import org.junit.Assert;
public class loginTestSteps {
private userLogsIn userlogsin;
private String username;
private String password;
@Given("^user is on the login page$")
public void userIsOnTheLogInPage() {
userlogsin = new userLogsIn();
}
@And("^user clicks login button$")
public void userClicksLoginButton() {
System.out.println("user clicks login button");
}
@And("^user with username (.*) and password (.*) is listed in database$")
public void userIsListedInDatabase(String name, String pass) {
userlogsin.SetUserInDataBase(name, pass);
}
@When("^user enters username (.*) and password (.*)$")
public void userEntersUserNameAndPassword$(String name, String pass) {
System.out.println("user enters username: "+ name + " and password: " + pass);
this.username = name;
this.password = <PASSWORD>;
userlogsin.logIn(name, pass);
}
@Then("^user logs in to home page$")
public void userLogsInToHomePage() {
Assert.assertTrue(userlogsin.isLoggedOn());
}
@And("^user sees successful log in message$")
public void userSeesSuccessfulLogInMessage() {
Assert.assertTrue(userlogsin.getMessage().equals("user is logged in"));
}
@But("^log in data is incorrect$")
public void logInDataIsIncorrect() {
String databaseUsername = userlogsin.getCurrentUsername();
String databasePassword = userlogsin.getCurrentPassword();
Assert.assertFalse(username.equals(databaseUsername) && password.equals(databasePassword));
}
@Then("^user is not forwarded to home page$")
public void userIsNotForwardedToHomePage() {
Assert.assertFalse(userlogsin.isLoggedOn());
}
@And("^user sees unsuccessful log in message$")
public void userSeesUnsuccessfulLogInMessage() {
Assert.assertTrue(userlogsin.getMessage().equals("user is not logged in"));
}
}
| 2,025 | 0.669143 | 0.669143 | 70 | 27.842857 | 27.337381 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.342857 | false | false |
0
|
e0d0290c0958ab3a928b70af711397d77da38cfc
| 32,469,952,775,968 |
f0b974c20b0f17ff0173c04d445cbe7c59dee1c5
|
/src/com/GeekTech/players/EnumSuperAbility.java
|
322f55a8830a2018b75740f0960ad925bd55a477
|
[] |
no_license
|
AskarIbraimov/homework8
|
https://github.com/AskarIbraimov/homework8
|
9cca5131c90f96af415674268553fdbe91ec7407
|
9c2a2dd7db90e557b7cc08aad341d5b36dae7402
|
refs/heads/master
| 2023-04-30T15:04:48.313000 | 2021-05-23T11:06:23 | 2021-05-23T11:06:23 | 369,302,102 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.GeekTech.players;
public enum EnumSuperAbility {
SHIELD_DAMAGE, TO_FLY, ALL_CRASH, TO_HEAL,TO_STUN,FACE_BLOCK,SECOND_LIFE;
}
|
UTF-8
|
Java
| 142 |
java
|
EnumSuperAbility.java
|
Java
|
[] | null |
[] |
package com.GeekTech.players;
public enum EnumSuperAbility {
SHIELD_DAMAGE, TO_FLY, ALL_CRASH, TO_HEAL,TO_STUN,FACE_BLOCK,SECOND_LIFE;
}
| 142 | 0.753521 | 0.753521 | 5 | 27.4 | 27.989998 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6 | false | false |
0
|
d6d4f2a9729dbcad19da6ae45c01290704c9c6d4
| 11,321,533,815,396 |
dbec444d769dd76ed192245ca134e3c7372a70ad
|
/app/src/main/java/com/example/hoanglong/bushelper/HistoryFragment.java
|
03d08a226352dd23b8b7d5d18e296655e31c6188
|
[] |
no_license
|
hoanglong26/BusHelper
|
https://github.com/hoanglong26/BusHelper
|
bba4eeb9cf220c42c1674d23cf2effb51ded6278
|
cdc0420e59d54346e23966852b99787de50b72b2
|
refs/heads/master
| 2020-12-02T23:54:36.617000 | 2017-11-07T01:10:30 | 2017-11-07T01:10:30 | 95,959,511 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.hoanglong.bushelper;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.hoanglong.bushelper.entities.TheLocation;
import com.example.hoanglong.bushelper.ormlite.DatabaseManager;
import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IAdapter;
import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter;
import org.greenrobot.eventbus.EventBus;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class HistoryFragment extends Fragment {
@BindView(R.id.rvHistory)
RecyclerView rvHistory;
@BindView(R.id.empty_view)
TextView empty;
private Handler handler;
@BindView(R.id.srlHistory)
SwipeRefreshLayout srlHistory;
FastItemAdapter<TheLocation> fastAdapter = new FastItemAdapter<>();
public HistoryFragment() {
// Required empty public constructor
}
public static HistoryFragment newInstance(String title) {
HistoryFragment fragment = new HistoryFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_history, container, false);
ButterKnife.bind(this, rootView);
DatabaseManager.init(getActivity().getBaseContext());
rvHistory.setLayoutManager(new GridLayoutManager(getActivity(), 2));
//set our adapters to the RecyclerView
//we wrap our FastAdapter inside the ItemAdapter -> This allows us to chain adapters for more complex useCases
rvHistory.setAdapter(fastAdapter);
//set the items to your ItemAdapter
List<TheLocation> locationList = DatabaseManager.getInstance().getAllLocations();
if (locationList.size() == 0) {
rvHistory.setVisibility(View.GONE);
empty.setVisibility(View.VISIBLE);
} else {
empty.setVisibility(View.GONE);
rvHistory.setVisibility(View.VISIBLE);
}
Collections.reverse(locationList);
fastAdapter.add(locationList);
fastAdapter.withSelectable(true);
fastAdapter.withOnClickListener(new FastAdapter.OnClickListener<TheLocation>() {
@Override
public boolean onClick(View v, IAdapter<TheLocation> adapter, TheLocation item, int position) {
EventBus.getDefault().post(new FragmentAdapter.OpenEvent(position, item.getLatitude(), item.getLongitude()));
return true;
}
});
handler = new Handler();
srlHistory.setDistanceToTriggerSync(550);
srlHistory.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (getContext() != null) {
//set the items to your ItemAdapter
List<TheLocation> locationList = DatabaseManager.getInstance().getAllLocations();
if (locationList.size() == 0) {
rvHistory.setVisibility(View.GONE);
empty.setVisibility(View.VISIBLE);
} else {
empty.setVisibility(View.GONE);
rvHistory.setVisibility(View.VISIBLE);
}
Collections.reverse(locationList);
fastAdapter.clear();
fastAdapter.add(locationList);
fastAdapter.notifyAdapterDataSetChanged();
srlHistory.setRefreshing(false);
}
}
}, 2000);
}
});
return rootView;
}
@Override
public void onStart() {
super.onStart();
}
}
|
UTF-8
|
Java
| 4,614 |
java
|
HistoryFragment.java
|
Java
|
[] | null |
[] |
package com.example.hoanglong.bushelper;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.hoanglong.bushelper.entities.TheLocation;
import com.example.hoanglong.bushelper.ormlite.DatabaseManager;
import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IAdapter;
import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter;
import org.greenrobot.eventbus.EventBus;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class HistoryFragment extends Fragment {
@BindView(R.id.rvHistory)
RecyclerView rvHistory;
@BindView(R.id.empty_view)
TextView empty;
private Handler handler;
@BindView(R.id.srlHistory)
SwipeRefreshLayout srlHistory;
FastItemAdapter<TheLocation> fastAdapter = new FastItemAdapter<>();
public HistoryFragment() {
// Required empty public constructor
}
public static HistoryFragment newInstance(String title) {
HistoryFragment fragment = new HistoryFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_history, container, false);
ButterKnife.bind(this, rootView);
DatabaseManager.init(getActivity().getBaseContext());
rvHistory.setLayoutManager(new GridLayoutManager(getActivity(), 2));
//set our adapters to the RecyclerView
//we wrap our FastAdapter inside the ItemAdapter -> This allows us to chain adapters for more complex useCases
rvHistory.setAdapter(fastAdapter);
//set the items to your ItemAdapter
List<TheLocation> locationList = DatabaseManager.getInstance().getAllLocations();
if (locationList.size() == 0) {
rvHistory.setVisibility(View.GONE);
empty.setVisibility(View.VISIBLE);
} else {
empty.setVisibility(View.GONE);
rvHistory.setVisibility(View.VISIBLE);
}
Collections.reverse(locationList);
fastAdapter.add(locationList);
fastAdapter.withSelectable(true);
fastAdapter.withOnClickListener(new FastAdapter.OnClickListener<TheLocation>() {
@Override
public boolean onClick(View v, IAdapter<TheLocation> adapter, TheLocation item, int position) {
EventBus.getDefault().post(new FragmentAdapter.OpenEvent(position, item.getLatitude(), item.getLongitude()));
return true;
}
});
handler = new Handler();
srlHistory.setDistanceToTriggerSync(550);
srlHistory.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (getContext() != null) {
//set the items to your ItemAdapter
List<TheLocation> locationList = DatabaseManager.getInstance().getAllLocations();
if (locationList.size() == 0) {
rvHistory.setVisibility(View.GONE);
empty.setVisibility(View.VISIBLE);
} else {
empty.setVisibility(View.GONE);
rvHistory.setVisibility(View.VISIBLE);
}
Collections.reverse(locationList);
fastAdapter.clear();
fastAdapter.add(locationList);
fastAdapter.notifyAdapterDataSetChanged();
srlHistory.setRefreshing(false);
}
}
}, 2000);
}
});
return rootView;
}
@Override
public void onStart() {
super.onStart();
}
}
| 4,614 | 0.627222 | 0.624187 | 135 | 33.177776 | 27.627647 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
0
|
08b17d7d6e5757e3c9a8c0075a007ab24bf88dab
| 14,070,312,876,154 |
f53e950e6b11003d096c7d1f454301479c19eb84
|
/_src/Chapter 04/CupcakeCounter_end/Particles.java
|
8f92e858634eab04d0452ee006ae35903411b894
|
[
"Apache-2.0"
] |
permissive
|
paullewallencom/greenfoot-978-1-7839-8038-3
|
https://github.com/paullewallencom/greenfoot-978-1-7839-8038-3
|
05c32d4a0870b52acf51f33b18e5bebd8f8568dc
|
ae6d6f79fd33e0dee4d002b4030f17c6f3a0c5d7
|
refs/heads/main
| 2023-02-04T14:16:43.184000 | 2020-12-28T18:08:39 | 2020-12-28T18:08:39 | 319,414,486 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import greenfoot.*;
public class Particles extends Enemy {
private int turnRate = 2;
private int speed = 5;
private int lifeSpan = 50;
public Particles(int tr, int s, int l) {
turnRate = tr;
speed = s;
lifeSpan = l;
setRotation(-90);
}
public void act() {
move();
remove();
}
private void move() {
move(speed);
turn(turnRate);
}
private void remove() {
lifeSpan--;
if( lifeSpan < 0 ) {
getWorld().removeObject(this);
}
}
}
|
UTF-8
|
Java
| 588 |
java
|
Particles.java
|
Java
|
[] | null |
[] |
import greenfoot.*;
public class Particles extends Enemy {
private int turnRate = 2;
private int speed = 5;
private int lifeSpan = 50;
public Particles(int tr, int s, int l) {
turnRate = tr;
speed = s;
lifeSpan = l;
setRotation(-90);
}
public void act() {
move();
remove();
}
private void move() {
move(speed);
turn(turnRate);
}
private void remove() {
lifeSpan--;
if( lifeSpan < 0 ) {
getWorld().removeObject(this);
}
}
}
| 588 | 0.488095 | 0.47619 | 31 | 17.967741 | 12.054938 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516129 | false | false |
0
|
7873d48146f045ad2b869337346ddf4c2a073914
| 18,897,856,118,915 |
ee3eb6a73dddabe0a43fc2bdf7ee68ed564114e2
|
/HW_7/HW_7/BookType.java
|
b65201b2a127d714b419a546d019b0964e8ed542
|
[] |
no_license
|
celt244/HomeWork
|
https://github.com/celt244/HomeWork
|
79cd812a907e4f49efdd8b0f537b065779eee668
|
8fcc77d67eb4a56bf19ae19a39c1a8efd0f07526
|
refs/heads/master
| 2020-12-24T12:41:11.684000 | 2017-05-24T22:54:03 | 2017-05-24T22:54:03 | 72,959,022 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public enum BookType {
NOVEL, TALE, COMEDY, DRAMA, SCIENCEFICTION, DETECTIVE
}
|
UTF-8
|
Java
| 80 |
java
|
BookType.java
|
Java
|
[] | null |
[] |
public enum BookType {
NOVEL, TALE, COMEDY, DRAMA, SCIENCEFICTION, DETECTIVE
}
| 80 | 0.7625 | 0.7625 | 4 | 19 | 21.505814 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false |
0
|
524707049d58165466041f7703d53749a61eadcb
| 17,678,085,410,801 |
86c6ebae300751209fd7fd6eef5ea9ce8a9b8995
|
/src/main/java/ua/ramax/task/LoadAndSaveCountryTask.java
|
b01ba6ba79e5aec93c9cab729ca707dfb8c26524
|
[] |
no_license
|
zccmj/Tripcomposer
|
https://github.com/zccmj/Tripcomposer
|
b0baf18ae0bdbce3ddbefdfa8e590caa32e6bc87
|
96401d00b56acb49381df230713d5dfead7fbacf
|
refs/heads/master
| 2018-01-12T00:51:56.123000 | 2015-11-07T14:56:17 | 2015-11-07T14:56:17 | 45,082,238 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ua.ramax.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.ramax.model.Country;
import ua.ramax.service.CountryService;
import ua.ramax.service.LoadFromApiService;
import java.util.List;
/**
* Created by ramax on 10/28/15.
*/
@Component
public class LoadAndSaveCountryTask implements Task {
@Autowired
private LoadFromApiService loadFromApiService;
@Autowired
private CountryService countryService;
@Override
public void execute() {
List<Country> countries = loadFromApiService.loadCountry();
countryService.save(countries);
}
}
|
UTF-8
|
Java
| 671 |
java
|
LoadAndSaveCountryTask.java
|
Java
|
[
{
"context": "ervice;\n\nimport java.util.List;\n\n/**\n * Created by ramax on 10/28/15.\n */\n@Component\npublic class LoadAndS",
"end": 299,
"score": 0.9996192455291748,
"start": 294,
"tag": "USERNAME",
"value": "ramax"
}
] | null |
[] |
package ua.ramax.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.ramax.model.Country;
import ua.ramax.service.CountryService;
import ua.ramax.service.LoadFromApiService;
import java.util.List;
/**
* Created by ramax on 10/28/15.
*/
@Component
public class LoadAndSaveCountryTask implements Task {
@Autowired
private LoadFromApiService loadFromApiService;
@Autowired
private CountryService countryService;
@Override
public void execute() {
List<Country> countries = loadFromApiService.loadCountry();
countryService.save(countries);
}
}
| 671 | 0.754098 | 0.745156 | 28 | 22.964285 | 20.854053 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392857 | false | false |
0
|
a4bc5e3f8313240275a4ebd1ed268192889791ea
| 9,354,438,792,502 |
2ec90784f0eae7adb74913b0090f5a3da11a4575
|
/app/src/main/java/com/lzx/demo/adapter/ExpandableItemAdapter.java
|
f8f0b4e929c567774c5fde4585165b47e640b551
|
[
"Apache-2.0"
] |
permissive
|
15637972610/LRecyclerView
|
https://github.com/15637972610/LRecyclerView
|
6bb06272b13fa0ff2b670d9b57ea6d72a1599cee
|
9ae6fc677a9d8fc4a6d0c62f0037c25241b2780f
|
refs/heads/master
| 2020-05-28T10:21:53.175000 | 2019-05-28T07:10:53 | 2019-05-28T07:10:53 | 188,968,626 | 1 | 0 |
Apache-2.0
| true | 2019-05-28T06:34:50 | 2019-05-28T06:34:50 | 2019-05-27T01:41:14 | 2019-03-13T03:22:57 | 38,343 | 0 | 0 | 0 | null | false | false |
package com.lzx.demo.adapter;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.lzx.demo.R;
import com.lzx.demo.base.BaseMultiAdapter;
import com.lzx.demo.base.SuperViewHolder;
import com.lzx.demo.bean.Level0Item;
import com.lzx.demo.bean.Level1Item;
import com.lzx.demo.bean.MultiItemEntity;
import com.lzx.demo.bean.Person;
import com.lzx.demo.util.AppToast;
/**
* 分组可点击展开的adapter
* @author lizhixian
* @time 2017/1/12 22:36
*/
public class ExpandableItemAdapter extends BaseMultiAdapter<MultiItemEntity> {
private static final String TAG = ExpandableItemAdapter.class.getSimpleName();
public static final int TYPE_LEVEL_ZERO = 0;
public static final int TYPE_LEVEL_ONE = 1;
public static final int TYPE_ENTITY = 2;
public ExpandableItemAdapter(Context context) {
super(context);
addItemType(TYPE_LEVEL_ZERO, R.layout.item_expandable_lv0);
addItemType(TYPE_LEVEL_ONE, R.layout.item_expandable_lv1);
addItemType(TYPE_ENTITY, R.layout.list_item_text);
}
@Override
public void onBindItemHolder(SuperViewHolder holder, int position) {
MultiItemEntity item = getDataList().get(position);
switch (item.getItemType()) {
case TYPE_LEVEL_ZERO:
bindLevel0Item(holder,position, (Level0Item)item);
break;
case TYPE_LEVEL_ONE:
bindLevel1Item(holder,position, (Level1Item)item);
break;
case TYPE_ENTITY:
bindEntityItem(holder,position, (Person) item);
break;
default:
break;
}
}
private void bindLevel0Item(final SuperViewHolder holder, final int position, final Level0Item item) {
TextView title = holder.getView(R.id.title);
TextView subTitle = holder.getView(R.id.sub_title);
TextView expandState = holder.getView(R.id.expand_state);
title.setText(item.title);
subTitle.setText(item.subTitle);
expandState.setText(item.isExpanded() ? R.string.expanded : R.string.collapsed);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Level 0 item pos: " + position);
if (item.isExpanded()) {
collapse(position);
} else {
if (position % 3 == 0) {
expandAll(position, false);
} else {
expand(position);
}
}
}
});
}
private void bindLevel1Item(final SuperViewHolder holder, final int position, final Level1Item item) {
TextView title = holder.getView(R.id.title);
TextView subTitle = holder.getView(R.id.sub_title);
TextView expandState = holder.getView(R.id.expand_state);
title.setText(item.title);
subTitle.setText(item.subTitle);
expandState.setText(item.isExpanded() ? R.string.expanded : R.string.collapsed);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Level 1 item pos: " + position);
if (item.isExpanded()) {
collapse(position, false);
} else {
expand(position, false);
}
}
});
}
private void bindEntityItem(SuperViewHolder holder, final int position, final Person person) {
TextView textView = holder.getView(R.id.info_text);
textView.setText(person.name + " parent pos: " + position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AppToast.showShortText(mContext,"person: " + person.name + " age: " + person.age);
}
});
}
}
|
UTF-8
|
Java
| 4,075 |
java
|
ExpandableItemAdapter.java
|
Java
|
[
{
"context": ".util.AppToast;\n\n/**\n * 分组可点击展开的adapter\n * @author lizhixian\n * @time 2017/1/12 22:36\n */\n\npublic class Expand",
"end": 483,
"score": 0.999401330947876,
"start": 474,
"tag": "USERNAME",
"value": "lizhixian"
}
] | null |
[] |
package com.lzx.demo.adapter;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.lzx.demo.R;
import com.lzx.demo.base.BaseMultiAdapter;
import com.lzx.demo.base.SuperViewHolder;
import com.lzx.demo.bean.Level0Item;
import com.lzx.demo.bean.Level1Item;
import com.lzx.demo.bean.MultiItemEntity;
import com.lzx.demo.bean.Person;
import com.lzx.demo.util.AppToast;
/**
* 分组可点击展开的adapter
* @author lizhixian
* @time 2017/1/12 22:36
*/
public class ExpandableItemAdapter extends BaseMultiAdapter<MultiItemEntity> {
private static final String TAG = ExpandableItemAdapter.class.getSimpleName();
public static final int TYPE_LEVEL_ZERO = 0;
public static final int TYPE_LEVEL_ONE = 1;
public static final int TYPE_ENTITY = 2;
public ExpandableItemAdapter(Context context) {
super(context);
addItemType(TYPE_LEVEL_ZERO, R.layout.item_expandable_lv0);
addItemType(TYPE_LEVEL_ONE, R.layout.item_expandable_lv1);
addItemType(TYPE_ENTITY, R.layout.list_item_text);
}
@Override
public void onBindItemHolder(SuperViewHolder holder, int position) {
MultiItemEntity item = getDataList().get(position);
switch (item.getItemType()) {
case TYPE_LEVEL_ZERO:
bindLevel0Item(holder,position, (Level0Item)item);
break;
case TYPE_LEVEL_ONE:
bindLevel1Item(holder,position, (Level1Item)item);
break;
case TYPE_ENTITY:
bindEntityItem(holder,position, (Person) item);
break;
default:
break;
}
}
private void bindLevel0Item(final SuperViewHolder holder, final int position, final Level0Item item) {
TextView title = holder.getView(R.id.title);
TextView subTitle = holder.getView(R.id.sub_title);
TextView expandState = holder.getView(R.id.expand_state);
title.setText(item.title);
subTitle.setText(item.subTitle);
expandState.setText(item.isExpanded() ? R.string.expanded : R.string.collapsed);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Level 0 item pos: " + position);
if (item.isExpanded()) {
collapse(position);
} else {
if (position % 3 == 0) {
expandAll(position, false);
} else {
expand(position);
}
}
}
});
}
private void bindLevel1Item(final SuperViewHolder holder, final int position, final Level1Item item) {
TextView title = holder.getView(R.id.title);
TextView subTitle = holder.getView(R.id.sub_title);
TextView expandState = holder.getView(R.id.expand_state);
title.setText(item.title);
subTitle.setText(item.subTitle);
expandState.setText(item.isExpanded() ? R.string.expanded : R.string.collapsed);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Level 1 item pos: " + position);
if (item.isExpanded()) {
collapse(position, false);
} else {
expand(position, false);
}
}
});
}
private void bindEntityItem(SuperViewHolder holder, final int position, final Person person) {
TextView textView = holder.getView(R.id.info_text);
textView.setText(person.name + " parent pos: " + position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AppToast.showShortText(mContext,"person: " + person.name + " age: " + person.age);
}
});
}
}
| 4,075 | 0.604829 | 0.597438 | 113 | 34.920353 | 26.577702 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672566 | false | false |
0
|
20de0a3c067897f2283dbc303b07bdae086cff55
| 16,784,732,212,327 |
b8d329b4ffec479595ed0c557c079a31e86ed8b9
|
/src/main/java/mrcao/exception/TipException.java
|
49e7e7db21d2e7d6647fcbf288052b8e58322096
|
[] |
no_license
|
mrcao20/MySite
|
https://github.com/mrcao20/MySite
|
195f090b0b0194373fb0bcdb185876ecb0aa5fb9
|
68d47d8584942baad53512c0230bf829f78bc062
|
refs/heads/master
| 2020-04-12T04:19:20.459000 | 2019-02-27T14:37:47 | 2019-02-27T14:37:47 | 162,292,126 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* All rights Reserved, Designed By https://github.com/mrcao20
* @Title: TipException.java
* @Package mrcao.exception
* @Description: TODO()
* @author: mrcao
* @date: 2019年1月20日 下午2:56:23
* @version V1.0
* @Copyright: 2019 https://github.com/mrcao20 Inc. All rights reserved.
* Note:转载请说明出处
*/
package mrcao.exception;
/**
* @ClassName: TipException
* @Description:TODO(自定义异常)
* @author: mrcao
* @date: 2019年1月20日 下午2:56:23
*
* @Copyright: 2019 https://github.com/mrcao20 Inc. All rights reserved.
* Note:转载请说明出处
*/
public class TipException extends RuntimeException {
/**
* @Fields serialVersionUID : TODO()
*/
private static final long serialVersionUID = -5028096674000970696L;
public TipException() {
}
public TipException(String message) {
super(message);
}
public TipException(String message, Throwable cause) {
super(message, cause);
}
public TipException(Throwable cause) {
super(cause);
}
}
|
UTF-8
|
Java
| 1,124 |
java
|
TipException.java
|
Java
|
[
{
"context": "l rights Reserved, Designed By https://github.com/mrcao20\r\n * @Title: TipException.java \r\n * @Package mr",
"end": 69,
"score": 0.9996077418327332,
"start": 62,
"tag": "USERNAME",
"value": "mrcao20"
},
{
"context": "ion \r\n * @Description: TODO() \r\n * @author: mrcao\r\n * @date: 2019年1月20日 下午2:56:23 \r\n * @version",
"end": 185,
"score": 0.9996656775474548,
"start": 180,
"tag": "USERNAME",
"value": "mrcao"
},
{
"context": "ion V1.0 \r\n * @Copyright: 2019 https://github.com/mrcao20 Inc. All rights reserved. \r\n * Note:转载请说明出处\r\n */\r",
"end": 289,
"score": 0.9995349645614624,
"start": 282,
"tag": "USERNAME",
"value": "mrcao20"
},
{
"context": "xception\r\n * @Description:TODO(自定义异常)\r\n * @author: mrcao\r\n * @date: 2019年1月20日 下午2:56:23\r\n * \r\n * @Copyr",
"end": 449,
"score": 0.9996617436408997,
"start": 444,
"tag": "USERNAME",
"value": "mrcao"
},
{
"context": "6:23\r\n * \r\n * @Copyright: 2019 https://github.com/mrcao20 Inc. All rights reserved.\r\n * Note:转载请说明出处\r\n */\r\n",
"end": 536,
"score": 0.9989892840385437,
"start": 529,
"tag": "USERNAME",
"value": "mrcao20"
}
] | null |
[] |
/**
* All rights Reserved, Designed By https://github.com/mrcao20
* @Title: TipException.java
* @Package mrcao.exception
* @Description: TODO()
* @author: mrcao
* @date: 2019年1月20日 下午2:56:23
* @version V1.0
* @Copyright: 2019 https://github.com/mrcao20 Inc. All rights reserved.
* Note:转载请说明出处
*/
package mrcao.exception;
/**
* @ClassName: TipException
* @Description:TODO(自定义异常)
* @author: mrcao
* @date: 2019年1月20日 下午2:56:23
*
* @Copyright: 2019 https://github.com/mrcao20 Inc. All rights reserved.
* Note:转载请说明出处
*/
public class TipException extends RuntimeException {
/**
* @Fields serialVersionUID : TODO()
*/
private static final long serialVersionUID = -5028096674000970696L;
public TipException() {
}
public TipException(String message) {
super(message);
}
public TipException(String message, Throwable cause) {
super(message, cause);
}
public TipException(Throwable cause) {
super(cause);
}
}
| 1,124 | 0.627119 | 0.571563 | 44 | 22.136364 | 21.124727 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295455 | false | false |
0
|
a122da69f7a5812c58fc6da6d936512bbff574a0
| 13,804,024,911,187 |
d528fe4f3aa3a7eca7c5ba4e0aee43421e60857f
|
/main/com/zfsoft/xgxt/rcsw/xsxwkh/jbfgl/JbfglForm.java
|
5e9121a8e7cb61b00c5be2fd1b781596fbb0ba06
|
[] |
no_license
|
gxlioper/xajd
|
https://github.com/gxlioper/xajd
|
81bd19a7c4b9f2d1a41a23295497b6de0dae4169
|
b7d4237acf7d6ffeca1c4a5a6717594ca55f1673
|
refs/heads/master
| 2022-03-06T15:49:34.004000 | 2019-11-19T07:43:25 | 2019-11-19T07:43:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* @部门:学工产品事业部
* @日期:2016-8-2 下午04:09:29
*/
package com.zfsoft.xgxt.rcsw.xsxwkh.jbfgl;
import org.apache.struts.action.ActionForm;
import xgxt.comm.search.SearchModel;
import xgxt.utils.Pages;
import com.zfsoft.xgxt.comm.export.model.ExportModel;
/**
* @系统名称: 学生工作管理系统
* @模块名称: XXXX管理模块
* @类功能描述: 基本分表pojo
* @作者: caopei[工号:1352]
* @时间: 2016-8-2 下午04:09:29
* @版本: V1.0
* @修改记录: 类修改者-修改日期-修改说明
*/
public class JbfglForm extends ActionForm{
private String jbfid;
private String xn;
private String xh;
private String bzrcpdj;//班主任或辅导员测评等级
private String bzrcpfz;//-------------测评分值
private String xscpdj;//学生测评等级
private String xscpfz;//-------分值
private String bz;
private Pages pages = new Pages();
private SearchModel searchModel = new SearchModel();
//自定义导出
private ExportModel exportModel = new ExportModel();
private String type;
/**
* @return the jbfid
*/
public String getJbfid() {
return jbfid;
}
/**
* @param jbfid要设置的 jbfid
*/
public void setJbfid(String jbfid) {
this.jbfid = jbfid;
}
/**
* @return the xn
*/
public String getXn() {
return xn;
}
/**
* @param xn要设置的 xn
*/
public void setXn(String xn) {
this.xn = xn;
}
/**
* @return the xh
*/
public String getXh() {
return xh;
}
/**
* @param xh要设置的 xh
*/
public void setXh(String xh) {
this.xh = xh;
}
/**
* @return the bzrcpdj
*/
public String getBzrcpdj() {
return bzrcpdj;
}
/**
* @param bzrcpdj要设置的 bzrcpdj
*/
public void setBzrcpdj(String bzrcpdj) {
this.bzrcpdj = bzrcpdj;
}
/**
* @return the bzrcpfz
*/
public String getBzrcpfz() {
return bzrcpfz;
}
/**
* @param bzrcpfz要设置的 bzrcpfz
*/
public void setBzrcpfz(String bzrcpfz) {
this.bzrcpfz = bzrcpfz;
}
/**
* @return the xscpdj
*/
public String getXscpdj() {
return xscpdj;
}
/**
* @param xscpdj要设置的 xscpdj
*/
public void setXscpdj(String xscpdj) {
this.xscpdj = xscpdj;
}
/**
* @return the xscpfz
*/
public String getXscpfz() {
return xscpfz;
}
/**
* @param xscpfz要设置的 xscpfz
*/
public void setXscpfz(String xscpfz) {
this.xscpfz = xscpfz;
}
/**
* @return the bz
*/
public String getBz() {
return bz;
}
/**
* @param bz要设置的 bz
*/
public void setBz(String bz) {
this.bz = bz;
}
/**
* @return the pages
*/
public Pages getPages() {
return pages;
}
/**
* @param pages要设置的 pages
*/
public void setPages(Pages pages) {
this.pages = pages;
}
/**
* @return the searchModel
*/
public SearchModel getSearchModel() {
return searchModel;
}
/**
* @param searchModel要设置的 searchModel
*/
public void setSearchModel(SearchModel searchModel) {
this.searchModel = searchModel;
}
/**
* @return the exportModel
*/
public ExportModel getExportModel() {
return exportModel;
}
/**
* @param exportModel要设置的 exportModel
*/
public void setExportModel(ExportModel exportModel) {
this.exportModel = exportModel;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type要设置的 type
*/
public void setType(String type) {
this.type = type;
}
/**
* @描述:TODO(这里用一句话描述这个方法的作用)
* @作者:张昌路[工号:982]
* @日期:2016-8-5 上午09:44:09
* @修改记录: 修改者名字-修改日期-修改内容
* @param split
* @return
* int 返回类型
* @throws
*/
}
|
GB18030
|
Java
| 3,878 |
java
|
JbfglForm.java
|
Java
|
[
{
"context": "\r\n * @模块名称: XXXX管理模块\r\n * @类功能描述: 基本分表pojo\r\n * @作者: caopei[工号:1352]\r\n * @时间: 2016-8-2 下午04:09:29 \r\n * @版本: V",
"end": 354,
"score": 0.9997149109840393,
"start": 348,
"tag": "USERNAME",
"value": "caopei"
},
{
"context": "\t}\r\n\t/** \r\n\t * @描述:TODO(这里用一句话描述这个方法的作用)\r\n\t * @作者:张昌路[工号:982]\r\n\t * @日期:2016-8-5 上午09:44:09\r\n\t * @修改记录: ",
"end": 3340,
"score": 0.9988808035850525,
"start": 3337,
"tag": "NAME",
"value": "张昌路"
}
] | null |
[] |
/**
* @部门:学工产品事业部
* @日期:2016-8-2 下午04:09:29
*/
package com.zfsoft.xgxt.rcsw.xsxwkh.jbfgl;
import org.apache.struts.action.ActionForm;
import xgxt.comm.search.SearchModel;
import xgxt.utils.Pages;
import com.zfsoft.xgxt.comm.export.model.ExportModel;
/**
* @系统名称: 学生工作管理系统
* @模块名称: XXXX管理模块
* @类功能描述: 基本分表pojo
* @作者: caopei[工号:1352]
* @时间: 2016-8-2 下午04:09:29
* @版本: V1.0
* @修改记录: 类修改者-修改日期-修改说明
*/
public class JbfglForm extends ActionForm{
private String jbfid;
private String xn;
private String xh;
private String bzrcpdj;//班主任或辅导员测评等级
private String bzrcpfz;//-------------测评分值
private String xscpdj;//学生测评等级
private String xscpfz;//-------分值
private String bz;
private Pages pages = new Pages();
private SearchModel searchModel = new SearchModel();
//自定义导出
private ExportModel exportModel = new ExportModel();
private String type;
/**
* @return the jbfid
*/
public String getJbfid() {
return jbfid;
}
/**
* @param jbfid要设置的 jbfid
*/
public void setJbfid(String jbfid) {
this.jbfid = jbfid;
}
/**
* @return the xn
*/
public String getXn() {
return xn;
}
/**
* @param xn要设置的 xn
*/
public void setXn(String xn) {
this.xn = xn;
}
/**
* @return the xh
*/
public String getXh() {
return xh;
}
/**
* @param xh要设置的 xh
*/
public void setXh(String xh) {
this.xh = xh;
}
/**
* @return the bzrcpdj
*/
public String getBzrcpdj() {
return bzrcpdj;
}
/**
* @param bzrcpdj要设置的 bzrcpdj
*/
public void setBzrcpdj(String bzrcpdj) {
this.bzrcpdj = bzrcpdj;
}
/**
* @return the bzrcpfz
*/
public String getBzrcpfz() {
return bzrcpfz;
}
/**
* @param bzrcpfz要设置的 bzrcpfz
*/
public void setBzrcpfz(String bzrcpfz) {
this.bzrcpfz = bzrcpfz;
}
/**
* @return the xscpdj
*/
public String getXscpdj() {
return xscpdj;
}
/**
* @param xscpdj要设置的 xscpdj
*/
public void setXscpdj(String xscpdj) {
this.xscpdj = xscpdj;
}
/**
* @return the xscpfz
*/
public String getXscpfz() {
return xscpfz;
}
/**
* @param xscpfz要设置的 xscpfz
*/
public void setXscpfz(String xscpfz) {
this.xscpfz = xscpfz;
}
/**
* @return the bz
*/
public String getBz() {
return bz;
}
/**
* @param bz要设置的 bz
*/
public void setBz(String bz) {
this.bz = bz;
}
/**
* @return the pages
*/
public Pages getPages() {
return pages;
}
/**
* @param pages要设置的 pages
*/
public void setPages(Pages pages) {
this.pages = pages;
}
/**
* @return the searchModel
*/
public SearchModel getSearchModel() {
return searchModel;
}
/**
* @param searchModel要设置的 searchModel
*/
public void setSearchModel(SearchModel searchModel) {
this.searchModel = searchModel;
}
/**
* @return the exportModel
*/
public ExportModel getExportModel() {
return exportModel;
}
/**
* @param exportModel要设置的 exportModel
*/
public void setExportModel(ExportModel exportModel) {
this.exportModel = exportModel;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type要设置的 type
*/
public void setType(String type) {
this.type = type;
}
/**
* @描述:TODO(这里用一句话描述这个方法的作用)
* @作者:张昌路[工号:982]
* @日期:2016-8-5 上午09:44:09
* @修改记录: 修改者名字-修改日期-修改内容
* @param split
* @return
* int 返回类型
* @throws
*/
}
| 3,878 | 0.59862 | 0.585681 | 193 | 16.020725 | 13.785537 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.207254 | false | false |
0
|
db742719459ca95126935a0f8fae801efe146786
| 27,822,798,166,325 |
022c6a9a3027d454e62605f2d872b6cdb4fdd267
|
/src/lv/mixam/comunidad/AccPaymentsActivity.java
|
6a71514d1c464817196e8763353699efd0b492e5
|
[] |
no_license
|
mixamlv/comunidad
|
https://github.com/mixamlv/comunidad
|
0088a4fffacf225d8088eb895d5035328deb8b4c
|
70acd6919d6670a55b8a41af8b8d58a7f640b2c5
|
refs/heads/master
| 2016-09-07T06:53:57.377000 | 2012-08-17T21:07:36 | 2012-08-17T21:07:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lv.mixam.comunidad;
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
public class AccPaymentsActivity extends ListActivity {
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
private AccDBAdapter mDbHelper;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payments_list);
mDbHelper = new AccDBAdapter(this);
mDbHelper.open();
Bundle b = getIntent().getExtras();
long accId = b.getLong("accid");
}
}
|
UTF-8
|
Java
| 1,126 |
java
|
AccPaymentsActivity.java
|
Java
|
[] | null |
[] |
package lv.mixam.comunidad;
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
public class AccPaymentsActivity extends ListActivity {
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
private AccDBAdapter mDbHelper;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payments_list);
mDbHelper = new AccDBAdapter(this);
mDbHelper.open();
Bundle b = getIntent().getExtras();
long accId = b.getLong("accid");
}
}
| 1,126 | 0.699822 | 0.699822 | 45 | 23.022223 | 18.867361 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622222 | false | false |
0
|
896402ad0d2032eaca2bfdcd77f5044fbba6c754
| 29,137,058,157,407 |
2779b245f591b173f0181b225f21320b23f38d4d
|
/List/src/com/psybergste/practise/linkedlist/MyLinkedList.java
|
55900d042571f62f6a34f488bb6014f80b9dcd10
|
[] |
no_license
|
kholsas/LearningArchive
|
https://github.com/kholsas/LearningArchive
|
cad9898e6fd7ff8e4c61d66f49e59e7d8158d96d
|
637ed94913efd9b3e10c55c668d02dbc3be72659
|
refs/heads/master
| 2020-07-07T06:21:51.006000 | 2016-08-24T11:59:09 | 2016-08-24T11:59:09 | 66,458,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.psybergste.practise.linkedlist;
import java.util.*;
public class MyLinkedList<T> implements List , Iterable
{
private Node head;
private int index;
/**
* default constructor
*/
public MyLinkedList ( ) {
this.head = null;
this.index = 0;
}
// this method is a general addition method for diff opperations
private void addToIndex ( int i , Object e ) {
if (head == null) {
head = new Node(e);
head.prev = null;
head.next = null;
}
else if (i > -1)// if position has been specified
{
int j = 0;
Node position = head;
while (position != null) {
if (j == i) {
Node<T> temp = new Node(e);
temp.prev = position;
position.next = temp;
}
position = position.next;
j++;
}
}
}
/**
* @param e
* - type : Object this adds a given object value onto the list
* from the back of the list.
**/
public boolean add ( Object e ) {
if (head == null) {
head = new Node(e);
head.prev = null;
head.next = null;
}
else {
Node position = head;
while (position.next != null) {
position = position.next;
}
// next is null... so this obj has to be the next one
Node<T> temp = new Node(e);
// temp.prev = position;// the previous node to a new obj is this
// position
// then the next value to position is this obj
position.next = temp;
}
return true;
}
public void add ( int index , Object element ) {
addToIndex(index, element);
}
public boolean addAll ( Collection c ) {
// take all objects in collection and add them to the list
for (Object obj : c) {
add(obj);
}
return true;
}
public boolean addAll ( int index , Collection c ) {
for (Object obj : c) {
addToIndex(index++, obj);
}
return true;
}
public void clear ( ) {
head = null;
}
public boolean contains ( Object o ) {
Node position = head;
while (position != null) {
if (o.equals(position.obj)) return true;
position = position.next;
}
return false;
}
public boolean containsAll ( Collection c ) {// I have to review this
// method
int size = c.size();
int i = 0;
Iterator iter = iterator();
while (iter.hasNext()) {
for (Object obj : c) {
if (obj == ((Node) iter.next()).obj) i++;
}
}
return size - 1 == i;
}
public Object get ( int index ) {
Object theObj = null;
int i = 0;
if (isEmpty()) { throw new IndexOutOfBoundsException(); }
Node position = head;
while (position != null) {
if (i == index) return position.obj;
position = position.next;
i++;
}
return null;
}
public int indexOf ( Object o ) {
int i = 0;
Iterator iter = iterator();
while (iter.hasNext()) {
if (((Node) iter.next()).obj == o) return i;
i++;
}
return -1;
}
public boolean isEmpty ( ) {
return head == null;
}
/**
* finds the last index of a given search item. if not found -1 is
* returned
**/
public int lastIndexOf ( Object o ) {
int i = 0 , found = -1;
Iterator iter = iterator();
while (iter.hasNext()) {
if (((Node) iter.next()).obj == o) {
found = i;
}
i++;
}
return found;
}
public Iterator iterator ( ) {
return new MyIterator(head, this);
}
public ListIterator listIterator ( ) {
return null;
}
public ListIterator listIterator ( int index ) {
return null;
}
public boolean remove ( Object o ) {
Iterator iter = iterator();
boolean removed = false;
while (iter.hasNext()) {
if (((Node) iter.next()).obj == o) {
iter.remove();
removed = true;
}
}
return removed;
}
public Object remove ( int index ) {
Object removed = null;
Iterator iter = iterator();
int i = 0;
while (iter.hasNext()) {
Node temp = (Node) iter.next();
if (i == index) {
removed = temp.obj;
iter.remove();
}
i++;
}
return removed;
}
public boolean removeAll ( Collection c ) {
if (c == null || c.size() == 0) return false;
Iterator iter = iterator();
while (iter.hasNext()) {
for (Object obj : c) {
if (obj == ((Node) iter.next()).obj) {
iter.remove();
}
}
}
return true;
}
public boolean retainAll ( Collection c ) {
return false;
}
public Object set ( int index , Object element ) {
Object obj = element;// whats the point anyway?
if (isEmpty()) { throw new IndexOutOfBoundsException(); }
if (index > size() - 1) { throw new IndexOutOfBoundsException(); }
Node position = head;
int i = 0;
while (position != null) {
if (index == i) {
obj = position.obj;
position.obj = element;
}
position = position.next;
i++;
}
return obj;
}
public int size ( ) {
int count = 0;
Node position = head;
while (position != null) {
count++;
position = position.next;
}
return count;
}
public List subList ( int fromIndex , int toIndex ) {
List subList = new MyLinkedList();
int i = 0;
Node position = head;
while (position != null) {
if (i >= fromIndex && i <= toIndex) {
subList.add(position.obj);
}
i++;
position = position.next;
}
return subList;
}
private void rehash ( Object[] arr ) {// resizes the arr size
Object[] temp = new Object[arr.length * 2];
for (int i = 0; i < arr.length; i++)
temp[i] = arr[i];
arr = temp;
}
public Object[] toArray ( ) {
Object[] arr = new Object[10];
if (isEmpty()) return null;
Iterator iter = iterator();
int i = 0;
while (iter.hasNext()) {
if (i == arr.length - 1) rehash(arr);
else arr[i++] = ((Node) iter.next()).obj;
}
return arr;
}
public Object[] toArray ( Object[] a ) {
return a = toArray();
}
}
|
UTF-8
|
Java
| 5,909 |
java
|
MyLinkedList.java
|
Java
|
[] | null |
[] |
package com.psybergste.practise.linkedlist;
import java.util.*;
public class MyLinkedList<T> implements List , Iterable
{
private Node head;
private int index;
/**
* default constructor
*/
public MyLinkedList ( ) {
this.head = null;
this.index = 0;
}
// this method is a general addition method for diff opperations
private void addToIndex ( int i , Object e ) {
if (head == null) {
head = new Node(e);
head.prev = null;
head.next = null;
}
else if (i > -1)// if position has been specified
{
int j = 0;
Node position = head;
while (position != null) {
if (j == i) {
Node<T> temp = new Node(e);
temp.prev = position;
position.next = temp;
}
position = position.next;
j++;
}
}
}
/**
* @param e
* - type : Object this adds a given object value onto the list
* from the back of the list.
**/
public boolean add ( Object e ) {
if (head == null) {
head = new Node(e);
head.prev = null;
head.next = null;
}
else {
Node position = head;
while (position.next != null) {
position = position.next;
}
// next is null... so this obj has to be the next one
Node<T> temp = new Node(e);
// temp.prev = position;// the previous node to a new obj is this
// position
// then the next value to position is this obj
position.next = temp;
}
return true;
}
public void add ( int index , Object element ) {
addToIndex(index, element);
}
public boolean addAll ( Collection c ) {
// take all objects in collection and add them to the list
for (Object obj : c) {
add(obj);
}
return true;
}
public boolean addAll ( int index , Collection c ) {
for (Object obj : c) {
addToIndex(index++, obj);
}
return true;
}
public void clear ( ) {
head = null;
}
public boolean contains ( Object o ) {
Node position = head;
while (position != null) {
if (o.equals(position.obj)) return true;
position = position.next;
}
return false;
}
public boolean containsAll ( Collection c ) {// I have to review this
// method
int size = c.size();
int i = 0;
Iterator iter = iterator();
while (iter.hasNext()) {
for (Object obj : c) {
if (obj == ((Node) iter.next()).obj) i++;
}
}
return size - 1 == i;
}
public Object get ( int index ) {
Object theObj = null;
int i = 0;
if (isEmpty()) { throw new IndexOutOfBoundsException(); }
Node position = head;
while (position != null) {
if (i == index) return position.obj;
position = position.next;
i++;
}
return null;
}
public int indexOf ( Object o ) {
int i = 0;
Iterator iter = iterator();
while (iter.hasNext()) {
if (((Node) iter.next()).obj == o) return i;
i++;
}
return -1;
}
public boolean isEmpty ( ) {
return head == null;
}
/**
* finds the last index of a given search item. if not found -1 is
* returned
**/
public int lastIndexOf ( Object o ) {
int i = 0 , found = -1;
Iterator iter = iterator();
while (iter.hasNext()) {
if (((Node) iter.next()).obj == o) {
found = i;
}
i++;
}
return found;
}
public Iterator iterator ( ) {
return new MyIterator(head, this);
}
public ListIterator listIterator ( ) {
return null;
}
public ListIterator listIterator ( int index ) {
return null;
}
public boolean remove ( Object o ) {
Iterator iter = iterator();
boolean removed = false;
while (iter.hasNext()) {
if (((Node) iter.next()).obj == o) {
iter.remove();
removed = true;
}
}
return removed;
}
public Object remove ( int index ) {
Object removed = null;
Iterator iter = iterator();
int i = 0;
while (iter.hasNext()) {
Node temp = (Node) iter.next();
if (i == index) {
removed = temp.obj;
iter.remove();
}
i++;
}
return removed;
}
public boolean removeAll ( Collection c ) {
if (c == null || c.size() == 0) return false;
Iterator iter = iterator();
while (iter.hasNext()) {
for (Object obj : c) {
if (obj == ((Node) iter.next()).obj) {
iter.remove();
}
}
}
return true;
}
public boolean retainAll ( Collection c ) {
return false;
}
public Object set ( int index , Object element ) {
Object obj = element;// whats the point anyway?
if (isEmpty()) { throw new IndexOutOfBoundsException(); }
if (index > size() - 1) { throw new IndexOutOfBoundsException(); }
Node position = head;
int i = 0;
while (position != null) {
if (index == i) {
obj = position.obj;
position.obj = element;
}
position = position.next;
i++;
}
return obj;
}
public int size ( ) {
int count = 0;
Node position = head;
while (position != null) {
count++;
position = position.next;
}
return count;
}
public List subList ( int fromIndex , int toIndex ) {
List subList = new MyLinkedList();
int i = 0;
Node position = head;
while (position != null) {
if (i >= fromIndex && i <= toIndex) {
subList.add(position.obj);
}
i++;
position = position.next;
}
return subList;
}
private void rehash ( Object[] arr ) {// resizes the arr size
Object[] temp = new Object[arr.length * 2];
for (int i = 0; i < arr.length; i++)
temp[i] = arr[i];
arr = temp;
}
public Object[] toArray ( ) {
Object[] arr = new Object[10];
if (isEmpty()) return null;
Iterator iter = iterator();
int i = 0;
while (iter.hasNext()) {
if (i == arr.length - 1) rehash(arr);
else arr[i++] = ((Node) iter.next()).obj;
}
return arr;
}
public Object[] toArray ( Object[] a ) {
return a = toArray();
}
}
| 5,909 | 0.556778 | 0.552885 | 330 | 16.9 | 17.426704 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.733333 | false | false |
0
|
3b98c6be1ea49ffb0a29db92d8ac48dbc765242a
| 12,378,095,771,506 |
7826588e64bb04dfb79c8262bad01235eb409b3d
|
/src/test/java/com/microsoft/bingads/v13/api/test/entities/negative_site/campaign/site/BulkCampaignNegativeSiteTests.java
|
66b2a3e698fc1725c89eb58e376a86c67836de96
|
[
"MIT"
] |
permissive
|
BingAds/BingAds-Java-SDK
|
https://github.com/BingAds/BingAds-Java-SDK
|
dcd43e5a1beeab0b59c1679da1151d7dd1658d50
|
a3d904bbf93a0a93d9c117bfff40f6911ad71d2f
|
refs/heads/main
| 2023-08-28T13:48:34.535000 | 2023-08-18T06:41:51 | 2023-08-18T06:41:51 | 29,510,248 | 33 | 44 |
NOASSERTION
| false | 2023-08-23T01:29:18 | 2015-01-20T03:40:03 | 2023-08-14T14:34:50 | 2023-08-18T06:43:55 | 173,910 | 38 | 41 | 11 |
Java
| false | false |
package com.microsoft.bingads.v13.api.test.entities.negative_site.campaign.site;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.microsoft.bingads.v13.api.test.entities.negative_site.campaign.site.read.BulkCampaignNegativeSiteReadTests;
import com.microsoft.bingads.v13.api.test.entities.negative_site.campaign.site.write.BulkCampaignNegativeSiteWriteTests;
@RunWith(Suite.class)
@SuiteClasses({BulkCampaignNegativeSiteReadTests.class, BulkCampaignNegativeSiteWriteTests.class})
public class BulkCampaignNegativeSiteTests {
}
|
UTF-8
|
Java
| 603 |
java
|
BulkCampaignNegativeSiteTests.java
|
Java
|
[] | null |
[] |
package com.microsoft.bingads.v13.api.test.entities.negative_site.campaign.site;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.microsoft.bingads.v13.api.test.entities.negative_site.campaign.site.read.BulkCampaignNegativeSiteReadTests;
import com.microsoft.bingads.v13.api.test.entities.negative_site.campaign.site.write.BulkCampaignNegativeSiteWriteTests;
@RunWith(Suite.class)
@SuiteClasses({BulkCampaignNegativeSiteReadTests.class, BulkCampaignNegativeSiteWriteTests.class})
public class BulkCampaignNegativeSiteTests {
}
| 603 | 0.854063 | 0.844113 | 14 | 42.07143 | 42.967537 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
5138e6e7ac1600894a7e5afb8febc97a70c59255
| 25,357,486,943,645 |
f463bbbcb41480573e62c27043cbfa844dedb777
|
/module_04/C0421G1_LeVanDiep_Module1/C0221_nhatbede/src/main/java/com/c02/model/service/QuestionService.java
|
8fc18e0448b11f7c61d4a56484a4f1b0e7f3d9b8
|
[] |
no_license
|
vantjn01/C0421G1_LeVanDiep_Module1
|
https://github.com/vantjn01/C0421G1_LeVanDiep_Module1
|
eb7c8ffbc34b2f2a4a8f672c274adefbb6977b76
|
199f8d99ef1d92cc1879a864000980bf4749ab1b
|
refs/heads/master
| 2023-04-21T07:35:42.144000 | 2022-02-22T03:13:06 | 2022-02-22T03:13:06 | 362,051,954 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.c02.model.service;
import com.c02.model.entity.Question;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface QuestionService {
@Query(value="select * from question q join question_type qt" +
" on q.question_type_id=qt.question_type_id where q.title like :name and qt.question_type_name like :questionType",nativeQuery=true)
Page<Question> findAll(Pageable pageable, @Param("name") String name, @Param("questionType") String questionType);
Question findById (Integer integer);
void delete(Integer integer);
void save(Question question);
}
|
UTF-8
|
Java
| 754 |
java
|
QuestionService.java
|
Java
|
[] | null |
[] |
package com.c02.model.service;
import com.c02.model.entity.Question;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface QuestionService {
@Query(value="select * from question q join question_type qt" +
" on q.question_type_id=qt.question_type_id where q.title like :name and qt.question_type_name like :questionType",nativeQuery=true)
Page<Question> findAll(Pageable pageable, @Param("name") String name, @Param("questionType") String questionType);
Question findById (Integer integer);
void delete(Integer integer);
void save(Question question);
}
| 754 | 0.766578 | 0.761273 | 17 | 43.35294 | 37.944141 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false |
0
|
2421f122ca47724f226dcd7f3bbd0b438508fd5d
| 2,911,987,860,852 |
f7dbd548b8cc1e27313d342c9ca4c14eeb835204
|
/src/DB/strategy.java
|
ce38b6c094eb162cfe5df9dffea53b556c02e599
|
[] |
no_license
|
xsomnus/e-mall-api
|
https://github.com/xsomnus/e-mall-api
|
63cf12beabb92bb3ee9d7a24acf93603e5cf898c
|
972ed3c1dc77d80faf6e458bab40a93b6dd3fb29
|
refs/heads/master
| 2021-06-30T14:06:58.511000 | 2017-09-23T02:15:18 | 2017-09-23T02:15:18 | 104,534,238 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package DB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class strategy {
public static String User_Log_in(Connection conn, String UserName, String pass) {
PreparedStatement past = null;
ResultSet rs = null;
String str = null;
try {
past = conn.prepareStatement("select Tel,UserNo,ImagePath,Integral,cStoreNo,rank,discount_rate from dbo.User_Table where (UserNo=? or Tel=? Or UserName=? or Email=?) and UserPass=? ");
past.setString(1, UserName);
past.setString(2, UserName);
past.setString(3, UserName);
past.setString(4, UserName);
past.setString(5, pass);
rs = past.executeQuery();
return str;
} catch (Exception e) {
e.printStackTrace();
} finally {
DB.closeRs_Con(rs, past, conn);
}
return null;
}
}
|
UTF-8
|
Java
| 844 |
java
|
strategy.java
|
Java
|
[] | null |
[] |
package DB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class strategy {
public static String User_Log_in(Connection conn, String UserName, String pass) {
PreparedStatement past = null;
ResultSet rs = null;
String str = null;
try {
past = conn.prepareStatement("select Tel,UserNo,ImagePath,Integral,cStoreNo,rank,discount_rate from dbo.User_Table where (UserNo=? or Tel=? Or UserName=? or Email=?) and UserPass=? ");
past.setString(1, UserName);
past.setString(2, UserName);
past.setString(3, UserName);
past.setString(4, UserName);
past.setString(5, pass);
rs = past.executeQuery();
return str;
} catch (Exception e) {
e.printStackTrace();
} finally {
DB.closeRs_Con(rs, past, conn);
}
return null;
}
}
| 844 | 0.671801 | 0.665877 | 31 | 25.225807 | 33.783665 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.709677 | false | false |
0
|
00b4fd773a1189a7f103565f466cf2aa2e4eb8c9
| 26,250,840,179,120 |
bfb316da5e12587780dbfb8c975f6a85a0f1051e
|
/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/visualization/Visualize.java
|
d8aa6fe6e9efe101602d5492a1660b68a324fe33
|
[] |
no_license
|
elBukkit/PreciousStones
|
https://github.com/elBukkit/PreciousStones
|
1b53b840df4381fedd36a0f0fb3df9935f8c83da
|
9865256de305a6323537c2044eca10cb70a6b1f6
|
refs/heads/master
| 2022-06-18T06:30:43.760000 | 2021-12-30T21:04:56 | 2021-12-30T21:04:56 | 259,953,009 | 9 | 39 | null | true | 2022-12-27T22:49:33 | 2020-04-29T14:43:53 | 2022-08-11T17:58:23 | 2022-05-30T20:45:40 | 5,467 | 9 | 9 | 32 |
Java
| false | false |
package net.sacredlabyrinth.Phaed.PreciousStones.visualization;
import net.sacredlabyrinth.Phaed.PreciousStones.PreciousStones;
import net.sacredlabyrinth.Phaed.PreciousStones.entries.BlockEntry;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* @author phaed
*/
public class Visualize implements Runnable {
private PreciousStones plugin;
private Queue<BlockEntry> visualizationQueue = new LinkedList<>();
private final int timerID;
private final Player player;
private final boolean reverting;
private final boolean skipRevert;
private final int seconds;
public Visualize(List<BlockEntry> blocks, Player player, boolean reverting, boolean skipRevert, int seconds) {
this.visualizationQueue.addAll(blocks);
this.plugin = PreciousStones.getInstance();
this.reverting = reverting;
this.player = player;
this.skipRevert = skipRevert;
this.seconds = seconds;
timerID = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this, 1, PreciousStones.getInstance().getSettingsManager().getVisualizeTicksBetweenSends());
}
@SuppressWarnings("deprecation")
public void run() {
int i = 0;
while (i < PreciousStones.getInstance().getSettingsManager().getVisualizeSendSize() && !visualizationQueue.isEmpty()) {
BlockEntry bd = visualizationQueue.poll();
Location loc = bd.getLocation();
if (!loc.equals(player.getLocation()) && !loc.equals(player.getLocation().add(0, 1, 0))) {
if (reverting) {
Block block = bd.getBlock();
player.sendBlockChange(loc, block.getBlockData());
} else {
player.sendBlockChange(loc, bd.getType(), (byte)0);
}
}
i++;
}
if (visualizationQueue.isEmpty()) {
Bukkit.getServer().getScheduler().cancelTask(timerID);
if (!reverting) {
if (!skipRevert) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> plugin.getVisualizationManager().revert(player), 20L * seconds);
}
}
}
}
}
|
UTF-8
|
Java
| 2,372 |
java
|
Visualize.java
|
Java
|
[
{
"context": "util.List;\nimport java.util.Queue;\n\n/**\n * @author phaed\n */\npublic class Visualize implements Runnable {\n",
"end": 413,
"score": 0.9995489716529846,
"start": 408,
"tag": "USERNAME",
"value": "phaed"
}
] | null |
[] |
package net.sacredlabyrinth.Phaed.PreciousStones.visualization;
import net.sacredlabyrinth.Phaed.PreciousStones.PreciousStones;
import net.sacredlabyrinth.Phaed.PreciousStones.entries.BlockEntry;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* @author phaed
*/
public class Visualize implements Runnable {
private PreciousStones plugin;
private Queue<BlockEntry> visualizationQueue = new LinkedList<>();
private final int timerID;
private final Player player;
private final boolean reverting;
private final boolean skipRevert;
private final int seconds;
public Visualize(List<BlockEntry> blocks, Player player, boolean reverting, boolean skipRevert, int seconds) {
this.visualizationQueue.addAll(blocks);
this.plugin = PreciousStones.getInstance();
this.reverting = reverting;
this.player = player;
this.skipRevert = skipRevert;
this.seconds = seconds;
timerID = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this, 1, PreciousStones.getInstance().getSettingsManager().getVisualizeTicksBetweenSends());
}
@SuppressWarnings("deprecation")
public void run() {
int i = 0;
while (i < PreciousStones.getInstance().getSettingsManager().getVisualizeSendSize() && !visualizationQueue.isEmpty()) {
BlockEntry bd = visualizationQueue.poll();
Location loc = bd.getLocation();
if (!loc.equals(player.getLocation()) && !loc.equals(player.getLocation().add(0, 1, 0))) {
if (reverting) {
Block block = bd.getBlock();
player.sendBlockChange(loc, block.getBlockData());
} else {
player.sendBlockChange(loc, bd.getType(), (byte)0);
}
}
i++;
}
if (visualizationQueue.isEmpty()) {
Bukkit.getServer().getScheduler().cancelTask(timerID);
if (!reverting) {
if (!skipRevert) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> plugin.getVisualizationManager().revert(player), 20L * seconds);
}
}
}
}
}
| 2,372 | 0.645025 | 0.641653 | 65 | 35.49231 | 35.293114 | 178 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723077 | false | false |
0
|
b006eaf3ffcac441ae882212618eceb5a4afc43a
| 22,668,837,411,909 |
d395faa4e2c4c5180492cc61eb921c19769fc2b3
|
/chapter_004/src/main/java/ru/job4j/dsagai/exam/server/game/round/GameCell.java
|
82bddbde4ef2945f8fd8d64535f0547c5f922e01
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
DSagai/dsagai
|
https://github.com/DSagai/dsagai
|
7d412e8be4b76d97f3afda0ca5bcfc35cb10744d
|
7cfa8d972560b29816dbc1eaa378e21437ac1087
|
refs/heads/master
| 2021-01-12T07:51:36.786000 | 2017-06-13T15:10:35 | 2017-06-13T15:10:35 | 77,045,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.job4j.dsagai.exam.server.game.round;
import java.io.Serializable;
/**
* Class holds game turn information - selected field cell
*
* @author dsagai
* @version 1.00
* @since 21.02.2017
*/
public final class GameCell implements Serializable {
private final int x;
private final int y;
private final int value;
/**
* default constructor.
* @param x int.
* @param y int.
*/
public GameCell(int x, int y, int value) {
this.x = x;
this.y = y;
this.value = value;
}
/**
* getter for x field.
* @return int.
*/
public int getX() {
return x;
}
/**
* getter for y field.
* @return int.
*/
public int getY() {
return y;
}
public int getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GameCell gameCell = (GameCell) o;
if (x != gameCell.x)
return false;
return y == gameCell.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
|
UTF-8
|
Java
| 1,277 |
java
|
GameCell.java
|
Java
|
[
{
"context": "rn information - selected field cell\n *\n * @author dsagai\n * @version 1.00\n * @since 21.02.2017\n */\n\npublic",
"end": 162,
"score": 0.9992818832397461,
"start": 156,
"tag": "USERNAME",
"value": "dsagai"
}
] | null |
[] |
package ru.job4j.dsagai.exam.server.game.round;
import java.io.Serializable;
/**
* Class holds game turn information - selected field cell
*
* @author dsagai
* @version 1.00
* @since 21.02.2017
*/
public final class GameCell implements Serializable {
private final int x;
private final int y;
private final int value;
/**
* default constructor.
* @param x int.
* @param y int.
*/
public GameCell(int x, int y, int value) {
this.x = x;
this.y = y;
this.value = value;
}
/**
* getter for x field.
* @return int.
*/
public int getX() {
return x;
}
/**
* getter for y field.
* @return int.
*/
public int getY() {
return y;
}
public int getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GameCell gameCell = (GameCell) o;
if (x != gameCell.x)
return false;
return y == gameCell.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
| 1,277 | 0.518403 | 0.507439 | 69 | 17.507246 | 14.405739 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
0
|
d170bfdb4c5cba006c67919e9ac20ac02f21dbb4
| 26,800,595,939,255 |
d01aed06051eb29982d9d63f105358e680c75821
|
/mybatis_demo_01/src/main/java/com/koki/dao/studentDao/StudentDao.java
|
0b07942c2bee4ef2845b7a9768bf991444dd8613
|
[] |
no_license
|
juicyai/mybatis_01
|
https://github.com/juicyai/mybatis_01
|
194c2543bcdcd77cd477213153b856de400a54d7
|
281df7b23bed63477db105804f7423252a69edb2
|
refs/heads/master
| 2022-12-25T04:17:29.887000 | 2020-09-21T14:05:45 | 2020-09-21T14:05:45 | 297,295,625 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.koki.dao.studentDao;
import com.koki.entity.Student;
import java.util.List;
public interface StudentDao {
//查询student表的所有数据
public List<Student> selectStudents();
//插入
public int insertStudent(Student student);
}
|
UTF-8
|
Java
| 264 |
java
|
StudentDao.java
|
Java
|
[] | null |
[] |
package com.koki.dao.studentDao;
import com.koki.entity.Student;
import java.util.List;
public interface StudentDao {
//查询student表的所有数据
public List<Student> selectStudents();
//插入
public int insertStudent(Student student);
}
| 264 | 0.737705 | 0.737705 | 12 | 19.333334 | 16.357126 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false |
0
|
0f138416a045a9c8c8c870ac1ac45028630db7a6
| 9,698,036,220,975 |
3af985cc74f20bc973925304ede8d41a2a900ac5
|
/src/main/java/dao1/LocationDetailsdao.java
|
d4a7aac2f9bbb5c5efa6c8d99c5d9f37d4852da3
|
[] |
no_license
|
sangeethpps/taxibookingsystem
|
https://github.com/sangeethpps/taxibookingsystem
|
ff17c771e1039b0919457857e7854147ac6dfbb7
|
2295ec19578c51e51dcf7dc32b8a73fe11a33206
|
refs/heads/master
| 2020-03-28T14:48:06.757000 | 2018-09-12T18:39:02 | 2018-09-12T18:39:02 | 148,524,001 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dao1;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import implementation.locationretreival;
import implementation.locationretreival.*;
import MODEL.LocationDetails;
import UTILS.ConnectionUtil;
public class LocationDetailsdao {
Connection con=null;
PreparedStatement psmt;
public void ADDLOCATIONDETAILS(LocationDetails loc) throws Exception
{
con=ConnectionUtil.getOracleConnection();
String q="select EYEOPEN.location_id1_seq.nextval from dual";
System.out.println("check1");
psmt=con.prepareStatement(q);
int myid = 0;
synchronized(this)
{
ResultSet ts=psmt.executeQuery();
if(ts.next())
{
myid=ts.getInt(1);
}
}
psmt.close();
String Sql="INSERT INTO EYEOPEN.LOCATIONDETAILS(LOCATIONID,PICKUP_LOCATION,DROP_LOCATION)VALUES(?,?,?)";
System.out.println("check2");
String a=loc.getPICKUP_LOCATION();
String b=loc.getDROP_LOCATION();
psmt= con.prepareStatement(Sql);
psmt.setInt(1, myid);
if(a!=null)
{
psmt.setString(2,a);
System.out.println(a);
}
if(b!=null)
{
psmt.setString(3,b);
System.out.println(b);
}
psmt.execute();
psmt.close();
con.close();
System.out.println("Succesfully inserted");
}
public void SHOWLOCATIONDETAILS() throws Exception
{
con=ConnectionUtil.getOracleConnection();
String sql="SELECT * FROM EYEOPEN.LOCATIONDETAILS";
psmt=con.prepareStatement(sql);
ResultSet rs=psmt.executeQuery();
while(rs.next())
{
int locationid =rs.getInt(1);
String pickuplocation=rs.getString(2);
String droplocation=rs.getString(3);
System.out.println(locationid+" "+pickuplocation+" "+droplocation);
}
System.out.println("All details are showed....");
}
public void UPDATELOCATIONDETAILS(LocationDetails loc) throws Exception
{
con=ConnectionUtil.getOracleConnection();
String sql="UPDATE EYEOPEN.LOCATIONDETAILS SET PICKUP_LOCATION=?,DROP_LOCATION=? WHERE LOCATIONID=?";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the userid to update values");
int uid=Integer.parseInt(br.readLine());
psmt=con.prepareStatement(sql);
psmt.setString(1, loc.getPICKUP_LOCATION().toString());
psmt.setString(2, loc.getDROP_LOCATION().toString());
psmt.setInt(3, uid);
psmt.executeUpdate();
System.out.println("updated successfully");
}
public void DELETELOCATIONDETAILS() throws Exception
{
con=ConnectionUtil.getOracleConnection();
String sql="DELETE FROM EYEOPEN.LOCATIONDETAILS WHERE LOCATIONID=?";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the userid to delete values");
int uid=Integer.parseInt(br.readLine());
psmt=con.prepareStatement(sql);
psmt.setInt(1, uid);
psmt.execute();
System.out.println("deleted successfully");
}
}
|
UTF-8
|
Java
| 3,018 |
java
|
LocationDetailsdao.java
|
Java
|
[] | null |
[] |
package dao1;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import implementation.locationretreival;
import implementation.locationretreival.*;
import MODEL.LocationDetails;
import UTILS.ConnectionUtil;
public class LocationDetailsdao {
Connection con=null;
PreparedStatement psmt;
public void ADDLOCATIONDETAILS(LocationDetails loc) throws Exception
{
con=ConnectionUtil.getOracleConnection();
String q="select EYEOPEN.location_id1_seq.nextval from dual";
System.out.println("check1");
psmt=con.prepareStatement(q);
int myid = 0;
synchronized(this)
{
ResultSet ts=psmt.executeQuery();
if(ts.next())
{
myid=ts.getInt(1);
}
}
psmt.close();
String Sql="INSERT INTO EYEOPEN.LOCATIONDETAILS(LOCATIONID,PICKUP_LOCATION,DROP_LOCATION)VALUES(?,?,?)";
System.out.println("check2");
String a=loc.getPICKUP_LOCATION();
String b=loc.getDROP_LOCATION();
psmt= con.prepareStatement(Sql);
psmt.setInt(1, myid);
if(a!=null)
{
psmt.setString(2,a);
System.out.println(a);
}
if(b!=null)
{
psmt.setString(3,b);
System.out.println(b);
}
psmt.execute();
psmt.close();
con.close();
System.out.println("Succesfully inserted");
}
public void SHOWLOCATIONDETAILS() throws Exception
{
con=ConnectionUtil.getOracleConnection();
String sql="SELECT * FROM EYEOPEN.LOCATIONDETAILS";
psmt=con.prepareStatement(sql);
ResultSet rs=psmt.executeQuery();
while(rs.next())
{
int locationid =rs.getInt(1);
String pickuplocation=rs.getString(2);
String droplocation=rs.getString(3);
System.out.println(locationid+" "+pickuplocation+" "+droplocation);
}
System.out.println("All details are showed....");
}
public void UPDATELOCATIONDETAILS(LocationDetails loc) throws Exception
{
con=ConnectionUtil.getOracleConnection();
String sql="UPDATE EYEOPEN.LOCATIONDETAILS SET PICKUP_LOCATION=?,DROP_LOCATION=? WHERE LOCATIONID=?";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the userid to update values");
int uid=Integer.parseInt(br.readLine());
psmt=con.prepareStatement(sql);
psmt.setString(1, loc.getPICKUP_LOCATION().toString());
psmt.setString(2, loc.getDROP_LOCATION().toString());
psmt.setInt(3, uid);
psmt.executeUpdate();
System.out.println("updated successfully");
}
public void DELETELOCATIONDETAILS() throws Exception
{
con=ConnectionUtil.getOracleConnection();
String sql="DELETE FROM EYEOPEN.LOCATIONDETAILS WHERE LOCATIONID=?";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the userid to delete values");
int uid=Integer.parseInt(br.readLine());
psmt=con.prepareStatement(sql);
psmt.setInt(1, uid);
psmt.execute();
System.out.println("deleted successfully");
}
}
| 3,018 | 0.719682 | 0.71438 | 119 | 24.361345 | 23.220076 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.789916 | false | false |
0
|
d2b3b34ceb3a4a2699b5d64d60b8ef53774ae48f
| 11,278,584,147,154 |
0e045dfe12561fdd856f0472750316a1e641ac92
|
/src/norn/MailingList/Definition.java
|
e5620f4cf200c9e53386e4a98ec8ba116c386667
|
[] |
no_license
|
quinnmagendanz/EmailParserServer
|
https://github.com/quinnmagendanz/EmailParserServer
|
f71d1315e739f1d834b0c51cf999f6c920e94ffc
|
ae4c0378086db841d759c5d81cb7341d0c025761
|
refs/heads/master
| 2021-01-15T12:01:57.002000 | 2017-08-12T03:24:59 | 2017-08-12T03:24:59 | 99,640,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package norn.MailingList;
import java.util.Objects;
import lib6005.parser.UnableToParseException;
import norn.Environment;
/**
* ADT for the command that assigns the name of a MailingList to a MailingList
*/
public class Definition implements MailingList {
// AF: AF(name, list) = the parsed definition of the assignment of list to name
// RI: true
// Safety from rep exposure: name and list are private, final, immutable
private final String name;
private final MailingList list;
/**
* Returns a MailingList command representing the definition of name to be list
* @param name the name of the list
* @param list a valid MailingList
*/
public Definition(String name, MailingList list) {
this.name = name;
this.list = list;
}
//
// INSTANCE METHODS
//
/**
* Returns the name of the definition
* @return the list's name
*/
public String getName() {
return name;
}
/**
* Returns the list of this assignment
* @return a valid mailing list with recipients
*/
public MailingList getList() {
return list;
}
/**
* Both assigns the definition in environment and evaluates the MailingList
* @param environment a mapping of EmailList names to EmailLists
* @return an EmailList representation of this ListExpression
*/
@Override
public EmailList evaluate(Environment environment) throws UnableToParseException {
environment.assign(name, list.simplify());
return list.evaluate(environment);
}
@Override
public MailingList evaluateName(String listname, Environment environment) {
// probably shouldn't ever be called on a definition...
return new Definition(this.name, this.list.evaluateName(listname, environment));
}
@Override
public MailingList simplify() {
return list.simplify();
}
@Override
public boolean dependsOn(String listname) {
return list.dependsOn(listname);
}
//
// OBJECT OVERRIDES
//
@Override
public String toString() {
return "(" + this.name + "=" + this.list.toString() + ")";
}
@Override
public boolean equals(Object thatObject) {
if (!(thatObject instanceof Definition)) { return false; }
Definition that = (Definition) thatObject;
return that.getName().equals(this.getName()) && that.getList().equals(this.getList());
}
@Override
public int hashCode() {
return Objects.hash(this.name, this.list, "DEFINITION");
//produces a unique hash code for a defintion name = list
}
}
|
UTF-8
|
Java
| 2,724 |
java
|
Definition.java
|
Java
|
[] | null |
[] |
package norn.MailingList;
import java.util.Objects;
import lib6005.parser.UnableToParseException;
import norn.Environment;
/**
* ADT for the command that assigns the name of a MailingList to a MailingList
*/
public class Definition implements MailingList {
// AF: AF(name, list) = the parsed definition of the assignment of list to name
// RI: true
// Safety from rep exposure: name and list are private, final, immutable
private final String name;
private final MailingList list;
/**
* Returns a MailingList command representing the definition of name to be list
* @param name the name of the list
* @param list a valid MailingList
*/
public Definition(String name, MailingList list) {
this.name = name;
this.list = list;
}
//
// INSTANCE METHODS
//
/**
* Returns the name of the definition
* @return the list's name
*/
public String getName() {
return name;
}
/**
* Returns the list of this assignment
* @return a valid mailing list with recipients
*/
public MailingList getList() {
return list;
}
/**
* Both assigns the definition in environment and evaluates the MailingList
* @param environment a mapping of EmailList names to EmailLists
* @return an EmailList representation of this ListExpression
*/
@Override
public EmailList evaluate(Environment environment) throws UnableToParseException {
environment.assign(name, list.simplify());
return list.evaluate(environment);
}
@Override
public MailingList evaluateName(String listname, Environment environment) {
// probably shouldn't ever be called on a definition...
return new Definition(this.name, this.list.evaluateName(listname, environment));
}
@Override
public MailingList simplify() {
return list.simplify();
}
@Override
public boolean dependsOn(String listname) {
return list.dependsOn(listname);
}
//
// OBJECT OVERRIDES
//
@Override
public String toString() {
return "(" + this.name + "=" + this.list.toString() + ")";
}
@Override
public boolean equals(Object thatObject) {
if (!(thatObject instanceof Definition)) { return false; }
Definition that = (Definition) thatObject;
return that.getName().equals(this.getName()) && that.getList().equals(this.getList());
}
@Override
public int hashCode() {
return Objects.hash(this.name, this.list, "DEFINITION");
//produces a unique hash code for a defintion name = list
}
}
| 2,724 | 0.634728 | 0.63326 | 100 | 26.24 | 26.190884 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false |
0
|
92f42fbe2fb183e8e8d3f5f8bffb8e8b87be6c15
| 13,305,808,713,948 |
0540dacfc8a8951cfc3b5abd25cbb2a239f3b5a0
|
/ProjetoFinal/dashcards/src/main/java/br/techinsiders/dashcards/repo/AgenteRepo.java
|
9826aee0bcae8a23e29ba39c0b22ae52bd639dbf
|
[] |
no_license
|
FabioCarvalho10/Repositorio18b
|
https://github.com/FabioCarvalho10/Repositorio18b
|
05514abc3cee164129b9ececfa2f6e08ec9a512a
|
c42f758cdbf79af16baf76790c96c7fbe088aae7
|
refs/heads/master
| 2023-04-28T08:16:01.641000 | 2021-05-21T12:34:18 | 2021-05-21T12:34:18 | 365,323,709 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.techinsiders.dashcards.repo;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import br.techinsiders.dashcards.model.Agente;
public interface AgenteRepo extends CrudRepository<Agente, Integer> {
public List<Agente> findAll(Sort by);
}
|
UTF-8
|
Java
| 330 |
java
|
AgenteRepo.java
|
Java
|
[] | null |
[] |
package br.techinsiders.dashcards.repo;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import br.techinsiders.dashcards.model.Agente;
public interface AgenteRepo extends CrudRepository<Agente, Integer> {
public List<Agente> findAll(Sort by);
}
| 330 | 0.818182 | 0.818182 | 10 | 32 | 23.714973 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false |
0
|
d447818eb68d1b6f30528743fb45398109afc70e
| 25,426,206,434,250 |
787d1b273258eeb55e9aa9da2700a9be3806cba5
|
/Transaction.java
|
297cc07a69cf2b6a183a0e08c68752a4c8fe52e9
|
[] |
no_license
|
zay31/Zaynab
|
https://github.com/zay31/Zaynab
|
c0039bd37371b6c56f095cecbffd6bef5e886471
|
cd994d9e78eb16839803f39195a0db93d08adfe8
|
refs/heads/master
| 2022-07-16T01:24:47.207000 | 2020-05-11T16:59:12 | 2020-05-11T16:59:12 | 247,484,151 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.CardLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;
import java.awt.Panel;
public class Transaction extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Transaction frame = new Transaction();
frame.setUndecorated(true);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTable table;
private JTable table_1;
private JTextField textField;
private static JTextField textField_1;
private JTextField textField_2;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_3;
/**
* Create the frame.
*/
public Transaction() {
connection = Database.dbConnector();
setUndecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1101, 600);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 255, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(20, 648, 1350, 64);
panel_1.setBackground(SystemColor.scrollbar);
contentPane.add(panel_1);
panel_1.setLayout(null);
JButton btnNewButton = new JButton("Cancel");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 30));
btnNewButton.setBackground(new Color(255, 0, 0));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton.setBounds(33, 11, 603, 39);
panel_1.add(btnNewButton);
JButton btnDone = new JButton("Done");
btnDone.setFont(new Font("Tahoma", Font.PLAIN, 30));
btnDone.setBackground(new Color(0, 128, 0));
btnDone.setBounds(688, 11, 645, 39);
panel_1.add(btnDone);
table = new JTable();
table.setBackground(new Color(255, 255, 204));
table.setShowVerticalLines(false);
table.setShowHorizontalLines(false);
table.setShowGrid(false);
table.setFillsViewportHeight(true);
table.setColumnSelectionAllowed(true);
table.setCellSelectionEnabled(true);
table.setBounds(227, 70, 856, 191);
contentPane.add(table);
table_1 = new JTable();
table_1.setBackground(new Color(255, 255, 204));
table_1.setBounds(227, 44, 856, 22);
contentPane.add(table_1);
JLabel lblNewLabel_2 = new JLabel("");
lblNewLabel_2.setBounds(0, 0, 236, 191);
contentPane.add(lblNewLabel_2);
lblNewLabel_2.setBackground(new Color(255, 255, 204));
lblNewLabel_2.setIcon(new ImageIcon(Transaction.class.getResource("/images/download.jpg")));
JLabel lblTransaction = new JLabel("Transaction");
lblTransaction.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblTransaction.setBounds(553, 13, 98, 32);
contentPane.add(lblTransaction);
//////////////////////////
DefaultTableModel model =new DefaultTableModel();
model.addColumn("Name");
model.addColumn("Price");
model.addColumn("Total");
try {
String query1="SELECT ID,name,price FROM tab";
PreparedStatement pst=connection.prepareStatement(query1);
ResultSet rs= pst.executeQuery();
table_1.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e1) {
e1.printStackTrace();
}
try {
String query="select Pid,Name,Price from transactionperson";
PreparedStatement pst=connection.prepareStatement(query);
ResultSet rs= pst.executeQuery();
while(rs.next()) {
model.addRow(new Object[] {
rs.getInt("Pid"),
rs.getString("Name"),
rs.getDouble("Price"),
});
}
// rs.close();
// pst.close();
table.setModel(model);
table.setAutoResizeMode(0);
table.getColumnModel().getColumn(0).setPreferredWidth(60);
table.getColumnModel().getColumn(1).setPreferredWidth(60);
table.getColumnModel().getColumn(2).setPreferredWidth(60);
//connection.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String query1="SELECT ID,name,price FROM tab";
PreparedStatement pst1=connection.prepareStatement(query1);
ResultSet rs1= pst1.executeQuery();
table_1.setModel(DbUtils.resultSetToTableModel(rs1));
}catch (Exception e1) {
e1.printStackTrace();
}
JLabel lblNewLabel_3 = new JLabel("Delete Menu");
lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblNewLabel_3.setBounds(881, 300, 103, 16);
contentPane.add(lblNewLabel_3);
JLabel lblId_1 = new JLabel("ID");
lblId_1.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblId_1.setBounds(798, 378, 33, 16);
contentPane.add(lblId_1);
textField_6 = new JTextField();
textField_6.setBounds(859, 375, 116, 22);
contentPane.add(textField_6);
textField_6.setColumns(10);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id = textField_6.getText();
try {
String query3="DELETE FROM product WHERE ID= '"+id+"'";
PreparedStatement pst=connection.prepareStatement(query3);
pst.execute();
JOptionPane.showMessageDialog(null, "Successful update Menu");
}catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnDelete.setBounds(887, 479, 97, 25);
contentPane.add(btnDelete);
JButton btnAdd = new JButton("Add Menu");
btnAdd.setBounds(85, 503, 151, 25);
contentPane.add(btnAdd);
JLabel lblItems = new JLabel("Items Name");
lblItems.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblItems.setBounds(11, 328, 88, 16);
contentPane.add(lblItems);
textField = new JTextField();
textField.setBounds(111, 326, 217, 22);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(111, 375, 217, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblPrice = new JLabel("Price");
lblPrice.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPrice.setBounds(20, 378, 56, 16);
contentPane.add(lblPrice);
textField_2 = new JTextField();
textField_2.setBounds(111, 421, 218, 22);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblCategory = new JLabel("Category");
lblCategory.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblCategory.setBounds(20, 424, 79, 16);
contentPane.add(lblCategory);
JLabel lblAddANew = new JLabel("Add a new Menu");
lblAddANew.setBounds(85, 300, 143, 16);
contentPane.add(lblAddANew);
lblAddANew.setFont(new Font("Tahoma", Font.PLAIN, 16));
JButton btnUpdate = new JButton("Update Menu");
btnUpdate.setBounds(500, 503, 165, 25);
contentPane.add(btnUpdate);
textField_4 = new JTextField();
textField_4.setBounds(469, 326, 209, 22);
contentPane.add(textField_4);
textField_4.setColumns(10);
JLabel lblId = new JLabel("ID");
lblId.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblId.setBounds(417, 329, 26, 16);
contentPane.add(lblId);
Choice choice = new Choice();
choice.setBounds(469, 375, 209, 22);
contentPane.add(choice);
JLabel lblField = new JLabel("Field");
lblField.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblField.setBounds(417, 381, 56, 16);
contentPane.add(lblField);
JLabel lblNewLabel = new JLabel("Update Menu");
lblNewLabel.setBounds(443, 300, 110, 16);
contentPane.add(lblNewLabel);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
JLabel lblValue = new JLabel("VALUE");
lblValue.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblValue.setBounds(417, 427, 56, 16);
contentPane.add(lblValue);
textField_5 = new JTextField();
textField_5.setBounds(469, 424, 209, 22);
contentPane.add(textField_5);
textField_5.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(111, 468, 217, 22);
contentPane.add(textField_3);
textField_3.setColumns(10);
JLabel lblType = new JLabel("Type");
lblType.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblType.setBounds(20, 471, 56, 16);
contentPane.add(lblType);
choice.add("Items");
choice.add("Price");
choice.add("Type");
choice.add("Category");
choice.add("Quantity");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String id = textField_4.getText();
String field = choice.getItem(choice.getSelectedIndex());
String value = textField_5.getText();
try {
String query2="UPDATE product SET "+field+" = '"+value+"' WHERE ID = "+id+"";
PreparedStatement pst=connection.prepareStatement(query2);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Successful update Menu");
}catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String item = textField.getText();
String price = textField_1.getText();
String category = textField_2.getText();
String type = textField_3.getText();
try {
String query1="INSERT INTO product (Items,Price,Category,Type,Quantity) VALUES ('"+item+"' , '"+price+"','"+category+"','"+type+"',300)";
PreparedStatement pst=connection.prepareStatement(query1);
int insert= pst.executeUpdate(query1);
JOptionPane.showMessageDialog(null, "Successful insert Menu");
}catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
}
|
UTF-8
|
Java
| 10,758 |
java
|
Transaction.java
|
Java
|
[] | null |
[] |
import java.awt.CardLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;
import java.awt.Panel;
public class Transaction extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Transaction frame = new Transaction();
frame.setUndecorated(true);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTable table;
private JTable table_1;
private JTextField textField;
private static JTextField textField_1;
private JTextField textField_2;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_3;
/**
* Create the frame.
*/
public Transaction() {
connection = Database.dbConnector();
setUndecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1101, 600);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 255, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(20, 648, 1350, 64);
panel_1.setBackground(SystemColor.scrollbar);
contentPane.add(panel_1);
panel_1.setLayout(null);
JButton btnNewButton = new JButton("Cancel");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 30));
btnNewButton.setBackground(new Color(255, 0, 0));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton.setBounds(33, 11, 603, 39);
panel_1.add(btnNewButton);
JButton btnDone = new JButton("Done");
btnDone.setFont(new Font("Tahoma", Font.PLAIN, 30));
btnDone.setBackground(new Color(0, 128, 0));
btnDone.setBounds(688, 11, 645, 39);
panel_1.add(btnDone);
table = new JTable();
table.setBackground(new Color(255, 255, 204));
table.setShowVerticalLines(false);
table.setShowHorizontalLines(false);
table.setShowGrid(false);
table.setFillsViewportHeight(true);
table.setColumnSelectionAllowed(true);
table.setCellSelectionEnabled(true);
table.setBounds(227, 70, 856, 191);
contentPane.add(table);
table_1 = new JTable();
table_1.setBackground(new Color(255, 255, 204));
table_1.setBounds(227, 44, 856, 22);
contentPane.add(table_1);
JLabel lblNewLabel_2 = new JLabel("");
lblNewLabel_2.setBounds(0, 0, 236, 191);
contentPane.add(lblNewLabel_2);
lblNewLabel_2.setBackground(new Color(255, 255, 204));
lblNewLabel_2.setIcon(new ImageIcon(Transaction.class.getResource("/images/download.jpg")));
JLabel lblTransaction = new JLabel("Transaction");
lblTransaction.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblTransaction.setBounds(553, 13, 98, 32);
contentPane.add(lblTransaction);
//////////////////////////
DefaultTableModel model =new DefaultTableModel();
model.addColumn("Name");
model.addColumn("Price");
model.addColumn("Total");
try {
String query1="SELECT ID,name,price FROM tab";
PreparedStatement pst=connection.prepareStatement(query1);
ResultSet rs= pst.executeQuery();
table_1.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e1) {
e1.printStackTrace();
}
try {
String query="select Pid,Name,Price from transactionperson";
PreparedStatement pst=connection.prepareStatement(query);
ResultSet rs= pst.executeQuery();
while(rs.next()) {
model.addRow(new Object[] {
rs.getInt("Pid"),
rs.getString("Name"),
rs.getDouble("Price"),
});
}
// rs.close();
// pst.close();
table.setModel(model);
table.setAutoResizeMode(0);
table.getColumnModel().getColumn(0).setPreferredWidth(60);
table.getColumnModel().getColumn(1).setPreferredWidth(60);
table.getColumnModel().getColumn(2).setPreferredWidth(60);
//connection.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String query1="SELECT ID,name,price FROM tab";
PreparedStatement pst1=connection.prepareStatement(query1);
ResultSet rs1= pst1.executeQuery();
table_1.setModel(DbUtils.resultSetToTableModel(rs1));
}catch (Exception e1) {
e1.printStackTrace();
}
JLabel lblNewLabel_3 = new JLabel("Delete Menu");
lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblNewLabel_3.setBounds(881, 300, 103, 16);
contentPane.add(lblNewLabel_3);
JLabel lblId_1 = new JLabel("ID");
lblId_1.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblId_1.setBounds(798, 378, 33, 16);
contentPane.add(lblId_1);
textField_6 = new JTextField();
textField_6.setBounds(859, 375, 116, 22);
contentPane.add(textField_6);
textField_6.setColumns(10);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id = textField_6.getText();
try {
String query3="DELETE FROM product WHERE ID= '"+id+"'";
PreparedStatement pst=connection.prepareStatement(query3);
pst.execute();
JOptionPane.showMessageDialog(null, "Successful update Menu");
}catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnDelete.setBounds(887, 479, 97, 25);
contentPane.add(btnDelete);
JButton btnAdd = new JButton("Add Menu");
btnAdd.setBounds(85, 503, 151, 25);
contentPane.add(btnAdd);
JLabel lblItems = new JLabel("Items Name");
lblItems.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblItems.setBounds(11, 328, 88, 16);
contentPane.add(lblItems);
textField = new JTextField();
textField.setBounds(111, 326, 217, 22);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(111, 375, 217, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblPrice = new JLabel("Price");
lblPrice.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPrice.setBounds(20, 378, 56, 16);
contentPane.add(lblPrice);
textField_2 = new JTextField();
textField_2.setBounds(111, 421, 218, 22);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblCategory = new JLabel("Category");
lblCategory.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblCategory.setBounds(20, 424, 79, 16);
contentPane.add(lblCategory);
JLabel lblAddANew = new JLabel("Add a new Menu");
lblAddANew.setBounds(85, 300, 143, 16);
contentPane.add(lblAddANew);
lblAddANew.setFont(new Font("Tahoma", Font.PLAIN, 16));
JButton btnUpdate = new JButton("Update Menu");
btnUpdate.setBounds(500, 503, 165, 25);
contentPane.add(btnUpdate);
textField_4 = new JTextField();
textField_4.setBounds(469, 326, 209, 22);
contentPane.add(textField_4);
textField_4.setColumns(10);
JLabel lblId = new JLabel("ID");
lblId.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblId.setBounds(417, 329, 26, 16);
contentPane.add(lblId);
Choice choice = new Choice();
choice.setBounds(469, 375, 209, 22);
contentPane.add(choice);
JLabel lblField = new JLabel("Field");
lblField.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblField.setBounds(417, 381, 56, 16);
contentPane.add(lblField);
JLabel lblNewLabel = new JLabel("Update Menu");
lblNewLabel.setBounds(443, 300, 110, 16);
contentPane.add(lblNewLabel);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
JLabel lblValue = new JLabel("VALUE");
lblValue.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblValue.setBounds(417, 427, 56, 16);
contentPane.add(lblValue);
textField_5 = new JTextField();
textField_5.setBounds(469, 424, 209, 22);
contentPane.add(textField_5);
textField_5.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(111, 468, 217, 22);
contentPane.add(textField_3);
textField_3.setColumns(10);
JLabel lblType = new JLabel("Type");
lblType.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblType.setBounds(20, 471, 56, 16);
contentPane.add(lblType);
choice.add("Items");
choice.add("Price");
choice.add("Type");
choice.add("Category");
choice.add("Quantity");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String id = textField_4.getText();
String field = choice.getItem(choice.getSelectedIndex());
String value = textField_5.getText();
try {
String query2="UPDATE product SET "+field+" = '"+value+"' WHERE ID = "+id+"";
PreparedStatement pst=connection.prepareStatement(query2);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Successful update Menu");
}catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String item = textField.getText();
String price = textField_1.getText();
String category = textField_2.getText();
String type = textField_3.getText();
try {
String query1="INSERT INTO product (Items,Price,Category,Type,Quantity) VALUES ('"+item+"' , '"+price+"','"+category+"','"+type+"',300)";
PreparedStatement pst=connection.prepareStatement(query1);
int insert= pst.executeUpdate(query1);
JOptionPane.showMessageDialog(null, "Successful insert Menu");
}catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
}
| 10,758 | 0.673266 | 0.626418 | 352 | 28.5625 | 19.639986 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.275568 | false | false |
0
|
3b749bbec88092333573de29ac2a36ea4e715f63
| 12,910,671,740,179 |
21222f7ea7d14fe4812d839b0196d64ad9c51e47
|
/shailaja/JdbcEx/src/InsertTable.java
|
5292ac29284982a8010b58467f33c8e47d5825fb
|
[] |
no_license
|
shailajasrjava/tekgroup
|
https://github.com/shailajasrjava/tekgroup
|
a30baf298b58a4c6a8112d09d37c52fea5f0a341
|
5d84c8f3b100f8588df301e0ad67c8d26d9bd0c6
|
refs/heads/master
| 2021-01-19T03:54:23.331000 | 2017-04-05T01:04:33 | 2017-04-05T01:04:33 | 87,342,072 | 0 | 0 | null | true | 2017-04-05T18:16:58 | 2017-04-05T18:16:58 | 2016-11-07T02:11:55 | 2017-04-05T01:04:52 | 42,252 | 0 | 0 | 0 | null | null | null |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class InsertTable {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection obj=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "shailaja");
String str="create table Table3(id number(10),name varchar(20),address varchar(20))";
Statement stmt=obj.createStatement();
ResultSet rs = stmt.executeQuery("select * from Table3");
System.out.println("-IF "+rs.next());
while(rs.next()){
System.out.println("--ID " + rs.getString("id"));
}
System.out.println("--"+rs.getFetchSize());
//stmt.execute(str);
/* String str1="insert into Table3 values(1,'shailu','Hyd')";
String str2="insert into Table3 values(2,'shailaja','India')";
String str3="insert into Table3 values(3,'abc','Hyderabad')";
String str4="insert into Table3 values(4,'bcd','USA')";
stmt.execute(str1);
stmt.execute(str2);
stmt.execute(str3);
stmt.execute(str4);
obj.close();*/
}
}
|
UTF-8
|
Java
| 1,097 |
java
|
InsertTable.java
|
Java
|
[] | null |
[] |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class InsertTable {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection obj=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "shailaja");
String str="create table Table3(id number(10),name varchar(20),address varchar(20))";
Statement stmt=obj.createStatement();
ResultSet rs = stmt.executeQuery("select * from Table3");
System.out.println("-IF "+rs.next());
while(rs.next()){
System.out.println("--ID " + rs.getString("id"));
}
System.out.println("--"+rs.getFetchSize());
//stmt.execute(str);
/* String str1="insert into Table3 values(1,'shailu','Hyd')";
String str2="insert into Table3 values(2,'shailaja','India')";
String str3="insert into Table3 values(3,'abc','Hyderabad')";
String str4="insert into Table3 values(4,'bcd','USA')";
stmt.execute(str1);
stmt.execute(str2);
stmt.execute(str3);
stmt.execute(str4);
obj.close();*/
}
}
| 1,097 | 0.702826 | 0.677302 | 31 | 34.387096 | 26.136955 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.483871 | false | false |
0
|
1d40715ee3deec2bae472ca9e7873146fb6c65f7
| 20,667,382,662,268 |
ffd9290319ea35763d6da538e43d808462852410
|
/src/main/java/cn/edu/hit/spat/system/service/impl/GoodsServiceImpl.java
|
e420bc56582e13f49168d20496fa06794cd628ca
|
[
"Apache-2.0"
] |
permissive
|
HIT-SoftwareProcessAndTools/GWARBMS
|
https://github.com/HIT-SoftwareProcessAndTools/GWARBMS
|
423768fde7e6d2bf5f0dad3d65e1d4f585f4571d
|
317c781cae1a768b0f80c435bf0d1651202e8435
|
refs/heads/main
| 2023-02-13T00:50:20.880000 | 2021-01-14T05:37:16 | 2021-01-14T05:37:16 | 315,177,166 | 3 | 2 |
Apache-2.0
| false | 2020-12-03T06:27:30 | 2020-11-23T02:13:02 | 2020-12-02T02:11:51 | 2020-12-03T06:27:28 | 6,259 | 0 | 0 | 0 |
Java
| false | false |
package cn.edu.hit.spat.system.service.impl;
import cn.edu.hit.spat.common.entity.GwarbmsConstant;
import cn.edu.hit.spat.common.entity.QueryRequest;
import cn.edu.hit.spat.common.utils.SortUtil;
import cn.edu.hit.spat.system.entity.Goods;
import cn.edu.hit.spat.system.entity.Record;
import cn.edu.hit.spat.system.entity.Role;
import cn.edu.hit.spat.system.mapper.GoodsMapper;
import cn.edu.hit.spat.system.service.IGoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
/**
* @author XuJian
*/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {
@Override
public Goods findByGoodsId(Long goodsId) {
return this.baseMapper.findByGoodsId(goodsId);
}
@Override
public List<Goods> findGoods(Goods goods) {
QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(goods.getName())) {
queryWrapper.lambda().like(Goods::getName, goods.getName());
}
return this.baseMapper.selectList(queryWrapper);
}
@Override
public IPage<Goods> findGoodsDetailList(Goods goods, QueryRequest request) {
Page<Goods> page = new Page<>(request.getPageNum(), request.getPageSize());
page.setSearchCount(false);
page.setTotal(baseMapper.countGoodsDetail(goods));
SortUtil.handlePageSort(request, page, "goodsId", GwarbmsConstant.ORDER_ASC, false);
return this.baseMapper.findGoodsDetailPage(page, goods);
}
@Override
public Goods findGoodsDetailList(Long goodsId) {
Goods param = new Goods();
param.setGoodsId(goodsId);
List<Goods> goods = this.baseMapper.findGoodsDetail(param);
return CollectionUtils.isNotEmpty(goods) ? goods.get(0) : null;
}
@Override
public List<Goods> findByName(String name) {
List<Goods> goodsList = this.baseMapper.findByName(name);
return CollectionUtils.isNotEmpty(goodsList) ? goodsList : null;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void createGoods(Goods goods) {
save(goods);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteGoods(String[] goodsIds) {
List<String> list = Arrays.asList(goodsIds);
this.removeByIds(list);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateGoods(Goods goods) {
updateById(goods);
}
}
|
UTF-8
|
Java
| 3,157 |
java
|
GoodsServiceImpl.java
|
Java
|
[
{
"context": "til.Arrays;\nimport java.util.List;\n\n/**\n * @author XuJian\n */\n@Service\n@RequiredArgsConstructor\n@Transactio",
"end": 1080,
"score": 0.974144697189331,
"start": 1074,
"tag": "NAME",
"value": "XuJian"
}
] | null |
[] |
package cn.edu.hit.spat.system.service.impl;
import cn.edu.hit.spat.common.entity.GwarbmsConstant;
import cn.edu.hit.spat.common.entity.QueryRequest;
import cn.edu.hit.spat.common.utils.SortUtil;
import cn.edu.hit.spat.system.entity.Goods;
import cn.edu.hit.spat.system.entity.Record;
import cn.edu.hit.spat.system.entity.Role;
import cn.edu.hit.spat.system.mapper.GoodsMapper;
import cn.edu.hit.spat.system.service.IGoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
/**
* @author XuJian
*/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {
@Override
public Goods findByGoodsId(Long goodsId) {
return this.baseMapper.findByGoodsId(goodsId);
}
@Override
public List<Goods> findGoods(Goods goods) {
QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(goods.getName())) {
queryWrapper.lambda().like(Goods::getName, goods.getName());
}
return this.baseMapper.selectList(queryWrapper);
}
@Override
public IPage<Goods> findGoodsDetailList(Goods goods, QueryRequest request) {
Page<Goods> page = new Page<>(request.getPageNum(), request.getPageSize());
page.setSearchCount(false);
page.setTotal(baseMapper.countGoodsDetail(goods));
SortUtil.handlePageSort(request, page, "goodsId", GwarbmsConstant.ORDER_ASC, false);
return this.baseMapper.findGoodsDetailPage(page, goods);
}
@Override
public Goods findGoodsDetailList(Long goodsId) {
Goods param = new Goods();
param.setGoodsId(goodsId);
List<Goods> goods = this.baseMapper.findGoodsDetail(param);
return CollectionUtils.isNotEmpty(goods) ? goods.get(0) : null;
}
@Override
public List<Goods> findByName(String name) {
List<Goods> goodsList = this.baseMapper.findByName(name);
return CollectionUtils.isNotEmpty(goodsList) ? goodsList : null;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void createGoods(Goods goods) {
save(goods);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteGoods(String[] goodsIds) {
List<String> list = Arrays.asList(goodsIds);
this.removeByIds(list);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateGoods(Goods goods) {
updateById(goods);
}
}
| 3,157 | 0.732658 | 0.732024 | 90 | 34.077778 | 26.459709 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
0
|
f7b5b6c8da5bc1e1a2ce3132e31651c90dbac99f
| 17,514,876,679,896 |
6a5078d6066b2b669b7f3ab8c44e0ee160b04f18
|
/class_src/homework/hw12/DamageCalculation.java
|
627caefd76feb11cdfa449052323871982a001c1
|
[] |
no_license
|
FoeverNa/JBS-Java
|
https://github.com/FoeverNa/JBS-Java
|
850b9e96a1858d0f364ba24de5ff0b82be9f2417
|
c5fcb4e03a3e5b585d86620f58fe29f91d6fbf32
|
refs/heads/master
| 2023-01-08T13:02:32.967000 | 2020-11-13T04:39:17 | 2020-11-13T04:39:17 | 309,682,374 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package homework.hw12;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 열거형 타입과 함수형 프로그래밍을 이용하여 플레이어의 공격력을 계산하는 알고리즘을 구현하시오.
*
* 플레이어 공격력을 계산하는 과정은 아래와 같다.
* 1. 플레이어의 무기에 따라 공격력이 변화한다. 무기는 최근에 장착한 무기의 공격력 만으로 계산된다.
* 1-1. BARE_HANDS - 공격력 5
* 1-2. DAGGER - 공격력 40
* 1-3. LONG_SWORD - 공격력 100
* 1-4. DRAGON_SLAYER - 공격력 250
* 2. 플레이어의 공격력에 영향을 주는 아이템에 따라 공격력 증가 방식이 다르며, 아이템은 중복 적용된다.
* 2-1. BLACK_POTION - 공격력 10% 증가
* 2-2. WHITE_POTION - 모든 공격력 계산이 끝난 후에 공격력 + 200
* 2-3. MUSHROOM - 무기 공격력 + 20
*
*/
enum Weapon {
// 무기 구현
BARE_HANDS(5), DAGGER(40), LONG_SWORD(100), DRAGON_SLAYER(250);
int weaponDamage ;
Weapon(int weaponDamage){
this.weaponDamage = weaponDamage;
}
public int getWeaponDamage() {
return weaponDamage;
}
}
enum Item {
// 소비 아이템 구현
BLACK_POTION, WHITE_POTION, MUSHROOM
}
class Player {
Weapon currentWeapon;
List<Item> items;
int weaponDamage;
public Player() {
currentWeapon = Weapon.BARE_HANDS;
items = new ArrayList<>();
weaponDamage = currentWeapon.getWeaponDamage();
}
void changeWeapon (Weapon weapon){
currentWeapon = weapon;
weaponDamage = currentWeapon.getWeaponDamage();
}
double calcDamage(){
Stream<Item> stream = items.stream();
Map<String, Long> map = stream.collect(Collectors.groupingBy(s -> s.toString(),Collectors.counting()));
long mushroom = map.get("MUSHROOM") != null ? map.get("MUSHROOM") : 0;
long black_potion = map.get("BLACK_POTION") != null ? map.get("BLACK_POTION") : 0;
long white_potion = map.get("WHITE_POTION") != null ? map.get("WHITE_POTION") : 0;
return (weaponDamage +(mushroom*20)) * (1 + (black_potion*0.1)) + (white_potion*200);
}
void useItem(Item item){
items.add(item);
}
// TODO: Player에 필요한 메소드 구현
// 무기 교체, 아이템 사용, 아이템 효과 종료 메소드 구현
}
public class DamageCalculation {
public static void main(String[] args) {
// 무기 및 아이템 장착/사용 시나리오 및 플레이어 공격력 출력
Player player = new Player();
System.out.println(player.calcDamage());
player.changeWeapon(Weapon.DAGGER);
System.out.println(player.calcDamage());
player.useItem(Item.MUSHROOM);
System.out.println(player.calcDamage());
player.useItem(Item.BLACK_POTION);
System.out.println(player.calcDamage());
player.useItem(Item.WHITE_POTION);
System.out.println(player.calcDamage());
player.changeWeapon(Weapon.LONG_SWORD);
System.out.println(player.calcDamage());
}
}
|
UTF-8
|
Java
| 3,213 |
java
|
DamageCalculation.java
|
Java
|
[] | null |
[] |
package homework.hw12;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 열거형 타입과 함수형 프로그래밍을 이용하여 플레이어의 공격력을 계산하는 알고리즘을 구현하시오.
*
* 플레이어 공격력을 계산하는 과정은 아래와 같다.
* 1. 플레이어의 무기에 따라 공격력이 변화한다. 무기는 최근에 장착한 무기의 공격력 만으로 계산된다.
* 1-1. BARE_HANDS - 공격력 5
* 1-2. DAGGER - 공격력 40
* 1-3. LONG_SWORD - 공격력 100
* 1-4. DRAGON_SLAYER - 공격력 250
* 2. 플레이어의 공격력에 영향을 주는 아이템에 따라 공격력 증가 방식이 다르며, 아이템은 중복 적용된다.
* 2-1. BLACK_POTION - 공격력 10% 증가
* 2-2. WHITE_POTION - 모든 공격력 계산이 끝난 후에 공격력 + 200
* 2-3. MUSHROOM - 무기 공격력 + 20
*
*/
enum Weapon {
// 무기 구현
BARE_HANDS(5), DAGGER(40), LONG_SWORD(100), DRAGON_SLAYER(250);
int weaponDamage ;
Weapon(int weaponDamage){
this.weaponDamage = weaponDamage;
}
public int getWeaponDamage() {
return weaponDamage;
}
}
enum Item {
// 소비 아이템 구현
BLACK_POTION, WHITE_POTION, MUSHROOM
}
class Player {
Weapon currentWeapon;
List<Item> items;
int weaponDamage;
public Player() {
currentWeapon = Weapon.BARE_HANDS;
items = new ArrayList<>();
weaponDamage = currentWeapon.getWeaponDamage();
}
void changeWeapon (Weapon weapon){
currentWeapon = weapon;
weaponDamage = currentWeapon.getWeaponDamage();
}
double calcDamage(){
Stream<Item> stream = items.stream();
Map<String, Long> map = stream.collect(Collectors.groupingBy(s -> s.toString(),Collectors.counting()));
long mushroom = map.get("MUSHROOM") != null ? map.get("MUSHROOM") : 0;
long black_potion = map.get("BLACK_POTION") != null ? map.get("BLACK_POTION") : 0;
long white_potion = map.get("WHITE_POTION") != null ? map.get("WHITE_POTION") : 0;
return (weaponDamage +(mushroom*20)) * (1 + (black_potion*0.1)) + (white_potion*200);
}
void useItem(Item item){
items.add(item);
}
// TODO: Player에 필요한 메소드 구현
// 무기 교체, 아이템 사용, 아이템 효과 종료 메소드 구현
}
public class DamageCalculation {
public static void main(String[] args) {
// 무기 및 아이템 장착/사용 시나리오 및 플레이어 공격력 출력
Player player = new Player();
System.out.println(player.calcDamage());
player.changeWeapon(Weapon.DAGGER);
System.out.println(player.calcDamage());
player.useItem(Item.MUSHROOM);
System.out.println(player.calcDamage());
player.useItem(Item.BLACK_POTION);
System.out.println(player.calcDamage());
player.useItem(Item.WHITE_POTION);
System.out.println(player.calcDamage());
player.changeWeapon(Weapon.LONG_SWORD);
System.out.println(player.calcDamage());
}
}
| 3,213 | 0.625046 | 0.605215 | 98 | 26.795918 | 24.275612 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479592 | false | false |
0
|
c3f517750eac5e08da17d930b6cb6fbe4647e9bc
| 19,078,244,770,067 |
1686a3db42ad24c2ae169e1065f982c46140829f
|
/src/main/java/com/example/externalservice/commom/ExternalServiceException.java
|
a95b1c024d7d90cfdd54f8eeb3f1c41de705f8e7
|
[] |
no_license
|
xiaotaosky/external-service
|
https://github.com/xiaotaosky/external-service
|
0edc740159387e07265ed33ac158ddcbaace1c52
|
8614e12e80549a70f6c127b0fa45fa13590055af
|
refs/heads/master
| 2022-06-28T00:50:19.526000 | 2019-06-20T16:54:25 | 2019-06-20T16:54:25 | 192,950,301 | 0 | 0 | null | false | 2022-06-17T02:14:26 | 2019-06-20T16:05:23 | 2019-06-20T16:55:29 | 2022-06-17T02:14:26 | 57 | 0 | 0 | 1 |
Java
| false | false |
package com.example.externalservice.commom;
public class ExternalServiceException extends RuntimeException {
public ExternalServiceException() {
super();
}
public ExternalServiceException(String msg) {
super(msg);
}
}
|
UTF-8
|
Java
| 253 |
java
|
ExternalServiceException.java
|
Java
|
[] | null |
[] |
package com.example.externalservice.commom;
public class ExternalServiceException extends RuntimeException {
public ExternalServiceException() {
super();
}
public ExternalServiceException(String msg) {
super(msg);
}
}
| 253 | 0.703557 | 0.703557 | 12 | 20.083334 | 21.784775 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
0
|
ad62168cb290c5e0e0b139edaff15b18bb4763e9
| 7,722,351,239,290 |
80dc3b2e3f1e53de6b5794842e49fdf4094d1892
|
/app/src/main/java/com/example/lzy/review/ChartActivity.java
|
58c57626df8c9d67a62997b755fc751a35b27b2c
|
[] |
no_license
|
liangzyyy/Review0122
|
https://github.com/liangzyyy/Review0122
|
74df10ebbee6350cae11aea4145962ef7ff0ab5b
|
3a34105c69f80375cfbddb1e35474c0b79bfc175
|
refs/heads/master
| 2020-04-17T21:16:31.870000 | 2019-01-22T10:26:20 | 2019-01-22T10:26:20 | 166,942,274 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.lzy.review;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.lzy.review.Fragment.HorizontalBarChartFragment;
import com.example.lzy.review.Fragment.PieFragment;
import java.util.ArrayList;
import java.util.List;
public class ChartActivity extends AppCompatActivity {
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chart);
initView();
}
private void initView() {
viewPager = findViewById(R.id.viewPage);
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int i) {
Fragment f=null;
switch (i){
case 0:
f = PieFragment.newInstance(i+"");
break;
case 1:
f = HorizontalBarChartFragment.newInstance();
break;
}
return f;
}
@Override
public int getCount() {
return 2;
}
});
}
}
|
UTF-8
|
Java
| 1,395 |
java
|
ChartActivity.java
|
Java
|
[] | null |
[] |
package com.example.lzy.review;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.lzy.review.Fragment.HorizontalBarChartFragment;
import com.example.lzy.review.Fragment.PieFragment;
import java.util.ArrayList;
import java.util.List;
public class ChartActivity extends AppCompatActivity {
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chart);
initView();
}
private void initView() {
viewPager = findViewById(R.id.viewPage);
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int i) {
Fragment f=null;
switch (i){
case 0:
f = PieFragment.newInstance(i+"");
break;
case 1:
f = HorizontalBarChartFragment.newInstance();
break;
}
return f;
}
@Override
public int getCount() {
return 2;
}
});
}
}
| 1,395 | 0.594982 | 0.589964 | 50 | 26.9 | 20.855934 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46 | false | false |
0
|
63f0267d30348d5e299381b8132cf16a25eb5468
| 14,465,449,902,003 |
7ff358f4d802b0ba5b1fbd314b1e4253a53cf2e5
|
/src/main/java/org/elasticsearch/plugin/HttpRequestTypes.java
|
44f2e36bd51e0ef1a296c8d20ebbb46bf38b83d9
|
[] |
no_license
|
master-thesis-ntnu/elasticsearch-plugin
|
https://github.com/master-thesis-ntnu/elasticsearch-plugin
|
3a5681cf0af52ca746648db113259ff47831669e
|
fc7fab688a5b33316b2314735b328084ca67cdc9
|
refs/heads/master
| 2021-01-23T00:15:48.638000 | 2017-05-25T10:42:51 | 2017-05-25T10:42:51 | 85,711,540 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.elasticsearch.plugin;
public class HttpRequestTypes {
public static final String GET = "GET";
public static final String POST = "POST";
}
|
UTF-8
|
Java
| 159 |
java
|
HttpRequestTypes.java
|
Java
|
[] | null |
[] |
package org.elasticsearch.plugin;
public class HttpRequestTypes {
public static final String GET = "GET";
public static final String POST = "POST";
}
| 159 | 0.72956 | 0.72956 | 6 | 25.5 | 18.364368 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
33ab96e30dc430ec92a9c857a041317acf5c33fa
| 9,036,611,234,312 |
2016365307d9e3e7f3d30cc81512da927f6d8e08
|
/Lab2/code/TestMachinery.java
|
f00503e5813c7c6cd8e92576ab6a223e9c96807c
|
[] |
no_license
|
twisty-n/SENG3160Labs
|
https://github.com/twisty-n/SENG3160Labs
|
36314b2d476a36b3686736591517512922c3b64e
|
8f58337c13d947c02fc1dc09f02a6b9525c5fff2
|
refs/heads/master
| 2021-01-17T18:43:56.247000 | 2016-08-10T03:03:11 | 2016-08-10T03:03:11 | 64,810,441 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(EasyMockRunner.class)
public class TestMachinery {
@TestSubject
TestMachine test = new TestMachine();
@Mock
IMachineService service;
@Test
public void testMachine() {
EasyMock.expect(service.getMachineCost(test))
.andReturn(1000.0);
EasyMock.replay(service);
Assert.assertEquals(test.getMachineCost(), 1000.0, 10.0);
}
}
|
UTF-8
|
Java
| 650 |
java
|
TestMachinery.java
|
Java
|
[] | null |
[] |
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(EasyMockRunner.class)
public class TestMachinery {
@TestSubject
TestMachine test = new TestMachine();
@Mock
IMachineService service;
@Test
public void testMachine() {
EasyMock.expect(service.getMachineCost(test))
.andReturn(1000.0);
EasyMock.replay(service);
Assert.assertEquals(test.getMachineCost(), 1000.0, 10.0);
}
}
| 650 | 0.690769 | 0.670769 | 30 | 20.700001 | 16.3384 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
90008162e85f99efb602301a50cdd723d29b7097
| 9,036,611,235,942 |
f44f77e7d2a82881e2e2d4fcf8e518fc0c267090
|
/annotation-demo/src/main/java/com/wordpython/controller/LoginController.java
|
f15d440664fafbfcc4dd404fe190f044b43daae9
|
[] |
no_license
|
lzx0009/springboot-HotelManagement
|
https://github.com/lzx0009/springboot-HotelManagement
|
081d7ec5b7e44d2c8d72650dd0cc5f1b2e648085
|
1e5f750ffb7da0cea01b2bd401f8bd5185f37f0a
|
refs/heads/master
| 2022-03-31T06:24:48.426000 | 2019-11-01T14:37:40 | 2019-11-01T14:37:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wordpython.controller;
import com.wordpython.dao.UserDao;
import com.wordpython.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@Autowired
private UserDao userDao;
@GetMapping(value = "/")
public Object text(){
User user=new User();
user.setUsername("wordpython");
System.out.println(userDao.selectUser(user));
return ";ljsl;las";
}
}
|
UTF-8
|
Java
| 599 |
java
|
LoginController.java
|
Java
|
[
{
"context": " User user=new User();\n user.setUsername(\"wordpython\");\n System.out.println(userDao.selectUser(",
"end": 505,
"score": 0.9995757341384888,
"start": 495,
"tag": "USERNAME",
"value": "wordpython"
}
] | null |
[] |
package com.wordpython.controller;
import com.wordpython.dao.UserDao;
import com.wordpython.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@Autowired
private UserDao userDao;
@GetMapping(value = "/")
public Object text(){
User user=new User();
user.setUsername("wordpython");
System.out.println(userDao.selectUser(user));
return ";ljsl;las";
}
}
| 599 | 0.734558 | 0.734558 | 21 | 27.523809 | 19.580406 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false |
0
|
66e0a542f6e1d685fa45425801340a13cdd0314d
| 22,857,815,998,380 |
ca030864a3a1c24be6b9d1802c2353da4ca0d441
|
/classes2.dex_source_from_JADX/com/facebook/widget/listview/ScrollListenerWithThrottlingSupport.java
|
64117b783d60572dc143cb0ce6d93d02f0d3ff09
|
[] |
no_license
|
pxson001/facebook-app
|
https://github.com/pxson001/facebook-app
|
87aa51e29195eeaae69adeb30219547f83a5b7b1
|
640630f078980f9818049625ebc42569c67c69f7
|
refs/heads/master
| 2020-04-07T20:36:45.758000 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.facebook.widget.listview;
import com.facebook.widget.listview.ScrollingViewProxy.OnScrollListener;
/* compiled from: photo_gallery */
public interface ScrollListenerWithThrottlingSupport extends OnScrollListener {
int mo1974a();
}
|
UTF-8
|
Java
| 249 |
java
|
ScrollListenerWithThrottlingSupport.java
|
Java
|
[] | null |
[] |
package com.facebook.widget.listview;
import com.facebook.widget.listview.ScrollingViewProxy.OnScrollListener;
/* compiled from: photo_gallery */
public interface ScrollListenerWithThrottlingSupport extends OnScrollListener {
int mo1974a();
}
| 249 | 0.819277 | 0.803213 | 8 | 30.125 | 29.611811 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
0
|
3e07eda5effe2f2869ecf1f3ad794357d530f79b
| 9,723,805,968,200 |
d610e459a50a12932dca8da07c9de11c4d5cb20c
|
/src/main/java/org/sagebionetworks/TableUtil.java
|
86fc8336759e420e14e2492ebe8e47164e950a2e
|
[] |
no_license
|
Sage-Bionetworks/NRGRSynapseGlue
|
https://github.com/Sage-Bionetworks/NRGRSynapseGlue
|
46632d56ee2b86db8cf1f20b423ed99abfa03964
|
1c7d32035785cfb564076822080b19f0f5423b0c
|
refs/heads/master
| 2021-07-04T01:15:45.939000 | 2021-06-29T18:48:04 | 2021-06-29T18:48:04 | 31,036,943 | 0 | 0 | null | false | 2021-06-04T02:45:03 | 2015-02-19T21:07:00 | 2021-06-04T00:56:57 | 2021-06-04T02:45:01 | 336 | 0 | 0 | 2 |
Java
| false | false |
package org.sagebionetworks;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.sagebionetworks.client.SynapseClient;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.client.exceptions.SynapseResultNotReadyException;
import org.sagebionetworks.repo.model.MembershipRequest;
import org.sagebionetworks.repo.model.table.ColumnModel;
import org.sagebionetworks.repo.model.table.QueryResultBundle;
import org.sagebionetworks.repo.model.table.Row;
import org.sagebionetworks.repo.model.table.RowSet;
import org.sagebionetworks.repo.model.table.SelectColumn;
public class TableUtil {
private static final int QUERY_PARTS_MASK =
SynapseClient.QUERY_PARTMASK |
SynapseClient.COUNT_PARTMASK |
SynapseClient.COLUMNS_PARTMASK |
SynapseClient.MAXROWS_PARTMASK;
public static final String USER_ID = "UserId";
public static final String APPLICATION_TEAM_ID = "ApplicationTeamId"; // new field
public static final String USER_NAME = "User Name";
public static final String FIRST_NAME = "First Name";
public static final String LAST_NAME = "Last Name";
public static final String TOKEN_SENT_DATE = "Date Email Sent";
public static final String MEMBERSHIP_REQUEST_EXPIRATION_DATE = "Date Membership Request Expires"; // new field
public static final String APPROVED_ON = "Date Approved/Rejected";
public static final String DATE_REVOKED = "Date Revoked";
public static final long TABLE_UPDATE_TIMEOUT = 100000L;
private SynapseClient synapseClient;
private String tableId;
private String configurationTableId;
public TableUtil(SynapseClient synapseClient, String tableId, String configurationTableId) {
this.synapseClient=synapseClient;
this.tableId=tableId;
this.configurationTableId=configurationTableId;
}
public static List<String> getSubnetsFromString(String s) {
if (StringUtils.isEmpty(s)) return Collections.EMPTY_LIST;
return Arrays.asList(s.split("[,;:]"));
}
/*
* return a map whose key is signup team ID and value is the collection of settings for that team
*/
public Map<String,DatasetSettings> getDatasetSettings() throws SynapseException, InterruptedException {
Pair<List<SelectColumn>, RowSet> queryResult = executeQuery(
"SELECT * FROM "+configurationTableId, configurationTableId, Integer.MAX_VALUE);
Map<String,DatasetSettings> result = new HashMap<String,DatasetSettings>();
for (Row row : queryResult.getSecond().getRows()) {
DatasetSettings setting = new DatasetSettings();
assert row.getValues().size()==queryResult.getSecond().getHeaders().size();
for (int i=0; i<queryResult.getSecond().getHeaders().size(); i++) {
SelectColumn sc = queryResult.getSecond().getHeaders().get(i);
String value = row.getValues().get(i);
if (sc.getName().equals("applicationTeamId")) {
setting.setApplicationTeamId(value);
} else if (sc.getName().equals("accessRequirementIds")) {
String[] arIdStrings = value.split(",");
List<Long> arIds = new ArrayList<Long>();
for (String arIdString : arIdStrings) arIds.add(Long.parseLong(arIdString));
setting.setAccessRequirementIds(arIds);
} else if (sc.getName().equals("tokenLabel")) {
setting.setTokenLabel(value);
} else if (sc.getName().equals("dataDescriptor")) {
setting.setDataDescriptor(value);
} else if (sc.getName().equals("tokenEmailSynapseId")) {
setting.setTokenEmailSynapseId(value);
} else if (sc.getName().equals("approvalEmailSynapseId")) {
setting.setApprovalEmailSynapseId(value);
} else if (sc.getName().equals("revocationEmailSynapseId")) {
setting.setRevocationEmailSynapseId(value);
} else if (sc.getName().equals("tokenExpirationDays")) {
setting.setTokenExpirationTimeDays(Integer.parseInt(value));
} else if (sc.getName().equals("originatingIpSubnet")) {
List<String> subnets = getSubnetsFromString(value);
setting.setOriginatingIPsubnets(subnets);
} else if (sc.getName().equals("expiresAfterDays")) {
if (!StringUtils.isEmpty(value))
setting.setExpiresAfterDays(Integer.parseInt(value));
} else if (sc.getName().equals("approverSynapseIds")) {
String[] approverSynapseIds = value.split(",");
setting.setApproverSynapseIds(Arrays.asList(approverSynapseIds));
} else {
throw new RuntimeException("Unexpected column "+sc.getName());
}
}
assert setting.getApplicationTeamId()!=null;
result.put(setting.getApplicationTeamId(), setting);
}
return result;
}
public List<MembershipRequest> getNewMembershipRequests(Collection<MembershipRequest> membershipRequests) throws SynapseException, InterruptedException {
if (membershipRequests.isEmpty()) return Collections.EMPTY_LIST;
StringBuilder sb = new StringBuilder("SELECT ");
sb.append("\""+USER_ID+"\", ");
sb.append("\""+MEMBERSHIP_REQUEST_EXPIRATION_DATE+"\" ");
sb.append(" FROM "+tableId+" WHERE "+USER_ID+" IN (");
boolean firstTime = true;
String teamId = null;
for (MembershipRequest mr : membershipRequests) {
if (teamId==null) {
teamId = mr.getTeamId();
} else {
// all mr's should be for the same teamId
if (!teamId.equals(mr.getTeamId()))
throw new IllegalStateException("Multiple Team IDs: "+teamId+" and "+mr.getTeamId());
}
if (firstTime) firstTime=false; else sb.append(",");
sb.append(mr.getUserId());
}
sb.append(")");
sb.append(" AND \""+APPLICATION_TEAM_ID+"\"='"+teamId+"'");
String sql = sb.toString();
Pair<List<SelectColumn>, RowSet> queryResult = executeQuery(sql, tableId, Integer.MAX_VALUE);
int userIdIndex = getColumnIndexForName(queryResult.getFirst(), USER_ID);
int expirationIndex = getColumnIndexForName(queryResult.getFirst(), MEMBERSHIP_REQUEST_EXPIRATION_DATE);
// starting from a list of all membership requests, remove the ones that have already been processed
List<MembershipRequest> newMembershipRequests = new ArrayList<MembershipRequest>(membershipRequests);
for (MembershipRequest mr : membershipRequests) {
String mrUserId = mr.getUserId();
Date mrExpiresOn = Util.cleanDate(mr.getExpiresOn());
for (Row row : queryResult.getSecond().getRows()) {
List<String> values = row.getValues();
String rowUserId = values.get(userIdIndex);
String rowExpiresOnString = values.get(expirationIndex);
Date rowExpiresOn = rowExpiresOnString==null ? null : new Date(Long.parseLong(rowExpiresOnString));
if (mrUserId.equals(rowUserId) && Util.datesEqualNoMillis(rowExpiresOn, mrExpiresOn)) {
newMembershipRequests.remove(mr);
break;
}
}
}
return newMembershipRequests;
}
/*
* Given a list of tcs, return the rows for those that have not yet been approved
*/
public TokenTableLookupResults getRowsForAcceptedButNotYetApprovedUserIds(Collection<TokenContent> tcs) throws SynapseException, InterruptedException {
TokenTableLookupResults result = new TokenTableLookupResults();
RowSet rowSet = new RowSet();
List<Row> rows = new ArrayList<Row>();
rowSet.setRows(rows);
result.setRowSet(rowSet);
if (tcs.isEmpty()) return result;
StringBuilder sb = new StringBuilder("SELECT * FROM ");
sb.append(tableId+" WHERE "+USER_ID+" IN (");
boolean firstTime = true;
for (TokenContent tc : tcs) {
if (firstTime) firstTime=false; else sb.append(",");
sb.append(tc.getUserId());
}
sb.append(") AND \"");
sb.append(APPROVED_ON);
sb.append("\" IS NULL");
String sql = sb.toString();
Pair<List<SelectColumn>, RowSet> queryResult = executeQuery(sql, tableId, Integer.MAX_VALUE);
int userIdIndex = getColumnIndexForName(queryResult.getFirst(), USER_ID);
int teamIdIndex = getColumnIndexForName(queryResult.getFirst(), APPLICATION_TEAM_ID);
int expirationIndex = getColumnIndexForName(queryResult.getFirst(), MEMBERSHIP_REQUEST_EXPIRATION_DATE);
for (TokenContent tc : tcs) {
String userId = ""+tc.getUserId();
String teamId = tc.getApplicationTeamId();
Date mrExpiration = tc.getMembershipRequestExpiration();
for (Row row : queryResult.getSecond().getRows()) {
List<String> values = row.getValues();
String rowUser = values.get(userIdIndex);
String rowTeam = values.get(teamIdIndex);
String rowExpiration = values.get(expirationIndex);
boolean datesMatch = rowExpiration==null ? mrExpiration==null :
Util.datesEqualNoMillis(new Date(Long.parseLong(rowExpiration)), mrExpiration);
if (userId.equals(rowUser) && StringUtils.equals(teamId, rowTeam) && datesMatch) {
// found it!
// make a new row and add it to the result that we return
// we copy the data from the query result to ensure that it's a
// mutable object
Row rowCopy = new Row();
rowCopy.setRowId(row.getRowId());
rowCopy.setVersionNumber(row.getVersionNumber());
rowCopy.setValues(new ArrayList<String>(values));
rows.add(rowCopy);
result.addToken(tc);
}
}
}
rowSet.setEtag(queryResult.getSecond().getEtag());
rowSet.setHeaders(queryResult.getFirst());
rowSet.setTableId(tableId);
return result;
}
private static final long MILLIS_PER_DAY = 1000*3600*24;
// query for users whose approval date is more than the given days prior to the present day
public Pair<List<SelectColumn>, RowSet> getExpiredAccess(DatasetSettings ds) throws Exception {
if (ds.getExpiresAfterDays()==null) throw new IllegalArgumentException();
long expirationThreshold = System.currentTimeMillis() - ds.getExpiresAfterDays()*MILLIS_PER_DAY;
StringBuilder sb = new StringBuilder("SELECT \""+USER_ID+"\",\""+DATE_REVOKED+"\" FROM ");
sb.append(tableId);
sb.append(" WHERE \"");
sb.append(APPLICATION_TEAM_ID);
sb.append("\" = ");
sb.append(ds.getApplicationTeamId());
sb.append(" and \"");
sb.append(APPROVED_ON);
sb.append("\"<");
sb.append(expirationThreshold);
sb.append(" and \"");
sb.append(DATE_REVOKED);
sb.append("\" is null");
String sql = sb.toString();
return executeQuery(sql, tableId, Integer.MAX_VALUE);
}
/*
* Executes a query for which the max number of returned rows is known (i.e. we retrieve in a single page)
*/
private Pair<List<SelectColumn>, RowSet> executeQuery(String sql, String tableId, long queryLimit) throws SynapseException, InterruptedException {
String asyncJobToken = synapseClient.queryTableEntityBundleAsyncStart(sql, 0L, queryLimit, QUERY_PARTS_MASK, tableId);
QueryResultBundle qrb=null;
long backoff = 100L;
for (int i=0; i<100; i++) {
try {
qrb = synapseClient.queryTableEntityBundleAsyncGet(asyncJobToken, tableId);
break;
} catch (SynapseResultNotReadyException e) {
// keep waiting
Thread.sleep(backoff);
backoff *=2L;
}
}
if (qrb==null) throw new RuntimeException("Query failed to return");
List<Row> rows = qrb.getQueryResult().getQueryResults().getRows();
if (qrb.getQueryCount()>rows.size()) throw new IllegalStateException(
"Queried for "+queryLimit+" users but got back "+ rows.size()+" and total count: "+qrb.getQueryCount());
return new Pair<List<SelectColumn>, RowSet>(qrb.getSelectColumns(), qrb.getQueryResult().getQueryResults());
}
/*
* returns a list of SelectColumns for the given columnNames in the same order as
* said columnNames.
*/
public List<SelectColumn> createRowSetHeaders(String tableId, String[] columnNames) throws SynapseException {
List<SelectColumn> result = new ArrayList<SelectColumn>();
List<ColumnModel> columns = synapseClient.getColumnModelsForTableEntity(tableId);
for (String columnName : columnNames) {
for (ColumnModel column : columns) {
if (column.getName().equals(columnName)) {
SelectColumn sc = new SelectColumn();
sc.setColumnType(column.getColumnType());
sc.setId(column.getId());
sc.setName(columnName);
result.add(sc);
break;
}
}
}
if (result.size()<columnNames.length) throw new RuntimeException("Could not find columns for all column names.");
return result;
}
public static int getColumnIndexForName(List<SelectColumn> columns, String name) {
for (int i=0; i<columns.size(); i++) {
if (columns.get(i).getName().equals(name)) return i;
}
List<String> names = new ArrayList<String>();
for (SelectColumn column : columns) names.add(column.getName());
throw new IllegalArgumentException("No column named "+name+". Available names: "+names);
}
}
|
UTF-8
|
Java
| 12,593 |
java
|
TableUtil.java
|
Java
|
[
{
"context": "PARTMASK;\n\n\tpublic static final String USER_ID = \"UserId\";\n\tpublic static final String APPLICATION_TEAM_ID",
"end": 1064,
"score": 0.9619017839431763,
"start": 1058,
"tag": "USERNAME",
"value": "UserId"
},
{
"context": "ew field\n\tpublic static final String USER_NAME = \"User Name\";\n\tpublic static final String FIRST_NAME = \"First",
"end": 1201,
"score": 0.9970478415489197,
"start": 1192,
"tag": "NAME",
"value": "User Name"
},
{
"context": " Name\";\n\tpublic static final String FIRST_NAME = \"First Name\";\n\tpublic static final String LAST_NAME = \"Last N",
"end": 1256,
"score": 0.9976410865783691,
"start": 1246,
"tag": "NAME",
"value": "First Name"
},
{
"context": "t Name\";\n\tpublic static final String LAST_NAME = \"Last Name\";\n\tpublic static final String TOKEN_SENT_DATE = \"",
"end": 1309,
"score": 0.9970101118087769,
"start": 1300,
"tag": "NAME",
"value": "Last Name"
}
] | null |
[] |
package org.sagebionetworks;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.sagebionetworks.client.SynapseClient;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.client.exceptions.SynapseResultNotReadyException;
import org.sagebionetworks.repo.model.MembershipRequest;
import org.sagebionetworks.repo.model.table.ColumnModel;
import org.sagebionetworks.repo.model.table.QueryResultBundle;
import org.sagebionetworks.repo.model.table.Row;
import org.sagebionetworks.repo.model.table.RowSet;
import org.sagebionetworks.repo.model.table.SelectColumn;
public class TableUtil {
private static final int QUERY_PARTS_MASK =
SynapseClient.QUERY_PARTMASK |
SynapseClient.COUNT_PARTMASK |
SynapseClient.COLUMNS_PARTMASK |
SynapseClient.MAXROWS_PARTMASK;
public static final String USER_ID = "UserId";
public static final String APPLICATION_TEAM_ID = "ApplicationTeamId"; // new field
public static final String USER_NAME = "<NAME>";
public static final String FIRST_NAME = "<NAME>";
public static final String LAST_NAME = "<NAME>";
public static final String TOKEN_SENT_DATE = "Date Email Sent";
public static final String MEMBERSHIP_REQUEST_EXPIRATION_DATE = "Date Membership Request Expires"; // new field
public static final String APPROVED_ON = "Date Approved/Rejected";
public static final String DATE_REVOKED = "Date Revoked";
public static final long TABLE_UPDATE_TIMEOUT = 100000L;
private SynapseClient synapseClient;
private String tableId;
private String configurationTableId;
public TableUtil(SynapseClient synapseClient, String tableId, String configurationTableId) {
this.synapseClient=synapseClient;
this.tableId=tableId;
this.configurationTableId=configurationTableId;
}
public static List<String> getSubnetsFromString(String s) {
if (StringUtils.isEmpty(s)) return Collections.EMPTY_LIST;
return Arrays.asList(s.split("[,;:]"));
}
/*
* return a map whose key is signup team ID and value is the collection of settings for that team
*/
public Map<String,DatasetSettings> getDatasetSettings() throws SynapseException, InterruptedException {
Pair<List<SelectColumn>, RowSet> queryResult = executeQuery(
"SELECT * FROM "+configurationTableId, configurationTableId, Integer.MAX_VALUE);
Map<String,DatasetSettings> result = new HashMap<String,DatasetSettings>();
for (Row row : queryResult.getSecond().getRows()) {
DatasetSettings setting = new DatasetSettings();
assert row.getValues().size()==queryResult.getSecond().getHeaders().size();
for (int i=0; i<queryResult.getSecond().getHeaders().size(); i++) {
SelectColumn sc = queryResult.getSecond().getHeaders().get(i);
String value = row.getValues().get(i);
if (sc.getName().equals("applicationTeamId")) {
setting.setApplicationTeamId(value);
} else if (sc.getName().equals("accessRequirementIds")) {
String[] arIdStrings = value.split(",");
List<Long> arIds = new ArrayList<Long>();
for (String arIdString : arIdStrings) arIds.add(Long.parseLong(arIdString));
setting.setAccessRequirementIds(arIds);
} else if (sc.getName().equals("tokenLabel")) {
setting.setTokenLabel(value);
} else if (sc.getName().equals("dataDescriptor")) {
setting.setDataDescriptor(value);
} else if (sc.getName().equals("tokenEmailSynapseId")) {
setting.setTokenEmailSynapseId(value);
} else if (sc.getName().equals("approvalEmailSynapseId")) {
setting.setApprovalEmailSynapseId(value);
} else if (sc.getName().equals("revocationEmailSynapseId")) {
setting.setRevocationEmailSynapseId(value);
} else if (sc.getName().equals("tokenExpirationDays")) {
setting.setTokenExpirationTimeDays(Integer.parseInt(value));
} else if (sc.getName().equals("originatingIpSubnet")) {
List<String> subnets = getSubnetsFromString(value);
setting.setOriginatingIPsubnets(subnets);
} else if (sc.getName().equals("expiresAfterDays")) {
if (!StringUtils.isEmpty(value))
setting.setExpiresAfterDays(Integer.parseInt(value));
} else if (sc.getName().equals("approverSynapseIds")) {
String[] approverSynapseIds = value.split(",");
setting.setApproverSynapseIds(Arrays.asList(approverSynapseIds));
} else {
throw new RuntimeException("Unexpected column "+sc.getName());
}
}
assert setting.getApplicationTeamId()!=null;
result.put(setting.getApplicationTeamId(), setting);
}
return result;
}
public List<MembershipRequest> getNewMembershipRequests(Collection<MembershipRequest> membershipRequests) throws SynapseException, InterruptedException {
if (membershipRequests.isEmpty()) return Collections.EMPTY_LIST;
StringBuilder sb = new StringBuilder("SELECT ");
sb.append("\""+USER_ID+"\", ");
sb.append("\""+MEMBERSHIP_REQUEST_EXPIRATION_DATE+"\" ");
sb.append(" FROM "+tableId+" WHERE "+USER_ID+" IN (");
boolean firstTime = true;
String teamId = null;
for (MembershipRequest mr : membershipRequests) {
if (teamId==null) {
teamId = mr.getTeamId();
} else {
// all mr's should be for the same teamId
if (!teamId.equals(mr.getTeamId()))
throw new IllegalStateException("Multiple Team IDs: "+teamId+" and "+mr.getTeamId());
}
if (firstTime) firstTime=false; else sb.append(",");
sb.append(mr.getUserId());
}
sb.append(")");
sb.append(" AND \""+APPLICATION_TEAM_ID+"\"='"+teamId+"'");
String sql = sb.toString();
Pair<List<SelectColumn>, RowSet> queryResult = executeQuery(sql, tableId, Integer.MAX_VALUE);
int userIdIndex = getColumnIndexForName(queryResult.getFirst(), USER_ID);
int expirationIndex = getColumnIndexForName(queryResult.getFirst(), MEMBERSHIP_REQUEST_EXPIRATION_DATE);
// starting from a list of all membership requests, remove the ones that have already been processed
List<MembershipRequest> newMembershipRequests = new ArrayList<MembershipRequest>(membershipRequests);
for (MembershipRequest mr : membershipRequests) {
String mrUserId = mr.getUserId();
Date mrExpiresOn = Util.cleanDate(mr.getExpiresOn());
for (Row row : queryResult.getSecond().getRows()) {
List<String> values = row.getValues();
String rowUserId = values.get(userIdIndex);
String rowExpiresOnString = values.get(expirationIndex);
Date rowExpiresOn = rowExpiresOnString==null ? null : new Date(Long.parseLong(rowExpiresOnString));
if (mrUserId.equals(rowUserId) && Util.datesEqualNoMillis(rowExpiresOn, mrExpiresOn)) {
newMembershipRequests.remove(mr);
break;
}
}
}
return newMembershipRequests;
}
/*
* Given a list of tcs, return the rows for those that have not yet been approved
*/
public TokenTableLookupResults getRowsForAcceptedButNotYetApprovedUserIds(Collection<TokenContent> tcs) throws SynapseException, InterruptedException {
TokenTableLookupResults result = new TokenTableLookupResults();
RowSet rowSet = new RowSet();
List<Row> rows = new ArrayList<Row>();
rowSet.setRows(rows);
result.setRowSet(rowSet);
if (tcs.isEmpty()) return result;
StringBuilder sb = new StringBuilder("SELECT * FROM ");
sb.append(tableId+" WHERE "+USER_ID+" IN (");
boolean firstTime = true;
for (TokenContent tc : tcs) {
if (firstTime) firstTime=false; else sb.append(",");
sb.append(tc.getUserId());
}
sb.append(") AND \"");
sb.append(APPROVED_ON);
sb.append("\" IS NULL");
String sql = sb.toString();
Pair<List<SelectColumn>, RowSet> queryResult = executeQuery(sql, tableId, Integer.MAX_VALUE);
int userIdIndex = getColumnIndexForName(queryResult.getFirst(), USER_ID);
int teamIdIndex = getColumnIndexForName(queryResult.getFirst(), APPLICATION_TEAM_ID);
int expirationIndex = getColumnIndexForName(queryResult.getFirst(), MEMBERSHIP_REQUEST_EXPIRATION_DATE);
for (TokenContent tc : tcs) {
String userId = ""+tc.getUserId();
String teamId = tc.getApplicationTeamId();
Date mrExpiration = tc.getMembershipRequestExpiration();
for (Row row : queryResult.getSecond().getRows()) {
List<String> values = row.getValues();
String rowUser = values.get(userIdIndex);
String rowTeam = values.get(teamIdIndex);
String rowExpiration = values.get(expirationIndex);
boolean datesMatch = rowExpiration==null ? mrExpiration==null :
Util.datesEqualNoMillis(new Date(Long.parseLong(rowExpiration)), mrExpiration);
if (userId.equals(rowUser) && StringUtils.equals(teamId, rowTeam) && datesMatch) {
// found it!
// make a new row and add it to the result that we return
// we copy the data from the query result to ensure that it's a
// mutable object
Row rowCopy = new Row();
rowCopy.setRowId(row.getRowId());
rowCopy.setVersionNumber(row.getVersionNumber());
rowCopy.setValues(new ArrayList<String>(values));
rows.add(rowCopy);
result.addToken(tc);
}
}
}
rowSet.setEtag(queryResult.getSecond().getEtag());
rowSet.setHeaders(queryResult.getFirst());
rowSet.setTableId(tableId);
return result;
}
private static final long MILLIS_PER_DAY = 1000*3600*24;
// query for users whose approval date is more than the given days prior to the present day
public Pair<List<SelectColumn>, RowSet> getExpiredAccess(DatasetSettings ds) throws Exception {
if (ds.getExpiresAfterDays()==null) throw new IllegalArgumentException();
long expirationThreshold = System.currentTimeMillis() - ds.getExpiresAfterDays()*MILLIS_PER_DAY;
StringBuilder sb = new StringBuilder("SELECT \""+USER_ID+"\",\""+DATE_REVOKED+"\" FROM ");
sb.append(tableId);
sb.append(" WHERE \"");
sb.append(APPLICATION_TEAM_ID);
sb.append("\" = ");
sb.append(ds.getApplicationTeamId());
sb.append(" and \"");
sb.append(APPROVED_ON);
sb.append("\"<");
sb.append(expirationThreshold);
sb.append(" and \"");
sb.append(DATE_REVOKED);
sb.append("\" is null");
String sql = sb.toString();
return executeQuery(sql, tableId, Integer.MAX_VALUE);
}
/*
* Executes a query for which the max number of returned rows is known (i.e. we retrieve in a single page)
*/
private Pair<List<SelectColumn>, RowSet> executeQuery(String sql, String tableId, long queryLimit) throws SynapseException, InterruptedException {
String asyncJobToken = synapseClient.queryTableEntityBundleAsyncStart(sql, 0L, queryLimit, QUERY_PARTS_MASK, tableId);
QueryResultBundle qrb=null;
long backoff = 100L;
for (int i=0; i<100; i++) {
try {
qrb = synapseClient.queryTableEntityBundleAsyncGet(asyncJobToken, tableId);
break;
} catch (SynapseResultNotReadyException e) {
// keep waiting
Thread.sleep(backoff);
backoff *=2L;
}
}
if (qrb==null) throw new RuntimeException("Query failed to return");
List<Row> rows = qrb.getQueryResult().getQueryResults().getRows();
if (qrb.getQueryCount()>rows.size()) throw new IllegalStateException(
"Queried for "+queryLimit+" users but got back "+ rows.size()+" and total count: "+qrb.getQueryCount());
return new Pair<List<SelectColumn>, RowSet>(qrb.getSelectColumns(), qrb.getQueryResult().getQueryResults());
}
/*
* returns a list of SelectColumns for the given columnNames in the same order as
* said columnNames.
*/
public List<SelectColumn> createRowSetHeaders(String tableId, String[] columnNames) throws SynapseException {
List<SelectColumn> result = new ArrayList<SelectColumn>();
List<ColumnModel> columns = synapseClient.getColumnModelsForTableEntity(tableId);
for (String columnName : columnNames) {
for (ColumnModel column : columns) {
if (column.getName().equals(columnName)) {
SelectColumn sc = new SelectColumn();
sc.setColumnType(column.getColumnType());
sc.setId(column.getId());
sc.setName(columnName);
result.add(sc);
break;
}
}
}
if (result.size()<columnNames.length) throw new RuntimeException("Could not find columns for all column names.");
return result;
}
public static int getColumnIndexForName(List<SelectColumn> columns, String name) {
for (int i=0; i<columns.size(); i++) {
if (columns.get(i).getName().equals(name)) return i;
}
List<String> names = new ArrayList<String>();
for (SelectColumn column : columns) names.add(column.getName());
throw new IllegalArgumentException("No column named "+name+". Available names: "+names);
}
}
| 12,583 | 0.724847 | 0.722624 | 298 | 41.258389 | 31.612009 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.201342 | false | false |
0
|
936df9a37b1049d56eb9306eb282bd5bb1c65cb0
| 9,723,805,969,785 |
2c3f8602138190797d8b01c23f022b9dbc16b823
|
/com.intel.llvm.ireditor/src-gen/com/intel/llvm/ireditor/lLVM_IR/impl/AggregateInstructionImpl.java
|
b0174a8f203da2aaaa07f1acd75056d2744d6f7d
|
[
"BSD-3-Clause"
] |
permissive
|
thSoft/llvm-ir-editor
|
https://github.com/thSoft/llvm-ir-editor
|
7be492aba9c0ce0c8c620832bcd0db44e14143a5
|
eb19fd7588da3e90dede48aabd7dba3939788c67
|
refs/heads/master
| 2020-12-14T07:32:23.210000 | 2014-02-19T15:38:36 | 2014-02-19T15:50:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*/
package com.intel.llvm.ireditor.lLVM_IR.impl;
import com.intel.llvm.ireditor.lLVM_IR.AggregateInstruction;
import com.intel.llvm.ireditor.lLVM_IR.Constant;
import com.intel.llvm.ireditor.lLVM_IR.LLVM_IRPackage;
import com.intel.llvm.ireditor.lLVM_IR.TypedValue;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Aggregate Instruction</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link com.intel.llvm.ireditor.lLVM_IR.impl.AggregateInstructionImpl#getOpcode <em>Opcode</em>}</li>
* <li>{@link com.intel.llvm.ireditor.lLVM_IR.impl.AggregateInstructionImpl#getAggregate <em>Aggregate</em>}</li>
* <li>{@link com.intel.llvm.ireditor.lLVM_IR.impl.AggregateInstructionImpl#getIndices <em>Indices</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class AggregateInstructionImpl extends MinimalEObjectImpl.Container implements AggregateInstruction
{
/**
* The default value of the '{@link #getOpcode() <em>Opcode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOpcode()
* @generated
* @ordered
*/
protected static final String OPCODE_EDEFAULT = null;
/**
* The cached value of the '{@link #getOpcode() <em>Opcode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOpcode()
* @generated
* @ordered
*/
protected String opcode = OPCODE_EDEFAULT;
/**
* The cached value of the '{@link #getAggregate() <em>Aggregate</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAggregate()
* @generated
* @ordered
*/
protected TypedValue aggregate;
/**
* The cached value of the '{@link #getIndices() <em>Indices</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIndices()
* @generated
* @ordered
*/
protected EList<Constant> indices;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AggregateInstructionImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return LLVM_IRPackage.Literals.AGGREGATE_INSTRUCTION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getOpcode()
{
return opcode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOpcode(String newOpcode)
{
String oldOpcode = opcode;
opcode = newOpcode;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE, oldOpcode, opcode));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypedValue getAggregate()
{
return aggregate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetAggregate(TypedValue newAggregate, NotificationChain msgs)
{
TypedValue oldAggregate = aggregate;
aggregate = newAggregate;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, oldAggregate, newAggregate);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAggregate(TypedValue newAggregate)
{
if (newAggregate != aggregate)
{
NotificationChain msgs = null;
if (aggregate != null)
msgs = ((InternalEObject)aggregate).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, null, msgs);
if (newAggregate != null)
msgs = ((InternalEObject)newAggregate).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, null, msgs);
msgs = basicSetAggregate(newAggregate, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, newAggregate, newAggregate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Constant> getIndices()
{
if (indices == null)
{
indices = new EObjectContainmentEList<Constant>(Constant.class, this, LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES);
}
return indices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
return basicSetAggregate(null, msgs);
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
return ((InternalEList<?>)getIndices()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
return getOpcode();
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
return getAggregate();
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
return getIndices();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
setOpcode((String)newValue);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
setAggregate((TypedValue)newValue);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
getIndices().clear();
getIndices().addAll((Collection<? extends Constant>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
setOpcode(OPCODE_EDEFAULT);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
setAggregate((TypedValue)null);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
getIndices().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
return OPCODE_EDEFAULT == null ? opcode != null : !OPCODE_EDEFAULT.equals(opcode);
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
return aggregate != null;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
return indices != null && !indices.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (opcode: ");
result.append(opcode);
result.append(')');
return result.toString();
}
} //AggregateInstructionImpl
|
UTF-8
|
Java
| 8,395 |
java
|
AggregateInstructionImpl.java
|
Java
|
[] | null |
[] |
/**
*/
package com.intel.llvm.ireditor.lLVM_IR.impl;
import com.intel.llvm.ireditor.lLVM_IR.AggregateInstruction;
import com.intel.llvm.ireditor.lLVM_IR.Constant;
import com.intel.llvm.ireditor.lLVM_IR.LLVM_IRPackage;
import com.intel.llvm.ireditor.lLVM_IR.TypedValue;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Aggregate Instruction</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link com.intel.llvm.ireditor.lLVM_IR.impl.AggregateInstructionImpl#getOpcode <em>Opcode</em>}</li>
* <li>{@link com.intel.llvm.ireditor.lLVM_IR.impl.AggregateInstructionImpl#getAggregate <em>Aggregate</em>}</li>
* <li>{@link com.intel.llvm.ireditor.lLVM_IR.impl.AggregateInstructionImpl#getIndices <em>Indices</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class AggregateInstructionImpl extends MinimalEObjectImpl.Container implements AggregateInstruction
{
/**
* The default value of the '{@link #getOpcode() <em>Opcode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOpcode()
* @generated
* @ordered
*/
protected static final String OPCODE_EDEFAULT = null;
/**
* The cached value of the '{@link #getOpcode() <em>Opcode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOpcode()
* @generated
* @ordered
*/
protected String opcode = OPCODE_EDEFAULT;
/**
* The cached value of the '{@link #getAggregate() <em>Aggregate</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAggregate()
* @generated
* @ordered
*/
protected TypedValue aggregate;
/**
* The cached value of the '{@link #getIndices() <em>Indices</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIndices()
* @generated
* @ordered
*/
protected EList<Constant> indices;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AggregateInstructionImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return LLVM_IRPackage.Literals.AGGREGATE_INSTRUCTION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getOpcode()
{
return opcode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOpcode(String newOpcode)
{
String oldOpcode = opcode;
opcode = newOpcode;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE, oldOpcode, opcode));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypedValue getAggregate()
{
return aggregate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetAggregate(TypedValue newAggregate, NotificationChain msgs)
{
TypedValue oldAggregate = aggregate;
aggregate = newAggregate;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, oldAggregate, newAggregate);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAggregate(TypedValue newAggregate)
{
if (newAggregate != aggregate)
{
NotificationChain msgs = null;
if (aggregate != null)
msgs = ((InternalEObject)aggregate).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, null, msgs);
if (newAggregate != null)
msgs = ((InternalEObject)newAggregate).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, null, msgs);
msgs = basicSetAggregate(newAggregate, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE, newAggregate, newAggregate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Constant> getIndices()
{
if (indices == null)
{
indices = new EObjectContainmentEList<Constant>(Constant.class, this, LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES);
}
return indices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
return basicSetAggregate(null, msgs);
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
return ((InternalEList<?>)getIndices()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
return getOpcode();
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
return getAggregate();
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
return getIndices();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
setOpcode((String)newValue);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
setAggregate((TypedValue)newValue);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
getIndices().clear();
getIndices().addAll((Collection<? extends Constant>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
setOpcode(OPCODE_EDEFAULT);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
setAggregate((TypedValue)null);
return;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
getIndices().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__OPCODE:
return OPCODE_EDEFAULT == null ? opcode != null : !OPCODE_EDEFAULT.equals(opcode);
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__AGGREGATE:
return aggregate != null;
case LLVM_IRPackage.AGGREGATE_INSTRUCTION__INDICES:
return indices != null && !indices.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (opcode: ");
result.append(opcode);
result.append(')');
return result.toString();
}
} //AggregateInstructionImpl
| 8,395 | 0.640739 | 0.640739 | 312 | 25.907051 | 28.450041 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.339744 | false | false |
0
|
02a74d28ad3c73ff83a2b4698d207666e631a573
| 29,549,375,067,476 |
f76f012aa05594dc9ebb62e92eeee7fa7d6e9edd
|
/Hardware/src/main/java/com/qualcomm/hardware/modernrobotics/comm/ModernRoboticsReaderWriter.java
|
546e936d88b891a7f93ea0e57c9621941258209f
|
[
"MIT"
] |
permissive
|
Volt40/FTCLib
|
https://github.com/Volt40/FTCLib
|
3d384434faed0c5adae4f7b8c22a87683c5667b6
|
a11fcd03178e92df1b80df9eaca3aa35b2dbf211
|
refs/heads/master
| 2022-12-16T15:09:40.701000 | 2020-09-24T14:03:16 | 2020-09-24T14:03:16 | 298,296,818 | 0 | 0 |
MIT
| true | 2020-09-24T14:02:06 | 2020-09-24T14:02:05 | 2020-09-22T19:17:22 | 2020-09-24T13:32:15 | 63,653 | 0 | 0 | 0 | null | false | false |
/*
* Copyright (c) 2014, 2015, 2016 Qualcomm Technologies Inc
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* (subject to the limitations in the disclaimer below) provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Qualcomm Technologies Inc nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS
* SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright (c) 2016-2017 Robert Atkinson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) provided that
the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.qualcomm.hardware.modernrobotics.comm;
import android.annotation.SuppressLint;
import android.support.annotation.Nullable;
import com.qualcomm.robotcore.hardware.usb.RobotUsbDevice;
import com.qualcomm.robotcore.util.RobotLog;
import org.firstinspires.ftc.robotcore.internal.system.Deadline;
import org.firstinspires.ftc.robotcore.internal.hardware.TimeWindow;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbException;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbProtocolException;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbTimeoutException;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbTooManySequentialErrorsException;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("WeakerAccess")
@SuppressLint("DefaultLocale")
public class ModernRoboticsReaderWriter
{
//----------------------------------------------------------------------------------------------
// State
//----------------------------------------------------------------------------------------------
public static final String TAG = "MRReaderWriter";
public static boolean DEBUG = false;
/**
* The timeouts defined by the MR USB spec are subtle. Our historical timeout of 100ms
* to read the header and the 100ms to read the payload was demonstrably insufficient, as teams
* were hitting the payload timeout in the wild. Per the MR spec, the payload timeout should
* be payload-length-dependent.
*
* Here's the skinny:
*
* The MR spec speaks thusly: "In order to detect a failure of too few Data payload bytes being
* received, a timeout is used. This timeout is set to 10mS. This timeout will start as a soon
* as the initial 0x55 is received. It is reset upon the arrival of each subsequent byte. [...]
* A similar timeout process may be performed by the host. The host may also use a timeout of
* 50mS for receipt of a response. If no response is received within 50mS, then it is assumed
* that either the USB VCP communication link is non-operational, or the controller power is
* not present"
*/
public static int MS_INTER_BYTE_TIMEOUT = 10;
public static int MS_USB_HUB_LATENCY = 2; // this is probably way overkill
public static int MS_REQUEST_RESPONSE_TIMEOUT = 50 + MS_USB_HUB_LATENCY * 2;
/**
* We run on a garbage collected system. That doesn't run very often, and doesn't run back to
* back, only one at a time, but when it does run it shuts things down for 15ms-40ms. One of
* those can happen in the middle of any of our timeouts. So we need to allow for same.
*/
public static int MS_GARBAGE_COLLECTION_SPURT = 40;
/** We made this up: we want to be very generous in trying to recover from failures as we
* read through possibly-old data trying to synchronize, and there's little harm in doing so */
public static int MS_RESYNCH_TIMEOUT = 1000;
public static int MS_FAILURE_WAIT = 40; // per email from MR
public static int MS_COMM_ERROR_WAIT = 100; // historical. we made this up
public static int MS_MAX_TIMEOUT = 100; // we made this up.
public static int MAX_SEQUENTIAL_USB_ERROR_COUNT = 5; // we made this up. Used to be 10, but can tighten with the better sync logic we now have
public final static String COMM_FAILURE_READ = "comm failure read";
public final static String COMM_FAILURE_WRITE = "comm failure write";
public final static String COMM_TIMEOUT_READ = "comm timeout awaiting response (read)";
public final static String COMM_TIMEOUT_WRITE = "comm timeout awaiting response (write)";
public final static String COMM_ERROR_READ = "comm error read";
public final static String COMM_ERROR_WRITE = "comm error write";
public final static String COMM_SYNC_LOST = "comm sync lost";
public final static String COMM_PAYLOAD_ERROR_READ = "comm payload error read";
public final static String COMM_PAYLOAD_ERROR_WRITE = "comm payload error write";
public final static String COMM_TYPE_ERROR_READ = "comm type error read";
public final static String COMM_TYPE_ERROR_WRITE = "comm type error write";
protected final RobotUsbDevice device;
protected int usbSequentialCommReadErrorCount = 0;
protected int usbSequentialCommWriteErrorCount = 0;
protected int usbReadRetryCount = 4;
protected int usbWriteRetryCount = 4;
protected int msUsbReadRetryInterval = 20;
protected int msUsbWriteRetryInterval = 20;
protected boolean isSynchronized = false;
protected Deadline responseDeadline = new Deadline(MS_RESYNCH_TIMEOUT, TimeUnit.MILLISECONDS);
protected ModernRoboticsDatagram.AllocationContext<ModernRoboticsRequest> requestAllocationContext = new ModernRoboticsDatagram.AllocationContext<ModernRoboticsRequest>();
protected ModernRoboticsDatagram.AllocationContext<ModernRoboticsResponse> responseAllocationContext = new ModernRoboticsDatagram.AllocationContext<ModernRoboticsResponse>();
//----------------------------------------------------------------------------------------------
// Construction
//----------------------------------------------------------------------------------------------
public ModernRoboticsReaderWriter(RobotUsbDevice device)
{
this.device = device;
this.device.setDebugRetainBuffers(true);
}
public void throwIfTooManySequentialCommErrors() throws RobotUsbTooManySequentialErrorsException
{
if (device.isOpen())
{
if (this.usbSequentialCommReadErrorCount > MAX_SEQUENTIAL_USB_ERROR_COUNT || this.usbSequentialCommWriteErrorCount > MAX_SEQUENTIAL_USB_ERROR_COUNT)
{
throw new RobotUsbTooManySequentialErrorsException("%s: too many sequential USB comm errors on device", device.getSerialNumber());
}
}
}
public void close()
{
this.device.close();
}
//----------------------------------------------------------------------------------------------
// Reading and writing
//----------------------------------------------------------------------------------------------
public void read(boolean retry, int address, byte[] buffer, @Nullable TimeWindow payloadTimeWindow) throws RobotUsbException, InterruptedException
{
if (DEBUG) RobotLog.vv(TAG, "%s: read(addr=%d cb=%d)", device.getSerialNumber(), address, buffer.length);
RobotUsbException exception = null;
for (int i = 0; i < usbReadRetryCount; i++)
{
if (i > 0)
{
RobotLog.ee(TAG, "%s: retry #%d read(addr=%d cb=%d)", device.getSerialNumber(), i, address, buffer.length);
}
try {
readOnce(address, buffer, payloadTimeWindow);
}
catch (RobotUsbException e)
{
// read failed
if (!this.device.isOpen())
{
return; // silent
}
else if (!retry)
{
RobotLog.ee(TAG, "%s: ignoring failed read(addr=%d cb=%d)", device.getSerialNumber(), address, buffer.length);
return; // ignore failure if we're not asked to retry
}
Thread.sleep(msUsbReadRetryInterval); // always sleep in order to give MR device chance to write to its FTDI chip before we reset same
this.device.resetAndFlushBuffers();
exception = e;
continue;
}
// read succeeded
return;
}
if (exception != null) throw exception;
}
protected void readOnce(int address, byte[] buffer, @Nullable TimeWindow payloadTimeWindow) throws RobotUsbException, InterruptedException
{
ModernRoboticsRequest request = null;
ModernRoboticsResponse response = null;
try {
// Create and send a read request
request = ModernRoboticsRequest.newInstance(requestAllocationContext, 0);
request.setRead(0);
request.setAddress(address);
request.setPayloadLength(buffer.length);
this.device.write(request.data);
try {
// Read the response
response = readResponse(request, payloadTimeWindow);
if (response.isFailure())
{
// In order to avoid having the MR firmware think we might be about to try to update
// it with a new version, we wait a prescribed delay per MR information
Thread.sleep(MS_FAILURE_WAIT);
logAndThrowProtocol(request, response, COMM_FAILURE_READ);
}
else if (response.isRead()
&& response.getFunction()==0
&& response.getAddress()==address
&& response.getPayloadLength()==buffer.length)
{
// Success! All is well.
this.usbSequentialCommReadErrorCount = 0;
System.arraycopy(response.data, ModernRoboticsDatagram.CB_HEADER, buffer, 0, buffer.length);
}
else
{
// Historical code had a sleep here. We don't believe that it's actually
// necessary, but it's harmless, so we keep it (for now) as it's harmless
// and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
logAndThrowProtocol(request, response, COMM_ERROR_READ);
}
}
catch (RobotUsbTimeoutException e)
{
// In *some cases* historical code had a sleep here, too, namely the 'incorrect sync
// bytes' case. In the present code paths, that ends up timing out instead, as our
// readResponse() intrinsically synchronizes. But we add the sleep here for good measure
// as it's harmless, and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
logAndRethrowTimeout(e, request, timeoutMessage(COMM_TIMEOUT_READ, e));
}
}
catch (RobotUsbException e)
{
++usbSequentialCommReadErrorCount;
throw e;
}
finally
{
// proactively reclaim instances
if (response != null) response.close();
if (request != null) request.close();
}
}
public void write(int address, byte[] buffer) throws RobotUsbException, InterruptedException
{
if (DEBUG) RobotLog.vv(TAG, "%s: write(addr=%d cb=%d)", device.getSerialNumber(), address, buffer.length);
// Retry a handful of times before giving up. The thing we have to deal with most here
// is USB transmission errors, which tend in our experience to be intermittent and not
// bursty, so retrying a couple of times seems worthwhile.
//
// Note that the correctness here of doing the write relies on the fact that writes
// are idempotent : some of the writes that appear to fail might instead actually succeed
// w/o our knowing, and there's nothing we can do about that.
//
RobotUsbException exception = null;
for (int i = 0; i < usbWriteRetryCount; i++)
{
if (i > 0)
{
RobotLog.ee(TAG, "%s: retry #%d write(addr=%d cb=%d)", device.getSerialNumber(), i, address, buffer.length);
}
try {
writeOnce(address, buffer);
}
catch (RobotUsbException e)
{
// write failed
if (!this.device.isOpen())
{
return; // silent
}
Thread.sleep(msUsbWriteRetryInterval); // same comment as in read()
this.device.resetAndFlushBuffers();
exception = e;
continue;
}
// write succeeded
return;
}
// If that didn't fix things, then fail : the write will (presumably) change
// state if it succeeds, so we need to eithe make the change happen or let the
// caller know that it won't
if (exception != null) throw exception;
}
protected void writeOnce(int address, byte[] buffer) throws RobotUsbException, InterruptedException
{
ModernRoboticsRequest request = null;
ModernRoboticsResponse response = null;
try {
// Create and send a write request
request = ModernRoboticsRequest.newInstance(requestAllocationContext, buffer.length);
request.setWrite(0);
request.setAddress(address);
request.setPayload(buffer);
this.device.write(request.data);
try {
// Read the response
response = readResponse(request, null);
if (response.isFailure())
{
// In order to avoid having the MR firmware think we might be about to try to update
// it with a new version, we wait a prescribed delay per MR information
Thread.sleep(MS_FAILURE_WAIT);
this.logAndThrowProtocol(request, response, COMM_FAILURE_WRITE);
}
else if (response.isWrite()
&& response.getFunction()==0
&& response.getAddress()==address
&& response.getPayloadLength()==0)
{
// All is well
this.usbSequentialCommWriteErrorCount = 0;
}
else
{
// Historical code had a sleep here. We don't believe that it's actually
// necessary, but it's harmless, so we keep it (for now) as it's harmless
// and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
this.logAndThrowProtocol(request, response, COMM_ERROR_WRITE);
}
}
catch (RobotUsbTimeoutException e)
{
// In *some cases* historical code had a sleep here, too, namely the 'incorrect sync
// bytes' case. In the present code paths, that ends up timing out instead, as our
// readResponse() intrinsically synchronizes. But we add the sleep here for good measure
// as it's harmless, and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
this.logAndRethrowTimeout(e, request, timeoutMessage(COMM_TIMEOUT_WRITE, e));
}
}
catch (RobotUsbException e)
{
++this.usbSequentialCommWriteErrorCount;
throw e;
}
finally
{
if (response != null) response.close();
if (request != null) request.close();
}
}
//----------------------------------------------------------------------------------------------
// Response reading
//----------------------------------------------------------------------------------------------
protected ModernRoboticsResponse readResponse(ModernRoboticsRequest request, @Nullable TimeWindow payloadTimeWindow) throws RobotUsbException, InterruptedException
{
responseDeadline.reset();
while (!responseDeadline.hasExpired())
{
// Synchronization bytes by their nature occur only at the start of USB packets. So if
// we're not currently there, then we can't possibly be synchronized.
if (!device.mightBeAtUsbPacketStart())
{
isSynchronized = false;
}
// Read the header, synchronizing carefully if we need to
ModernRoboticsResponse header = ModernRoboticsResponse.newInstance(responseAllocationContext, 0);
try {
if (!isSynchronized)
{
byte[] singleByte = new byte[1];
byte[] headerSuffix = new byte[ModernRoboticsDatagram.CB_HEADER-2];
// Synchronization bytes by their nature occur only at the start of USB packets.
// So if we know we're not at such a boundary, skip along until the next one.
device.skipToLikelyUsbPacketStart();
// Synchronize by looking for the first synchronization byte
if (readSingleByte(singleByte, MS_REQUEST_RESPONSE_TIMEOUT, null, "sync0") != ModernRoboticsResponse.syncBytes[0])
{
continue;
}
// Having found the first, if we don't next see the second, then go back to looking for the first
if (readSingleByte(singleByte, 0, null, "sync1") != ModernRoboticsResponse.syncBytes[1])
{
continue;
}
// Read the remaining header bytes
readIncomingBytes(headerSuffix, 0, headerSuffix.length, 0, null, "syncSuffix");
// Assemble the header from the pieces
System.arraycopy(ModernRoboticsResponse.syncBytes, 0, header.data, 0, 2);
System.arraycopy(headerSuffix, 0, header.data, 2, headerSuffix.length);
}
else
{
readIncomingBytes(header.data, 0, header.data.length, MS_REQUEST_RESPONSE_TIMEOUT, null, "header");
if (!header.syncBytesValid())
{
// We've lost synchronization, yet we received *some* data. Thus, since there
// is no retransmission in the USB protocol, we're never going to get the response
// that we were looking for. So get out of Dodge with an error.
logAndThrowProtocol(request, header, COMM_SYNC_LOST);
}
}
// Make sure the request and response types match
if (!header.isFailure())
{
if (request.isRead() != header.isRead() || request.getFunction() != header.getFunction())
{
logAndThrowProtocol(request, header, request.isWrite() ? COMM_TYPE_ERROR_WRITE: COMM_TYPE_ERROR_READ);
}
}
// How big of a payload is expected in the response? It should match the expectations
// set in the request. If it doesn't, get out of Dodge.
int cbPayloadExpected = header.isFailure()
? 0
: request.isWrite()
? 0
: request.getPayloadLength();
if (cbPayloadExpected != header.getPayloadLength())
{
// We're out of sync some how
logAndThrowProtocol(request, header, request.isWrite() ? COMM_PAYLOAD_ERROR_WRITE: COMM_PAYLOAD_ERROR_READ);
}
// Assemble a response and read the payload data thereinto
ModernRoboticsResponse result = ModernRoboticsResponse.newInstance(responseAllocationContext, header.getPayloadLength());
System.arraycopy(header.data, 0, result.data, 0, header.data.length);
readIncomingBytes(result.data, header.data.length, header.getPayloadLength(), 0, payloadTimeWindow, "payload");
// We're ok to go more quickly the next time
isSynchronized = true;
return result;
}
finally
{
if (header != null) header.close();
}
}
throw new RobotUsbTimeoutException(responseDeadline.startTimeNanoseconds(), "timeout waiting %d ms for response", responseDeadline.getDuration(TimeUnit.MILLISECONDS));
}
protected void readIncomingBytes(byte[] buffer, int ibFirst, int cbToRead, int msExtraTimeout, @Nullable TimeWindow timeWindow, String debugContext) throws RobotUsbException, InterruptedException
{
if (cbToRead > 0)
{
// In theory, per the MR spec, we might see MS_INTER_BYTE_TIMEOUT elapse
// between each incoming byte. For a long-ish read response, that can amount
// to some significant time: we routinely read 31 byte swaths of data on the
// motor controller, for example, which would amount to nearly a third of a second
// to see the response. Now that doesn't happen in practice: most inter-byte intervals
// are actually much smaller than permitted. We could in theory do the MS_INTER_BYTE_TIMEOUT
// timeouts on each individual byte, but that's cumbersome and inefficient given the read
// API we have to work with. So instead we specify the pessimistic maximum, plus a little
// extra to help avoid false hits, and thus see any communications failure a little
// later than we otherwise would see (but not ridiculously later).
//
// Additionally, we allow for any extra timeout duration that has to do with other protocol
// aspects unrelated to inter-byte timing.
//
// Finally, we allow for a garbage collection.
//
long msReadTimeout = MS_INTER_BYTE_TIMEOUT * (cbToRead + 2 /* just being generous */) + msExtraTimeout + MS_GARBAGE_COLLECTION_SPURT;
//
// That all said, that leads to rediculously long timeouts. We got by for a long time with
// a fixed 100ms timeout, and the retry logic above will help us even more. So we prune that
// down
//
msReadTimeout = Math.min(msReadTimeout, MS_MAX_TIMEOUT);
long nsTimerStart = System.nanoTime();
int cbRead = device.read(buffer, ibFirst, cbToRead, msReadTimeout, timeWindow);
if (cbRead == cbToRead)
{
// We got all the data we came for. Just return gracefully
}
else if (cbRead == 0)
{
// Couldn't read all the data in the time allotted.
throw new RobotUsbTimeoutException(nsTimerStart, "%s: unable to read %d bytes in %d ms", debugContext, cbToRead, msReadTimeout);
}
else
{
// An unexpected error occurred. We'll classify as a protocol error as a good guess, as
// we did get *some* data, just not all we were expecting.
logAndThrowProtocol("readIncomingBytes(%s) cbToRead=%d cbRead=%d", debugContext, cbToRead, cbRead);
}
}
}
protected byte readSingleByte(byte[] buffer, int msExtraTimeout, @Nullable TimeWindow timeWindow, String debugContext) throws RobotUsbException, InterruptedException
{
readIncomingBytes(buffer, 0, 1, msExtraTimeout, timeWindow, debugContext);
return buffer[0];
}
//----------------------------------------------------------------------------------------------
// Utility
//----------------------------------------------------------------------------------------------
protected String timeoutMessage(String root, RobotUsbTimeoutException e)
{
return String.format("%s: %s", root, e.getMessage());
}
protected void doExceptionBookkeeping()
{
isSynchronized = false;
}
protected void logAndRethrowTimeout(RobotUsbTimeoutException e, ModernRoboticsRequest request, String message) throws RobotUsbTimeoutException
{
ModernRoboticsRequest requestHeader = ModernRoboticsRequest.newInstance(requestAllocationContext, 0); // Don't log the payload data
System.arraycopy(request.data, 0, requestHeader.data, 0, requestHeader.data.length);
//
RobotLog.ee(TAG, "%s: %s request=%s", device.getSerialNumber(), message, bufferToString(requestHeader.data));
device.logRetainedBuffers(e.nsTimerStart, e.nsTimerExpire, TAG, "recent data on %s", device.getSerialNumber());
doExceptionBookkeeping();
throw e;
}
protected void logAndThrowProtocol(String format, Object... args) throws RobotUsbProtocolException
{
String message = String.format(format, args);
RobotLog.ee(TAG, "%s: %s", device.getSerialNumber(), message);
doExceptionBookkeeping();
throw new RobotUsbProtocolException(message);
}
protected void logAndThrowProtocol(ModernRoboticsRequest request, ModernRoboticsResponse response, String message) throws RobotUsbProtocolException
{
ModernRoboticsRequest requestHeader = ModernRoboticsRequest.newInstance(requestAllocationContext, 0); // Don't log the payload data
System.arraycopy(request.data, 0, requestHeader.data, 0, requestHeader.data.length);
//
ModernRoboticsResponse responseHeader = ModernRoboticsResponse.newInstance(responseAllocationContext, 0); // Don't log the payload data
System.arraycopy(response.data, 0, responseHeader.data, 0, responseHeader.data.length);
//
RobotLog.ee(TAG, "%s: %s: request:%s response:%s", device.getSerialNumber(), message, bufferToString(requestHeader.data), bufferToString(responseHeader.data));
doExceptionBookkeeping();
throw new RobotUsbProtocolException(message);
}
protected static String bufferToString(byte[] buffer)
{
StringBuilder result = new StringBuilder();
result.append("[");
if (buffer.length > 0)
{
result.append(String.format("%02x", buffer[0]));
}
int cbMax = 16;
int cb = Math.min(buffer.length, cbMax);
for (int ib = 1; ib < cb; ++ib)
{
result.append(String.format(" %02x", buffer[ib]));
}
if (cb < buffer.length)
{
result.append(" ...");
}
result.append("]");
return result.toString();
}
}
|
UTF-8
|
Java
| 30,604 |
java
|
ModernRoboticsReaderWriter.java
|
Java
|
[
{
"context": "TY OF SUCH DAMAGE.\n */\n /*\nCopyright (c) 2016-2017 Robert Atkinson\n\nAll rights reserved.\n\nRedistribution and use in ",
"end": 1770,
"score": 0.9998503923416138,
"start": 1755,
"tag": "NAME",
"value": "Robert Atkinson"
}
] | null |
[] |
/*
* Copyright (c) 2014, 2015, 2016 Qualcomm Technologies Inc
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* (subject to the limitations in the disclaimer below) provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Qualcomm Technologies Inc nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS
* SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright (c) 2016-2017 <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) provided that
the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.qualcomm.hardware.modernrobotics.comm;
import android.annotation.SuppressLint;
import android.support.annotation.Nullable;
import com.qualcomm.robotcore.hardware.usb.RobotUsbDevice;
import com.qualcomm.robotcore.util.RobotLog;
import org.firstinspires.ftc.robotcore.internal.system.Deadline;
import org.firstinspires.ftc.robotcore.internal.hardware.TimeWindow;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbException;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbProtocolException;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbTimeoutException;
import org.firstinspires.ftc.robotcore.internal.usb.exception.RobotUsbTooManySequentialErrorsException;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("WeakerAccess")
@SuppressLint("DefaultLocale")
public class ModernRoboticsReaderWriter
{
//----------------------------------------------------------------------------------------------
// State
//----------------------------------------------------------------------------------------------
public static final String TAG = "MRReaderWriter";
public static boolean DEBUG = false;
/**
* The timeouts defined by the MR USB spec are subtle. Our historical timeout of 100ms
* to read the header and the 100ms to read the payload was demonstrably insufficient, as teams
* were hitting the payload timeout in the wild. Per the MR spec, the payload timeout should
* be payload-length-dependent.
*
* Here's the skinny:
*
* The MR spec speaks thusly: "In order to detect a failure of too few Data payload bytes being
* received, a timeout is used. This timeout is set to 10mS. This timeout will start as a soon
* as the initial 0x55 is received. It is reset upon the arrival of each subsequent byte. [...]
* A similar timeout process may be performed by the host. The host may also use a timeout of
* 50mS for receipt of a response. If no response is received within 50mS, then it is assumed
* that either the USB VCP communication link is non-operational, or the controller power is
* not present"
*/
public static int MS_INTER_BYTE_TIMEOUT = 10;
public static int MS_USB_HUB_LATENCY = 2; // this is probably way overkill
public static int MS_REQUEST_RESPONSE_TIMEOUT = 50 + MS_USB_HUB_LATENCY * 2;
/**
* We run on a garbage collected system. That doesn't run very often, and doesn't run back to
* back, only one at a time, but when it does run it shuts things down for 15ms-40ms. One of
* those can happen in the middle of any of our timeouts. So we need to allow for same.
*/
public static int MS_GARBAGE_COLLECTION_SPURT = 40;
/** We made this up: we want to be very generous in trying to recover from failures as we
* read through possibly-old data trying to synchronize, and there's little harm in doing so */
public static int MS_RESYNCH_TIMEOUT = 1000;
public static int MS_FAILURE_WAIT = 40; // per email from MR
public static int MS_COMM_ERROR_WAIT = 100; // historical. we made this up
public static int MS_MAX_TIMEOUT = 100; // we made this up.
public static int MAX_SEQUENTIAL_USB_ERROR_COUNT = 5; // we made this up. Used to be 10, but can tighten with the better sync logic we now have
public final static String COMM_FAILURE_READ = "comm failure read";
public final static String COMM_FAILURE_WRITE = "comm failure write";
public final static String COMM_TIMEOUT_READ = "comm timeout awaiting response (read)";
public final static String COMM_TIMEOUT_WRITE = "comm timeout awaiting response (write)";
public final static String COMM_ERROR_READ = "comm error read";
public final static String COMM_ERROR_WRITE = "comm error write";
public final static String COMM_SYNC_LOST = "comm sync lost";
public final static String COMM_PAYLOAD_ERROR_READ = "comm payload error read";
public final static String COMM_PAYLOAD_ERROR_WRITE = "comm payload error write";
public final static String COMM_TYPE_ERROR_READ = "comm type error read";
public final static String COMM_TYPE_ERROR_WRITE = "comm type error write";
protected final RobotUsbDevice device;
protected int usbSequentialCommReadErrorCount = 0;
protected int usbSequentialCommWriteErrorCount = 0;
protected int usbReadRetryCount = 4;
protected int usbWriteRetryCount = 4;
protected int msUsbReadRetryInterval = 20;
protected int msUsbWriteRetryInterval = 20;
protected boolean isSynchronized = false;
protected Deadline responseDeadline = new Deadline(MS_RESYNCH_TIMEOUT, TimeUnit.MILLISECONDS);
protected ModernRoboticsDatagram.AllocationContext<ModernRoboticsRequest> requestAllocationContext = new ModernRoboticsDatagram.AllocationContext<ModernRoboticsRequest>();
protected ModernRoboticsDatagram.AllocationContext<ModernRoboticsResponse> responseAllocationContext = new ModernRoboticsDatagram.AllocationContext<ModernRoboticsResponse>();
//----------------------------------------------------------------------------------------------
// Construction
//----------------------------------------------------------------------------------------------
public ModernRoboticsReaderWriter(RobotUsbDevice device)
{
this.device = device;
this.device.setDebugRetainBuffers(true);
}
public void throwIfTooManySequentialCommErrors() throws RobotUsbTooManySequentialErrorsException
{
if (device.isOpen())
{
if (this.usbSequentialCommReadErrorCount > MAX_SEQUENTIAL_USB_ERROR_COUNT || this.usbSequentialCommWriteErrorCount > MAX_SEQUENTIAL_USB_ERROR_COUNT)
{
throw new RobotUsbTooManySequentialErrorsException("%s: too many sequential USB comm errors on device", device.getSerialNumber());
}
}
}
public void close()
{
this.device.close();
}
//----------------------------------------------------------------------------------------------
// Reading and writing
//----------------------------------------------------------------------------------------------
public void read(boolean retry, int address, byte[] buffer, @Nullable TimeWindow payloadTimeWindow) throws RobotUsbException, InterruptedException
{
if (DEBUG) RobotLog.vv(TAG, "%s: read(addr=%d cb=%d)", device.getSerialNumber(), address, buffer.length);
RobotUsbException exception = null;
for (int i = 0; i < usbReadRetryCount; i++)
{
if (i > 0)
{
RobotLog.ee(TAG, "%s: retry #%d read(addr=%d cb=%d)", device.getSerialNumber(), i, address, buffer.length);
}
try {
readOnce(address, buffer, payloadTimeWindow);
}
catch (RobotUsbException e)
{
// read failed
if (!this.device.isOpen())
{
return; // silent
}
else if (!retry)
{
RobotLog.ee(TAG, "%s: ignoring failed read(addr=%d cb=%d)", device.getSerialNumber(), address, buffer.length);
return; // ignore failure if we're not asked to retry
}
Thread.sleep(msUsbReadRetryInterval); // always sleep in order to give MR device chance to write to its FTDI chip before we reset same
this.device.resetAndFlushBuffers();
exception = e;
continue;
}
// read succeeded
return;
}
if (exception != null) throw exception;
}
protected void readOnce(int address, byte[] buffer, @Nullable TimeWindow payloadTimeWindow) throws RobotUsbException, InterruptedException
{
ModernRoboticsRequest request = null;
ModernRoboticsResponse response = null;
try {
// Create and send a read request
request = ModernRoboticsRequest.newInstance(requestAllocationContext, 0);
request.setRead(0);
request.setAddress(address);
request.setPayloadLength(buffer.length);
this.device.write(request.data);
try {
// Read the response
response = readResponse(request, payloadTimeWindow);
if (response.isFailure())
{
// In order to avoid having the MR firmware think we might be about to try to update
// it with a new version, we wait a prescribed delay per MR information
Thread.sleep(MS_FAILURE_WAIT);
logAndThrowProtocol(request, response, COMM_FAILURE_READ);
}
else if (response.isRead()
&& response.getFunction()==0
&& response.getAddress()==address
&& response.getPayloadLength()==buffer.length)
{
// Success! All is well.
this.usbSequentialCommReadErrorCount = 0;
System.arraycopy(response.data, ModernRoboticsDatagram.CB_HEADER, buffer, 0, buffer.length);
}
else
{
// Historical code had a sleep here. We don't believe that it's actually
// necessary, but it's harmless, so we keep it (for now) as it's harmless
// and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
logAndThrowProtocol(request, response, COMM_ERROR_READ);
}
}
catch (RobotUsbTimeoutException e)
{
// In *some cases* historical code had a sleep here, too, namely the 'incorrect sync
// bytes' case. In the present code paths, that ends up timing out instead, as our
// readResponse() intrinsically synchronizes. But we add the sleep here for good measure
// as it's harmless, and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
logAndRethrowTimeout(e, request, timeoutMessage(COMM_TIMEOUT_READ, e));
}
}
catch (RobotUsbException e)
{
++usbSequentialCommReadErrorCount;
throw e;
}
finally
{
// proactively reclaim instances
if (response != null) response.close();
if (request != null) request.close();
}
}
public void write(int address, byte[] buffer) throws RobotUsbException, InterruptedException
{
if (DEBUG) RobotLog.vv(TAG, "%s: write(addr=%d cb=%d)", device.getSerialNumber(), address, buffer.length);
// Retry a handful of times before giving up. The thing we have to deal with most here
// is USB transmission errors, which tend in our experience to be intermittent and not
// bursty, so retrying a couple of times seems worthwhile.
//
// Note that the correctness here of doing the write relies on the fact that writes
// are idempotent : some of the writes that appear to fail might instead actually succeed
// w/o our knowing, and there's nothing we can do about that.
//
RobotUsbException exception = null;
for (int i = 0; i < usbWriteRetryCount; i++)
{
if (i > 0)
{
RobotLog.ee(TAG, "%s: retry #%d write(addr=%d cb=%d)", device.getSerialNumber(), i, address, buffer.length);
}
try {
writeOnce(address, buffer);
}
catch (RobotUsbException e)
{
// write failed
if (!this.device.isOpen())
{
return; // silent
}
Thread.sleep(msUsbWriteRetryInterval); // same comment as in read()
this.device.resetAndFlushBuffers();
exception = e;
continue;
}
// write succeeded
return;
}
// If that didn't fix things, then fail : the write will (presumably) change
// state if it succeeds, so we need to eithe make the change happen or let the
// caller know that it won't
if (exception != null) throw exception;
}
protected void writeOnce(int address, byte[] buffer) throws RobotUsbException, InterruptedException
{
ModernRoboticsRequest request = null;
ModernRoboticsResponse response = null;
try {
// Create and send a write request
request = ModernRoboticsRequest.newInstance(requestAllocationContext, buffer.length);
request.setWrite(0);
request.setAddress(address);
request.setPayload(buffer);
this.device.write(request.data);
try {
// Read the response
response = readResponse(request, null);
if (response.isFailure())
{
// In order to avoid having the MR firmware think we might be about to try to update
// it with a new version, we wait a prescribed delay per MR information
Thread.sleep(MS_FAILURE_WAIT);
this.logAndThrowProtocol(request, response, COMM_FAILURE_WRITE);
}
else if (response.isWrite()
&& response.getFunction()==0
&& response.getAddress()==address
&& response.getPayloadLength()==0)
{
// All is well
this.usbSequentialCommWriteErrorCount = 0;
}
else
{
// Historical code had a sleep here. We don't believe that it's actually
// necessary, but it's harmless, so we keep it (for now) as it's harmless
// and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
this.logAndThrowProtocol(request, response, COMM_ERROR_WRITE);
}
}
catch (RobotUsbTimeoutException e)
{
// In *some cases* historical code had a sleep here, too, namely the 'incorrect sync
// bytes' case. In the present code paths, that ends up timing out instead, as our
// readResponse() intrinsically synchronizes. But we add the sleep here for good measure
// as it's harmless, and only very rarely happens.
Thread.sleep(MS_COMM_ERROR_WAIT);
this.logAndRethrowTimeout(e, request, timeoutMessage(COMM_TIMEOUT_WRITE, e));
}
}
catch (RobotUsbException e)
{
++this.usbSequentialCommWriteErrorCount;
throw e;
}
finally
{
if (response != null) response.close();
if (request != null) request.close();
}
}
//----------------------------------------------------------------------------------------------
// Response reading
//----------------------------------------------------------------------------------------------
protected ModernRoboticsResponse readResponse(ModernRoboticsRequest request, @Nullable TimeWindow payloadTimeWindow) throws RobotUsbException, InterruptedException
{
responseDeadline.reset();
while (!responseDeadline.hasExpired())
{
// Synchronization bytes by their nature occur only at the start of USB packets. So if
// we're not currently there, then we can't possibly be synchronized.
if (!device.mightBeAtUsbPacketStart())
{
isSynchronized = false;
}
// Read the header, synchronizing carefully if we need to
ModernRoboticsResponse header = ModernRoboticsResponse.newInstance(responseAllocationContext, 0);
try {
if (!isSynchronized)
{
byte[] singleByte = new byte[1];
byte[] headerSuffix = new byte[ModernRoboticsDatagram.CB_HEADER-2];
// Synchronization bytes by their nature occur only at the start of USB packets.
// So if we know we're not at such a boundary, skip along until the next one.
device.skipToLikelyUsbPacketStart();
// Synchronize by looking for the first synchronization byte
if (readSingleByte(singleByte, MS_REQUEST_RESPONSE_TIMEOUT, null, "sync0") != ModernRoboticsResponse.syncBytes[0])
{
continue;
}
// Having found the first, if we don't next see the second, then go back to looking for the first
if (readSingleByte(singleByte, 0, null, "sync1") != ModernRoboticsResponse.syncBytes[1])
{
continue;
}
// Read the remaining header bytes
readIncomingBytes(headerSuffix, 0, headerSuffix.length, 0, null, "syncSuffix");
// Assemble the header from the pieces
System.arraycopy(ModernRoboticsResponse.syncBytes, 0, header.data, 0, 2);
System.arraycopy(headerSuffix, 0, header.data, 2, headerSuffix.length);
}
else
{
readIncomingBytes(header.data, 0, header.data.length, MS_REQUEST_RESPONSE_TIMEOUT, null, "header");
if (!header.syncBytesValid())
{
// We've lost synchronization, yet we received *some* data. Thus, since there
// is no retransmission in the USB protocol, we're never going to get the response
// that we were looking for. So get out of Dodge with an error.
logAndThrowProtocol(request, header, COMM_SYNC_LOST);
}
}
// Make sure the request and response types match
if (!header.isFailure())
{
if (request.isRead() != header.isRead() || request.getFunction() != header.getFunction())
{
logAndThrowProtocol(request, header, request.isWrite() ? COMM_TYPE_ERROR_WRITE: COMM_TYPE_ERROR_READ);
}
}
// How big of a payload is expected in the response? It should match the expectations
// set in the request. If it doesn't, get out of Dodge.
int cbPayloadExpected = header.isFailure()
? 0
: request.isWrite()
? 0
: request.getPayloadLength();
if (cbPayloadExpected != header.getPayloadLength())
{
// We're out of sync some how
logAndThrowProtocol(request, header, request.isWrite() ? COMM_PAYLOAD_ERROR_WRITE: COMM_PAYLOAD_ERROR_READ);
}
// Assemble a response and read the payload data thereinto
ModernRoboticsResponse result = ModernRoboticsResponse.newInstance(responseAllocationContext, header.getPayloadLength());
System.arraycopy(header.data, 0, result.data, 0, header.data.length);
readIncomingBytes(result.data, header.data.length, header.getPayloadLength(), 0, payloadTimeWindow, "payload");
// We're ok to go more quickly the next time
isSynchronized = true;
return result;
}
finally
{
if (header != null) header.close();
}
}
throw new RobotUsbTimeoutException(responseDeadline.startTimeNanoseconds(), "timeout waiting %d ms for response", responseDeadline.getDuration(TimeUnit.MILLISECONDS));
}
protected void readIncomingBytes(byte[] buffer, int ibFirst, int cbToRead, int msExtraTimeout, @Nullable TimeWindow timeWindow, String debugContext) throws RobotUsbException, InterruptedException
{
if (cbToRead > 0)
{
// In theory, per the MR spec, we might see MS_INTER_BYTE_TIMEOUT elapse
// between each incoming byte. For a long-ish read response, that can amount
// to some significant time: we routinely read 31 byte swaths of data on the
// motor controller, for example, which would amount to nearly a third of a second
// to see the response. Now that doesn't happen in practice: most inter-byte intervals
// are actually much smaller than permitted. We could in theory do the MS_INTER_BYTE_TIMEOUT
// timeouts on each individual byte, but that's cumbersome and inefficient given the read
// API we have to work with. So instead we specify the pessimistic maximum, plus a little
// extra to help avoid false hits, and thus see any communications failure a little
// later than we otherwise would see (but not ridiculously later).
//
// Additionally, we allow for any extra timeout duration that has to do with other protocol
// aspects unrelated to inter-byte timing.
//
// Finally, we allow for a garbage collection.
//
long msReadTimeout = MS_INTER_BYTE_TIMEOUT * (cbToRead + 2 /* just being generous */) + msExtraTimeout + MS_GARBAGE_COLLECTION_SPURT;
//
// That all said, that leads to rediculously long timeouts. We got by for a long time with
// a fixed 100ms timeout, and the retry logic above will help us even more. So we prune that
// down
//
msReadTimeout = Math.min(msReadTimeout, MS_MAX_TIMEOUT);
long nsTimerStart = System.nanoTime();
int cbRead = device.read(buffer, ibFirst, cbToRead, msReadTimeout, timeWindow);
if (cbRead == cbToRead)
{
// We got all the data we came for. Just return gracefully
}
else if (cbRead == 0)
{
// Couldn't read all the data in the time allotted.
throw new RobotUsbTimeoutException(nsTimerStart, "%s: unable to read %d bytes in %d ms", debugContext, cbToRead, msReadTimeout);
}
else
{
// An unexpected error occurred. We'll classify as a protocol error as a good guess, as
// we did get *some* data, just not all we were expecting.
logAndThrowProtocol("readIncomingBytes(%s) cbToRead=%d cbRead=%d", debugContext, cbToRead, cbRead);
}
}
}
protected byte readSingleByte(byte[] buffer, int msExtraTimeout, @Nullable TimeWindow timeWindow, String debugContext) throws RobotUsbException, InterruptedException
{
readIncomingBytes(buffer, 0, 1, msExtraTimeout, timeWindow, debugContext);
return buffer[0];
}
//----------------------------------------------------------------------------------------------
// Utility
//----------------------------------------------------------------------------------------------
protected String timeoutMessage(String root, RobotUsbTimeoutException e)
{
return String.format("%s: %s", root, e.getMessage());
}
protected void doExceptionBookkeeping()
{
isSynchronized = false;
}
protected void logAndRethrowTimeout(RobotUsbTimeoutException e, ModernRoboticsRequest request, String message) throws RobotUsbTimeoutException
{
ModernRoboticsRequest requestHeader = ModernRoboticsRequest.newInstance(requestAllocationContext, 0); // Don't log the payload data
System.arraycopy(request.data, 0, requestHeader.data, 0, requestHeader.data.length);
//
RobotLog.ee(TAG, "%s: %s request=%s", device.getSerialNumber(), message, bufferToString(requestHeader.data));
device.logRetainedBuffers(e.nsTimerStart, e.nsTimerExpire, TAG, "recent data on %s", device.getSerialNumber());
doExceptionBookkeeping();
throw e;
}
protected void logAndThrowProtocol(String format, Object... args) throws RobotUsbProtocolException
{
String message = String.format(format, args);
RobotLog.ee(TAG, "%s: %s", device.getSerialNumber(), message);
doExceptionBookkeeping();
throw new RobotUsbProtocolException(message);
}
protected void logAndThrowProtocol(ModernRoboticsRequest request, ModernRoboticsResponse response, String message) throws RobotUsbProtocolException
{
ModernRoboticsRequest requestHeader = ModernRoboticsRequest.newInstance(requestAllocationContext, 0); // Don't log the payload data
System.arraycopy(request.data, 0, requestHeader.data, 0, requestHeader.data.length);
//
ModernRoboticsResponse responseHeader = ModernRoboticsResponse.newInstance(responseAllocationContext, 0); // Don't log the payload data
System.arraycopy(response.data, 0, responseHeader.data, 0, responseHeader.data.length);
//
RobotLog.ee(TAG, "%s: %s: request:%s response:%s", device.getSerialNumber(), message, bufferToString(requestHeader.data), bufferToString(responseHeader.data));
doExceptionBookkeeping();
throw new RobotUsbProtocolException(message);
}
protected static String bufferToString(byte[] buffer)
{
StringBuilder result = new StringBuilder();
result.append("[");
if (buffer.length > 0)
{
result.append(String.format("%02x", buffer[0]));
}
int cbMax = 16;
int cb = Math.min(buffer.length, cbMax);
for (int ib = 1; ib < cb; ++ib)
{
result.append(String.format(" %02x", buffer[ib]));
}
if (cb < buffer.length)
{
result.append(" ...");
}
result.append("]");
return result.toString();
}
}
| 30,595 | 0.593158 | 0.588812 | 620 | 48.36129 | 40.84544 | 199 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735484 | false | false |
0
|
51db69a984d8284d069499951d73c8f5a94b3414
| 884,763,288,719 |
00242f1bed28157fd45eccc5b4fb7126c19b44b9
|
/D05-Hackathon-master/Proyecto/Acme-Rebujito/src/main/java/services/SystemRequirementsService.java
|
4df4ff28411b2d2337993a2c4836a68b1b682db6
|
[] |
no_license
|
juanmiguelruiz/DP2
|
https://github.com/juanmiguelruiz/DP2
|
13961224645a1b1ac8cedf568a9b69fc2d727353
|
a5afdbe5e3ababb99069e12716ade3f0b43e08e4
|
refs/heads/master
| 2020-08-29T15:44:25.624000 | 2020-06-03T15:13:24 | 2020-06-03T15:13:24 | 218,077,147 | 0 | 0 | null | false | 2020-10-13T19:07:55 | 2019-10-28T15:18:29 | 2020-06-03T15:13:56 | 2020-10-13T19:07:54 | 415,072 | 0 | 0 | 26 |
Java
| false | false |
package services;
import java.util.Collection;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import repositories.SystemRequirementsRepository;
import domain.SystemRequirements;
@Service
@Transactional
public class SystemRequirementsService {
@Autowired
private SystemRequirementsRepository systemRequirementsRepository;
public SystemRequirements create() {
final SystemRequirements sr = new SystemRequirements();
return sr;
}
public Collection<SystemRequirements> findAll() {
return this.systemRequirementsRepository.findAll();
}
public SystemRequirements save(final SystemRequirements sr) {
Assert.notNull(sr);
final SystemRequirements sn = this.systemRequirementsRepository.save(sr);
Assert.notNull(sn);
Assert.isTrue(this.systemRequirementsRepository.exists(sn.getId()));
return sn;
}
public String getSystemName() {
return this.systemRequirementsRepository.getSystemName();
}
public String getBanner() {
return this.systemRequirementsRepository.getBanner();
}
public String getWelcomeMessageEn() {
return this.systemRequirementsRepository.getWelcomeMessageEn();
}
public String getWelcomeMessageEs() {
return this.systemRequirementsRepository.getWelcomeMessageEs();
}
public Collection<String> getWrongWords() {
return this.systemRequirementsRepository.getWrongWords();
}
public Integer getTimeCacheFinder() {
return this.systemRequirementsRepository.getTimeCacheFinder();
}
public Integer maxSearch() {
return this.systemRequirementsRepository.getMaxSearch();
}
// Other business methods
public boolean checkWrongWords(final String string) {
Assert.notNull(string);
int cont = 0;
final Collection<String> wrongWords = this.getWrongWords();
string.replaceAll(".*'.*|.*`.*|.*Ž.*", "");
for (final String wrongWord : wrongWords) {
wrongWord.replaceAll(".*'.*|.*`.*|.*Ž.*", "");
final boolean match = string.matches("(?i).*" + wrongWord + ".*");
if (match)
cont++;
}
return cont > 0;
}
}
|
UTF-8
|
Java
| 2,151 |
java
|
SystemRequirementsService.java
|
Java
|
[] | null |
[] |
package services;
import java.util.Collection;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import repositories.SystemRequirementsRepository;
import domain.SystemRequirements;
@Service
@Transactional
public class SystemRequirementsService {
@Autowired
private SystemRequirementsRepository systemRequirementsRepository;
public SystemRequirements create() {
final SystemRequirements sr = new SystemRequirements();
return sr;
}
public Collection<SystemRequirements> findAll() {
return this.systemRequirementsRepository.findAll();
}
public SystemRequirements save(final SystemRequirements sr) {
Assert.notNull(sr);
final SystemRequirements sn = this.systemRequirementsRepository.save(sr);
Assert.notNull(sn);
Assert.isTrue(this.systemRequirementsRepository.exists(sn.getId()));
return sn;
}
public String getSystemName() {
return this.systemRequirementsRepository.getSystemName();
}
public String getBanner() {
return this.systemRequirementsRepository.getBanner();
}
public String getWelcomeMessageEn() {
return this.systemRequirementsRepository.getWelcomeMessageEn();
}
public String getWelcomeMessageEs() {
return this.systemRequirementsRepository.getWelcomeMessageEs();
}
public Collection<String> getWrongWords() {
return this.systemRequirementsRepository.getWrongWords();
}
public Integer getTimeCacheFinder() {
return this.systemRequirementsRepository.getTimeCacheFinder();
}
public Integer maxSearch() {
return this.systemRequirementsRepository.getMaxSearch();
}
// Other business methods
public boolean checkWrongWords(final String string) {
Assert.notNull(string);
int cont = 0;
final Collection<String> wrongWords = this.getWrongWords();
string.replaceAll(".*'.*|.*`.*|.*Ž.*", "");
for (final String wrongWord : wrongWords) {
wrongWord.replaceAll(".*'.*|.*`.*|.*Ž.*", "");
final boolean match = string.matches("(?i).*" + wrongWord + ".*");
if (match)
cont++;
}
return cont > 0;
}
}
| 2,151 | 0.756631 | 0.7557 | 96 | 21.375 | 24.259127 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.260417 | false | false |
0
|
97d7589d6635674a3d959046ced0d829c941346c
| 7,567,732,394,664 |
845ee455b46c20034a22e11d7bc99490ddaa1008
|
/JavaFX.Examen.FXCodeGenerator.JavierAlejandroFuentesOchoa/gen/dad/agenda/model/Identificable.java
|
897c4597553763833b897e551135e66ff13f0813
|
[] |
no_license
|
Jaxier/dadEjercicios
|
https://github.com/Jaxier/dadEjercicios
|
c96934fcae15589fa78ad0ccc5b9136fbfd5780e
|
4c2a9da4085ca243e2f1c4d49401654c00755e62
|
refs/heads/master
| 2021-09-05T07:34:16.351000 | 2018-01-25T08:37:31 | 2018-01-25T08:37:31 | 111,685,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dad.agenda.model;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
public class Identificable {
private LongProperty id;
public Identificable() {
id = new SimpleLongProperty(this, "id");
}
public Long getId() {
return this.idProperty().get();
}
public void setId(final Long id) {
this.idProperty().set(id);
}
public LongProperty idProperty() {
return this.id;
}
}
|
UTF-8
|
Java
| 439 |
java
|
Identificable.java
|
Java
|
[] | null |
[] |
package dad.agenda.model;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
public class Identificable {
private LongProperty id;
public Identificable() {
id = new SimpleLongProperty(this, "id");
}
public Long getId() {
return this.idProperty().get();
}
public void setId(final Long id) {
this.idProperty().set(id);
}
public LongProperty idProperty() {
return this.id;
}
}
| 439 | 0.722096 | 0.722096 | 25 | 16.559999 | 16.429438 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.04 | false | false |
0
|
a1116c438614162bbb653d4facd2ed22796e696f
| 25,134,148,642,899 |
28870e816cd263848753f9bae5c3279afcc38ace
|
/enginewithadvancedopengl/src/engine/graphics/text/TextMaster.java
|
37323c35dd25464dd2dec9621ad8ad5d876de49a
|
[
"Apache-2.0"
] |
permissive
|
sharhar/LudumDareGame
|
https://github.com/sharhar/LudumDareGame
|
abaf7b818de73c9f885d1b9cc0cf432bc13d3976
|
1e74f67bcff1a6d6d537bd03d07ae1ff4e92ed25
|
refs/heads/master
| 2021-01-19T03:27:00.791000 | 2016-06-06T23:52:34 | 2016-06-06T23:52:34 | 43,473,026 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package engine.graphics.text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import engine.utils.Loader;
public class TextMaster {
private static Map<FontType, List<Text>> texts = new HashMap<FontType, List<Text>>();
public static void init(){
FontShader.init();
}
public static void render(){
FontRenderer.render(texts);
}
public static void loadText(Text text){
FontType font = text.getFont();
TextMeshData data = font.loadText(text);
int vao = Loader.loadToVAO(data.getVertexPositions(), data.getTextureCoords());
text.setMeshInfo(vao, data.getVertexCount());
List<Text> textBatch = texts.get(font);
if(textBatch == null){
textBatch = new ArrayList<Text>();
texts.put(font, textBatch);
}
textBatch.add(text);
}
public static void removeText(Text text){
List<Text> textBatch = texts.get(text.getFont());
textBatch.remove(text);
if(textBatch.isEmpty()){
texts.remove(texts.get(text.getFont()));
}
}
public static void cleanUp(){
FontShader.current.cleanUp();
}
}
|
UTF-8
|
Java
| 1,082 |
java
|
TextMaster.java
|
Java
|
[] | null |
[] |
package engine.graphics.text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import engine.utils.Loader;
public class TextMaster {
private static Map<FontType, List<Text>> texts = new HashMap<FontType, List<Text>>();
public static void init(){
FontShader.init();
}
public static void render(){
FontRenderer.render(texts);
}
public static void loadText(Text text){
FontType font = text.getFont();
TextMeshData data = font.loadText(text);
int vao = Loader.loadToVAO(data.getVertexPositions(), data.getTextureCoords());
text.setMeshInfo(vao, data.getVertexCount());
List<Text> textBatch = texts.get(font);
if(textBatch == null){
textBatch = new ArrayList<Text>();
texts.put(font, textBatch);
}
textBatch.add(text);
}
public static void removeText(Text text){
List<Text> textBatch = texts.get(text.getFont());
textBatch.remove(text);
if(textBatch.isEmpty()){
texts.remove(texts.get(text.getFont()));
}
}
public static void cleanUp(){
FontShader.current.cleanUp();
}
}
| 1,082 | 0.707948 | 0.707948 | 47 | 22.021276 | 20.391373 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.744681 | false | false |
0
|
1714fe711b6871c3d8ac889774d03589d0b0eaf7
| 28,424,093,593,318 |
6d63dd5c08fbbb6c11ff1b2947ae5b6bb76c6e02
|
/src/main/java/com/beesndraw/web/Trade.java
|
4b54aef4c9d5ff1b556e1b400e16f9c8bc1ad4a1
|
[] |
no_license
|
beesndraw/frontend
|
https://github.com/beesndraw/frontend
|
e6032f64ca9331091c1f8603e4d0110c3de66981
|
00e3fa53eb42161551d1934607838f0fd248e5dc
|
refs/heads/master
| 2021-04-27T00:01:52.233000 | 2018-04-15T15:47:49 | 2018-04-15T15:47:49 | 123,745,981 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.beesndraw.web;
import java.text.ParseException;
import java.util.Date;
public class Trade {
int id;
String strategy;
String side;
double quantity;
double amount;
double price;
Date date;
double tradePl;
double profileLoss;
String position;
boolean round;
public Trade(int id, String strategy, String side, double quantity, double amount, double price, Date date, double tradePl,
double profileLoss, String position, boolean round) {
super();
this.id = id;
this.strategy = strategy;
this.side = side;
this.quantity = quantity;
this.amount = amount;
this.price = price;
this.date = date;
this.tradePl = tradePl;
this.profileLoss = profileLoss;
this.position = position;
this.round = round;
}
public boolean isRound() {
return this.round;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStrategy() {
return strategy;
}
public void setStrategy(String strategy) {
this.strategy = strategy;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public double getTradePl() {
return tradePl;
}
public double getProfileLoss() {
return profileLoss;
}
public void setProfileLoss(double profileLoss) {
this.profileLoss = profileLoss;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public static Trade parseString(String string) {
int i = 0;
try {
int id;
String strategy;
String side;
double quantity;
double amount;
double price;
Date date;
double tradePl;
double profileLoss;
String position;
//Id,Strategy,Side,Quantity,Amount,Price,Date/Time,Trade P/L,P/L,Position,,,,,
//[1, Double_D_Strat_Alert_1(Sell @1.0324), Sell to Open, -1, -125000, $1.03 , 6/20/17 19:55, , $12.50 , -125000]
String seperator = ",";
if(string.contains(";")) {
seperator = ";";
}
String [] rawData = string.split(seperator);
if(rawData.length == 0) {
System.out.println("Ingonred : " + string);
return null; //This row is proabaly not valid data. log this so we dont' loose this infor
}
try {
id = Integer.parseInt(rawData[i++]);
}catch(NumberFormatException e) {
System.out.println("Ingonred : " + string);
return null; //This row is proabaly not valid data.
}
strategy = rawData[i++];
side = rawData[i++];
try {
quantity = Double.parseDouble(rawData[i++]);
}catch(NumberFormatException e) {
throw e;
}
try{
amount = Double.parseDouble(rawData[i++]);
}catch(NumberFormatException e) {
throw e;
}
String priceString = rawData[i++];
price = parseDouble(priceString);
date = null; //6/20/17 19:55
String dateStr = rawData[i++];
try {
date = ReportGenerator.DATE_FORMAT.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
date = null;
}
String tradePLString = rawData[i++];
// if(tradePLString.isEmpty())
// return null;
tradePl = parseDouble(tradePLString);
boolean round = false;
if(!tradePLString.isEmpty())
round = true;
String profiltLossString = rawData[i++];
profileLoss = parseDouble(profiltLossString);
position = rawData[i++];;
return new Trade(id, strategy, side,quantity, amount, price, date, tradePl, profileLoss, position, round);
}catch(Exception e) {
System.err.println("Skipping this row. Failed to parse record: " + string);
System.err.println(e.getMessage());
return null;
}
}
static double parseDouble(String data) {
if(!data.isEmpty()) {
try {
double multipler = 1;
if(data.contains(","))
data = data.replaceAll(",", "");
if(data.startsWith("(")) {
data = data.substring(1);
multipler = -1;
}
if(data.startsWith("\"")) {
data = data.substring(1);
}
if(data.startsWith("$")) {
data = data.substring(1);
}
if(data.endsWith(")")) {
data = data.substring(0, data.length() - 1);
}
if(data.endsWith("\"")) {
data = data.substring(0, data.length() - 1);
}
return Double.parseDouble(data) * multipler;
}catch(NumberFormatException e) {
throw e;
}
}
else {
return 0.0;
}
}
@Override
public String toString() {
return "Trade [id=" + id + ", strategy=" + strategy + ", side=" + side + ", quantity=" + quantity + ", amount="
+ amount + ", price=" + price + ", date=" + date + ", tradePl=" + tradePl + ", profileLoss="
+ profileLoss + ", position=" + position + "]";
}
}
|
UTF-8
|
Java
| 4,923 |
java
|
Trade.java
|
Java
|
[] | null |
[] |
package com.beesndraw.web;
import java.text.ParseException;
import java.util.Date;
public class Trade {
int id;
String strategy;
String side;
double quantity;
double amount;
double price;
Date date;
double tradePl;
double profileLoss;
String position;
boolean round;
public Trade(int id, String strategy, String side, double quantity, double amount, double price, Date date, double tradePl,
double profileLoss, String position, boolean round) {
super();
this.id = id;
this.strategy = strategy;
this.side = side;
this.quantity = quantity;
this.amount = amount;
this.price = price;
this.date = date;
this.tradePl = tradePl;
this.profileLoss = profileLoss;
this.position = position;
this.round = round;
}
public boolean isRound() {
return this.round;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStrategy() {
return strategy;
}
public void setStrategy(String strategy) {
this.strategy = strategy;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public double getTradePl() {
return tradePl;
}
public double getProfileLoss() {
return profileLoss;
}
public void setProfileLoss(double profileLoss) {
this.profileLoss = profileLoss;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public static Trade parseString(String string) {
int i = 0;
try {
int id;
String strategy;
String side;
double quantity;
double amount;
double price;
Date date;
double tradePl;
double profileLoss;
String position;
//Id,Strategy,Side,Quantity,Amount,Price,Date/Time,Trade P/L,P/L,Position,,,,,
//[1, Double_D_Strat_Alert_1(Sell @1.0324), Sell to Open, -1, -125000, $1.03 , 6/20/17 19:55, , $12.50 , -125000]
String seperator = ",";
if(string.contains(";")) {
seperator = ";";
}
String [] rawData = string.split(seperator);
if(rawData.length == 0) {
System.out.println("Ingonred : " + string);
return null; //This row is proabaly not valid data. log this so we dont' loose this infor
}
try {
id = Integer.parseInt(rawData[i++]);
}catch(NumberFormatException e) {
System.out.println("Ingonred : " + string);
return null; //This row is proabaly not valid data.
}
strategy = rawData[i++];
side = rawData[i++];
try {
quantity = Double.parseDouble(rawData[i++]);
}catch(NumberFormatException e) {
throw e;
}
try{
amount = Double.parseDouble(rawData[i++]);
}catch(NumberFormatException e) {
throw e;
}
String priceString = rawData[i++];
price = parseDouble(priceString);
date = null; //6/20/17 19:55
String dateStr = rawData[i++];
try {
date = ReportGenerator.DATE_FORMAT.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
date = null;
}
String tradePLString = rawData[i++];
// if(tradePLString.isEmpty())
// return null;
tradePl = parseDouble(tradePLString);
boolean round = false;
if(!tradePLString.isEmpty())
round = true;
String profiltLossString = rawData[i++];
profileLoss = parseDouble(profiltLossString);
position = rawData[i++];;
return new Trade(id, strategy, side,quantity, amount, price, date, tradePl, profileLoss, position, round);
}catch(Exception e) {
System.err.println("Skipping this row. Failed to parse record: " + string);
System.err.println(e.getMessage());
return null;
}
}
static double parseDouble(String data) {
if(!data.isEmpty()) {
try {
double multipler = 1;
if(data.contains(","))
data = data.replaceAll(",", "");
if(data.startsWith("(")) {
data = data.substring(1);
multipler = -1;
}
if(data.startsWith("\"")) {
data = data.substring(1);
}
if(data.startsWith("$")) {
data = data.substring(1);
}
if(data.endsWith(")")) {
data = data.substring(0, data.length() - 1);
}
if(data.endsWith("\"")) {
data = data.substring(0, data.length() - 1);
}
return Double.parseDouble(data) * multipler;
}catch(NumberFormatException e) {
throw e;
}
}
else {
return 0.0;
}
}
@Override
public String toString() {
return "Trade [id=" + id + ", strategy=" + strategy + ", side=" + side + ", quantity=" + quantity + ", amount="
+ amount + ", price=" + price + ", date=" + date + ", tradePl=" + tradePl + ", profileLoss="
+ profileLoss + ", position=" + position + "]";
}
}
| 4,923 | 0.637619 | 0.625838 | 206 | 22.898058 | 21.625772 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.014563 | false | false |
0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.