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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b4ae226c69599749c0f27f425f82e90f16f830a0 | 33,835,752,410,459 | 5c9fea0687022c6795b33e32e7146a15f29dfbae | /PatientSOA/src/com/perficient/pojo/PftServiceDetails.java | 9a6237612278fc4392f4ba801c0c260ffb1cb3c6 | []
| no_license | SChinnamutu/SpringMethodLevelSecurity | https://github.com/SChinnamutu/SpringMethodLevelSecurity | 2ba89f576bf5ad581518290000853de0ee9dd87e | 5e5e6945f1831dd9bbf78209398f8541f6399836 | refs/heads/master | 2021-01-22T07:51:54.574000 | 2017-05-27T09:10:08 | 2017-05-27T09:10:08 | 92,580,031 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.perficient.pojo;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="PFT_SERVICE_DETAILS")
public class PftServiceDetails {
@Id
@Column(name="PSD_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="PSD_SERVICE_ID")
private int serviceId;
@Column(name="PSD_SERVICE_NAME")
private String serviceName;
//@Column(name="PSD_SERVICE_HASHKEY")
//private String hashKey;
/*@OneToMany(fetch=FetchType.EAGER, targetEntity=PftServiceFieldDetail.class, cascade=CascadeType.ALL)
@JoinColumn(name = "PSD_SERVICE_ID", referencedColumnName="PSFD_SERVICE_ID")
private Set<PftServiceFieldDetail> pftServiceFieldDetail = new HashSet<PftServiceFieldDetail>();
*/
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="PSFD_SERVICE_ID")
private Set<PftServiceFieldDetail> pftServiceFieldDetail;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getServiceId() {
return serviceId;
}
public void setServiceId(int serviceId) {
this.serviceId = serviceId;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/*public String getHashKey() {
return hashKey;
}
public void setHashKey(String hashKey) {
this.hashKey = hashKey;
}
*/
/*@JoinColumn
@OneToMany(fetch = FetchType.LAZY,mappedBy="PSFD_SERVICE_ID")*/
public Set<PftServiceFieldDetail> getPftServiceFieldDetail() {
return pftServiceFieldDetail;
}
public void setPftServiceFieldDetail(
Set<PftServiceFieldDetail> pftServiceFieldDetail) {
this.pftServiceFieldDetail = pftServiceFieldDetail;
}
}
| UTF-8 | Java | 1,980 | java | PftServiceDetails.java | Java | []
| null | []
| package com.perficient.pojo;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="PFT_SERVICE_DETAILS")
public class PftServiceDetails {
@Id
@Column(name="PSD_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="PSD_SERVICE_ID")
private int serviceId;
@Column(name="PSD_SERVICE_NAME")
private String serviceName;
//@Column(name="PSD_SERVICE_HASHKEY")
//private String hashKey;
/*@OneToMany(fetch=FetchType.EAGER, targetEntity=PftServiceFieldDetail.class, cascade=CascadeType.ALL)
@JoinColumn(name = "PSD_SERVICE_ID", referencedColumnName="PSFD_SERVICE_ID")
private Set<PftServiceFieldDetail> pftServiceFieldDetail = new HashSet<PftServiceFieldDetail>();
*/
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="PSFD_SERVICE_ID")
private Set<PftServiceFieldDetail> pftServiceFieldDetail;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getServiceId() {
return serviceId;
}
public void setServiceId(int serviceId) {
this.serviceId = serviceId;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/*public String getHashKey() {
return hashKey;
}
public void setHashKey(String hashKey) {
this.hashKey = hashKey;
}
*/
/*@JoinColumn
@OneToMany(fetch = FetchType.LAZY,mappedBy="PSFD_SERVICE_ID")*/
public Set<PftServiceFieldDetail> getPftServiceFieldDetail() {
return pftServiceFieldDetail;
}
public void setPftServiceFieldDetail(
Set<PftServiceFieldDetail> pftServiceFieldDetail) {
this.pftServiceFieldDetail = pftServiceFieldDetail;
}
}
| 1,980 | 0.766162 | 0.766162 | 84 | 22.571428 | 22.343256 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 1 |
e42e6ffb9eba420b188a2c345602d041342d725a | 38,465,727,120,760 | 96d85de0d7d7d84d0b7efa6042b30a5d97f81895 | /src/Finonnaci.java | e03067e9248916a9480e074682b6160af0610dcf | []
| no_license | shrijanabakbak/SampleTry | https://github.com/shrijanabakbak/SampleTry | c7ee1361688cfbe2f4b1b678dd1f10ff13225a05 | 252d26cd1b018472ef41d6c6778cadd08c9f0c0f | refs/heads/main | 2023-04-29T21:41:32.731000 | 2021-05-24T16:31:09 | 2021-05-24T16:31:09 | 370,417,721 | 0 | 0 | null | true | 2021-05-24T16:30:17 | 2021-05-24T16:30:17 | 2021-05-24T16:22:06 | 2021-05-24T16:23:43 | 0 | 0 | 0 | 0 | null | false | false | //
//public class Finonnaci {
// static int n1=0, n2=1, n3=0;
// static void printFibo( int count) {
//
// }
// public static void main(String[] args) {
// int count=10;
// System.out.println(" ");
// }
//}
//------recursion relation-------
//tree method, master theorem, (back) substitution
// T(n)=T(n-1)+T(n-2)+c (c for constant time)
// t(n)=t(n-1)+t(n-1)+c (t-2) lai we can ignore since it runs 1 time less
//t(n)=2t(n-1)+c----------- eqn i
//putting n=n-1 in eqn i
//t(n-1)=2t(n-1-1)+c
//t(n-1)=2t(n-2)+c)
//putting value of t in eqn i
//t(n)=2*2t(n-2)+c
//t(n)=4t(n-2)+c-------eqn ii
//t(n-2)=2t(n-2-1) + c
//t(n-2)=2t(n-3)+c
//putting value of t(n-2) in eqn ii
//t(n)=4*2t(n-3)+c+c
//t(n)=8t(n-3)+c----------eqn iii
//n=n-3 eqn 1
//t(n-3)=2t(n-3-1)+c
//t(n-3)=2t(n-3)+c
// putting value of t(n-3) in eqn iii
//t(n)=8*2t(n-4)+c+c
//t(n)=16t(n-4)+c
// for kth term
//t(n)=2^k(n-k)+c
// t(n)= 2^nt(n-n)+c
//t(n)= 2^nt(0)+c is the worst time complexity
public class Finonnaci{
public static void main (String[] args) {
int n1=0, n2=1, n3,i, count=10;
System.out.println(n1+" "+n2);
for (i=2; i<count; i++) {
n3=n1+n2;
System.out.println(" "+ n3);
n1=n2;
n2=n3;
}
}
} | UTF-8 | Java | 1,214 | java | Finonnaci.java | Java | []
| null | []
| //
//public class Finonnaci {
// static int n1=0, n2=1, n3=0;
// static void printFibo( int count) {
//
// }
// public static void main(String[] args) {
// int count=10;
// System.out.println(" ");
// }
//}
//------recursion relation-------
//tree method, master theorem, (back) substitution
// T(n)=T(n-1)+T(n-2)+c (c for constant time)
// t(n)=t(n-1)+t(n-1)+c (t-2) lai we can ignore since it runs 1 time less
//t(n)=2t(n-1)+c----------- eqn i
//putting n=n-1 in eqn i
//t(n-1)=2t(n-1-1)+c
//t(n-1)=2t(n-2)+c)
//putting value of t in eqn i
//t(n)=2*2t(n-2)+c
//t(n)=4t(n-2)+c-------eqn ii
//t(n-2)=2t(n-2-1) + c
//t(n-2)=2t(n-3)+c
//putting value of t(n-2) in eqn ii
//t(n)=4*2t(n-3)+c+c
//t(n)=8t(n-3)+c----------eqn iii
//n=n-3 eqn 1
//t(n-3)=2t(n-3-1)+c
//t(n-3)=2t(n-3)+c
// putting value of t(n-3) in eqn iii
//t(n)=8*2t(n-4)+c+c
//t(n)=16t(n-4)+c
// for kth term
//t(n)=2^k(n-k)+c
// t(n)= 2^nt(n-n)+c
//t(n)= 2^nt(0)+c is the worst time complexity
public class Finonnaci{
public static void main (String[] args) {
int n1=0, n2=1, n3,i, count=10;
System.out.println(n1+" "+n2);
for (i=2; i<count; i++) {
n3=n1+n2;
System.out.println(" "+ n3);
n1=n2;
n2=n3;
}
}
} | 1,214 | 0.53542 | 0.469522 | 62 | 18.596775 | 16.048777 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.903226 | false | false | 1 |
7540fac65a89c6781778b1c67ddcdc9efb4d716f | 34,660,386,129,308 | 63f49a31ef957a2fa34fdf7c3f3fb211a1a44930 | /test/uk/ac/cam/jdb75/fjava/tick0/test/TestJavaStreams.java | 17937e65f3411b30a32a66a5b6ddb13cab430d21 | []
| no_license | jdb8/java-cambridge-tick0-part-1b | https://github.com/jdb8/java-cambridge-tick0-part-1b | 9971455ad5513a93617e57ba9989a3c434c3c76b | bf537c7336978beadfa2938536d4ab50e79ffd3d | refs/heads/master | 2019-01-02T05:34:00.706000 | 2014-01-29T14:22:55 | 2014-01-29T14:22:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.ac.cam.jdb75.fjava.tick0.test;
import static org.junit.Assert.*;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import uk.ac.cam.jdb75.fjava.tick0.ExternalSort;
public class TestJavaStreams {
RandomAccessFile file1;
RandomAccessFile file2;
DataInputStream[] iss;
int[] vals = {1,2,3,4,5,6,7,8,9};
@Before
public void setUp() throws Exception {
this.file1 = new RandomAccessFile("example1", "rw");
this.file2 = new RandomAccessFile("example1", "r");
iss = new DataInputStream[9];
RandomAccessFile newFile;
for (int i = 0; i<9; i++){
file1.seek(0);
newFile = new RandomAccessFile("example1", "r");
iss[i] = new DataInputStream(new BufferedInputStream(new FileInputStream(newFile.getFD())));
iss[i].skipBytes(4*i);
}
for (int val : vals){
file1.writeInt(val);
}
file1.seek(0);
file2.seek(0);
}
class MyFileInputStream extends FileInputStream {
public MyFileInputStream(FileDescriptor fd) {super(fd);}
protected void finalize() {} //disable double-free of file descriptor
}
@Test
public void test() throws FileNotFoundException, IOException {
int val;
for (int i = 0; i<iss.length; i++){
val = iss[i].readInt();
System.out.println(val);
assertEquals(vals[i], val);
}
}
}
| UTF-8 | Java | 1,717 | java | TestJavaStreams.java | Java | []
| null | []
| package uk.ac.cam.jdb75.fjava.tick0.test;
import static org.junit.Assert.*;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import uk.ac.cam.jdb75.fjava.tick0.ExternalSort;
public class TestJavaStreams {
RandomAccessFile file1;
RandomAccessFile file2;
DataInputStream[] iss;
int[] vals = {1,2,3,4,5,6,7,8,9};
@Before
public void setUp() throws Exception {
this.file1 = new RandomAccessFile("example1", "rw");
this.file2 = new RandomAccessFile("example1", "r");
iss = new DataInputStream[9];
RandomAccessFile newFile;
for (int i = 0; i<9; i++){
file1.seek(0);
newFile = new RandomAccessFile("example1", "r");
iss[i] = new DataInputStream(new BufferedInputStream(new FileInputStream(newFile.getFD())));
iss[i].skipBytes(4*i);
}
for (int val : vals){
file1.writeInt(val);
}
file1.seek(0);
file2.seek(0);
}
class MyFileInputStream extends FileInputStream {
public MyFileInputStream(FileDescriptor fd) {super(fd);}
protected void finalize() {} //disable double-free of file descriptor
}
@Test
public void test() throws FileNotFoundException, IOException {
int val;
for (int i = 0; i<iss.length; i++){
val = iss[i].readInt();
System.out.println(val);
assertEquals(vals[i], val);
}
}
}
| 1,717 | 0.630169 | 0.610367 | 66 | 25.015152 | 22.162958 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.757576 | false | false | 1 |
2296df1b163b73a8bd658932068f1da69f0c1853 | 22,978,075,087,113 | ac6525b87f28f96176a30155f332e944cd72e8f7 | /LeetCode/src/main/second/RotateImage.java | f4d9c64bb9f4abbf49e6e328cd9f103411bf23b9 | []
| no_license | woodfox/LeetCode | https://github.com/woodfox/LeetCode | e18272a2b9be5ad5447e57210aab5daa8d027c32 | f9f807e8f47b5218551aa0574be4ad68b9b03830 | refs/heads/master | 2021-01-18T23:02:32.389000 | 2016-03-23T05:47:11 | 2016-03-23T05:47:11 | 15,998,626 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package second;
public class RotateImage {
public void rotate(int[][] a) {
int n = a.length;
if(n == 0){
return;
}
for(int k=0;k<=(n-1)/2;k++){
move(a, k, n-2*k);
}
}
void move(int[][] a, int k, int n){
for(int i=0;i<n-1;i++){
int tmp = a[k][k+i];
a[k][k+i] = a[k+n-1-i][k];
a[k+n-1-i][k] = a[k+n-1][k+n-1-i];
a[k+n-1][k+n-1-i] = a[k+i][k+n-1];
a[k+i][k+n-1] = tmp;
}
}
}
| UTF-8 | Java | 534 | java | RotateImage.java | Java | []
| null | []
| package second;
public class RotateImage {
public void rotate(int[][] a) {
int n = a.length;
if(n == 0){
return;
}
for(int k=0;k<=(n-1)/2;k++){
move(a, k, n-2*k);
}
}
void move(int[][] a, int k, int n){
for(int i=0;i<n-1;i++){
int tmp = a[k][k+i];
a[k][k+i] = a[k+n-1-i][k];
a[k+n-1-i][k] = a[k+n-1][k+n-1-i];
a[k+n-1][k+n-1-i] = a[k+i][k+n-1];
a[k+i][k+n-1] = tmp;
}
}
}
| 534 | 0.350187 | 0.322097 | 23 | 22.217392 | 14.494246 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false | 1 |
80eaffa3c10a5b1cb917f1987145157538810fa0 | 29,016,799,092,716 | 3ad8a22526ea6858ba354180ff72b5015d05b0e7 | /wizard-common/src/main/java/org/cobbzilla/wizard/api/NotFoundException.java | 2cc79db87640d1fc4d452a59a368012686aae9a0 | [
"Apache-2.0"
]
| permissive | cobbzilla/cobbzilla-wizard | https://github.com/cobbzilla/cobbzilla-wizard | d4df7d3dc132798d5720f9f5fd5d79a5128f90ba | 9792c0ac6d6a7cfde87c65a109cc239ab196f1f9 | refs/heads/master | 2022-12-23T04:54:07.878000 | 2020-12-11T15:46:15 | 2020-12-11T15:46:15 | 9,473,488 | 3 | 7 | Apache-2.0 | false | 2018-10-23T17:11:53 | 2013-04-16T13:48:22 | 2018-10-08T22:10:07 | 2018-10-23T17:11:53 | 1,796 | 0 | 5 | 0 | Java | false | null | package org.cobbzilla.wizard.api;
import org.cobbzilla.util.http.HttpRequestBean;
import org.cobbzilla.wizard.util.RestResponse;
public class NotFoundException extends ApiException {
public NotFoundException(RestResponse response) { this(null, response); }
public NotFoundException(HttpRequestBean request, RestResponse response) { super(request, response); }
}
| UTF-8 | Java | 374 | java | NotFoundException.java | Java | []
| null | []
| package org.cobbzilla.wizard.api;
import org.cobbzilla.util.http.HttpRequestBean;
import org.cobbzilla.wizard.util.RestResponse;
public class NotFoundException extends ApiException {
public NotFoundException(RestResponse response) { this(null, response); }
public NotFoundException(HttpRequestBean request, RestResponse response) { super(request, response); }
}
| 374 | 0.802139 | 0.802139 | 11 | 33 | 34.915482 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 1 |
761fe558c216d7fa18bfe51eb2c20e94b1cd2474 | 30,880,814,917,732 | 9432374d2e5cec429afa64b82484198f7333fab9 | /src/miscellaneous/HornersMethod.java | fbd91807df7d9314604b7e5dfd0fb02c5fd58517 | []
| no_license | Poorvankbhatia/Data-Structures-In-Java | https://github.com/Poorvankbhatia/Data-Structures-In-Java | cdf5f6cecb6ca0e526c17f4d6263f60b19329f99 | 8c2d4e875fb7ef998d88adb72120add3cfb30825 | refs/heads/master | 2020-04-11T06:50:48.881000 | 2018-05-25T05:46:05 | 2018-05-25T05:46:05 | 31,535,467 | 10 | 15 | null | false | 2016-05-17T16:12:02 | 2015-03-02T10:37:10 | 2016-01-11T09:57:38 | 2016-05-16T19:51:24 | 3,895 | 0 | 3 | 1 | Java | null | null | /*
Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + … + c1x + c0 and a value of x,
find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.
Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for xn-1 and so on.
*/
package miscellaneous;
/**
* Created by poorvank on 04/07/16.
*/
public class HornersMethod {
private int x;
public HornersMethod(int x) {
this.x = x;
}
public int calculate(int[] pol) {
int n = pol.length;
int result = pol[0];
for (int i=1;i<n;i++) {
result = (result*x) + pol[i];
}
return result;
}
public static void main(String[] args) {
// Let us evaluate value of 2(x^3) – 6(x^2) + 2^x – 1 for x = 3
int poly[] = {2, -6, 2, -1};
int x = 3;
HornersMethod hm = new HornersMethod(x);
System.out.println(hm.calculate(poly));
}
}
/*
Horner’s method can be used to evaluate polynomial in O(n) time.
To understand the method, let us consider the example of 2(x^3) – 6(x^2) + 2^x – 1.
The polynomial can be evaluated as ((2x – 6)x + 2)x – 1. The idea is to initialize result as coefficient of x^n which is 2 in this case,
repeatedly multiply result with x and add next coefficient to result. Finally return result.
*/
| UTF-8 | Java | 1,454 | java | HornersMethod.java | Java | [
{
"context": "n.\n\n */\n\npackage miscellaneous;\n\n/**\n * Created by poorvank on 04/07/16.\n */\npublic class HornersMethod {\n\n ",
"end": 426,
"score": 0.9995906949043274,
"start": 418,
"tag": "USERNAME",
"value": "poorvank"
}
]
| null | []
| /*
Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + … + c1x + c0 and a value of x,
find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.
Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for xn-1 and so on.
*/
package miscellaneous;
/**
* Created by poorvank on 04/07/16.
*/
public class HornersMethod {
private int x;
public HornersMethod(int x) {
this.x = x;
}
public int calculate(int[] pol) {
int n = pol.length;
int result = pol[0];
for (int i=1;i<n;i++) {
result = (result*x) + pol[i];
}
return result;
}
public static void main(String[] args) {
// Let us evaluate value of 2(x^3) – 6(x^2) + 2^x – 1 for x = 3
int poly[] = {2, -6, 2, -1};
int x = 3;
HornersMethod hm = new HornersMethod(x);
System.out.println(hm.calculate(poly));
}
}
/*
Horner’s method can be used to evaluate polynomial in O(n) time.
To understand the method, let us consider the example of 2(x^3) – 6(x^2) + 2^x – 1.
The polynomial can be evaluated as ((2x – 6)x + 2)x – 1. The idea is to initialize result as coefficient of x^n which is 2 in this case,
repeatedly multiply result with x and add next coefficient to result. Finally return result.
*/
| 1,454 | 0.616134 | 0.587622 | 55 | 25.145454 | 36.160961 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.381818 | false | false | 1 |
df83d3fa7b1f5618df40df40dd304a805856e85a | 30,640,296,742,099 | 5eee926bb469af426b1bb54e366fc0224b31523c | /dlimiter/src/main/java/br/com/rhm/dlimiter/annotation/Position.java | 63246fd5c28e859cda7219b4e2e576ced18e1813 | []
| no_license | rhmoreira/d-limiter | https://github.com/rhmoreira/d-limiter | ed0d07bdb58e9b398d02cf9ee4e41c2bf8540450 | ca5a7ab10d4e04377d582e69a63b1ae48de01153 | refs/heads/master | 2021-08-28T12:45:50.097000 | 2021-08-25T14:44:38 | 2021-08-25T14:44:38 | 77,386,215 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.rhm.dlimiter.annotation;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RUNTIME)
public @interface Position {
int start();
int end();
boolean trim() default true;
Orientation orientation() default @Orientation;
}
| UTF-8 | Java | 422 | java | Position.java | Java | []
| null | []
| package br.com.rhm.dlimiter.annotation;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RUNTIME)
public @interface Position {
int start();
int end();
boolean trim() default true;
Orientation orientation() default @Orientation;
}
| 422 | 0.758294 | 0.758294 | 17 | 22.82353 | 18.43984 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 1 |
e4a5b89cd0a3fbe7e500502836829ed359122ec7 | 10,831,907,543,527 | bc1f35fca7b5837986ff861042a8e2e3d8faf1ba | /Core/src/org/sleuthkit/autopsy/casemodule/LogicalEvidenceFilePanel.java | 103fd8fd6c52f0016109a359f1ad47a11e5d294b | [
"Zlib",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-oracle-bcl-javase-javafx-2012",
"Apache-2.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"WTFPL"
]
| permissive | R-Autopsy-translation/autopsy | https://github.com/R-Autopsy-translation/autopsy | 24515ff593d2ef3f41434a0daa99f342ed88484b | 302db3751751c000182a304adfd604bc1dd50cfd | refs/heads/japanese-translations-2019 | 2020-09-15T02:28:12.560000 | 2019-12-10T07:36:27 | 2019-12-10T07:36:27 | 219,912,805 | 1 | 2 | Apache-2.0 | true | 2019-11-06T06:24:45 | 2019-11-06T04:37:26 | 2019-11-06T05:03:51 | 2019-11-06T06:24:44 | 1,046,988 | 0 | 1 | 0 | Java | false | false | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.casemodule;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JFileChooser;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataSourceProcessor;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import java.util.logging.Level;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.PathValidator;
/**
* A panel which allows the user to select a Logical Evidence File (L01)
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
final class LogicalEvidenceFilePanel extends javax.swing.JPanel implements DocumentListener {
private static final long serialVersionUID = 1L;
private final Set<File> currentFiles = new TreeSet<>(); //keep currents in a set to disallow duplicates per add
private static final Logger logger = Logger.getLogger(LocalFilesPanel.class.getName());
private String displayName = "";
/**
* Creates new form LogicalEvidenceFilePanel
*/
private LogicalEvidenceFilePanel() {
initComponents();
logicalEvidenceFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
logicalEvidenceFileChooser.setAcceptAllFileFilterUsed(false);
logicalEvidenceFileChooser.setMultiSelectionEnabled(false);
logicalEvidenceFileChooser.setFileFilter(LocalFilesDSProcessor.getLogicalEvidenceFilter());
}
/**
* Create a new LogicalEvidencePanel.
*
* @return
*/
static LogicalEvidenceFilePanel createInstance() {
synchronized (LogicalEvidenceFilePanel.class) {
final LogicalEvidenceFilePanel instance = new LogicalEvidenceFilePanel();
// post-constructor initialization of listener support without leaking references of uninitialized objects
instance.logicalEvidencePathField.getDocument().addDocumentListener(instance);
return instance;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
logicalEvidenceFileChooser = new javax.swing.JFileChooser();
selectButton = new javax.swing.JButton();
logicalEvidencePathField = new javax.swing.JTextField();
errorLabel = new javax.swing.JLabel();
logicalEvidenceFileChooser.setApproveButtonText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidenceFileChooser.approveButtonText")); // NOI18N
logicalEvidenceFileChooser.setApproveButtonToolTipText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidenceFileChooser.approveButtonToolTipText")); // NOI18N
logicalEvidenceFileChooser.setDialogTitle(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidenceFileChooser.dialogTitle")); // NOI18N
logicalEvidenceFileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES);
org.openide.awt.Mnemonics.setLocalizedText(selectButton, org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.selectButton.text")); // NOI18N
selectButton.setToolTipText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.selectButton.toolTipText")); // NOI18N
selectButton.setActionCommand(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.selectButton.actionCommand")); // NOI18N
selectButton.setMaximumSize(new java.awt.Dimension(70, 23));
selectButton.setMinimumSize(new java.awt.Dimension(70, 23));
selectButton.setPreferredSize(new java.awt.Dimension(70, 23));
selectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectButtonActionPerformed(evt);
}
});
logicalEvidencePathField.setText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidencePathField.text")); // NOI18N
logicalEvidencePathField.setPreferredSize(new java.awt.Dimension(379, 20));
errorLabel.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(errorLabel, org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.errorLabel.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(logicalEvidencePathField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(selectButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(logicalEvidencePathField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(errorLabel)
.addContainerGap(105, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void selectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectButtonActionPerformed
final int returnVal = logicalEvidenceFileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = logicalEvidenceFileChooser.getSelectedFile();
final StringBuilder allPaths = new StringBuilder();
currentFiles.add(file);
allPaths.append(file.getAbsolutePath());
logicalEvidencePathField.setText(allPaths.toString());
logicalEvidencePathField.setToolTipText(allPaths.toString());
}
fireChange();
}//GEN-LAST:event_selectButtonActionPerformed
/*
* Clear previously selected items on the panel.
*/
void reset() {
currentFiles.clear();
logicalEvidencePathField.setText("");
logicalEvidencePathField.setToolTipText("");
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel errorLabel;
private javax.swing.JFileChooser logicalEvidenceFileChooser;
private javax.swing.JTextField logicalEvidencePathField;
private javax.swing.JButton selectButton;
// End of variables declaration//GEN-END:variables
/**
* Check if the current selection exists and is a logical evidence file and
* therefore the panel is valid.
*
* @return true for a valid selection, false for an invalid or empty
* selection
*/
@Messages({
"LogicalEvidenceFilePanel.validatePanel.nonL01Error.text=Only files with the .l01 file extension are supported here.",
"LogicalEvidenceFilePanel.pathValidation.dataSourceOnCDriveError=Warning: Path to multi-user data source is on \"C:\" drive",
"LogicalEvidenceFilePanel.pathValidation.getOpenCase.Error=Warning: Exception while getting open case."
})
boolean validatePanel() {
errorLabel.setVisible(false);
// display warning if there is one (but don't disable "next" button)
final String path = logicalEvidencePathField.getText();
if (StringUtils.isBlank(path)) {
return false;
}
// display warning if there is one (but don't disable "next" button)
try {
if (!PathValidator.isValidForMultiUserCase(path, Case.getCurrentCaseThrows().getCaseType())) {
errorLabel.setVisible(true);
errorLabel.setText(Bundle.LogicalEvidenceFilePanel_pathValidation_dataSourceOnCDriveError());
return false;
}
} catch (NoCurrentCaseException ex) {
errorLabel.setVisible(true);
errorLabel.setText(Bundle.LogicalEvidenceFilePanel_pathValidation_getOpenCase_Error());
return false;
}
//check the extension incase the path was manually entered
if (!LocalFilesDSProcessor.getLogicalEvidenceFilter().accept(new File(path))) {
errorLabel.setVisible(true);
errorLabel.setText(Bundle.LogicalEvidenceFilePanel_validatePanel_nonL01Error_text());
return false;
}
displayName = FilenameUtils.getName(path);
return new File(path).isFile();
}
/**
* Get the path(s) which have been selected on this panel
*
* @return a List of Strings representing the path(s) for the selected files
*/
List<String> getContentPaths() {
final List<String> pathsList = new ArrayList<>();
if (currentFiles == null) {
return pathsList;
}
for (final File f : currentFiles) {
pathsList.add(f.getAbsolutePath());
}
return pathsList;
}
/**
* Get the name of the logical evidence file which was selected.
*
* @return the name of the logical evidence file
*/
String getFileSetName() {
return displayName;
}
@Override
public void insertUpdate(final DocumentEvent docEvent) {
fireChange();
}
@Override
public void removeUpdate(final DocumentEvent docEvent) {
fireChange();
}
@Override
public void changedUpdate(final DocumentEvent docEvent) {
fireChange();
}
@Messages({
"LogicalEvidenceFilePanel.moduleErr.name=Module Error",
"LogicalEvidenceFilePanel.moduleErr.msg=A module caused an error listening to LogicalEvidenceFilePanel updates. See log to determine which module. Some data could be incomplete."
})
private void fireChange() {
try {
firePropertyChange(DataSourceProcessor.DSP_PANEL_EVENT.UPDATE_UI.toString(), false, true);
} catch (Exception e) {
logger.log(Level.SEVERE, "LogicalEvidenceFilePanel listener threw exception", e); //NON-NLS
MessageNotifyUtil.Notify.show(NbBundle.getMessage(this.getClass(), "LogicalEvidenceFilePanel.moduleErr"),
NbBundle.getMessage(this.getClass(), "LogicalEvidenceFilePanel.moduleErr.msg"),
MessageNotifyUtil.MessageType.ERROR);
}
}
}
| UTF-8 | Java | 12,872 | java | LogicalEvidenceFilePanel.java | Java | []
| null | []
| /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.casemodule;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JFileChooser;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataSourceProcessor;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import java.util.logging.Level;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.PathValidator;
/**
* A panel which allows the user to select a Logical Evidence File (L01)
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
final class LogicalEvidenceFilePanel extends javax.swing.JPanel implements DocumentListener {
private static final long serialVersionUID = 1L;
private final Set<File> currentFiles = new TreeSet<>(); //keep currents in a set to disallow duplicates per add
private static final Logger logger = Logger.getLogger(LocalFilesPanel.class.getName());
private String displayName = "";
/**
* Creates new form LogicalEvidenceFilePanel
*/
private LogicalEvidenceFilePanel() {
initComponents();
logicalEvidenceFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
logicalEvidenceFileChooser.setAcceptAllFileFilterUsed(false);
logicalEvidenceFileChooser.setMultiSelectionEnabled(false);
logicalEvidenceFileChooser.setFileFilter(LocalFilesDSProcessor.getLogicalEvidenceFilter());
}
/**
* Create a new LogicalEvidencePanel.
*
* @return
*/
static LogicalEvidenceFilePanel createInstance() {
synchronized (LogicalEvidenceFilePanel.class) {
final LogicalEvidenceFilePanel instance = new LogicalEvidenceFilePanel();
// post-constructor initialization of listener support without leaking references of uninitialized objects
instance.logicalEvidencePathField.getDocument().addDocumentListener(instance);
return instance;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
logicalEvidenceFileChooser = new javax.swing.JFileChooser();
selectButton = new javax.swing.JButton();
logicalEvidencePathField = new javax.swing.JTextField();
errorLabel = new javax.swing.JLabel();
logicalEvidenceFileChooser.setApproveButtonText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidenceFileChooser.approveButtonText")); // NOI18N
logicalEvidenceFileChooser.setApproveButtonToolTipText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidenceFileChooser.approveButtonToolTipText")); // NOI18N
logicalEvidenceFileChooser.setDialogTitle(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidenceFileChooser.dialogTitle")); // NOI18N
logicalEvidenceFileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES);
org.openide.awt.Mnemonics.setLocalizedText(selectButton, org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.selectButton.text")); // NOI18N
selectButton.setToolTipText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.selectButton.toolTipText")); // NOI18N
selectButton.setActionCommand(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.selectButton.actionCommand")); // NOI18N
selectButton.setMaximumSize(new java.awt.Dimension(70, 23));
selectButton.setMinimumSize(new java.awt.Dimension(70, 23));
selectButton.setPreferredSize(new java.awt.Dimension(70, 23));
selectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectButtonActionPerformed(evt);
}
});
logicalEvidencePathField.setText(org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.logicalEvidencePathField.text")); // NOI18N
logicalEvidencePathField.setPreferredSize(new java.awt.Dimension(379, 20));
errorLabel.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(errorLabel, org.openide.util.NbBundle.getMessage(LogicalEvidenceFilePanel.class, "LogicalEvidenceFilePanel.errorLabel.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(logicalEvidencePathField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(selectButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(logicalEvidencePathField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(errorLabel)
.addContainerGap(105, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void selectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectButtonActionPerformed
final int returnVal = logicalEvidenceFileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = logicalEvidenceFileChooser.getSelectedFile();
final StringBuilder allPaths = new StringBuilder();
currentFiles.add(file);
allPaths.append(file.getAbsolutePath());
logicalEvidencePathField.setText(allPaths.toString());
logicalEvidencePathField.setToolTipText(allPaths.toString());
}
fireChange();
}//GEN-LAST:event_selectButtonActionPerformed
/*
* Clear previously selected items on the panel.
*/
void reset() {
currentFiles.clear();
logicalEvidencePathField.setText("");
logicalEvidencePathField.setToolTipText("");
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel errorLabel;
private javax.swing.JFileChooser logicalEvidenceFileChooser;
private javax.swing.JTextField logicalEvidencePathField;
private javax.swing.JButton selectButton;
// End of variables declaration//GEN-END:variables
/**
* Check if the current selection exists and is a logical evidence file and
* therefore the panel is valid.
*
* @return true for a valid selection, false for an invalid or empty
* selection
*/
@Messages({
"LogicalEvidenceFilePanel.validatePanel.nonL01Error.text=Only files with the .l01 file extension are supported here.",
"LogicalEvidenceFilePanel.pathValidation.dataSourceOnCDriveError=Warning: Path to multi-user data source is on \"C:\" drive",
"LogicalEvidenceFilePanel.pathValidation.getOpenCase.Error=Warning: Exception while getting open case."
})
boolean validatePanel() {
errorLabel.setVisible(false);
// display warning if there is one (but don't disable "next" button)
final String path = logicalEvidencePathField.getText();
if (StringUtils.isBlank(path)) {
return false;
}
// display warning if there is one (but don't disable "next" button)
try {
if (!PathValidator.isValidForMultiUserCase(path, Case.getCurrentCaseThrows().getCaseType())) {
errorLabel.setVisible(true);
errorLabel.setText(Bundle.LogicalEvidenceFilePanel_pathValidation_dataSourceOnCDriveError());
return false;
}
} catch (NoCurrentCaseException ex) {
errorLabel.setVisible(true);
errorLabel.setText(Bundle.LogicalEvidenceFilePanel_pathValidation_getOpenCase_Error());
return false;
}
//check the extension incase the path was manually entered
if (!LocalFilesDSProcessor.getLogicalEvidenceFilter().accept(new File(path))) {
errorLabel.setVisible(true);
errorLabel.setText(Bundle.LogicalEvidenceFilePanel_validatePanel_nonL01Error_text());
return false;
}
displayName = FilenameUtils.getName(path);
return new File(path).isFile();
}
/**
* Get the path(s) which have been selected on this panel
*
* @return a List of Strings representing the path(s) for the selected files
*/
List<String> getContentPaths() {
final List<String> pathsList = new ArrayList<>();
if (currentFiles == null) {
return pathsList;
}
for (final File f : currentFiles) {
pathsList.add(f.getAbsolutePath());
}
return pathsList;
}
/**
* Get the name of the logical evidence file which was selected.
*
* @return the name of the logical evidence file
*/
String getFileSetName() {
return displayName;
}
@Override
public void insertUpdate(final DocumentEvent docEvent) {
fireChange();
}
@Override
public void removeUpdate(final DocumentEvent docEvent) {
fireChange();
}
@Override
public void changedUpdate(final DocumentEvent docEvent) {
fireChange();
}
@Messages({
"LogicalEvidenceFilePanel.moduleErr.name=Module Error",
"LogicalEvidenceFilePanel.moduleErr.msg=A module caused an error listening to LogicalEvidenceFilePanel updates. See log to determine which module. Some data could be incomplete."
})
private void fireChange() {
try {
firePropertyChange(DataSourceProcessor.DSP_PANEL_EVENT.UPDATE_UI.toString(), false, true);
} catch (Exception e) {
logger.log(Level.SEVERE, "LogicalEvidenceFilePanel listener threw exception", e); //NON-NLS
MessageNotifyUtil.Notify.show(NbBundle.getMessage(this.getClass(), "LogicalEvidenceFilePanel.moduleErr"),
NbBundle.getMessage(this.getClass(), "LogicalEvidenceFilePanel.moduleErr.msg"),
MessageNotifyUtil.MessageType.ERROR);
}
}
}
| 12,872 | 0.705019 | 0.699347 | 269 | 46.851299 | 44.345219 | 223 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557621 | false | false | 1 |
187685a031d508bde55fdb333a20967529a4276c | 8,211,977,523,269 | e16c9de07f9925e1bc45fea539357849e6b46ae9 | /Java Source/com/agencyport/autob/custom/OBELCoverageView.java | 073da1fe129516967e09b2a2e3177637c3487a4c | []
| no_license | philipjohnsolomon/ap-test-devops | https://github.com/philipjohnsolomon/ap-test-devops | 2aacf1630ebd8e5230ecd945fce64afc131445d8 | a522ea1e6fb074c38694416779782a778de58d1c | refs/heads/master | 2021-08-29T21:38:43.751000 | 2017-12-15T03:03:09 | 2017-12-15T03:03:09 | 114,320,448 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created on February 6, 2012 / Agencyport Software
*/
package com.agencyport.autob.custom;//NOSONAR
import com.agencyport.domXML.APDataCollection;
import com.agencyport.domXML.view.AggregateExistsBooleanView;
import com.agencyport.logging.ExceptionLogger;
import com.agencyport.xpath.XPathException;
/**
* The CustomOBELView class
*/
public class OBELCoverageView extends AggregateExistsBooleanView {
/**
* The <code>serialVersionUID</code>
*/
private static final long serialVersionUID = -7686516900997161367L;
/**
* The <code>STATE_LEVEL_OBEL_LIMIT</code> is the XPath for the state level
* OBEL coverage.
*/
private static final String STATE_LEVEL_OBEL_LIMIT_XPATH = ICommlAutoConstants.COMML_RATE_STATE_OPTIONAL_COVERAGES_XPATH
+ ".CommlCoverage[CoverageCd='OBEL']";
/**
* Constructs an instance.
*/
public OBELCoverageView() {
super();
}
/**
* {@inheritDoc} Extend the base class's update method. Check to see if this
* is the last OBEL coverage for the vehicles under this state.
*/
@Override
public void update(APDataCollection apData, int[] indices, String value, String associatedElementPath) {
super.update(apData, indices, value, associatedElementPath);
if (!isTrueValue(value)) {
try {
String searchOBELOnAllVehiclesInStateXPath = "CommlAutoLineBusiness/CommlRateState[position()=" + (indices[0] + 1)
+ "]/CommlVeh/CommlCoverage[CoverageCd='OBEL']";
// If this is the last OBEL limit on this vehicle then we will
// delete the one at the state level.
if (apData.selectSingleNode(searchOBELOnAllVehiclesInStateXPath) == null && apData.exists(STATE_LEVEL_OBEL_LIMIT_XPATH, indices)) {
apData.deleteElement(STATE_LEVEL_OBEL_LIMIT_XPATH, indices);
}
} catch (XPathException e) {
ExceptionLogger.log(e, this.getClass(), "update");
throw new IllegalStateException(e);
}
}
}
}
| UTF-8 | Java | 2,128 | java | OBELCoverageView.java | Java | []
| null | []
| /**
* Created on February 6, 2012 / Agencyport Software
*/
package com.agencyport.autob.custom;//NOSONAR
import com.agencyport.domXML.APDataCollection;
import com.agencyport.domXML.view.AggregateExistsBooleanView;
import com.agencyport.logging.ExceptionLogger;
import com.agencyport.xpath.XPathException;
/**
* The CustomOBELView class
*/
public class OBELCoverageView extends AggregateExistsBooleanView {
/**
* The <code>serialVersionUID</code>
*/
private static final long serialVersionUID = -7686516900997161367L;
/**
* The <code>STATE_LEVEL_OBEL_LIMIT</code> is the XPath for the state level
* OBEL coverage.
*/
private static final String STATE_LEVEL_OBEL_LIMIT_XPATH = ICommlAutoConstants.COMML_RATE_STATE_OPTIONAL_COVERAGES_XPATH
+ ".CommlCoverage[CoverageCd='OBEL']";
/**
* Constructs an instance.
*/
public OBELCoverageView() {
super();
}
/**
* {@inheritDoc} Extend the base class's update method. Check to see if this
* is the last OBEL coverage for the vehicles under this state.
*/
@Override
public void update(APDataCollection apData, int[] indices, String value, String associatedElementPath) {
super.update(apData, indices, value, associatedElementPath);
if (!isTrueValue(value)) {
try {
String searchOBELOnAllVehiclesInStateXPath = "CommlAutoLineBusiness/CommlRateState[position()=" + (indices[0] + 1)
+ "]/CommlVeh/CommlCoverage[CoverageCd='OBEL']";
// If this is the last OBEL limit on this vehicle then we will
// delete the one at the state level.
if (apData.selectSingleNode(searchOBELOnAllVehiclesInStateXPath) == null && apData.exists(STATE_LEVEL_OBEL_LIMIT_XPATH, indices)) {
apData.deleteElement(STATE_LEVEL_OBEL_LIMIT_XPATH, indices);
}
} catch (XPathException e) {
ExceptionLogger.log(e, this.getClass(), "update");
throw new IllegalStateException(e);
}
}
}
}
| 2,128 | 0.648966 | 0.636748 | 57 | 36.333332 | 36.308296 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 1 |
039606f16fd5d02b7de66d0af860b978944a2ba3 | 16,123,307,252,730 | cbfeab701440a5e1ed0aa3fac697887a7b10f09e | /RPC-Client/build/generated-sources/jax-ws/sale/package-info.java | fa229cd729b2b4ca2e9ded655ad86546dc89afda | []
| no_license | AlanWei/Loyalty-Services | https://github.com/AlanWei/Loyalty-Services | e120e4a24a7714c7173e94499d61d375f0e7aaa1 | df7d47950294ae5c1a3e5e2a9e854858e931fc37 | refs/heads/master | 2021-01-10T19:11:35.636000 | 2015-09-08T15:02:58 | 2015-09-08T15:02:58 | 42,108,908 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | @javax.xml.bind.annotation.XmlSchema(namespace = "http://sale/")
package sale;
| UTF-8 | Java | 79 | java | package-info.java | Java | []
| null | []
| @javax.xml.bind.annotation.XmlSchema(namespace = "http://sale/")
package sale;
| 79 | 0.746835 | 0.746835 | 2 | 38.5 | 25.5 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
81f045275a331d90461447b9b0b852ac47aa8c20 | 27,462,020,926,197 | cfed651e8a776d86812672eec01119ec04acbbe7 | /src/main/java/at/austroControl/DFCOM/gui/model/ChannelMessageArray.java | d8e7c76e91baf69d5231ee5a976df5464c62d707 | []
| no_license | dkudernatsch/DFCOM | https://github.com/dkudernatsch/DFCOM | 3d6d67993aa1e4c3ede4848a67bfef3483705b5c | ae292f7b3e34908a8da9414f479e1be177247650 | refs/heads/master | 2019-01-04T16:41:12.277000 | 2016-12-05T02:07:06 | 2016-12-05T02:07:06 | 75,579,632 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* javafx.collections.FXCollections
* javafx.collections.ObservableMap
*/
package at.austroControl.DFCOM.gui.model;
import at.austroControl.DFCOM.Main;
import at.austroControl.DFCOM.config.LocationConfig;
import at.austroControl.DFCOM.gui.model.DFData;
import at.austroControl.DFCOM.util.CarrierStatus;
import at.austroControl.DFCOM.config.Frequency;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
public class ChannelMessageArray {
private final long channelTimeout = 10000;
private final long messageActiveTimeout = 2000;
private ObservableMap<DFKey, DFData> channels = FXCollections.observableHashMap();
private DFData currentActive;
private long timeCurrentActive;
private int counter = 0;
public synchronized boolean put(DFData value) {
if (value != null) {
if (value.getCarrierStatus() == CarrierStatus.CARRIER_ON) {
value.startCounting();
return this.channels.put(new DFKey(value.getChannelId(), value.getLocation()), value) != null;
}
if (value.getCarrierStatus() != CarrierStatus.CARRIER_OFF_NO_ERROR) {
Main.logger.warning("Location: " + value.getLocation().getLocationName() + "Channel:" + value.getChannelId() + " Frequency: " + value.getFrequency() + " Carrier Status:" + value.getCarrierStatus());
value.startCounting();
return this.channels.put(new DFKey(value.getChannelId(), value.getLocation()), value) != null;
}
return false;
}
return false;
}
public ObservableMap<DFKey, DFData> getMap() {
return this.channels;
}
public void clear() {
this.channels.clear();
}
public class DFKey {
private int channelID;
private LocationConfig loaction;
public DFKey(int channelID, LocationConfig loaction) {
this.channelID = channelID;
this.loaction = loaction;
}
public int getChannelID() {
return this.channelID;
}
public LocationConfig getLoaction() {
return this.loaction;
}
public int hashCode() {
return this.loaction.hashCode();
}
public boolean equals(Object obj) {
if (obj instanceof DFKey && this.channelID == ((DFKey)obj).channelID && this.loaction.getLocationName().equals(((DFKey)obj).loaction.getLocationName())) {
return true;
}
return false;
}
}
}
| UTF-8 | Java | 2,677 | java | ChannelMessageArray.java | Java | []
| null | []
| /*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* javafx.collections.FXCollections
* javafx.collections.ObservableMap
*/
package at.austroControl.DFCOM.gui.model;
import at.austroControl.DFCOM.Main;
import at.austroControl.DFCOM.config.LocationConfig;
import at.austroControl.DFCOM.gui.model.DFData;
import at.austroControl.DFCOM.util.CarrierStatus;
import at.austroControl.DFCOM.config.Frequency;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
public class ChannelMessageArray {
private final long channelTimeout = 10000;
private final long messageActiveTimeout = 2000;
private ObservableMap<DFKey, DFData> channels = FXCollections.observableHashMap();
private DFData currentActive;
private long timeCurrentActive;
private int counter = 0;
public synchronized boolean put(DFData value) {
if (value != null) {
if (value.getCarrierStatus() == CarrierStatus.CARRIER_ON) {
value.startCounting();
return this.channels.put(new DFKey(value.getChannelId(), value.getLocation()), value) != null;
}
if (value.getCarrierStatus() != CarrierStatus.CARRIER_OFF_NO_ERROR) {
Main.logger.warning("Location: " + value.getLocation().getLocationName() + "Channel:" + value.getChannelId() + " Frequency: " + value.getFrequency() + " Carrier Status:" + value.getCarrierStatus());
value.startCounting();
return this.channels.put(new DFKey(value.getChannelId(), value.getLocation()), value) != null;
}
return false;
}
return false;
}
public ObservableMap<DFKey, DFData> getMap() {
return this.channels;
}
public void clear() {
this.channels.clear();
}
public class DFKey {
private int channelID;
private LocationConfig loaction;
public DFKey(int channelID, LocationConfig loaction) {
this.channelID = channelID;
this.loaction = loaction;
}
public int getChannelID() {
return this.channelID;
}
public LocationConfig getLoaction() {
return this.loaction;
}
public int hashCode() {
return this.loaction.hashCode();
}
public boolean equals(Object obj) {
if (obj instanceof DFKey && this.channelID == ((DFKey)obj).channelID && this.loaction.getLocationName().equals(((DFKey)obj).loaction.getLocationName())) {
return true;
}
return false;
}
}
}
| 2,677 | 0.639522 | 0.634292 | 80 | 32.450001 | 34.954937 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
97b3e4d115f12e452d28fd9f14258425edd8d1be | 15,865,609,227,289 | 2cf3b4a787f170911d139c1c20d16c3068d8268d | /JavaVM/src/vm/classLoad/AboutSPI.java | 329a7958e68c6cb892f5e6036be5c36535b3969a | []
| no_license | OswaldZhuang/JAVA_SUMMARY | https://github.com/OswaldZhuang/JAVA_SUMMARY | 1376cac3b6fc4ee95463f2c3438e6668ec6eba59 | fd4d1e36f9c67cbf7d8dc02dd45d64e0fc36c0df | refs/heads/master | 2022-05-08T01:49:42.830000 | 2019-06-15T04:56:16 | 2019-06-15T04:56:16 | 115,479,589 | 1 | 0 | null | false | 2021-06-04T01:01:18 | 2017-12-27T03:59:00 | 2019-10-24T13:11:53 | 2021-06-04T01:01:17 | 348 | 1 | 0 | 3 | Java | false | false | package vm.classLoad;
public class AboutSPI {
/**
* SPI:Service Provider Interface
*
*/
/**
* java.util.ServiceLoader
* "service"是一系列的接口和(抽象)类的集合,"service provider"是"service"的指定的实现
*
*/
}
| UTF-8 | Java | 275 | java | AboutSPI.java | Java | []
| null | []
| package vm.classLoad;
public class AboutSPI {
/**
* SPI:Service Provider Interface
*
*/
/**
* java.util.ServiceLoader
* "service"是一系列的接口和(抽象)类的集合,"service provider"是"service"的指定的实现
*
*/
}
| 275 | 0.579399 | 0.579399 | 14 | 15.642858 | 18.069735 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 1 |
1c61a30f4fc99c5695b3e699d18a9972bfae533c | 7,464,653,189,330 | 475a41231c1853cdd7210f5884dd03517cbbf6c6 | /64-矩阵的最小路径和/src/main/java/Solution.java | e71e89ff09b976d6173e34acb0ba1e4713430de0 | []
| no_license | ColdPepsi/Leetcode | https://github.com/ColdPepsi/Leetcode | dd349c1ddf3187ecbc32c0ddee9fff59e405ed89 | 1adac49f864bf57b0db41dbd6616d3b4cc5ebf19 | refs/heads/master | 2021-02-24T22:29:58.713000 | 2020-12-16T08:44:12 | 2020-12-16T08:44:12 | 245,442,512 | 9 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author WuBiao
* @date 2020/3/14 14:15
*/
public class Solution {
/**
* @param grid
* @return int
* @description 动态规划,二维数组:dp[i][j]=grid[i][j]+min(dp[i-1][j],dp[i][j-1]),
* 一维数组:dp[j]=grid[i][j]+min(dp[j-1],dp[j]);
* @author WuBiao
* @date 2020/3/14 14:43
*/
//dp[i][j]=grid[i][j]+min(dp[i-1][j],dp[i][j-1]),dp[j]=grid[i][j]+min(d[j-1],d[j])
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int row = grid.length, col = grid[0].length;
int[] dp = new int[col];//动态规划结果数组
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (j == 0) {//第一列元素,只能来自其上边
//dp[j]=dp[j];
} else if (i == 0) {//第一行元素,只能来自其左边
dp[j] = dp[j - 1];
} else {//取其中的最小值
dp[j] = Math.min(dp[j - 1], dp[j]);
}
dp[j] += grid[i][j];
}
}
return dp[col - 1];//循环完,最后一个元素就是结果
}
} | UTF-8 | Java | 1,250 | java | Solution.java | Java | [
{
"context": "/**\n * @author WuBiao\n * @date 2020/3/14 14:15\n */\npublic class Solutio",
"end": 21,
"score": 0.9995638132095337,
"start": 15,
"tag": "NAME",
"value": "WuBiao"
},
{
"context": "p[j]=grid[i][j]+min(dp[j-1],dp[j]);\n * @author WuBiao\n * @date 2020/3/14 14:43\n */\n //dp[i][",
"end": 269,
"score": 0.9986966848373413,
"start": 263,
"tag": "NAME",
"value": "WuBiao"
}
]
| null | []
| /**
* @author WuBiao
* @date 2020/3/14 14:15
*/
public class Solution {
/**
* @param grid
* @return int
* @description 动态规划,二维数组:dp[i][j]=grid[i][j]+min(dp[i-1][j],dp[i][j-1]),
* 一维数组:dp[j]=grid[i][j]+min(dp[j-1],dp[j]);
* @author WuBiao
* @date 2020/3/14 14:43
*/
//dp[i][j]=grid[i][j]+min(dp[i-1][j],dp[i][j-1]),dp[j]=grid[i][j]+min(d[j-1],d[j])
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int row = grid.length, col = grid[0].length;
int[] dp = new int[col];//动态规划结果数组
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (j == 0) {//第一列元素,只能来自其上边
//dp[j]=dp[j];
} else if (i == 0) {//第一行元素,只能来自其左边
dp[j] = dp[j - 1];
} else {//取其中的最小值
dp[j] = Math.min(dp[j - 1], dp[j]);
}
dp[j] += grid[i][j];
}
}
return dp[col - 1];//循环完,最后一个元素就是结果
}
} | 1,250 | 0.406306 | 0.37027 | 35 | 30.742857 | 21.270157 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 1 |
153a758e0a8c8f75ef88b4694fd9d2d2d5017a87 | 22,892,175,720,813 | d47de314923acf7826c0b0a7f504b04e37667a29 | /TimeToDecompress.java | 95446639a0afbe3308511ba1a3b9e7936c47ec4e | []
| no_license | nickr145/CCC-SOLUTIONS-Junior | https://github.com/nickr145/CCC-SOLUTIONS-Junior | 3f4494922d22b94757708df19a17eb354daf4cdb | 7a1086b967060176eb0329092bc7a10be513e8fd | refs/heads/main | 2023-03-01T07:04:27.988000 | 2021-02-06T04:27:36 | 2021-02-06T04:27:36 | 334,231,960 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class TimeToDecompress
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int L = input.nextInt();
if (L < 0 || L > 80)
{
L = input.nextInt();
}
int [] numOfSymbol = new int [L];
String [] symType = new String [L];
for (int i = 0; i < L; i++)
{
numOfSymbol[i] = input.nextInt();
symType[i] = input.nextLine();
symType[i] = symType[i].trim();
}
input.close();
for (int i = 0; i < L; i++)
{
for (int j = 0; j < numOfSymbol[i]; j++)
{
System.out.print(symType[i]);
}
System.out.println("");
}
}
} | UTF-8 | Java | 832 | java | TimeToDecompress.java | Java | []
| null | []
| import java.util.*;
public class TimeToDecompress
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int L = input.nextInt();
if (L < 0 || L > 80)
{
L = input.nextInt();
}
int [] numOfSymbol = new int [L];
String [] symType = new String [L];
for (int i = 0; i < L; i++)
{
numOfSymbol[i] = input.nextInt();
symType[i] = input.nextLine();
symType[i] = symType[i].trim();
}
input.close();
for (int i = 0; i < L; i++)
{
for (int j = 0; j < numOfSymbol[i]; j++)
{
System.out.print(symType[i]);
}
System.out.println("");
}
}
} | 832 | 0.40625 | 0.399038 | 37 | 20.540541 | 17.56316 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false | 1 |
ea5fd6cf47849158fb70c5446b6d154214db6602 | 20,907,900,829,507 | 7b1389f7d891afbc325459867b3907bc501a8c90 | /src/main/java/com/aliwo/GeneticAlgorithm.java | 7a226d93203af4a734238b5f3a0acd5c51c63810 | []
| no_license | xiaoxu111/genetic-algorithms-by-java | https://github.com/xiaoxu111/genetic-algorithms-by-java | 8f254bb43745476ded681af9834975638175d5de | 4e09e98ec1a1b0da53cdcdb1e19859c215742ef5 | refs/heads/master | 2023-02-28T01:03:20.989000 | 2021-02-01T09:22:32 | 2021-02-01T09:22:32 | 334,824,319 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.aliwo;
/**
* package_name:com.aliwo
*
* @author:xuyy19 Date:2021/2/1 11:58
* 项目名:genetic-algorithms-by-java
* Description:简单的遗传算法
* Version: 1.0
**/
public class GeneticAlgorithm {
/**
* 种群大小
*/
private int populationSize;
/**
* 交叉率
*/
private double crossoverRate;
/**
* 变异率
*/
private double mutationRate;
/**
* 精英主义,如果个体是精英注主义之一,则它不会被交叉或者变异
*/
private int elitismCount;
public GeneticAlgorithm(int populationSize, double crossoverRate, double mutationRate, int elitismCount) {
this.populationSize = populationSize;
this.crossoverRate = crossoverRate;
this.mutationRate = mutationRate;
this.elitismCount = elitismCount;
}
/**
* @param chromosomeLength 个体染色体的长度
* @return 初始化种群
*/
public Population initPopulation(int chromosomeLength) {
Population population = new Population(this.populationSize, chromosomeLength);
return population;
}
/**
* @param individual
* @return 对每一个个体计算适应值, 个体评估
* 计算染色体中1的个数,然后除以染色体的长度
*/
public double calcFitness(Individual individual) {
// 记录正确基因的数量
int correctGenes = 0;
// 循环遍历个体中的基因
for (int geneIndex = 0; geneIndex < individual.getChromosomeLength(); geneIndex++) {
// 为找到的每个1添加一个适应点
if (individual.getGene(geneIndex) == 1) {
correctGenes += -1;
}
}
// 计算适应值
double fitness = correctGenes / individual.getChromosomeLength();
// 储存适应值
individual.setFitness(fitness);
// 返回适应值
return fitness;
}
/**
* @param population 评估整个种群,
*/
public void evalPopulation(Population population) {
double populationFitness = 0;
// 循环遍历种群中的每个个体并计算个体的适应值,然后再相加适应值
for (Individual individual : population.getIndividuals()) {
populationFitness += calcFitness(individual);
}
// 存储种群的适应值
population.setPopulationFitness(populationFitness);
}
/**
* @param population
* @return 检查种群是否到达终止条件, 正确的适应度是1
*/
public boolean isTerminationConditionMet(Population population) {
for (Individual individual : population.getIndividuals()) {
if (individual.getFitness() == 1) {
return true;
}
}
return false;
}
/**
* @param population
* @return 从交叉中选择作为父代
* 选择
*/
public Individual selectParent(Population population) {
// 得到个体(数组)
Individual individuals[] = population.getIndividuals();
// 轮盘赌选择
double populationFitness = population.getPopulationFitness();
double rouletteWheelPosition = Math.random() * populationFitness;
double spinWheel = 0;
for (Individual individual : individuals) {
spinWheel += individual.getFitness();
if (spinWheel >= rouletteWheelPosition) {
return individual;
}
}
return individuals[population.size() - 1];
}
/**
* @param population
* @return Population
* 交叉
*/
public Population crossoverPopulation(Population population) {
// 初始化种群规模
Population newPopulation = new Population(population.size());
// 根据适应值循环当前种群,得到父代1
for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) {
Individual parent1 = population.getFittest(populationIndex);
// 对个体执行交叉
if (this.crossoverRate > Math.random() && populationIndex >= this.elitismCount) {
// 初始化后代
Individual offspring = new Individual(parent1.getChromosomeLength());
// 找到第二个父代
Individual parent2 = selectParent(population);
// 循环基因组
for (int geneIndex = 0; geneIndex < parent1.getChromosomeLength(); geneIndex++) {
//使用parent1一半的基因或者parent2一半的基因
if (0.5 > Math.random()) {
offspring.setGene(geneIndex, parent1.getGene(geneIndex));
} else {
offspring.setGene(geneIndex, parent2.getGene(geneIndex));
}
}
// 往新的种群中添加后代
newPopulation.setIndividual(populationIndex, offspring);
} else {
// 如果没有使用交叉往新的种群中添加个体
newPopulation.setIndividual(populationIndex, parent1);
}
}
// 返回新的种群
return newPopulation;
}
/**
* @param population
* @return Population
* 突变
*/
public Population mutatePopulation(Population population) {
// 初始化新的种群
Population newPopulation = new Population(this.populationSize);
// 根据适应值循环遍历当前种群
for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) {
Individual individual = population.getFittest(populationIndex);
// 循环个体中的基因
for (int geneIndex = 0; geneIndex < individual.getChromosomeLength(); geneIndex++) {
//如果是精英个体跳过突变
if (populationIndex > this.elitismCount) {
// 判断是否要基因突变
if (this.mutationRate > Math.random()) {
// 得到新的基因
int newGene = 1;
if (individual.getGene(geneIndex) == 1) {
newGene = 0;
}
// 设置突变基因
individual.setGene(geneIndex, newGene);
}
}
}
// 添加个体到种群中
newPopulation.setIndividual(populationIndex, individual);
}
// 返回突变的种群
return newPopulation;
}
}
| UTF-8 | Java | 6,697 | java | GeneticAlgorithm.java | Java | [
{
"context": "wo;\n\n\n/**\n * package_name:com.aliwo\n *\n * @author:xuyy19 Date:2021/2/1 11:58\n * 项目名:genetic-algorithms-by-",
"end": 71,
"score": 0.9996024370193481,
"start": 65,
"tag": "USERNAME",
"value": "xuyy19"
}
]
| null | []
| package com.aliwo;
/**
* package_name:com.aliwo
*
* @author:xuyy19 Date:2021/2/1 11:58
* 项目名:genetic-algorithms-by-java
* Description:简单的遗传算法
* Version: 1.0
**/
public class GeneticAlgorithm {
/**
* 种群大小
*/
private int populationSize;
/**
* 交叉率
*/
private double crossoverRate;
/**
* 变异率
*/
private double mutationRate;
/**
* 精英主义,如果个体是精英注主义之一,则它不会被交叉或者变异
*/
private int elitismCount;
public GeneticAlgorithm(int populationSize, double crossoverRate, double mutationRate, int elitismCount) {
this.populationSize = populationSize;
this.crossoverRate = crossoverRate;
this.mutationRate = mutationRate;
this.elitismCount = elitismCount;
}
/**
* @param chromosomeLength 个体染色体的长度
* @return 初始化种群
*/
public Population initPopulation(int chromosomeLength) {
Population population = new Population(this.populationSize, chromosomeLength);
return population;
}
/**
* @param individual
* @return 对每一个个体计算适应值, 个体评估
* 计算染色体中1的个数,然后除以染色体的长度
*/
public double calcFitness(Individual individual) {
// 记录正确基因的数量
int correctGenes = 0;
// 循环遍历个体中的基因
for (int geneIndex = 0; geneIndex < individual.getChromosomeLength(); geneIndex++) {
// 为找到的每个1添加一个适应点
if (individual.getGene(geneIndex) == 1) {
correctGenes += -1;
}
}
// 计算适应值
double fitness = correctGenes / individual.getChromosomeLength();
// 储存适应值
individual.setFitness(fitness);
// 返回适应值
return fitness;
}
/**
* @param population 评估整个种群,
*/
public void evalPopulation(Population population) {
double populationFitness = 0;
// 循环遍历种群中的每个个体并计算个体的适应值,然后再相加适应值
for (Individual individual : population.getIndividuals()) {
populationFitness += calcFitness(individual);
}
// 存储种群的适应值
population.setPopulationFitness(populationFitness);
}
/**
* @param population
* @return 检查种群是否到达终止条件, 正确的适应度是1
*/
public boolean isTerminationConditionMet(Population population) {
for (Individual individual : population.getIndividuals()) {
if (individual.getFitness() == 1) {
return true;
}
}
return false;
}
/**
* @param population
* @return 从交叉中选择作为父代
* 选择
*/
public Individual selectParent(Population population) {
// 得到个体(数组)
Individual individuals[] = population.getIndividuals();
// 轮盘赌选择
double populationFitness = population.getPopulationFitness();
double rouletteWheelPosition = Math.random() * populationFitness;
double spinWheel = 0;
for (Individual individual : individuals) {
spinWheel += individual.getFitness();
if (spinWheel >= rouletteWheelPosition) {
return individual;
}
}
return individuals[population.size() - 1];
}
/**
* @param population
* @return Population
* 交叉
*/
public Population crossoverPopulation(Population population) {
// 初始化种群规模
Population newPopulation = new Population(population.size());
// 根据适应值循环当前种群,得到父代1
for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) {
Individual parent1 = population.getFittest(populationIndex);
// 对个体执行交叉
if (this.crossoverRate > Math.random() && populationIndex >= this.elitismCount) {
// 初始化后代
Individual offspring = new Individual(parent1.getChromosomeLength());
// 找到第二个父代
Individual parent2 = selectParent(population);
// 循环基因组
for (int geneIndex = 0; geneIndex < parent1.getChromosomeLength(); geneIndex++) {
//使用parent1一半的基因或者parent2一半的基因
if (0.5 > Math.random()) {
offspring.setGene(geneIndex, parent1.getGene(geneIndex));
} else {
offspring.setGene(geneIndex, parent2.getGene(geneIndex));
}
}
// 往新的种群中添加后代
newPopulation.setIndividual(populationIndex, offspring);
} else {
// 如果没有使用交叉往新的种群中添加个体
newPopulation.setIndividual(populationIndex, parent1);
}
}
// 返回新的种群
return newPopulation;
}
/**
* @param population
* @return Population
* 突变
*/
public Population mutatePopulation(Population population) {
// 初始化新的种群
Population newPopulation = new Population(this.populationSize);
// 根据适应值循环遍历当前种群
for (int populationIndex = 0; populationIndex < population.size(); populationIndex++) {
Individual individual = population.getFittest(populationIndex);
// 循环个体中的基因
for (int geneIndex = 0; geneIndex < individual.getChromosomeLength(); geneIndex++) {
//如果是精英个体跳过突变
if (populationIndex > this.elitismCount) {
// 判断是否要基因突变
if (this.mutationRate > Math.random()) {
// 得到新的基因
int newGene = 1;
if (individual.getGene(geneIndex) == 1) {
newGene = 0;
}
// 设置突变基因
individual.setGene(geneIndex, newGene);
}
}
}
// 添加个体到种群中
newPopulation.setIndividual(populationIndex, individual);
}
// 返回突变的种群
return newPopulation;
}
}
| 6,697 | 0.558569 | 0.55111 | 194 | 29.407217 | 25.682522 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371134 | false | false | 1 |
b88084e83b2bd9e31c274fa745b6bf20482cd238 | 12,163,347,418,755 | 336701961d6ff48ff80f65d32ad83d5e1c582577 | /src/main/java/JoaoVFG/com/github/repositories/security/RoleRepository.java | 7436b2b93da1c3951f10ff62e27369955807c663 | []
| no_license | JoaoVFG/sysrlog | https://github.com/JoaoVFG/sysrlog | e695b3d777a067592f85bf417ceb6ce187a066b5 | 38ca6035ccbb37ba44f8b0bb6a50ba52e22fa7c4 | refs/heads/master | 2020-03-21T05:53:36.297000 | 2018-12-06T19:08:04 | 2018-12-06T19:08:04 | 138,184,586 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package JoaoVFG.com.github.repositories.security;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import JoaoVFG.com.github.entity.security.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Integer>{
@Transactional(readOnly = true)
@Query("SELECT role FROM Role role WHERE role.id = :idBusca")
public Role buscaPorId(@Param("idBusca")Integer id);
}
| UTF-8 | Java | 624 | java | RoleRepository.java | Java | []
| null | []
| package JoaoVFG.com.github.repositories.security;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import JoaoVFG.com.github.entity.security.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Integer>{
@Transactional(readOnly = true)
@Query("SELECT role FROM Role role WHERE role.id = :idBusca")
public Role buscaPorId(@Param("idBusca")Integer id);
}
| 624 | 0.823718 | 0.823718 | 17 | 35.705883 | 26.064997 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 1 |
316f3bc6cdf6425d6d5850e05ce05d3a790a3289 | 13,503,377,212,300 | cfbd69e319dfd14e77a7aa13d7e492f96f0c9436 | /src/main/java/org/delin/algorithm/backtrack/EightQueen.java | fa3ee74123901cd11634a0a2dbc05c3d61efd95b | []
| no_license | delin10/Custom | https://github.com/delin10/Custom | 13b88dc1857f31406421e993c5ff7221cd731e59 | ebbf9df9375db7560d30fb5361aef0dbad01fa75 | refs/heads/master | 2020-05-04T17:04:56.239000 | 2019-05-21T01:50:39 | 2019-05-21T01:50:39 | 179,297,559 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.delin.algorithm.backtrack;
import org.delin.util.ArrayUtils;
import java.util.LinkedList;
import java.util.List;
/**
* 八皇后问题
* S1、获取单个解
* S2、获取所有解的列表
*/
public class EightQueen {
private static boolean[][] chessboard = new boolean[8][8];
private static int num = 8;
private static List<boolean[][]> all = new LinkedList<>();
/**
* 判断当前给定位置放置皇后是否合法
* @param row
* @param col
* @return
*/
private static boolean isValid(int row, int col) {
return isColumnValid(row, col) && isLeftTopValid(row, col) && isRightTopValid(row, col);
}
/**
* 同一列是否存在皇后
* @param row
* @param col
* @return
*/
private static boolean isColumnValid(int row, int col) {
for (int i = row; i >= 0; --i) {
if (chessboard[i][col]) {
return false;
}
}
return true;
}
/**
* 左上对角线判断是否存在皇后
* @param row
* @param col
* @return
*/
private static boolean isLeftTopValid(int row, int col) {
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
if (chessboard[i][j]) {
return false;
}
}
return true;
}
/**
* 在右上对角线判断是否存在皇后
* @param row
* @param col
* @return
*/
private static boolean isRightTopValid(int row, int col) {
for (int i = row - 1, j = col + 1; i >= 0 && j < 8; --i, ++j) {
if (chessboard[i][j]) {
return false;
}
}
return true;
}
/**
* 是否已经放置八个皇后
* @return
*/
private static boolean isEnd() {
return num == 0;
}
/**
* 回溯
* @param row
* @param col
*/
private static void backTrace(int row, int col) {
chessboard[row][col] = false;
++num;
}
/**
* 放置皇后
* @param row
* @param col
*/
private static void put(int row, int col) {
chessboard[row][col] = true;
}
/**
* 获得一个解
* @param row
* @param lastCol
*/
public static void queen(int row, int lastCol) {
for (int i = 0; i < 8 && !isEnd(); ++i) {
if (isValid(row, i)) {
put(row, i);
num--;
printQueen(chessboard);
queen(row + 1, i);
}
}
if (!isEnd()) {
backTrace(row - 1, lastCol);
}
}
/**
* 获得92种解法
* @param row
* @param lastCol
*/
public static void queenAll(int row, int lastCol) {
for (int i = 0; i < 8; ++i) {
if (isValid(row, i)) {
put(row, i);
num--;
if (row + 1 < 8) {
queenAll(row + 1, i);
}
if (isEnd()) {
all.add(ArrayUtils.copy(chessboard));
backTrace(row, i);
}
}
}
if (row > 0) {
backTrace(row - 1, lastCol);
}
}
/**
* 按照一定格式打印棋盘
* @param chessboard
*/
public static void printQueen(boolean[][] chessboard) {
printHorizentalBorder(49);
for (int i = 0; i < 8; ++i) {
System.out.print("|");
for (int j = 0; j < 8; ++j) {
if (chessboard[i][j]) {
System.out.print(" 1 ");
} else {
System.out.print(" 0 ");
}
System.out.print("|");
}
System.out.println();
printHorizentalBorder(49);
}
}
/**
* 打印横向边界线,类似 “-----”
* @param n
*/
public static void printHorizentalBorder(int n) {
for (int i = 0; i < n; ++i) {
System.out.print("-");
}
System.out.println();
}
public static void main(String[] args) {
queenAll(0, -1);
System.out.println("共有:" + all.size() + "种结果");
all.forEach(EightQueen::printQueen);
}
}
| UTF-8 | Java | 4,336 | java | EightQueen.java | Java | []
| null | []
| package org.delin.algorithm.backtrack;
import org.delin.util.ArrayUtils;
import java.util.LinkedList;
import java.util.List;
/**
* 八皇后问题
* S1、获取单个解
* S2、获取所有解的列表
*/
public class EightQueen {
private static boolean[][] chessboard = new boolean[8][8];
private static int num = 8;
private static List<boolean[][]> all = new LinkedList<>();
/**
* 判断当前给定位置放置皇后是否合法
* @param row
* @param col
* @return
*/
private static boolean isValid(int row, int col) {
return isColumnValid(row, col) && isLeftTopValid(row, col) && isRightTopValid(row, col);
}
/**
* 同一列是否存在皇后
* @param row
* @param col
* @return
*/
private static boolean isColumnValid(int row, int col) {
for (int i = row; i >= 0; --i) {
if (chessboard[i][col]) {
return false;
}
}
return true;
}
/**
* 左上对角线判断是否存在皇后
* @param row
* @param col
* @return
*/
private static boolean isLeftTopValid(int row, int col) {
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
if (chessboard[i][j]) {
return false;
}
}
return true;
}
/**
* 在右上对角线判断是否存在皇后
* @param row
* @param col
* @return
*/
private static boolean isRightTopValid(int row, int col) {
for (int i = row - 1, j = col + 1; i >= 0 && j < 8; --i, ++j) {
if (chessboard[i][j]) {
return false;
}
}
return true;
}
/**
* 是否已经放置八个皇后
* @return
*/
private static boolean isEnd() {
return num == 0;
}
/**
* 回溯
* @param row
* @param col
*/
private static void backTrace(int row, int col) {
chessboard[row][col] = false;
++num;
}
/**
* 放置皇后
* @param row
* @param col
*/
private static void put(int row, int col) {
chessboard[row][col] = true;
}
/**
* 获得一个解
* @param row
* @param lastCol
*/
public static void queen(int row, int lastCol) {
for (int i = 0; i < 8 && !isEnd(); ++i) {
if (isValid(row, i)) {
put(row, i);
num--;
printQueen(chessboard);
queen(row + 1, i);
}
}
if (!isEnd()) {
backTrace(row - 1, lastCol);
}
}
/**
* 获得92种解法
* @param row
* @param lastCol
*/
public static void queenAll(int row, int lastCol) {
for (int i = 0; i < 8; ++i) {
if (isValid(row, i)) {
put(row, i);
num--;
if (row + 1 < 8) {
queenAll(row + 1, i);
}
if (isEnd()) {
all.add(ArrayUtils.copy(chessboard));
backTrace(row, i);
}
}
}
if (row > 0) {
backTrace(row - 1, lastCol);
}
}
/**
* 按照一定格式打印棋盘
* @param chessboard
*/
public static void printQueen(boolean[][] chessboard) {
printHorizentalBorder(49);
for (int i = 0; i < 8; ++i) {
System.out.print("|");
for (int j = 0; j < 8; ++j) {
if (chessboard[i][j]) {
System.out.print(" 1 ");
} else {
System.out.print(" 0 ");
}
System.out.print("|");
}
System.out.println();
printHorizentalBorder(49);
}
}
/**
* 打印横向边界线,类似 “-----”
* @param n
*/
public static void printHorizentalBorder(int n) {
for (int i = 0; i < n; ++i) {
System.out.print("-");
}
System.out.println();
}
public static void main(String[] args) {
queenAll(0, -1);
System.out.println("共有:" + all.size() + "种结果");
all.forEach(EightQueen::printQueen);
}
}
| 4,336 | 0.434655 | 0.424621 | 182 | 21.45055 | 17.955845 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 1 |
1ec02fef513a356d617e9842da7d8876f5801ea9 | 22,651,657,557,787 | 792759f9ae046eccb2b1dfa2025ec14fa1dc4b9a | /src/com/pankaj/chatapp/service/DataParser.java | 58f827bfefa1bbb9b65f7e069af673fa8b1c268e | []
| no_license | chiefyarik/chatDemo | https://github.com/chiefyarik/chatDemo | 0fb4ab430d5b789ca4ba5a0e98138e1474da56d3 | cfd82b7eabb7c6c9748120b1460e9508bc23ede2 | refs/heads/master | 2021-01-15T11:46:19.367000 | 2015-04-18T19:55:10 | 2015-04-18T19:55:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pankaj.chatapp.service;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONException;
import org.json.JSONObject;
import com.pankaj.chatapp.entities.MessageList;
import com.pankaj.chatapp.entities.ResponseResult;
import com.pankaj.chatapp.util.Base64EncodeDecode;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
public class DataParser {
Context context;
public String getStringFromInputStream(InputStream in) {
if (in == null) {
;
return null;
}
StringBuffer out = new StringBuffer();
byte[] b = new byte[1024];
try {
for (int i; (i = in.read(b)) != -1;) {
out.append(new String(b, 0, i));
}
String responseString = out.toString();
if (responseString != null) {
;
return out.toString();
}
} catch (IOException e) {
System.out.println(">>> Exception >>> " + e + " >>> Message >>> "
+ e.getMessage());
}
return null;
}
public Bitmap getImage(String jsonString) {
JSONObject objJsonObject;
try {
objJsonObject = new JSONObject(jsonString);
String encodedString = objJsonObject.getString("image");
return new Base64EncodeDecode().StringToBitMap(encodedString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Bitmap getImage(InputStream inputStream) {
return getImage(getStringFromInputStream(inputStream));
}
public String deleteImage(String jsonString) {
JSONObject objJsonObject;
try {
objJsonObject = new JSONObject(jsonString);
String message = objJsonObject.getString("message");
return message;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String deleteImage(InputStream inputStream) {
return deleteImage(getStringFromInputStream(inputStream));
}
public String uploadImage(String jsonString) {
JSONObject objJsonObject;
try {
objJsonObject = new JSONObject(jsonString);
String message = objJsonObject.getString("error");
return message;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String uploadImage(InputStream inputStream) {
return uploadImage(getStringFromInputStream(inputStream));
}
public ResponseResult addUserToList(String jsonString) {
JSONObject objJsonObject;
ResponseResult objResponseResult = new ResponseResult();
try {
objJsonObject = new JSONObject(jsonString);
try {
objResponseResult.Success = objJsonObject.getString("Success");
} catch (JSONException e) {
e.printStackTrace();
}
try {
objResponseResult.message = objJsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return objResponseResult;
}
public ResponseResult addUserToList(InputStream inputStream) {
return addUserToList(getStringFromInputStream(inputStream));
}
public ResponseResult updateUserToList(String jsonString) {
JSONObject objJsonObject;
ResponseResult objResponseResult = new ResponseResult();
try {
objJsonObject = new JSONObject(jsonString);
try {
objResponseResult.Success = objJsonObject.getString("Success");
} catch (JSONException e) {
e.printStackTrace();
}
try {
objResponseResult.message = objJsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return objResponseResult;
}
public ResponseResult updateUserToList(InputStream inputStream) {
return updateUserToList(getStringFromInputStream(inputStream));
}
}
| UTF-8 | Java | 3,745 | java | DataParser.java | Java | []
| null | []
| package com.pankaj.chatapp.service;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONException;
import org.json.JSONObject;
import com.pankaj.chatapp.entities.MessageList;
import com.pankaj.chatapp.entities.ResponseResult;
import com.pankaj.chatapp.util.Base64EncodeDecode;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
public class DataParser {
Context context;
public String getStringFromInputStream(InputStream in) {
if (in == null) {
;
return null;
}
StringBuffer out = new StringBuffer();
byte[] b = new byte[1024];
try {
for (int i; (i = in.read(b)) != -1;) {
out.append(new String(b, 0, i));
}
String responseString = out.toString();
if (responseString != null) {
;
return out.toString();
}
} catch (IOException e) {
System.out.println(">>> Exception >>> " + e + " >>> Message >>> "
+ e.getMessage());
}
return null;
}
public Bitmap getImage(String jsonString) {
JSONObject objJsonObject;
try {
objJsonObject = new JSONObject(jsonString);
String encodedString = objJsonObject.getString("image");
return new Base64EncodeDecode().StringToBitMap(encodedString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Bitmap getImage(InputStream inputStream) {
return getImage(getStringFromInputStream(inputStream));
}
public String deleteImage(String jsonString) {
JSONObject objJsonObject;
try {
objJsonObject = new JSONObject(jsonString);
String message = objJsonObject.getString("message");
return message;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String deleteImage(InputStream inputStream) {
return deleteImage(getStringFromInputStream(inputStream));
}
public String uploadImage(String jsonString) {
JSONObject objJsonObject;
try {
objJsonObject = new JSONObject(jsonString);
String message = objJsonObject.getString("error");
return message;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String uploadImage(InputStream inputStream) {
return uploadImage(getStringFromInputStream(inputStream));
}
public ResponseResult addUserToList(String jsonString) {
JSONObject objJsonObject;
ResponseResult objResponseResult = new ResponseResult();
try {
objJsonObject = new JSONObject(jsonString);
try {
objResponseResult.Success = objJsonObject.getString("Success");
} catch (JSONException e) {
e.printStackTrace();
}
try {
objResponseResult.message = objJsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return objResponseResult;
}
public ResponseResult addUserToList(InputStream inputStream) {
return addUserToList(getStringFromInputStream(inputStream));
}
public ResponseResult updateUserToList(String jsonString) {
JSONObject objJsonObject;
ResponseResult objResponseResult = new ResponseResult();
try {
objJsonObject = new JSONObject(jsonString);
try {
objResponseResult.Success = objJsonObject.getString("Success");
} catch (JSONException e) {
e.printStackTrace();
}
try {
objResponseResult.message = objJsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return objResponseResult;
}
public ResponseResult updateUserToList(InputStream inputStream) {
return updateUserToList(getStringFromInputStream(inputStream));
}
}
| 3,745 | 0.718024 | 0.715354 | 156 | 23.006411 | 21.50626 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.185897 | false | false | 1 |
494cef670682558790a247ca3a9d1e5b8eeb248b | 32,796,370,283,321 | 9e477cc9dd8690cfd7cee86c7cc3127d36f28384 | /app/src/main/java/com/gxtc/huchuan/ui/live/series/SeriesActivity.java | 2362914ef4d443ebb4323c56c0de14d9359a3b15 | []
| no_license | zhangzzg/xmzj | https://github.com/zhangzzg/xmzj | f0682b5e32c96777405d5985b632b6a4f0ab1d4b | 23a76820b33d1766ca196f538fd7e0b44dd26c81 | refs/heads/master | 2020-03-27T21:59:16.175000 | 2018-09-03T11:27:58 | 2018-09-03T11:27:58 | 147,194,314 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gxtc.huchuan.ui.live.series;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.helper.ImageHelper;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.SeriesPageAdapter;
import com.gxtc.huchuan.bean.ChatInfosBean;
import com.gxtc.huchuan.bean.CreateLiveTopicBean;
import com.gxtc.huchuan.bean.SeriesPageBean;
import com.gxtc.huchuan.bean.event.EventDelSeries;
import com.gxtc.huchuan.bean.event.EventLoginBean;
import com.gxtc.huchuan.bean.event.EventSelectFriendBean;
import com.gxtc.huchuan.bean.event.EventSeriesInviteBean;
import com.gxtc.huchuan.bean.event.EventSeriesPayBean;
import com.gxtc.huchuan.bean.pay.OrdersRequestBean;
import com.gxtc.huchuan.bean.pay.OrdersResultBean;
import com.gxtc.huchuan.bean.pay.PayBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.dialog.SeriesCourseInviteDialog;
import com.gxtc.huchuan.dialog.ShareDialog;
import com.gxtc.huchuan.handler.CircleShareHandler;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.AllApi;
import com.gxtc.huchuan.http.service.LiveApi;
import com.gxtc.huchuan.http.service.PayApi;
import com.gxtc.huchuan.im.ui.ConversationActivity;
import com.gxtc.huchuan.im.ui.ConversationListActivity;
import com.gxtc.huchuan.ui.circle.dynamic.IssueDynamicActivity;
import com.gxtc.huchuan.ui.circle.erweicode.ErWeiCodeActivity;
import com.gxtc.huchuan.ui.live.hostpage.IGetChatinfos;
import com.gxtc.huchuan.ui.live.hostpage.LiveHostPageActivity;
import com.gxtc.huchuan.ui.live.hostpage.NewLiveTopicFragment;
import com.gxtc.huchuan.ui.live.intro.ShareImgActivity;
import com.gxtc.huchuan.ui.live.series.count.SeriesSignCountActivity;
import com.gxtc.huchuan.ui.live.series.share.SeriesShareListActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.createseriescourse.CreateSeriesCourseActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.createtopic.CreateTopicActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.livebgsetting.InvitedGuestsActivity;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.ui.pay.PayActivity;
import com.gxtc.huchuan.utils.DialogUtil;
import com.gxtc.huchuan.utils.ImMessageUtils;
import com.gxtc.huchuan.utils.JumpPermissionManagement;
import com.gxtc.huchuan.utils.LoginErrorCodeUtil;
import com.gxtc.huchuan.utils.RIMErrorCodeUtil;
import com.gxtc.huchuan.utils.RongIMTextUtil;
import com.gxtc.huchuan.utils.UMShareUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* 系列课主页
*/
public class SeriesActivity extends BaseTitleActivity implements IGetChatinfos,
View.OnClickListener {
public static final String AUDITION_TYPE = "1"; //免费试听模式
public static final String AUDITION_INVITE_TYPE = "2"; //邀请制免费试听模式
private static final String TAG = "SeriesActivity";
private static final int PLAYSERIES_REQUEST = 1 << 2;
private static final int SETTING_SERIES = 1 << 3;
//<!--headpic 系列课头像-->
//<!--buycount 购买人数 buyUsers 参与购买人信息列表-->
@BindView(R.id.iv_head) ImageView mIvHead;// <!--headpic 系列课头像-->
@BindView(R.id.tv_title) TextView mTvTitle;//<!--seriesname 系列课名称-->
@BindView(R.id.tv_price) TextView mTvPrice;//<!--fee 价格-->
@BindView(R.id.tv_return_livepage) ImageView mTvMore;
@BindView(R.id.layout_count) View mLayoutCount;
@BindView(R.id.tv_free_invite) TextView tvFreeInvite;
@BindView(R.id.tv_count) TextView mTvCount;
@BindView(R.id.ll_head_area) LinearLayout mLlHeadArea;
@BindView(R.id.tl_series_page_indicator) TabLayout mTlSeriesPageIndicator;
@BindView(R.id.app_bar) AppBarLayout mAppBar;
@BindView(R.id.vp_series_viewpager) ViewPager mVpSeriesViewpager;
@BindView(R.id.btn_create_topic) Button mBtnCreateTopic;
@BindView(R.id.btn_buy_series) TextView mBtnBuySeries;
@BindView(R.id.ll_audience_area) LinearLayout mLlAudienceArea;
@BindView(R.id.ll_owner_area) LinearLayout mLlOwnerArea;
@BindView(R.id.rl_series_owner_intro) RelativeLayout mRlSeriesOwnerIntro;
@BindView(R.id.ll_owner_share_btn) LinearLayout mLlOwnerShareBtn;
@BindView(R.id.ll_owner_setting_btn) LinearLayout mLlOwnerSettingBtn;
@BindView(R.id.ll_share_person_area) LinearLayout layoutShare;
@BindView(R.id.live_intro_follow_head) ImageView mLiveIntroImage;
@BindView(R.id.live_intro_follow_ownername) TextView tvName;
@BindView(R.id.live_intro_follow_attention) ImageView mImageView;
@BindView(R.id.img_sign_more) ImageView imgSignMore;
private List<Fragment> mFragments = new ArrayList<>();
private static String[] labTitles = {"详情", "课程"};
private SeriesIntroFragment mSeriesIntroFragment;
private NewLiveTopicFragment mNewLiveTopicFragment;
private SeriesPageAdapter mSeriesPageAdapter;
private SeriesPageBean mData;
private HashMap<String, String> map;
private UMShareUtils shareUtils;
private String mId;
private String shareUserCode;
private String freeSign;
private AlertDialog mAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
}
@Override
public void initView() {
EventBusUtil.register(this);
getBaseHeadView().showTitle("系列课主页");
getBaseHeadView().showBackButton(this);
getBaseHeadView().showHeadRightImageButton(R.drawable.navigation_icon_share, this);
}
@Override
public void initData() {
//这里去请求数据 如果请求成功了 才把空的view yinchangdiao
labTitles[1] = "课程2";
getData();
}
private void getData() {
hideContentView();
getBaseLoadingView().showLoading();
mId = getIntent().getStringExtra("id");
freeSign = getIntent().getStringExtra("freeSign");
//现在app所有的内部分享都不得佣金 除非是微信外部分享 圈子也是这样
if (!TextUtils.isEmpty(freeSign)) {
shareUserCode = getIntent().getStringExtra("userCode");
}
setdata();
}
private void setdata() {
Subscription sub = LiveApi.getInstance().getChatSeriesInfo(
UserManager.getInstance().getToken(), mId).subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<SeriesPageBean>>(new ApiCallBack<SeriesPageBean>() {
@Override
public void onSuccess(SeriesPageBean data) {
if (data != null && getBaseLoadingView() != null) {
getBaseLoadingView().hideLoading();
showContentView();
setdata(data);
}
}
@Override
public void onError(String errorCode, String message) {
if (getBaseLoadingView() != null) {
getBaseLoadingView().hideLoading();
LoginErrorCodeUtil.showHaveTokenError(SeriesActivity.this, errorCode,
message);
}
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private void setdata(SeriesPageBean data) {
mData = data;
if (mData == null || mTvTitle == null) return;
imgSignMore.setVisibility(mData.bIsSelf() ? View.GONE : View.VISIBLE);
ImageHelper.loadRound(this, mIvHead, mData.getHeadpic(), 4);
mTvTitle.setText(mData.getSeriesname());
mImageView.setPadding(0, 0, getResources().getDimensionPixelSize(R.dimen.px5dp), 0);
mImageView.setImageResource(R.drawable.person_icon_more);
ImageHelper.loadCircle(this, mLiveIntroImage, data.getAnchorPic(),
R.drawable.live_host_defaual_bg);
if (!TextUtils.isEmpty(mData.getUserName())) {
tvName.setText(mData.getUserName());
}
if (Double.valueOf(mData.getFee()) > 0d) {
mTvPrice.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
mTvPrice.setTextColor(getResources().getColor(R.color.color_price_ec6b46));
} else {
mTvPrice.setText("免费");
mTvPrice.setTextColor(getResources().getColor(R.color.color_119b1e));
}
mBtnCreateTopic.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
tvFreeInvite.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
mTlSeriesPageIndicator.setupWithViewPager(mVpSeriesViewpager);
labTitles[1] = "课程"; //+ mData.getChatInfos().size();
mTvCount.setText(mData.getBuyCount() + "人正在参与");
addPersonHead();
setModel();
setBuySeriesBtn();
mSeriesPageAdapter = new SeriesPageAdapter(getSupportFragmentManager(), getFragments(mData),
labTitles);
mVpSeriesViewpager.setAdapter(mSeriesPageAdapter);
mVpSeriesViewpager.setCurrentItem(1);
}
private void addPersonHead() {
if (mLlHeadArea != null) {
mLlHeadArea.removeAllViews();
}
int cout = mData.getBuyUsers().size() > 5 ? 5 : mData.getBuyUsers().size();
for (int i = 0; i < cout; i++) {
mLlHeadArea.addView(getPersonHead(mData.getBuyUsers().get(i).getHeadPic()));
}
if (layoutShare != null) {
layoutShare.removeAllViews();
}
if (mData.getUmVoList() != null) {
cout = mData.getUmVoList().size() > 5 ? 5 : mData.getUmVoList().size();
for (int i = 0; i < cout; i++) {
layoutShare.addView(getPersonHead(mData.getUmVoList().get(i).getName()));
}
}
}
private void setBuySeriesBtn() {
mBtnBuySeries.setVisibility(mData.bIsSelf() || mData.bIsBuy() ? View.GONE : View.VISIBLE);
mLlAudienceArea.setVisibility(mData.bIsSelf() || mData.bIsBuy() ? View.GONE : View.VISIBLE);
if (Double.valueOf(mData.getFee()) > 0d) {
mBtnBuySeries.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
} else {
mBtnBuySeries.setText("报名");
}
if (!mData.bIsSelf() && "1".equals(mData.getIsGroupUser()) && !mData.bIsBuy()) {
mTvPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
mTvPrice.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
mTvPrice.setTextColor(getResources().getColor(R.color.text_color_999));
mBtnBuySeries.setText("圈内成员,免费报名");
}
if (!TextUtils.isEmpty(freeSign)) {
mBtnBuySeries.setText("免费邀请,立即报名");
mData.setFee("0");
}
//显示免费邀请制按钮 没达成邀请人数都要显示
if (!mData.bIsSelf() && AUDITION_INVITE_TYPE.equals(
mData.getIsAuditions()) && !mData.isFinishInvite()) {
if (!mData.bIsBuy()) {
mBtnBuySeries.setText("报名试听");
mBtnBuySeries.setVisibility(View.VISIBLE);
mLlAudienceArea.setVisibility(View.VISIBLE);
}
}
}
private boolean isExamine(List<ChatInfosBean> list) {
for (ChatInfosBean bean : list) {
if (bean.getAudit().equals("1")) return true;
}
return false;
}
private boolean isCanShare() {
List<ChatInfosBean> list = mNewLiveTopicFragment.mLiveTopicAdapter.getList();
if (list == null || list.size() == 0) {
ToastUtil.showLong(this, "没创建子课程的系列课不能分享");
return false;
} else if (!isExamine(list)) {
ToastUtil.showLong(this, "子课程审核通过后才能分享");
return false;
}
return true;
}
@Override
public void initListener() {
mTvMore.setOnClickListener(this);
tvFreeInvite.setOnClickListener(this);
mBtnCreateTopic.setOnClickListener(this);
}
public List<Fragment> getFragments(SeriesPageBean o) {
mFragments.clear();
mSeriesIntroFragment = new SeriesIntroFragment();
mNewLiveTopicFragment = new NewLiveTopicFragment();
Bundle bundleChatInfos = new Bundle();
bundleChatInfos.putString("chatRoom", o.getChatRoom());
bundleChatInfos.putBoolean("series", true);
bundleChatInfos.putString("chatSeries", mId);
bundleChatInfos.putString("shareUserCode", shareUserCode);
bundleChatInfos.putString("freeSign", freeSign);
bundleChatInfos.putString("isAuditions", mData.getIsAuditions());
bundleChatInfos.putString("isBuy", mData.getIsBuy());
bundleChatInfos.putDouble("seriesFree", Double.valueOf(mData.getFee()));
bundleChatInfos.putSerializable("seriesBean", mData);
mNewLiveTopicFragment.setArguments(bundleChatInfos);
Bundle bundle = new Bundle();
bundle.putString("introduce", o.getIntroduce());
mSeriesIntroFragment.setArguments(bundle);
mFragments.add(mSeriesIntroFragment);
mFragments.add(mNewLiveTopicFragment);
return mFragments;
}
@Override
protected void onDestroy() {
RxTaskHelper.getInstance().cancelTask(this);
EventBusUtil.unregister(this);
ImageHelper.onDestroy(MyApplication.getInstance());
mAlertDialog = null;
super.onDestroy();
}
@OnClick({R.id.btn_create_topic, R.id.btn_buy_series, R.id.layout_count, R.id.ll_owner_setting_btn, R.id.ll_owner_share_btn, R.id.rl_series_owner_intro, R.id.layout_follow, R.id.layout_share, R.id.tv_free_invite})
public void onClick(View view) {
switch (view.getId()) {
case R.id.rl_series_owner_intro:
// finish();
break;
case R.id.layout_count:
//只有自己的系列课才可以点击查看报名的成员
if (UserManager.getInstance().isLogin(this)) {
if (mData.bIsSelf()) {
SeriesSignCountActivity.jumpToSeriesSignCountActivity(this, mData.getId(),
mData.getJoinType() + "");
}
}
break;
case R.id.btn_create_topic:
if (!UserManager.getInstance().isLogin()) {
GotoUtil.goToActivity(SeriesActivity.this, LoginAndRegisteActivity.class);
return;
}
//新建课程
map = new HashMap<>();
map.put("chatSeries", mData.getId());
map.put("chatInfoTypeId", mData.getChatInfoTypeId());
GotoUtil.goToActivityWithData(this, CreateTopicActivity.class, map);
break;
case R.id.btn_buy_series:
if (!UserManager.getInstance().isLogin()) {
GotoUtil.goToActivity(SeriesActivity.this, LoginAndRegisteActivity.class);
return;
}
//这里是已经成功报名,但是还未完成任务, 点击显示弹窗
if (AUDITION_INVITE_TYPE.equals(
mData.getIsAuditions()) && mData.bIsBuy() && !mData.isFinishInvite()) {
showInviteModel();
return;
}
if ("0".equals(mData.getFee())) {
playSeries();
return;
}
//圈内成员免费报名
if ("1".equals(mData.getIsGroupUser())) {
saveFreeChatSeries();
return;
}
playSeries();
break;
case R.id.headBackButton:
finish();
break;
case R.id.tv_free_invite:
if (!isCanShare()) return;
InvitedGuestsActivity.startActivity(SeriesActivity.this, mData.getId(), "4",
mData.getSeriesname(), mData.getHeadpic());
break;
case R.id.layout_follow:
if (mData != null) {
LiveHostPageActivity.startActivity(this, "1", mData.getChatRoom());
}
break;
case R.id.ll_owner_setting_btn:
//设置 把当前对象传递到下一个页面
if (mData != null) {
Intent intent = new Intent(this, CreateSeriesCourseActivity.class);
intent.putExtra("bean", mData);
startActivityForResult(intent, SETTING_SERIES);
//GotoUtil.goToActivityWithBean(SeriesActivity.this,CreateSeriesCourseActivity.class,mData);
}
break;
//分享
case R.id.HeadRightImageButton:
case R.id.ll_owner_share_btn:
if (!UserManager.getInstance().isLogin(this)) return;
if (!isCanShare()) return;
if (mData != null) {
String[] pers = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
performRequestPermissions(getString(R.string.txt_card_permission), pers, 2200,
new PermissionsResultListener() {
@Override
public void onPermissionGranted() {
final String uri = TextUtils.isEmpty(
mData.getHeadpic()) ? Constant.DEFUAL_SHARE_IMAGE_URI : mData.getHeadpic();
ShareDialog.Action[] actions = {new ShareDialog.Action(
ShareDialog.ACTION_INVITE,
R.drawable.share_icon_invitation,
null), new ShareDialog.Action(ShareDialog.ACTION_QRCODE,
R.drawable.share_icon_erweima,
null), new ShareDialog.Action(
ShareDialog.ACTION_COLLECT,
R.drawable.share_icon_collect,
null), new ShareDialog.Action(ShareDialog.ACTION_COPY,
R.drawable.share_icon_copy,
null), new ShareDialog.Action(ShareDialog.ACTION_CIRCLE,
R.drawable.share_icon_my_dynamic,
null), new ShareDialog.Action(
ShareDialog.ACTION_FRIENDS,
R.drawable.share_icon_friends, null)};
shareUtils = new UMShareUtils(SeriesActivity.this);
shareUtils.shareCustom(uri, mData.getSeriesname(),
mData.getIntroduce(), mData.getShareUrl(), actions,
new ShareDialog.OnShareLisntener() {
@Override
public void onShare(@Nullable String key,
@Nullable SHARE_MEDIA media) {
switch (key) {
//这里跳去邀请卡
case ShareDialog.ACTION_INVITE:
ShareImgActivity.startActivity(
SeriesActivity.this,
mData.getId());
break;
//分享到动态
case ShareDialog.ACTION_CIRCLE:
IssueDynamicActivity.share(
SeriesActivity.this,
mData.getId(), "6",
mData.getSeriesname(), uri);
break;
//分享到好友
case ShareDialog.ACTION_FRIENDS:
ConversationListActivity.startActivity(
SeriesActivity.this,
ConversationActivity.REQUEST_SHARE_CONTENT,
Constant.SELECT_TYPE_SHARE);
break;
//收藏
case ShareDialog.ACTION_COLLECT:
collect(mData.getId());
break;
//二维码
case ShareDialog.ACTION_QRCODE:
ErWeiCodeActivity.startActivity(
SeriesActivity.this,
ErWeiCodeActivity.TYPE_SERIES,
Integer.valueOf(mData.getId()),
"");
break;
}
}
});
}
@Override
public void onPermissionDenied() {
mAlertDialog = DialogUtil.showDeportDialog(SeriesActivity.this,
false, null, getString(R.string.pre_storage_notice_msg),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.tv_dialog_confirm) {
JumpPermissionManagement.GoToSetting(
SeriesActivity.this);
}
mAlertDialog.dismiss();
}
});
}
});
}
break;
//分享达人榜
case R.id.layout_share:
if (UserManager.getInstance().isLogin()) {
if (!isCanShare()) return;
Intent intent = new Intent(SeriesActivity.this, SeriesShareListActivity.class);
intent.putExtra(Constant.INTENT_DATA, mData);
startActivity(intent);
} else GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
break;
}
}
private SeriesCourseInviteDialog mInviteDialog;
private void showInviteModel() {
mInviteDialog = new SeriesCourseInviteDialog(mData);
mInviteDialog.show(getSupportFragmentManager(),
SeriesCourseInviteDialog.class.getSimpleName());
}
private void saveFreeChatSeries() {
Subscription sub = LiveApi.getInstance().saveFreeChatSeriesBuy(
UserManager.getInstance().getToken(), mId).subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack<Void>() {
@Override
public void onSuccess(Void data) {
ToastUtil.showShort(MyApplication.getInstance(), "报名成功");
setdata();
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(MyApplication.getInstance(), message);
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private void collect(String classId) {
HashMap<String, String> map = new HashMap<>();
map.put("token", UserManager.getInstance().getToken());
map.put("bizType", "9");
map.put("bizId", classId);
Subscription sub = AllApi.getInstance().saveCollection(map).subscribeOn(
Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<Object>>(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if (mData.getIsCollect() == 0) {
mData.setIsCollect(1);
ToastUtil.showShort(SeriesActivity.this, "收藏成功");
} else {
mData.setIsCollect(0);
ToastUtil.showShort(SeriesActivity.this, "取消收藏");
}
}
@Override
public void onError(String errorCode, String message) {
LoginErrorCodeUtil.showHaveTokenError(SeriesActivity.this, errorCode,
message);
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private boolean playing = false;
private void playSeries() {
if (!TextUtils.isEmpty(freeSign) && !TextUtils.isEmpty(shareUserCode)) {
freeInviteJoin();
return;
}
String fee = mData.getFee();
BigDecimal moneyB = new BigDecimal(fee);
//计算总价
double total = moneyB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
JSONObject jsonObject = new JSONObject();
jsonObject.put("chatSeriesId", mData.getId());
if (!TextUtils.isEmpty(shareUserCode)) {
jsonObject.put("userCode", shareUserCode);
jsonObject.put("joinType", 0);
jsonObject.put("type", 1);
}
String extra = jsonObject.toJSONString();
OrdersRequestBean requestBean = new OrdersRequestBean();
requestBean.setToken(UserManager.getInstance().getToken());
requestBean.setTransType("CS");
requestBean.setTotalPrice(total + "");
requestBean.setExtra(extra);
requestBean.setGoodsName("系列课购买");
if ("0".equals(fee)) {
requestBean.setPayType("ALIPAY");
HashMap<String, String> map = new HashMap<>();
map.put("token", requestBean.getToken());
map.put("transType", requestBean.getTransType());
map.put("payType", requestBean.getPayType());
map.put("totalPrice", requestBean.getTotalPrice());
map.put("extra", requestBean.getExtra());
getBaseLoadingView().showLoading();
Subscription sub = PayApi.getInstance().getOrder(map).subscribeOn(
Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<OrdersResultBean>>(
new ApiCallBack<OrdersResultBean>() {
@Override
public void onSuccess(OrdersResultBean data) {
getBaseLoadingView().hideLoading();
Toast.makeText(SeriesActivity.this, "报名成功",
Toast.LENGTH_SHORT).show();
//显示免费邀请制规则弹窗
if (AUDITION_INVITE_TYPE.equals(mData.getIsAuditions())) {
showInviteModel();
}
if (mData != null) {
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
}
@Override
public void onError(String errorCode, String message) {
getBaseLoadingView().hideLoading();
Toast.makeText(SeriesActivity.this, "报名失败",
Toast.LENGTH_SHORT).show();
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
} else {
playing = true;
GotoUtil.goToActivity(this, PayActivity.class, Constant.INTENT_PAY_RESULT, requestBean);
}
}
//免费邀请报名
private void freeInviteJoin() {
getBaseLoadingView().showLoading();
String token = UserManager.getInstance().getToken();
String transType = "CS";
String payType = "WX";
String totalPrice = "0";
JSONObject jobj = new JSONObject();
jobj.put("chatSeriesId", mData.getId());
jobj.put("freeSign", freeSign);
jobj.put("userCode", shareUserCode);
jobj.put("joinType", 4);
String extra = jobj.toString();
HashMap<String, String> map = new HashMap<>();
map.put("token", token);
map.put("transType", transType);
map.put("payType", payType);
map.put("totalPrice", totalPrice);
map.put("extra", extra);
Subscription sub = PayApi.getInstance().getOrder(map).observeOn(
AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(
new ApiObserver<ApiResponseBean<OrdersResultBean>>(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if (mData != null) {
Toast.makeText(SeriesActivity.this, "报名成功", Toast.LENGTH_SHORT).show();
getBaseLoadingView().hideLoading();
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
}
@Override
public void onError(String errorCode, String message) {
if (mData != null) {
ToastUtil.showShort(SeriesActivity.this, message);
getBaseLoadingView().hideLoading();
}
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
/**
* 添加头像
*
* @param uri
* @return
*/
private ImageView getPersonHead(String uri) {
int dimensionPixelOffset = getResources().getDimensionPixelOffset(R.dimen.px60dp);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dimensionPixelOffset,
dimensionPixelOffset);
int margin = getResources().getDimensionPixelOffset(R.dimen.margin_small);
layoutParams.setMargins(margin, margin, margin, margin);
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(layoutParams);
ImageHelper.loadCircle(this, imageView, uri, R.drawable.person_icon_head_120);
return imageView;
}
private void setModel() {
mLlOwnerArea.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
}
@Subscribe
public void onEvent(EventSeriesInviteBean bean) {
showInviteModel();
}
@Subscribe
public void onEvent(CreateLiveTopicBean bean) {
this.getData();
}
@Subscribe
public void SeriesPayEvent(EventSeriesPayBean bean) {
if (bean.flag) {
getData();
}
}
/**
* 支付回调
*
* @param bean
*/
@Subscribe
public void onEvent(PayBean bean) {
if (!playing) return;
if (!bean.isPaySucc) {//支付失败
ToastUtil.showShort(this, "支付失败");
} else {
getData();
}
playing = false;
}
/**
* 更新修改系列课后的内容
*/
@Subscribe
public void onEvent(SeriesPageBean bean) {
getData();
}
@Subscribe
public void onEvent(EventDelSeries bean) {
this.finish();
}
@Subscribe
public void onEvent(EventLoginBean bean) {
if (bean.status == EventLoginBean.LOGIN || bean.status == EventLoginBean.REGISTE || bean.status == EventLoginBean.THIRDLOGIN) {
getData();
}
}
//分享到好友
private void shareMessage(final String targetId, final Conversation.ConversationType type,
final String liuyan) {
String title = mData.getSeriesname();
String img = TextUtils.isEmpty(
mData.getHeadpic()) ? Constant.DEFUAL_SHARE_IMAGE_URI : mData.getHeadpic();
String id = mData.getId();
ImMessageUtils.shareMessage(targetId, type, id, title, img, CircleShareHandler.SHARE_SERIES,
new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {
}
@Override
public void onSuccess(Message message) {
ToastUtil.showShort(SeriesActivity.this, "分享成功");
if (!TextUtils.isEmpty(liuyan)) {
RongIMTextUtil.INSTANCE.relayMessage(liuyan, targetId, type);
}
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
ToastUtil.showShort(SeriesActivity.this,
"分享失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLAYSERIES_REQUEST && resultCode == RESULT_OK) {
if (mData != null) {
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
} else if (requestCode == SETTING_SERIES && resultCode == RESULT_OK) {
setdata((SeriesPageBean) data.getSerializableExtra("seriesBean"));
}
if (resultCode == Constant.ResponseCode.CIRCLE_ISSUE) {
ToastUtil.showShort(this, "分享成功");
}
if (requestCode == ConversationActivity.REQUEST_SHARE_CONTENT && resultCode == RESULT_OK) {
EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA);
String targetId = bean.targetId;
Conversation.ConversationType type = bean.mType;
shareMessage(targetId, type, bean.liuyan);
}
if (requestCode == 666 && resultCode == Constant.ResponseCode.ISSUE_TONG_BU) {
mNewLiveTopicFragment.onActivityResult(requestCode, resultCode, data);
}
if (requestCode == NewLiveTopicFragment.REQUEST_TOPIC_INTRO && resultCode == 999) {
showInviteModel();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public List<ChatInfosBean> getChatinfosList() {
if (mData != null) {
return mData.getChatInfos();
}
return null;
}
public static void startActivity(Context context, String id) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
context.startActivity(intent);
}
public static void startActivityForResult(Activity context, String id, int recode) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
context.startActivityForResult(intent, recode);
}
//免费邀请报名 freeSign 免费邀请码
public static void freeInvite(Context context, String id, String shareUserCode,
String freeSign) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("userCode", shareUserCode);
intent.putExtra("freeSign", freeSign);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, String userCode) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("userCode", userCode);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, boolean isByLiveFragment) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("isByLiveFragment", isByLiveFragment);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, boolean isByLiveFragment,
int flag) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("isByLiveFragment", isByLiveFragment);
intent.addFlags(flag);
context.startActivity(intent);
}
}
| UTF-8 | Java | 41,219 | java | SeriesActivity.java | Java | [
{
"context": "g> map = new HashMap<>();\n map.put(\"token\", UserManager.getInstance().getToken());\n map.put(\"bizType\", \"9\");\n map.",
"end": 27179,
"score": 0.7874279618263245,
"start": 27145,
"tag": "KEY",
"value": "UserManager.getInstance().getToken"
}
]
| null | []
| package com.gxtc.huchuan.ui.live.series;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.helper.ImageHelper;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.SeriesPageAdapter;
import com.gxtc.huchuan.bean.ChatInfosBean;
import com.gxtc.huchuan.bean.CreateLiveTopicBean;
import com.gxtc.huchuan.bean.SeriesPageBean;
import com.gxtc.huchuan.bean.event.EventDelSeries;
import com.gxtc.huchuan.bean.event.EventLoginBean;
import com.gxtc.huchuan.bean.event.EventSelectFriendBean;
import com.gxtc.huchuan.bean.event.EventSeriesInviteBean;
import com.gxtc.huchuan.bean.event.EventSeriesPayBean;
import com.gxtc.huchuan.bean.pay.OrdersRequestBean;
import com.gxtc.huchuan.bean.pay.OrdersResultBean;
import com.gxtc.huchuan.bean.pay.PayBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.dialog.SeriesCourseInviteDialog;
import com.gxtc.huchuan.dialog.ShareDialog;
import com.gxtc.huchuan.handler.CircleShareHandler;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.AllApi;
import com.gxtc.huchuan.http.service.LiveApi;
import com.gxtc.huchuan.http.service.PayApi;
import com.gxtc.huchuan.im.ui.ConversationActivity;
import com.gxtc.huchuan.im.ui.ConversationListActivity;
import com.gxtc.huchuan.ui.circle.dynamic.IssueDynamicActivity;
import com.gxtc.huchuan.ui.circle.erweicode.ErWeiCodeActivity;
import com.gxtc.huchuan.ui.live.hostpage.IGetChatinfos;
import com.gxtc.huchuan.ui.live.hostpage.LiveHostPageActivity;
import com.gxtc.huchuan.ui.live.hostpage.NewLiveTopicFragment;
import com.gxtc.huchuan.ui.live.intro.ShareImgActivity;
import com.gxtc.huchuan.ui.live.series.count.SeriesSignCountActivity;
import com.gxtc.huchuan.ui.live.series.share.SeriesShareListActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.createseriescourse.CreateSeriesCourseActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.createtopic.CreateTopicActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.livebgsetting.InvitedGuestsActivity;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.ui.pay.PayActivity;
import com.gxtc.huchuan.utils.DialogUtil;
import com.gxtc.huchuan.utils.ImMessageUtils;
import com.gxtc.huchuan.utils.JumpPermissionManagement;
import com.gxtc.huchuan.utils.LoginErrorCodeUtil;
import com.gxtc.huchuan.utils.RIMErrorCodeUtil;
import com.gxtc.huchuan.utils.RongIMTextUtil;
import com.gxtc.huchuan.utils.UMShareUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* 系列课主页
*/
public class SeriesActivity extends BaseTitleActivity implements IGetChatinfos,
View.OnClickListener {
public static final String AUDITION_TYPE = "1"; //免费试听模式
public static final String AUDITION_INVITE_TYPE = "2"; //邀请制免费试听模式
private static final String TAG = "SeriesActivity";
private static final int PLAYSERIES_REQUEST = 1 << 2;
private static final int SETTING_SERIES = 1 << 3;
//<!--headpic 系列课头像-->
//<!--buycount 购买人数 buyUsers 参与购买人信息列表-->
@BindView(R.id.iv_head) ImageView mIvHead;// <!--headpic 系列课头像-->
@BindView(R.id.tv_title) TextView mTvTitle;//<!--seriesname 系列课名称-->
@BindView(R.id.tv_price) TextView mTvPrice;//<!--fee 价格-->
@BindView(R.id.tv_return_livepage) ImageView mTvMore;
@BindView(R.id.layout_count) View mLayoutCount;
@BindView(R.id.tv_free_invite) TextView tvFreeInvite;
@BindView(R.id.tv_count) TextView mTvCount;
@BindView(R.id.ll_head_area) LinearLayout mLlHeadArea;
@BindView(R.id.tl_series_page_indicator) TabLayout mTlSeriesPageIndicator;
@BindView(R.id.app_bar) AppBarLayout mAppBar;
@BindView(R.id.vp_series_viewpager) ViewPager mVpSeriesViewpager;
@BindView(R.id.btn_create_topic) Button mBtnCreateTopic;
@BindView(R.id.btn_buy_series) TextView mBtnBuySeries;
@BindView(R.id.ll_audience_area) LinearLayout mLlAudienceArea;
@BindView(R.id.ll_owner_area) LinearLayout mLlOwnerArea;
@BindView(R.id.rl_series_owner_intro) RelativeLayout mRlSeriesOwnerIntro;
@BindView(R.id.ll_owner_share_btn) LinearLayout mLlOwnerShareBtn;
@BindView(R.id.ll_owner_setting_btn) LinearLayout mLlOwnerSettingBtn;
@BindView(R.id.ll_share_person_area) LinearLayout layoutShare;
@BindView(R.id.live_intro_follow_head) ImageView mLiveIntroImage;
@BindView(R.id.live_intro_follow_ownername) TextView tvName;
@BindView(R.id.live_intro_follow_attention) ImageView mImageView;
@BindView(R.id.img_sign_more) ImageView imgSignMore;
private List<Fragment> mFragments = new ArrayList<>();
private static String[] labTitles = {"详情", "课程"};
private SeriesIntroFragment mSeriesIntroFragment;
private NewLiveTopicFragment mNewLiveTopicFragment;
private SeriesPageAdapter mSeriesPageAdapter;
private SeriesPageBean mData;
private HashMap<String, String> map;
private UMShareUtils shareUtils;
private String mId;
private String shareUserCode;
private String freeSign;
private AlertDialog mAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
}
@Override
public void initView() {
EventBusUtil.register(this);
getBaseHeadView().showTitle("系列课主页");
getBaseHeadView().showBackButton(this);
getBaseHeadView().showHeadRightImageButton(R.drawable.navigation_icon_share, this);
}
@Override
public void initData() {
//这里去请求数据 如果请求成功了 才把空的view yinchangdiao
labTitles[1] = "课程2";
getData();
}
private void getData() {
hideContentView();
getBaseLoadingView().showLoading();
mId = getIntent().getStringExtra("id");
freeSign = getIntent().getStringExtra("freeSign");
//现在app所有的内部分享都不得佣金 除非是微信外部分享 圈子也是这样
if (!TextUtils.isEmpty(freeSign)) {
shareUserCode = getIntent().getStringExtra("userCode");
}
setdata();
}
private void setdata() {
Subscription sub = LiveApi.getInstance().getChatSeriesInfo(
UserManager.getInstance().getToken(), mId).subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<SeriesPageBean>>(new ApiCallBack<SeriesPageBean>() {
@Override
public void onSuccess(SeriesPageBean data) {
if (data != null && getBaseLoadingView() != null) {
getBaseLoadingView().hideLoading();
showContentView();
setdata(data);
}
}
@Override
public void onError(String errorCode, String message) {
if (getBaseLoadingView() != null) {
getBaseLoadingView().hideLoading();
LoginErrorCodeUtil.showHaveTokenError(SeriesActivity.this, errorCode,
message);
}
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private void setdata(SeriesPageBean data) {
mData = data;
if (mData == null || mTvTitle == null) return;
imgSignMore.setVisibility(mData.bIsSelf() ? View.GONE : View.VISIBLE);
ImageHelper.loadRound(this, mIvHead, mData.getHeadpic(), 4);
mTvTitle.setText(mData.getSeriesname());
mImageView.setPadding(0, 0, getResources().getDimensionPixelSize(R.dimen.px5dp), 0);
mImageView.setImageResource(R.drawable.person_icon_more);
ImageHelper.loadCircle(this, mLiveIntroImage, data.getAnchorPic(),
R.drawable.live_host_defaual_bg);
if (!TextUtils.isEmpty(mData.getUserName())) {
tvName.setText(mData.getUserName());
}
if (Double.valueOf(mData.getFee()) > 0d) {
mTvPrice.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
mTvPrice.setTextColor(getResources().getColor(R.color.color_price_ec6b46));
} else {
mTvPrice.setText("免费");
mTvPrice.setTextColor(getResources().getColor(R.color.color_119b1e));
}
mBtnCreateTopic.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
tvFreeInvite.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
mTlSeriesPageIndicator.setupWithViewPager(mVpSeriesViewpager);
labTitles[1] = "课程"; //+ mData.getChatInfos().size();
mTvCount.setText(mData.getBuyCount() + "人正在参与");
addPersonHead();
setModel();
setBuySeriesBtn();
mSeriesPageAdapter = new SeriesPageAdapter(getSupportFragmentManager(), getFragments(mData),
labTitles);
mVpSeriesViewpager.setAdapter(mSeriesPageAdapter);
mVpSeriesViewpager.setCurrentItem(1);
}
private void addPersonHead() {
if (mLlHeadArea != null) {
mLlHeadArea.removeAllViews();
}
int cout = mData.getBuyUsers().size() > 5 ? 5 : mData.getBuyUsers().size();
for (int i = 0; i < cout; i++) {
mLlHeadArea.addView(getPersonHead(mData.getBuyUsers().get(i).getHeadPic()));
}
if (layoutShare != null) {
layoutShare.removeAllViews();
}
if (mData.getUmVoList() != null) {
cout = mData.getUmVoList().size() > 5 ? 5 : mData.getUmVoList().size();
for (int i = 0; i < cout; i++) {
layoutShare.addView(getPersonHead(mData.getUmVoList().get(i).getName()));
}
}
}
private void setBuySeriesBtn() {
mBtnBuySeries.setVisibility(mData.bIsSelf() || mData.bIsBuy() ? View.GONE : View.VISIBLE);
mLlAudienceArea.setVisibility(mData.bIsSelf() || mData.bIsBuy() ? View.GONE : View.VISIBLE);
if (Double.valueOf(mData.getFee()) > 0d) {
mBtnBuySeries.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
} else {
mBtnBuySeries.setText("报名");
}
if (!mData.bIsSelf() && "1".equals(mData.getIsGroupUser()) && !mData.bIsBuy()) {
mTvPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
mTvPrice.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
mTvPrice.setTextColor(getResources().getColor(R.color.text_color_999));
mBtnBuySeries.setText("圈内成员,免费报名");
}
if (!TextUtils.isEmpty(freeSign)) {
mBtnBuySeries.setText("免费邀请,立即报名");
mData.setFee("0");
}
//显示免费邀请制按钮 没达成邀请人数都要显示
if (!mData.bIsSelf() && AUDITION_INVITE_TYPE.equals(
mData.getIsAuditions()) && !mData.isFinishInvite()) {
if (!mData.bIsBuy()) {
mBtnBuySeries.setText("报名试听");
mBtnBuySeries.setVisibility(View.VISIBLE);
mLlAudienceArea.setVisibility(View.VISIBLE);
}
}
}
private boolean isExamine(List<ChatInfosBean> list) {
for (ChatInfosBean bean : list) {
if (bean.getAudit().equals("1")) return true;
}
return false;
}
private boolean isCanShare() {
List<ChatInfosBean> list = mNewLiveTopicFragment.mLiveTopicAdapter.getList();
if (list == null || list.size() == 0) {
ToastUtil.showLong(this, "没创建子课程的系列课不能分享");
return false;
} else if (!isExamine(list)) {
ToastUtil.showLong(this, "子课程审核通过后才能分享");
return false;
}
return true;
}
@Override
public void initListener() {
mTvMore.setOnClickListener(this);
tvFreeInvite.setOnClickListener(this);
mBtnCreateTopic.setOnClickListener(this);
}
public List<Fragment> getFragments(SeriesPageBean o) {
mFragments.clear();
mSeriesIntroFragment = new SeriesIntroFragment();
mNewLiveTopicFragment = new NewLiveTopicFragment();
Bundle bundleChatInfos = new Bundle();
bundleChatInfos.putString("chatRoom", o.getChatRoom());
bundleChatInfos.putBoolean("series", true);
bundleChatInfos.putString("chatSeries", mId);
bundleChatInfos.putString("shareUserCode", shareUserCode);
bundleChatInfos.putString("freeSign", freeSign);
bundleChatInfos.putString("isAuditions", mData.getIsAuditions());
bundleChatInfos.putString("isBuy", mData.getIsBuy());
bundleChatInfos.putDouble("seriesFree", Double.valueOf(mData.getFee()));
bundleChatInfos.putSerializable("seriesBean", mData);
mNewLiveTopicFragment.setArguments(bundleChatInfos);
Bundle bundle = new Bundle();
bundle.putString("introduce", o.getIntroduce());
mSeriesIntroFragment.setArguments(bundle);
mFragments.add(mSeriesIntroFragment);
mFragments.add(mNewLiveTopicFragment);
return mFragments;
}
@Override
protected void onDestroy() {
RxTaskHelper.getInstance().cancelTask(this);
EventBusUtil.unregister(this);
ImageHelper.onDestroy(MyApplication.getInstance());
mAlertDialog = null;
super.onDestroy();
}
@OnClick({R.id.btn_create_topic, R.id.btn_buy_series, R.id.layout_count, R.id.ll_owner_setting_btn, R.id.ll_owner_share_btn, R.id.rl_series_owner_intro, R.id.layout_follow, R.id.layout_share, R.id.tv_free_invite})
public void onClick(View view) {
switch (view.getId()) {
case R.id.rl_series_owner_intro:
// finish();
break;
case R.id.layout_count:
//只有自己的系列课才可以点击查看报名的成员
if (UserManager.getInstance().isLogin(this)) {
if (mData.bIsSelf()) {
SeriesSignCountActivity.jumpToSeriesSignCountActivity(this, mData.getId(),
mData.getJoinType() + "");
}
}
break;
case R.id.btn_create_topic:
if (!UserManager.getInstance().isLogin()) {
GotoUtil.goToActivity(SeriesActivity.this, LoginAndRegisteActivity.class);
return;
}
//新建课程
map = new HashMap<>();
map.put("chatSeries", mData.getId());
map.put("chatInfoTypeId", mData.getChatInfoTypeId());
GotoUtil.goToActivityWithData(this, CreateTopicActivity.class, map);
break;
case R.id.btn_buy_series:
if (!UserManager.getInstance().isLogin()) {
GotoUtil.goToActivity(SeriesActivity.this, LoginAndRegisteActivity.class);
return;
}
//这里是已经成功报名,但是还未完成任务, 点击显示弹窗
if (AUDITION_INVITE_TYPE.equals(
mData.getIsAuditions()) && mData.bIsBuy() && !mData.isFinishInvite()) {
showInviteModel();
return;
}
if ("0".equals(mData.getFee())) {
playSeries();
return;
}
//圈内成员免费报名
if ("1".equals(mData.getIsGroupUser())) {
saveFreeChatSeries();
return;
}
playSeries();
break;
case R.id.headBackButton:
finish();
break;
case R.id.tv_free_invite:
if (!isCanShare()) return;
InvitedGuestsActivity.startActivity(SeriesActivity.this, mData.getId(), "4",
mData.getSeriesname(), mData.getHeadpic());
break;
case R.id.layout_follow:
if (mData != null) {
LiveHostPageActivity.startActivity(this, "1", mData.getChatRoom());
}
break;
case R.id.ll_owner_setting_btn:
//设置 把当前对象传递到下一个页面
if (mData != null) {
Intent intent = new Intent(this, CreateSeriesCourseActivity.class);
intent.putExtra("bean", mData);
startActivityForResult(intent, SETTING_SERIES);
//GotoUtil.goToActivityWithBean(SeriesActivity.this,CreateSeriesCourseActivity.class,mData);
}
break;
//分享
case R.id.HeadRightImageButton:
case R.id.ll_owner_share_btn:
if (!UserManager.getInstance().isLogin(this)) return;
if (!isCanShare()) return;
if (mData != null) {
String[] pers = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
performRequestPermissions(getString(R.string.txt_card_permission), pers, 2200,
new PermissionsResultListener() {
@Override
public void onPermissionGranted() {
final String uri = TextUtils.isEmpty(
mData.getHeadpic()) ? Constant.DEFUAL_SHARE_IMAGE_URI : mData.getHeadpic();
ShareDialog.Action[] actions = {new ShareDialog.Action(
ShareDialog.ACTION_INVITE,
R.drawable.share_icon_invitation,
null), new ShareDialog.Action(ShareDialog.ACTION_QRCODE,
R.drawable.share_icon_erweima,
null), new ShareDialog.Action(
ShareDialog.ACTION_COLLECT,
R.drawable.share_icon_collect,
null), new ShareDialog.Action(ShareDialog.ACTION_COPY,
R.drawable.share_icon_copy,
null), new ShareDialog.Action(ShareDialog.ACTION_CIRCLE,
R.drawable.share_icon_my_dynamic,
null), new ShareDialog.Action(
ShareDialog.ACTION_FRIENDS,
R.drawable.share_icon_friends, null)};
shareUtils = new UMShareUtils(SeriesActivity.this);
shareUtils.shareCustom(uri, mData.getSeriesname(),
mData.getIntroduce(), mData.getShareUrl(), actions,
new ShareDialog.OnShareLisntener() {
@Override
public void onShare(@Nullable String key,
@Nullable SHARE_MEDIA media) {
switch (key) {
//这里跳去邀请卡
case ShareDialog.ACTION_INVITE:
ShareImgActivity.startActivity(
SeriesActivity.this,
mData.getId());
break;
//分享到动态
case ShareDialog.ACTION_CIRCLE:
IssueDynamicActivity.share(
SeriesActivity.this,
mData.getId(), "6",
mData.getSeriesname(), uri);
break;
//分享到好友
case ShareDialog.ACTION_FRIENDS:
ConversationListActivity.startActivity(
SeriesActivity.this,
ConversationActivity.REQUEST_SHARE_CONTENT,
Constant.SELECT_TYPE_SHARE);
break;
//收藏
case ShareDialog.ACTION_COLLECT:
collect(mData.getId());
break;
//二维码
case ShareDialog.ACTION_QRCODE:
ErWeiCodeActivity.startActivity(
SeriesActivity.this,
ErWeiCodeActivity.TYPE_SERIES,
Integer.valueOf(mData.getId()),
"");
break;
}
}
});
}
@Override
public void onPermissionDenied() {
mAlertDialog = DialogUtil.showDeportDialog(SeriesActivity.this,
false, null, getString(R.string.pre_storage_notice_msg),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.tv_dialog_confirm) {
JumpPermissionManagement.GoToSetting(
SeriesActivity.this);
}
mAlertDialog.dismiss();
}
});
}
});
}
break;
//分享达人榜
case R.id.layout_share:
if (UserManager.getInstance().isLogin()) {
if (!isCanShare()) return;
Intent intent = new Intent(SeriesActivity.this, SeriesShareListActivity.class);
intent.putExtra(Constant.INTENT_DATA, mData);
startActivity(intent);
} else GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
break;
}
}
private SeriesCourseInviteDialog mInviteDialog;
private void showInviteModel() {
mInviteDialog = new SeriesCourseInviteDialog(mData);
mInviteDialog.show(getSupportFragmentManager(),
SeriesCourseInviteDialog.class.getSimpleName());
}
private void saveFreeChatSeries() {
Subscription sub = LiveApi.getInstance().saveFreeChatSeriesBuy(
UserManager.getInstance().getToken(), mId).subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack<Void>() {
@Override
public void onSuccess(Void data) {
ToastUtil.showShort(MyApplication.getInstance(), "报名成功");
setdata();
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(MyApplication.getInstance(), message);
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private void collect(String classId) {
HashMap<String, String> map = new HashMap<>();
map.put("token", UserManager.getInstance().getToken());
map.put("bizType", "9");
map.put("bizId", classId);
Subscription sub = AllApi.getInstance().saveCollection(map).subscribeOn(
Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<Object>>(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if (mData.getIsCollect() == 0) {
mData.setIsCollect(1);
ToastUtil.showShort(SeriesActivity.this, "收藏成功");
} else {
mData.setIsCollect(0);
ToastUtil.showShort(SeriesActivity.this, "取消收藏");
}
}
@Override
public void onError(String errorCode, String message) {
LoginErrorCodeUtil.showHaveTokenError(SeriesActivity.this, errorCode,
message);
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private boolean playing = false;
private void playSeries() {
if (!TextUtils.isEmpty(freeSign) && !TextUtils.isEmpty(shareUserCode)) {
freeInviteJoin();
return;
}
String fee = mData.getFee();
BigDecimal moneyB = new BigDecimal(fee);
//计算总价
double total = moneyB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
JSONObject jsonObject = new JSONObject();
jsonObject.put("chatSeriesId", mData.getId());
if (!TextUtils.isEmpty(shareUserCode)) {
jsonObject.put("userCode", shareUserCode);
jsonObject.put("joinType", 0);
jsonObject.put("type", 1);
}
String extra = jsonObject.toJSONString();
OrdersRequestBean requestBean = new OrdersRequestBean();
requestBean.setToken(UserManager.getInstance().getToken());
requestBean.setTransType("CS");
requestBean.setTotalPrice(total + "");
requestBean.setExtra(extra);
requestBean.setGoodsName("系列课购买");
if ("0".equals(fee)) {
requestBean.setPayType("ALIPAY");
HashMap<String, String> map = new HashMap<>();
map.put("token", requestBean.getToken());
map.put("transType", requestBean.getTransType());
map.put("payType", requestBean.getPayType());
map.put("totalPrice", requestBean.getTotalPrice());
map.put("extra", requestBean.getExtra());
getBaseLoadingView().showLoading();
Subscription sub = PayApi.getInstance().getOrder(map).subscribeOn(
Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<OrdersResultBean>>(
new ApiCallBack<OrdersResultBean>() {
@Override
public void onSuccess(OrdersResultBean data) {
getBaseLoadingView().hideLoading();
Toast.makeText(SeriesActivity.this, "报名成功",
Toast.LENGTH_SHORT).show();
//显示免费邀请制规则弹窗
if (AUDITION_INVITE_TYPE.equals(mData.getIsAuditions())) {
showInviteModel();
}
if (mData != null) {
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
}
@Override
public void onError(String errorCode, String message) {
getBaseLoadingView().hideLoading();
Toast.makeText(SeriesActivity.this, "报名失败",
Toast.LENGTH_SHORT).show();
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
} else {
playing = true;
GotoUtil.goToActivity(this, PayActivity.class, Constant.INTENT_PAY_RESULT, requestBean);
}
}
//免费邀请报名
private void freeInviteJoin() {
getBaseLoadingView().showLoading();
String token = UserManager.getInstance().getToken();
String transType = "CS";
String payType = "WX";
String totalPrice = "0";
JSONObject jobj = new JSONObject();
jobj.put("chatSeriesId", mData.getId());
jobj.put("freeSign", freeSign);
jobj.put("userCode", shareUserCode);
jobj.put("joinType", 4);
String extra = jobj.toString();
HashMap<String, String> map = new HashMap<>();
map.put("token", token);
map.put("transType", transType);
map.put("payType", payType);
map.put("totalPrice", totalPrice);
map.put("extra", extra);
Subscription sub = PayApi.getInstance().getOrder(map).observeOn(
AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(
new ApiObserver<ApiResponseBean<OrdersResultBean>>(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if (mData != null) {
Toast.makeText(SeriesActivity.this, "报名成功", Toast.LENGTH_SHORT).show();
getBaseLoadingView().hideLoading();
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
}
@Override
public void onError(String errorCode, String message) {
if (mData != null) {
ToastUtil.showShort(SeriesActivity.this, message);
getBaseLoadingView().hideLoading();
}
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
/**
* 添加头像
*
* @param uri
* @return
*/
private ImageView getPersonHead(String uri) {
int dimensionPixelOffset = getResources().getDimensionPixelOffset(R.dimen.px60dp);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dimensionPixelOffset,
dimensionPixelOffset);
int margin = getResources().getDimensionPixelOffset(R.dimen.margin_small);
layoutParams.setMargins(margin, margin, margin, margin);
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(layoutParams);
ImageHelper.loadCircle(this, imageView, uri, R.drawable.person_icon_head_120);
return imageView;
}
private void setModel() {
mLlOwnerArea.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
}
@Subscribe
public void onEvent(EventSeriesInviteBean bean) {
showInviteModel();
}
@Subscribe
public void onEvent(CreateLiveTopicBean bean) {
this.getData();
}
@Subscribe
public void SeriesPayEvent(EventSeriesPayBean bean) {
if (bean.flag) {
getData();
}
}
/**
* 支付回调
*
* @param bean
*/
@Subscribe
public void onEvent(PayBean bean) {
if (!playing) return;
if (!bean.isPaySucc) {//支付失败
ToastUtil.showShort(this, "支付失败");
} else {
getData();
}
playing = false;
}
/**
* 更新修改系列课后的内容
*/
@Subscribe
public void onEvent(SeriesPageBean bean) {
getData();
}
@Subscribe
public void onEvent(EventDelSeries bean) {
this.finish();
}
@Subscribe
public void onEvent(EventLoginBean bean) {
if (bean.status == EventLoginBean.LOGIN || bean.status == EventLoginBean.REGISTE || bean.status == EventLoginBean.THIRDLOGIN) {
getData();
}
}
//分享到好友
private void shareMessage(final String targetId, final Conversation.ConversationType type,
final String liuyan) {
String title = mData.getSeriesname();
String img = TextUtils.isEmpty(
mData.getHeadpic()) ? Constant.DEFUAL_SHARE_IMAGE_URI : mData.getHeadpic();
String id = mData.getId();
ImMessageUtils.shareMessage(targetId, type, id, title, img, CircleShareHandler.SHARE_SERIES,
new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {
}
@Override
public void onSuccess(Message message) {
ToastUtil.showShort(SeriesActivity.this, "分享成功");
if (!TextUtils.isEmpty(liuyan)) {
RongIMTextUtil.INSTANCE.relayMessage(liuyan, targetId, type);
}
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
ToastUtil.showShort(SeriesActivity.this,
"分享失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLAYSERIES_REQUEST && resultCode == RESULT_OK) {
if (mData != null) {
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
} else if (requestCode == SETTING_SERIES && resultCode == RESULT_OK) {
setdata((SeriesPageBean) data.getSerializableExtra("seriesBean"));
}
if (resultCode == Constant.ResponseCode.CIRCLE_ISSUE) {
ToastUtil.showShort(this, "分享成功");
}
if (requestCode == ConversationActivity.REQUEST_SHARE_CONTENT && resultCode == RESULT_OK) {
EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA);
String targetId = bean.targetId;
Conversation.ConversationType type = bean.mType;
shareMessage(targetId, type, bean.liuyan);
}
if (requestCode == 666 && resultCode == Constant.ResponseCode.ISSUE_TONG_BU) {
mNewLiveTopicFragment.onActivityResult(requestCode, resultCode, data);
}
if (requestCode == NewLiveTopicFragment.REQUEST_TOPIC_INTRO && resultCode == 999) {
showInviteModel();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public List<ChatInfosBean> getChatinfosList() {
if (mData != null) {
return mData.getChatInfos();
}
return null;
}
public static void startActivity(Context context, String id) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
context.startActivity(intent);
}
public static void startActivityForResult(Activity context, String id, int recode) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
context.startActivityForResult(intent, recode);
}
//免费邀请报名 freeSign 免费邀请码
public static void freeInvite(Context context, String id, String shareUserCode,
String freeSign) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("userCode", shareUserCode);
intent.putExtra("freeSign", freeSign);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, String userCode) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("userCode", userCode);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, boolean isByLiveFragment) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("isByLiveFragment", isByLiveFragment);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, boolean isByLiveFragment,
int flag) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("isByLiveFragment", isByLiveFragment);
intent.addFlags(flag);
context.startActivity(intent);
}
}
| 41,219 | 0.542872 | 0.540917 | 962 | 41.007275 | 30.467033 | 217 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.700624 | false | false | 1 |
fdd3332cc7b90cdafb315c76b53588bdf6a08687 | 14,705,968,029,938 | f861f9ed739615e1f58c0aad6a80bcdcf66f0f14 | /MaterialDesign/src/main/java/com/example/myapplication/adapter/MenusAdapter.java | acfd58492a9d1208c597187d632c371ac25f010b | []
| no_license | mgdbaby/MyApplication | https://github.com/mgdbaby/MyApplication | 6b61f9041b609d31166601c2080f89a472732c1c | 03a79cc61471cd9e4f2d9afb35a07df0bbf7d519 | refs/heads/master | 2021-01-12T03:20:58.235000 | 2017-01-20T11:07:46 | 2017-01-20T11:07:46 | 78,199,353 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //package com.example.myapplication.adapter;
//
//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.myapplication.R;
//import com.example.myapplication.entity.DataListBean;
//import com.yanzhenjie.recyclerview.swipe.SwipeMenuAdapter;
//
//import java.util.List;
//
///**
// * Created by vargo on 2017/1/20.
// */
//
//public class MenusAdapter extends SwipeMenuAdapter<MenusAdapter.DataInfoViewHolder>{
// private List<DataListBean> dataBeanList;
// private OnItemClickListener onItemClickListener;
//
// public MenusAdapter(List<DataListBean> dataBeanList) {
// this.dataBeanList = dataBeanList;
// }
//
// public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
// this.onItemClickListener = onItemClickListener;
// }
// @Override
// public View onCreateContentView(ViewGroup parent, int viewType) {
// return LayoutInflater.from(parent.getContext()).inflate(R.layout.lhc_data_item, parent, false);
// }
//
// @Override
// public DataInfoViewHolder onCompatCreateViewHolder(View realContentView, int viewType) {
// return new DataInfoViewHolder(realContentView);
// }
//
// @Override
// public void onBindViewHolder(DataInfoViewHolder holder, int position) {
// holder.setTextData(dataBeanList.get(position).getData());
// holder.setTextMoney(String.valueOf(dataBeanList.get(position).getMoney()));
// holder.setOnItemClickListener(onItemClickListener);
// }
//
// @Override
// public int getItemCount() {
// return dataBeanList == null ? 0 : dataBeanList.size();
// }
//
//
// public class DataInfoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// TextView textData;
// TextView textMoney;
// OnItemClickListener onItemClickListener;
//
// public DataInfoViewHolder(View view) {
// super(view);
// view.setOnClickListener(this);
// textData = (TextView) view.findViewById(R.id.textData);
// textMoney = (TextView) view.findViewById(R.id.textMoney);
// }
//
// public void setTextData(String textData) {
// this.textData.setText(textData);
// }
//
// public void setTextMoney(String textMoney) {
// this.textMoney.setText(textMoney);
// }
//
// @Override
// public void onClick(View view) {
// if(onItemClickListener != null){
// onItemClickListener.onItemClick(getAdapterPosition());
// }
// }
//
// public void setOnItemClickListener(OnItemClickListener onItemClickListener){
// this.onItemClickListener = onItemClickListener;
// }
// }
//
// public interface OnItemClickListener {
//
// void onItemClick(int position);
//
// }
//}
| UTF-8 | Java | 2,982 | java | MenusAdapter.java | Java | [
{
"context": "\n//import java.util.List;\n//\n///**\n// * Created by vargo on 2017/1/20.\n// */\n//\n//public class MenusAdapte",
"end": 446,
"score": 0.9993295073509216,
"start": 441,
"tag": "USERNAME",
"value": "vargo"
}
]
| null | []
| //package com.example.myapplication.adapter;
//
//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.myapplication.R;
//import com.example.myapplication.entity.DataListBean;
//import com.yanzhenjie.recyclerview.swipe.SwipeMenuAdapter;
//
//import java.util.List;
//
///**
// * Created by vargo on 2017/1/20.
// */
//
//public class MenusAdapter extends SwipeMenuAdapter<MenusAdapter.DataInfoViewHolder>{
// private List<DataListBean> dataBeanList;
// private OnItemClickListener onItemClickListener;
//
// public MenusAdapter(List<DataListBean> dataBeanList) {
// this.dataBeanList = dataBeanList;
// }
//
// public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
// this.onItemClickListener = onItemClickListener;
// }
// @Override
// public View onCreateContentView(ViewGroup parent, int viewType) {
// return LayoutInflater.from(parent.getContext()).inflate(R.layout.lhc_data_item, parent, false);
// }
//
// @Override
// public DataInfoViewHolder onCompatCreateViewHolder(View realContentView, int viewType) {
// return new DataInfoViewHolder(realContentView);
// }
//
// @Override
// public void onBindViewHolder(DataInfoViewHolder holder, int position) {
// holder.setTextData(dataBeanList.get(position).getData());
// holder.setTextMoney(String.valueOf(dataBeanList.get(position).getMoney()));
// holder.setOnItemClickListener(onItemClickListener);
// }
//
// @Override
// public int getItemCount() {
// return dataBeanList == null ? 0 : dataBeanList.size();
// }
//
//
// public class DataInfoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// TextView textData;
// TextView textMoney;
// OnItemClickListener onItemClickListener;
//
// public DataInfoViewHolder(View view) {
// super(view);
// view.setOnClickListener(this);
// textData = (TextView) view.findViewById(R.id.textData);
// textMoney = (TextView) view.findViewById(R.id.textMoney);
// }
//
// public void setTextData(String textData) {
// this.textData.setText(textData);
// }
//
// public void setTextMoney(String textMoney) {
// this.textMoney.setText(textMoney);
// }
//
// @Override
// public void onClick(View view) {
// if(onItemClickListener != null){
// onItemClickListener.onItemClick(getAdapterPosition());
// }
// }
//
// public void setOnItemClickListener(OnItemClickListener onItemClickListener){
// this.onItemClickListener = onItemClickListener;
// }
// }
//
// public interface OnItemClickListener {
//
// void onItemClick(int position);
//
// }
//}
| 2,982 | 0.661636 | 0.658618 | 90 | 32.133335 | 28.62369 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411111 | false | false | 1 |
51815ff32bf02671b7c1efe9cd1f969769b412b0 | 10,307,921,530,384 | 3c178b1dbb44237afe8d435336a265a73f4d66ea | /com/android/globalsearch/TestSuggestionSource.java | c28fc671254b454f9a226a9240af7a85ae55f7e3 | []
| no_license | AndroidSDKSources/android-sdk-sources-for-api-level-5 | https://github.com/AndroidSDKSources/android-sdk-sources-for-api-level-5 | b7806884853389ff288b3adbdaf28f14893549a0 | baef9e37c1298f278f4fc212b9910810bf262a0b | refs/heads/master | 2021-01-15T15:05:15.383000 | 2015-06-13T15:27:01 | 2015-06-13T15:27:01 | 37,376,449 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.globalsearch;
import android.content.ComponentName;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import java.util.HashSet;
/**
* For testing, delivers a canned set of suggestions after fixed delay.
*/
class TestSuggestionSource extends AbstractSuggestionSource {
private final ComponentName mComponent;
private final long mDelay;
private final Map<String, List<SuggestionData>> mCannedResponses;
private final HashSet<String> mErrorQueries;
private final boolean mQueryAfterZeroResults;
private final String mLabel;
private TestSuggestionSource(
ComponentName component,
long delay,
Map<String, List<SuggestionData>> cannedResponses,
HashSet<String> errorQueries, boolean queryAfterZeroResults, String label) {
mComponent = component;
mDelay = delay;
mCannedResponses = cannedResponses;
mErrorQueries = errorQueries;
mQueryAfterZeroResults = queryAfterZeroResults;
mLabel = label;
}
public ComponentName getComponentName() {
return mComponent;
}
public String getIcon() {
return null;
}
public String getLabel() {
return mLabel;
}
public String getSettingsDescription() {
return "settings description";
}
@Override
protected SuggestionResult getSuggestions(String query, int maxResults, int queryLimit) {
if (mDelay > 0) {
try {
Thread.sleep(mDelay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return mEmptyResult;
}
}
if (mErrorQueries.contains(query)) {
return SuggestionResult.createErrorResult(this);
}
final List<SuggestionData> result = mCannedResponses.get(query);
return result != null ?
new SuggestionResult(this, result) :
mEmptyResult;
}
@Override
protected SuggestionData validateShortcut(SuggestionData shortcut) {
String shortcutId = shortcut.getShortcutId();
for (List<SuggestionData> suggestionDatas : mCannedResponses.values()) {
for (SuggestionData suggestionData : suggestionDatas) {
if (shortcutId.equals(suggestionData.getShortcutId())) {
return suggestionData;
}
}
}
return null;
}
public boolean queryAfterZeroResults() {
return mQueryAfterZeroResults;
}
@Override
public String toString() {
return mComponent.toShortString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestSuggestionSource that = (TestSuggestionSource) o;
if (mDelay != that.mDelay) return false;
if (mQueryAfterZeroResults != that.mQueryAfterZeroResults) return false;
if (mCannedResponses != null ?
!mCannedResponses.equals(that.mCannedResponses)
: that.mCannedResponses != null)
return false;
if (!mComponent.equals(that.mComponent)) return false;
if (mLabel != null ? !mLabel.equals(that.mLabel) : that.mLabel != null) return false;
return true;
}
@Override
public int hashCode() {
int result = mComponent.hashCode();
result = 31 * result + (int) (mDelay ^ (mDelay >>> 32));
result = 31 * result + (mCannedResponses != null ? mCannedResponses.hashCode() : 0);
result = 31 * result + (mQueryAfterZeroResults ? 1 : 0);
result = 31 * result + (mLabel != null ? mLabel.hashCode() : 0);
return result;
}
/**
* Makes a test source that will returned 1 canned result matching the given query.
*/
public static SuggestionSource makeCanned(String query, String s, long delay) {
final ComponentName name = new ComponentName("com.test." + s, "Class$" + s);
final SuggestionData suggestion = new SuggestionData.Builder(name)
.title(s)
.intentAction("view")
.intentData(s)
.build();
return new TestSuggestionSource.Builder()
.setComponent(name)
.setLabel(s)
.setDelay(delay)
.addCannedResponse(query, suggestion)
.create();
}
static class Builder {
private ComponentName mComponent =
new ComponentName(
"com.android.globalsearch", "com.android.globalsearch.GlobalSearch");
private long mDelay = 0;
private Map<String, List<SuggestionData>> mCannedResponses =
new HashMap<String, List<SuggestionData>>();
private HashSet<String> mErrorQueries = new HashSet<String>();
private boolean mQueryAfterZeroResults = false;
private String mLabel = "TestSuggestionSource";
public Builder setComponent(ComponentName component) {
mComponent = component;
return this;
}
public Builder setDelay(long delay) {
mDelay = delay;
return this;
}
public Builder setQueryAfterZeroResults(boolean queryAfterNoResults) {
mQueryAfterZeroResults = queryAfterNoResults;
return this;
}
public Builder setLabel(String label) {
mLabel = label;
return this;
}
/**
* Adds a list of canned suggestions as a result for the query and all prefixes of it.
*
* @param query The query
* @param suggestions The suggetions to return for the query and its prefixes.
*/
public Builder addCannedResponse(String query, SuggestionData... suggestions) {
final List<SuggestionData> suggestionList = Arrays.asList(suggestions);
mCannedResponses.put(query, suggestionList);
final int queryLength = query.length();
for (int i = 1; i < queryLength; i++) {
final String subQuery = query.substring(0, queryLength - i);
mCannedResponses.put(subQuery, suggestionList);
}
return this;
}
/**
* Makes it so the source will return a <code>null</code> result for this query.
*/
public Builder addErrorResponse(String query) {
mErrorQueries.add(query);
return this;
}
public TestSuggestionSource create() {
return new TestSuggestionSource(
mComponent, mDelay, mCannedResponses, mErrorQueries,
mQueryAfterZeroResults, mLabel);
}
}
}
| UTF-8 | Java | 7,494 | java | TestSuggestionSource.java | Java | []
| null | []
| /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.globalsearch;
import android.content.ComponentName;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import java.util.HashSet;
/**
* For testing, delivers a canned set of suggestions after fixed delay.
*/
class TestSuggestionSource extends AbstractSuggestionSource {
private final ComponentName mComponent;
private final long mDelay;
private final Map<String, List<SuggestionData>> mCannedResponses;
private final HashSet<String> mErrorQueries;
private final boolean mQueryAfterZeroResults;
private final String mLabel;
private TestSuggestionSource(
ComponentName component,
long delay,
Map<String, List<SuggestionData>> cannedResponses,
HashSet<String> errorQueries, boolean queryAfterZeroResults, String label) {
mComponent = component;
mDelay = delay;
mCannedResponses = cannedResponses;
mErrorQueries = errorQueries;
mQueryAfterZeroResults = queryAfterZeroResults;
mLabel = label;
}
public ComponentName getComponentName() {
return mComponent;
}
public String getIcon() {
return null;
}
public String getLabel() {
return mLabel;
}
public String getSettingsDescription() {
return "settings description";
}
@Override
protected SuggestionResult getSuggestions(String query, int maxResults, int queryLimit) {
if (mDelay > 0) {
try {
Thread.sleep(mDelay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return mEmptyResult;
}
}
if (mErrorQueries.contains(query)) {
return SuggestionResult.createErrorResult(this);
}
final List<SuggestionData> result = mCannedResponses.get(query);
return result != null ?
new SuggestionResult(this, result) :
mEmptyResult;
}
@Override
protected SuggestionData validateShortcut(SuggestionData shortcut) {
String shortcutId = shortcut.getShortcutId();
for (List<SuggestionData> suggestionDatas : mCannedResponses.values()) {
for (SuggestionData suggestionData : suggestionDatas) {
if (shortcutId.equals(suggestionData.getShortcutId())) {
return suggestionData;
}
}
}
return null;
}
public boolean queryAfterZeroResults() {
return mQueryAfterZeroResults;
}
@Override
public String toString() {
return mComponent.toShortString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestSuggestionSource that = (TestSuggestionSource) o;
if (mDelay != that.mDelay) return false;
if (mQueryAfterZeroResults != that.mQueryAfterZeroResults) return false;
if (mCannedResponses != null ?
!mCannedResponses.equals(that.mCannedResponses)
: that.mCannedResponses != null)
return false;
if (!mComponent.equals(that.mComponent)) return false;
if (mLabel != null ? !mLabel.equals(that.mLabel) : that.mLabel != null) return false;
return true;
}
@Override
public int hashCode() {
int result = mComponent.hashCode();
result = 31 * result + (int) (mDelay ^ (mDelay >>> 32));
result = 31 * result + (mCannedResponses != null ? mCannedResponses.hashCode() : 0);
result = 31 * result + (mQueryAfterZeroResults ? 1 : 0);
result = 31 * result + (mLabel != null ? mLabel.hashCode() : 0);
return result;
}
/**
* Makes a test source that will returned 1 canned result matching the given query.
*/
public static SuggestionSource makeCanned(String query, String s, long delay) {
final ComponentName name = new ComponentName("com.test." + s, "Class$" + s);
final SuggestionData suggestion = new SuggestionData.Builder(name)
.title(s)
.intentAction("view")
.intentData(s)
.build();
return new TestSuggestionSource.Builder()
.setComponent(name)
.setLabel(s)
.setDelay(delay)
.addCannedResponse(query, suggestion)
.create();
}
static class Builder {
private ComponentName mComponent =
new ComponentName(
"com.android.globalsearch", "com.android.globalsearch.GlobalSearch");
private long mDelay = 0;
private Map<String, List<SuggestionData>> mCannedResponses =
new HashMap<String, List<SuggestionData>>();
private HashSet<String> mErrorQueries = new HashSet<String>();
private boolean mQueryAfterZeroResults = false;
private String mLabel = "TestSuggestionSource";
public Builder setComponent(ComponentName component) {
mComponent = component;
return this;
}
public Builder setDelay(long delay) {
mDelay = delay;
return this;
}
public Builder setQueryAfterZeroResults(boolean queryAfterNoResults) {
mQueryAfterZeroResults = queryAfterNoResults;
return this;
}
public Builder setLabel(String label) {
mLabel = label;
return this;
}
/**
* Adds a list of canned suggestions as a result for the query and all prefixes of it.
*
* @param query The query
* @param suggestions The suggetions to return for the query and its prefixes.
*/
public Builder addCannedResponse(String query, SuggestionData... suggestions) {
final List<SuggestionData> suggestionList = Arrays.asList(suggestions);
mCannedResponses.put(query, suggestionList);
final int queryLength = query.length();
for (int i = 1; i < queryLength; i++) {
final String subQuery = query.substring(0, queryLength - i);
mCannedResponses.put(subQuery, suggestionList);
}
return this;
}
/**
* Makes it so the source will return a <code>null</code> result for this query.
*/
public Builder addErrorResponse(String query) {
mErrorQueries.add(query);
return this;
}
public TestSuggestionSource create() {
return new TestSuggestionSource(
mComponent, mDelay, mCannedResponses, mErrorQueries,
mQueryAfterZeroResults, mLabel);
}
}
}
| 7,494 | 0.614892 | 0.611289 | 224 | 32.455357 | 26.944185 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.495536 | false | false | 1 |
1fc42c64e55b37ce67450728c960eb806487d87f | 1,563,368,140,727 | d53d7df2e1d2274936df34f82452573b90888b9a | /src/public/com/seentao/stpedu/common/dao/ClubMemberDao.java | 9b1e212c45fce24e1082d00a476ae89a8ed45eb0 | []
| no_license | wzxzmw/teach | https://github.com/wzxzmw/teach | 80cb2d6dc0663ecfdb5d05308a6727f75e50a9b5 | 7c7a96590a37ef25eb5908dd664486c0f4765ef2 | refs/heads/master | 2021-01-11T09:17:46.099000 | 2017-03-05T08:07:15 | 2017-03-05T08:07:15 | 76,958,654 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.seentao.stpedu.common.dao;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import com.seentao.stpedu.common.entity.ClubMember;
import com.seentao.stpedu.common.sqlmap.ClubMemberMapper;
import com.seentao.stpedu.utils.LogUtil;
@Repository
public class ClubMemberDao {
@Autowired
private ClubMemberMapper clubMemberMapper;
public int insertClubMember(ClubMember clubMember){
clubMemberMapper .insertClubMember(clubMember);
return clubMember.getMemberId();
}
public void deleteClubMember(ClubMember clubMember){
clubMemberMapper .deleteClubMember(clubMember);
}
public void updateClubMemberByKey(ClubMember clubMember){
clubMemberMapper .updateClubMemberByKey(clubMember);
}
/**
* 根据距主键ID修改
* @param
* @return
*/
public void updateClubMemberById(Integer memberId,Integer memberStatus)throws RuntimeException{
try {
clubMemberMapper.updateClubMemberById(memberId, memberStatus);
} catch (RuntimeException e) {
LogUtil.error(this.getClass(), "updateClubMemberById", "更新失败");
throw new RuntimeException(e);
}
}
public List<ClubMember> selectSingleClubMember(ClubMember clubMember){
return clubMemberMapper .selectSingleClubMember(clubMember);
}
public ClubMember selectClubMember(ClubMember clubMember){
List<ClubMember> clubMemberList = clubMemberMapper .selectSingleClubMember(clubMember);
if(clubMemberList == null || clubMemberList .size() == 0){
return null;
}
return clubMemberList .get(0);
}
public ClubMember queryClubMemberSome(Map<String,Object> map){
return clubMemberMapper.queryClubMemberSome(map);
}
/**
*
* @return
*/
public ClubMember selectOnlyClubMember(Integer userId){
return clubMemberMapper.selectOnlyClubMember(userId);
}
public List<ClubMember> selectAllClubMember(){
return clubMemberMapper .selectAllClubMember();
}
public Integer queryCount(ClubMember c) {
return clubMemberMapper.queryCount( c);
}
public ClubMember checkPresidentAndArenaCompetition(ClubMember member) {
List<ClubMember> list = clubMemberMapper.checkPresidentAndArenaCompetition(member);
if(CollectionUtils.isEmpty(list)){
return null;
}
return list.get(0);
}
public boolean validatePresidentAndArenaCompetition(Map<String,Object> conditionMap) {
int num= clubMemberMapper.validatePresidentAndArenaCompetition(conditionMap);
if(num>0){
return true;
}
return false;
}
/**
* redis组件 反射调用获取单表数据
*/
public ClubMember getEntityForDB(Map<String, Object> paramMap){
ClubMember tmp = new ClubMember();
tmp.setMemberId(Integer.valueOf(paramMap.get("id_key").toString()));
return this.selectClubMember(tmp);
}
public List<ClubMember> selectClubMemberByClubId(ClubMember member) {
return clubMemberMapper.selectClubMemberByClubId(member);
}
/**
* @Description:判断是否有待审核的会员
*/
public int checkClubMemberStatuts(ClubMember clubMember){
if(clubMemberMapper.queryCount(clubMember)>0){
return 1;
}else{
return 0;
}
}
public List<ClubMember> getClubMemberList(ClubMember param) {
return clubMemberMapper.getClubMemberList(param) ;
}
public Integer getClubMemberCount(ClubMember param) {
return clubMemberMapper.getClubMemberCount( param) ;
}
public void batchUpdateByUserIdAndClubId(List<ClubMember> list) {
clubMemberMapper.batchUpdateByUserIdAndClubId(list);
}
public void updateByUserIdAndClubId(ClubMember club) {
clubMemberMapper.updateByUserIdAndClubId(club);
}
public List<ClubMember> getClubMemberByStatus(ClubMember c) {
return clubMemberMapper.getClubMemberByStatus(c);
}
public Integer queryCountByStatus(ClubMember c) {
return clubMemberMapper.queryCountByStatus( c) ;
}
public void updateClubmemerIsremoind(ClubMember clubMember) {
clubMemberMapper.updateClubmemerIsremoind(clubMember);
}
public List<ClubMember> selectClubMemberByUserIds(Map<String, Object> paramMap) {
return clubMemberMapper.selectClubMemberByUserIds(paramMap);
}
public void updateIsNewRemindByUserIds(Map<String, Object> paramMap) {
clubMemberMapper.updateIsNewRemindByUserIds(paramMap);
}
public void updateIsNewRemindByMemberIds(Map<String, Object> paramMap) {
clubMemberMapper.updateIsNewRemindByMemberIds(paramMap);
}
public void updateIsNewNoticeByMemberIds(Map<String, Object> paramMap) {
clubMemberMapper.updateIsNewNoticeByMemberIds(paramMap);
}
// 根据俱乐部clubId 和用户id ,以及1,2状态查询
public ClubMember queryClubMemberByClubIdAndUserId(Integer userId,Integer clubId) {
return clubMemberMapper.queryClubMemberByClubIdAndUserId(userId,clubId);
}
} | UTF-8 | Java | 4,984 | java | ClubMemberDao.java | Java | []
| null | []
| package com.seentao.stpedu.common.dao;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import com.seentao.stpedu.common.entity.ClubMember;
import com.seentao.stpedu.common.sqlmap.ClubMemberMapper;
import com.seentao.stpedu.utils.LogUtil;
@Repository
public class ClubMemberDao {
@Autowired
private ClubMemberMapper clubMemberMapper;
public int insertClubMember(ClubMember clubMember){
clubMemberMapper .insertClubMember(clubMember);
return clubMember.getMemberId();
}
public void deleteClubMember(ClubMember clubMember){
clubMemberMapper .deleteClubMember(clubMember);
}
public void updateClubMemberByKey(ClubMember clubMember){
clubMemberMapper .updateClubMemberByKey(clubMember);
}
/**
* 根据距主键ID修改
* @param
* @return
*/
public void updateClubMemberById(Integer memberId,Integer memberStatus)throws RuntimeException{
try {
clubMemberMapper.updateClubMemberById(memberId, memberStatus);
} catch (RuntimeException e) {
LogUtil.error(this.getClass(), "updateClubMemberById", "更新失败");
throw new RuntimeException(e);
}
}
public List<ClubMember> selectSingleClubMember(ClubMember clubMember){
return clubMemberMapper .selectSingleClubMember(clubMember);
}
public ClubMember selectClubMember(ClubMember clubMember){
List<ClubMember> clubMemberList = clubMemberMapper .selectSingleClubMember(clubMember);
if(clubMemberList == null || clubMemberList .size() == 0){
return null;
}
return clubMemberList .get(0);
}
public ClubMember queryClubMemberSome(Map<String,Object> map){
return clubMemberMapper.queryClubMemberSome(map);
}
/**
*
* @return
*/
public ClubMember selectOnlyClubMember(Integer userId){
return clubMemberMapper.selectOnlyClubMember(userId);
}
public List<ClubMember> selectAllClubMember(){
return clubMemberMapper .selectAllClubMember();
}
public Integer queryCount(ClubMember c) {
return clubMemberMapper.queryCount( c);
}
public ClubMember checkPresidentAndArenaCompetition(ClubMember member) {
List<ClubMember> list = clubMemberMapper.checkPresidentAndArenaCompetition(member);
if(CollectionUtils.isEmpty(list)){
return null;
}
return list.get(0);
}
public boolean validatePresidentAndArenaCompetition(Map<String,Object> conditionMap) {
int num= clubMemberMapper.validatePresidentAndArenaCompetition(conditionMap);
if(num>0){
return true;
}
return false;
}
/**
* redis组件 反射调用获取单表数据
*/
public ClubMember getEntityForDB(Map<String, Object> paramMap){
ClubMember tmp = new ClubMember();
tmp.setMemberId(Integer.valueOf(paramMap.get("id_key").toString()));
return this.selectClubMember(tmp);
}
public List<ClubMember> selectClubMemberByClubId(ClubMember member) {
return clubMemberMapper.selectClubMemberByClubId(member);
}
/**
* @Description:判断是否有待审核的会员
*/
public int checkClubMemberStatuts(ClubMember clubMember){
if(clubMemberMapper.queryCount(clubMember)>0){
return 1;
}else{
return 0;
}
}
public List<ClubMember> getClubMemberList(ClubMember param) {
return clubMemberMapper.getClubMemberList(param) ;
}
public Integer getClubMemberCount(ClubMember param) {
return clubMemberMapper.getClubMemberCount( param) ;
}
public void batchUpdateByUserIdAndClubId(List<ClubMember> list) {
clubMemberMapper.batchUpdateByUserIdAndClubId(list);
}
public void updateByUserIdAndClubId(ClubMember club) {
clubMemberMapper.updateByUserIdAndClubId(club);
}
public List<ClubMember> getClubMemberByStatus(ClubMember c) {
return clubMemberMapper.getClubMemberByStatus(c);
}
public Integer queryCountByStatus(ClubMember c) {
return clubMemberMapper.queryCountByStatus( c) ;
}
public void updateClubmemerIsremoind(ClubMember clubMember) {
clubMemberMapper.updateClubmemerIsremoind(clubMember);
}
public List<ClubMember> selectClubMemberByUserIds(Map<String, Object> paramMap) {
return clubMemberMapper.selectClubMemberByUserIds(paramMap);
}
public void updateIsNewRemindByUserIds(Map<String, Object> paramMap) {
clubMemberMapper.updateIsNewRemindByUserIds(paramMap);
}
public void updateIsNewRemindByMemberIds(Map<String, Object> paramMap) {
clubMemberMapper.updateIsNewRemindByMemberIds(paramMap);
}
public void updateIsNewNoticeByMemberIds(Map<String, Object> paramMap) {
clubMemberMapper.updateIsNewNoticeByMemberIds(paramMap);
}
// 根据俱乐部clubId 和用户id ,以及1,2状态查询
public ClubMember queryClubMemberByClubIdAndUserId(Integer userId,Integer clubId) {
return clubMemberMapper.queryClubMemberByClubIdAndUserId(userId,clubId);
}
} | 4,984 | 0.759206 | 0.757365 | 168 | 27.107143 | 28.102711 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.577381 | false | false | 1 |
a83ac3fbbab5377928319a7c02fd144d713879af | 1,563,368,143,286 | 0b7313a558401df7c6a82f293074e2c0b74bf9b1 | /app/src/main/java/com/example/databasetutorials/CRUDGenreActivity.java | 1d754d4c99f90506f127f8e822ce4b9ba2a38c69 | []
| no_license | tranquang7979/Android-Studio | https://github.com/tranquang7979/Android-Studio | 95d62eb7e63c591914984bb6862c0b9e19d14bbf | 89e8c2c744762e75568a56c2c297ac0f5cab008f | refs/heads/master | 2021-05-26T10:14:16.753000 | 2020-04-14T00:23:13 | 2020-04-14T00:23:13 | 254,090,354 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.databasetutorials;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.databasetutorials.provider.MovieStoreProvider;
import java.util.ArrayList;
public class CRUDGenreActivity extends AppCompatActivity {
Uri uri_select = MovieStoreProvider.CONTENT_URI;
Uri uri_crud = MovieStoreProvider.CONTENT_URI;
Button btn_add,btn_update, btn_delete,btn_viewall;
EditText ed_genre_name, ed_genre_desc,ed_genre_image;
Spinner sp_genre_id;
ContentResolver resolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c_r_u_d_genre);
sp_genre_id = findViewById(R.id.sp_genre_id);
btn_add =findViewById(R.id.btn_add);
btn_delete = findViewById(R.id.btn_delete);
btn_update = findViewById(R.id.btn_update);
btn_viewall = findViewById(R.id.btn_viewall);
ed_genre_name = findViewById(R.id.ed_genre_name);
ed_genre_desc = findViewById(R.id.ed_genre_desc);
ed_genre_image = findViewById(R.id.ed_genre_image);
resolver = getContentResolver();
getAllGenreId();
sp_genre_id.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected_genre_id =(String) parent.getSelectedItem();
getGenreDetailsById(selected_genre_id);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createGenre();
getAllGenreId();
}
});
btn_viewall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it =new Intent(CRUDGenreActivity.this, GenreManagementActivity.class);
startActivity(it);
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateGenre();
getAllGenreId();
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteGenre();
getAllGenreId();
}
});
}
private void updateGenre(){
String id= sp_genre_id.getSelectedItem().toString();
String url = MovieStoreProvider.CONTENT_URI+"/"+id;
uri_crud = Uri.parse(url);
ContentValues values = new ContentValues();
values.put("name", ed_genre_name.getText().toString());
values.put("description", ed_genre_desc.getText().toString());
values.put("imageurl", ed_genre_image.getText().toString());
resolver.update(uri_crud,values,"id=?" , new String[] {id});
Toast.makeText(this, "Genre is updated!!", Toast.LENGTH_LONG).show();
}
private void deleteGenre(){
String id= sp_genre_id.getSelectedItem().toString();
String url = MovieStoreProvider.CONTENT_URI+"/"+id;
uri_crud = Uri.parse(url);
resolver.delete(uri_crud,"id=?", new String[]{id});
Toast.makeText(this, "Genre is deleted!!", Toast.LENGTH_LONG).show();
}
private void createGenre(){
String url = MovieStoreProvider.CONTENT_URI+"";
uri_crud = Uri.parse(url);
ContentValues values = new ContentValues();
values.put("name", ed_genre_name.getText().toString());
values.put("description", ed_genre_desc.getText().toString());
values.put("imageurl", ed_genre_image.getText().toString());
Uri uri_new= resolver.insert(uri_crud, values);
Toast.makeText(this, "Genre is added!!", Toast.LENGTH_LONG).show();
}
private void getGenreDetailsById(String id){
String url = MovieStoreProvider.CONTENT_URI + "/"+id;
uri_select = Uri.parse(url);
Cursor c = resolver.query(uri_select, new String[] {"id","name","description","imageurl"},
"id=?",new String[]{id},null);
if(c.moveToFirst()){
String name= c.getString(c.getColumnIndex("name"));
String desc= c.getString(c.getColumnIndex("description"));
String imageurl= c.getString(c.getColumnIndex("imageurl"));
ed_genre_name.setText(name);
ed_genre_desc.setText(desc);
ed_genre_image.setText(imageurl);
}
c.close();
}
private void getAllGenreId(){
uri_select = MovieStoreProvider.CONTENT_URI;
ArrayList<String> genreIdList =new ArrayList<String>();
Cursor c = resolver.query(uri_select, new String[] {"id"},null,null,null);
if(c.moveToFirst()){
while(!c.isAfterLast()){
String id= c.getString(c.getColumnIndex("id"));
genreIdList.add(id);
c.moveToNext();
}
}
c.close();
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genreIdList);
sp_genre_id.setAdapter(adapter);
}
}
| UTF-8 | Java | 5,816 | java | CRUDGenreActivity.java | Java | []
| null | []
| package com.example.databasetutorials;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.databasetutorials.provider.MovieStoreProvider;
import java.util.ArrayList;
public class CRUDGenreActivity extends AppCompatActivity {
Uri uri_select = MovieStoreProvider.CONTENT_URI;
Uri uri_crud = MovieStoreProvider.CONTENT_URI;
Button btn_add,btn_update, btn_delete,btn_viewall;
EditText ed_genre_name, ed_genre_desc,ed_genre_image;
Spinner sp_genre_id;
ContentResolver resolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c_r_u_d_genre);
sp_genre_id = findViewById(R.id.sp_genre_id);
btn_add =findViewById(R.id.btn_add);
btn_delete = findViewById(R.id.btn_delete);
btn_update = findViewById(R.id.btn_update);
btn_viewall = findViewById(R.id.btn_viewall);
ed_genre_name = findViewById(R.id.ed_genre_name);
ed_genre_desc = findViewById(R.id.ed_genre_desc);
ed_genre_image = findViewById(R.id.ed_genre_image);
resolver = getContentResolver();
getAllGenreId();
sp_genre_id.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected_genre_id =(String) parent.getSelectedItem();
getGenreDetailsById(selected_genre_id);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createGenre();
getAllGenreId();
}
});
btn_viewall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it =new Intent(CRUDGenreActivity.this, GenreManagementActivity.class);
startActivity(it);
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateGenre();
getAllGenreId();
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteGenre();
getAllGenreId();
}
});
}
private void updateGenre(){
String id= sp_genre_id.getSelectedItem().toString();
String url = MovieStoreProvider.CONTENT_URI+"/"+id;
uri_crud = Uri.parse(url);
ContentValues values = new ContentValues();
values.put("name", ed_genre_name.getText().toString());
values.put("description", ed_genre_desc.getText().toString());
values.put("imageurl", ed_genre_image.getText().toString());
resolver.update(uri_crud,values,"id=?" , new String[] {id});
Toast.makeText(this, "Genre is updated!!", Toast.LENGTH_LONG).show();
}
private void deleteGenre(){
String id= sp_genre_id.getSelectedItem().toString();
String url = MovieStoreProvider.CONTENT_URI+"/"+id;
uri_crud = Uri.parse(url);
resolver.delete(uri_crud,"id=?", new String[]{id});
Toast.makeText(this, "Genre is deleted!!", Toast.LENGTH_LONG).show();
}
private void createGenre(){
String url = MovieStoreProvider.CONTENT_URI+"";
uri_crud = Uri.parse(url);
ContentValues values = new ContentValues();
values.put("name", ed_genre_name.getText().toString());
values.put("description", ed_genre_desc.getText().toString());
values.put("imageurl", ed_genre_image.getText().toString());
Uri uri_new= resolver.insert(uri_crud, values);
Toast.makeText(this, "Genre is added!!", Toast.LENGTH_LONG).show();
}
private void getGenreDetailsById(String id){
String url = MovieStoreProvider.CONTENT_URI + "/"+id;
uri_select = Uri.parse(url);
Cursor c = resolver.query(uri_select, new String[] {"id","name","description","imageurl"},
"id=?",new String[]{id},null);
if(c.moveToFirst()){
String name= c.getString(c.getColumnIndex("name"));
String desc= c.getString(c.getColumnIndex("description"));
String imageurl= c.getString(c.getColumnIndex("imageurl"));
ed_genre_name.setText(name);
ed_genre_desc.setText(desc);
ed_genre_image.setText(imageurl);
}
c.close();
}
private void getAllGenreId(){
uri_select = MovieStoreProvider.CONTENT_URI;
ArrayList<String> genreIdList =new ArrayList<String>();
Cursor c = resolver.query(uri_select, new String[] {"id"},null,null,null);
if(c.moveToFirst()){
while(!c.isAfterLast()){
String id= c.getString(c.getColumnIndex("id"));
genreIdList.add(id);
c.moveToNext();
}
}
c.close();
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genreIdList);
sp_genre_id.setAdapter(adapter);
}
}
| 5,816 | 0.620701 | 0.620701 | 160 | 35.349998 | 25.882475 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.81875 | false | false | 1 |
bcab2b3a84c65a8fb555301f5d01b209e4aafae6 | 9,474,697,870,290 | 65eefb2486b294c84407b79c280dd9db63eb5369 | /app/src/main/java/com/cheweibao/liuliu/checker/AfterServiceFragment.java | 7b7f59212d33c1a486c79bd28cb759c78ab94c22 | []
| no_license | pwhbys/liuliuCar | https://github.com/pwhbys/liuliuCar | 48beedbb8f19688a2a001f4dab199fa393a53373 | abfded9c2cbec537c6a83d72e1d6d2d726dfc9ab | refs/heads/master | 2021-10-19T03:23:21.719000 | 2019-02-17T08:11:51 | 2019-02-17T08:11:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cheweibao.liuliu.checker;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.cheweibao.liuliu.R;
import com.cheweibao.liuliu.common.BaseFragment;
import com.cheweibao.liuliu.common.MyConstants;
import com.cheweibao.liuliu.data.CheckCarData;
import com.cheweibao.liuliu.data.MessageEvent;
import com.cheweibao.liuliu.net.ServerUrl;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.HashMap;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* 主界面-订单
*/
public class AfterServiceFragment extends BaseFragment {
String orderId;
@Bind(R.id.et_price)
EditText etPrice;
@Bind(R.id.zhibaoqi_wu_rd)
RadioButton zhibaoqiWuRd;
@Bind(R.id.zhibaoqi_1_rd)
RadioButton zhibaoqi1Rd;
@Bind(R.id.zhibaoqi_2_rd)
RadioButton zhibaoqi2Rd;
@Bind(R.id.zhiBaoQi_rg)
RadioGroup zhiBaoQiRg;
@Bind(R.id.zhibaofangshi_baohuan_rd)
RadioButton zhibaofangshiBaohuanRd;
@Bind(R.id.zhibaofangshi_youtiaojian_rd)
RadioButton zhibaofangshiYoutiaojianRd;
@Bind(R.id.zhibaofangshi_wutiaojian_rd)
RadioButton zhibaofangshiWutiaojianRd;
@Bind(R.id.zhiBaoFangShi_rg)
RadioGroup zhiBaoFangShiRg;
@Bind(R.id.et_remark)
EditText etRemark;
@Bind(R.id.btn_save)
Button btnSave;
@Bind(R.id.ll_after_srv)
LinearLayout llAfterSrv;
public static AfterServiceFragment newInstance(String _orderId) {
Bundle args = new Bundle();
args.putString("orderId", _orderId);
AfterServiceFragment fragment = new AfterServiceFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
orderId = args.getString("orderId");
View view = inflater.inflate(R.layout.fragment_checker_order_after_srv, container, false);
ButterKnife.bind(this, view);
EventBus.getDefault().register(this);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView();
}
private void initView() {
etPrice.setText(CheckCarData.jcPrice);
etRemark.setText(CheckCarData.remark);
zhibaofangshiWutiaojianRd.setChecked(true);
switch (Integer.parseInt(CheckCarData.period)) {
case 0:
zhiBaoQiRg.check(R.id.zhibaoqi_wu_rd);
break;
case 1:
zhiBaoQiRg.check(R.id.zhibaoqi_1_rd);
break;
case 2:
zhiBaoQiRg.check(R.id.zhibaoqi_2_rd);
break;
}
if ("1".equals(CheckCarData.period) || "2".equals(CheckCarData.period)) {
llAfterSrv.setVisibility(View.VISIBLE);
switch (Integer.parseInt(CheckCarData.srvMode)) {
case 1:
zhiBaoFangShiRg.check(R.id.zhibaofangshi_baohuan_rd);
break;
case 2:
zhiBaoFangShiRg.check(R.id.zhibaofangshi_youtiaojian_rd);
break;
case 3:
zhiBaoFangShiRg.check(R.id.zhibaofangshi_wutiaojian_rd);
break;
}
}
zhiBaoQiRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != R.id.zhibaoqi_1_rd && checkedId != R.id.zhibaoqi_2_rd) {
llAfterSrv.setVisibility(View.INVISIBLE);
} else {
llAfterSrv.setVisibility(View.VISIBLE);
}
}
});
if ("1".equals(CheckCarData.checkAll)) {
disableAll();
}
}
private void disableAll(){
etPrice.setEnabled(false);
etRemark.setEnabled(false);
zhibaoqiWuRd.setEnabled(false);
zhibaoqi1Rd.setEnabled(false);
zhibaoqi2Rd.setEnabled(false);
zhibaofangshiBaohuanRd.setEnabled(false);
zhibaofangshiYoutiaojianRd.setEnabled(false);
zhibaofangshiWutiaojianRd.setEnabled(false);
btnSave.setVisibility(View.GONE);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
EventBus.getDefault().unregister(this);
}
@OnClick({R.id.btn_save})
public void onClick(View view) {
Intent it;
switch (view.getId()) {
case R.id.btn_save:
saveData();
break;
}
}
private void saveData() {
CheckCarData.remark = etRemark.getText().toString().trim();
CheckCarData.jcPrice = etPrice.getText().toString().trim();
if (TextUtils.isEmpty(CheckCarData.jcPrice)) {
shortToast("请输入卖家报价");
return;
}
switch (zhiBaoQiRg.getCheckedRadioButtonId()) {
case R.id.zhibaoqi_wu_rd:
CheckCarData.period = "0";
break;
case R.id.zhibaoqi_1_rd:
CheckCarData.period = "1";
break;
case R.id.zhibaoqi_2_rd:
CheckCarData.period = "2";
break;
}
switch (zhiBaoFangShiRg.getCheckedRadioButtonId()) {
case R.id.zhibaofangshi_baohuan_rd:
CheckCarData.srvMode = "1";
break;
case R.id.zhibaofangshi_youtiaojian_rd:
CheckCarData.srvMode = "2";
break;
case R.id.zhibaofangshi_wutiaojian_rd:
CheckCarData.srvMode = "3";
break;
}
if (ServerUrl.isNetworkConnected(mContext)) {
try {
showProgress();
HashMap<String, String> fields = new HashMap<String, String>();
fields.put("token", myglobal.user.token);
fields.put("orderId", CheckCarData.jcdId);
fields.put("detailId", CheckCarData.detailId);
fields.put("carId", CheckCarData.carId);
fields.put("jcPrice", CheckCarData.jcPrice);
fields.put("period", CheckCarData.period);
fields.put("srvMode", CheckCarData.srvMode);
fields.put("remark", CheckCarData.remark);
postMap(ServerUrl.saveAfterService, fields, saveHandler);
} catch (Exception e) {
e.printStackTrace();
setThread_flag(false);
}
} else {
if (mContext != null)
shortToast("网络连接不可用");
setThread_flag(false);
}
}
private Handler saveHandler = new Handler() {
public void handleMessage(Message msg) {
setThread_flag(false);
hideProgress();
switch (msg.what) {
case 0:
@SuppressWarnings("unchecked")
HashMap<String, Object> result = (HashMap<String, Object>) msg.obj;
try {
String status = result.get("result_code") + "";
if ("200".equals(status)) {
shortToast("已保存~~");
CheckCarData.afterSrvSave = "1";
MessageEvent event = new MessageEvent(MyConstants.SAVE_CHECK_INFO);
postEvent(event);
}else if("401".equals(status)){
String message = result.get("message") + "";
shortToast(message);
goLoginPage();
} else {
String message = result.get("message") + "";
shortToast(message);
}
} catch (Exception e) {
shortToast("抱歉数据异常");
}
break;
default:
shortToast("网络不给力!");
break;
}
}
;
};
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
if (event.isMsgOf(MyConstants.CHECK_ALL)) {
disableAll();
}
}
}
| UTF-8 | Java | 9,126 | java | AfterServiceFragment.java | Java | [
{
"context": "ng, String>();\n fields.put(\"token\", myglobal.user.token);\n fields.put(\"or",
"end": 6640,
"score": 0.4398038685321808,
"start": 6638,
"tag": "EMAIL",
"value": "my"
}
]
| null | []
| package com.cheweibao.liuliu.checker;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.cheweibao.liuliu.R;
import com.cheweibao.liuliu.common.BaseFragment;
import com.cheweibao.liuliu.common.MyConstants;
import com.cheweibao.liuliu.data.CheckCarData;
import com.cheweibao.liuliu.data.MessageEvent;
import com.cheweibao.liuliu.net.ServerUrl;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.HashMap;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* 主界面-订单
*/
public class AfterServiceFragment extends BaseFragment {
String orderId;
@Bind(R.id.et_price)
EditText etPrice;
@Bind(R.id.zhibaoqi_wu_rd)
RadioButton zhibaoqiWuRd;
@Bind(R.id.zhibaoqi_1_rd)
RadioButton zhibaoqi1Rd;
@Bind(R.id.zhibaoqi_2_rd)
RadioButton zhibaoqi2Rd;
@Bind(R.id.zhiBaoQi_rg)
RadioGroup zhiBaoQiRg;
@Bind(R.id.zhibaofangshi_baohuan_rd)
RadioButton zhibaofangshiBaohuanRd;
@Bind(R.id.zhibaofangshi_youtiaojian_rd)
RadioButton zhibaofangshiYoutiaojianRd;
@Bind(R.id.zhibaofangshi_wutiaojian_rd)
RadioButton zhibaofangshiWutiaojianRd;
@Bind(R.id.zhiBaoFangShi_rg)
RadioGroup zhiBaoFangShiRg;
@Bind(R.id.et_remark)
EditText etRemark;
@Bind(R.id.btn_save)
Button btnSave;
@Bind(R.id.ll_after_srv)
LinearLayout llAfterSrv;
public static AfterServiceFragment newInstance(String _orderId) {
Bundle args = new Bundle();
args.putString("orderId", _orderId);
AfterServiceFragment fragment = new AfterServiceFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
orderId = args.getString("orderId");
View view = inflater.inflate(R.layout.fragment_checker_order_after_srv, container, false);
ButterKnife.bind(this, view);
EventBus.getDefault().register(this);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView();
}
private void initView() {
etPrice.setText(CheckCarData.jcPrice);
etRemark.setText(CheckCarData.remark);
zhibaofangshiWutiaojianRd.setChecked(true);
switch (Integer.parseInt(CheckCarData.period)) {
case 0:
zhiBaoQiRg.check(R.id.zhibaoqi_wu_rd);
break;
case 1:
zhiBaoQiRg.check(R.id.zhibaoqi_1_rd);
break;
case 2:
zhiBaoQiRg.check(R.id.zhibaoqi_2_rd);
break;
}
if ("1".equals(CheckCarData.period) || "2".equals(CheckCarData.period)) {
llAfterSrv.setVisibility(View.VISIBLE);
switch (Integer.parseInt(CheckCarData.srvMode)) {
case 1:
zhiBaoFangShiRg.check(R.id.zhibaofangshi_baohuan_rd);
break;
case 2:
zhiBaoFangShiRg.check(R.id.zhibaofangshi_youtiaojian_rd);
break;
case 3:
zhiBaoFangShiRg.check(R.id.zhibaofangshi_wutiaojian_rd);
break;
}
}
zhiBaoQiRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != R.id.zhibaoqi_1_rd && checkedId != R.id.zhibaoqi_2_rd) {
llAfterSrv.setVisibility(View.INVISIBLE);
} else {
llAfterSrv.setVisibility(View.VISIBLE);
}
}
});
if ("1".equals(CheckCarData.checkAll)) {
disableAll();
}
}
private void disableAll(){
etPrice.setEnabled(false);
etRemark.setEnabled(false);
zhibaoqiWuRd.setEnabled(false);
zhibaoqi1Rd.setEnabled(false);
zhibaoqi2Rd.setEnabled(false);
zhibaofangshiBaohuanRd.setEnabled(false);
zhibaofangshiYoutiaojianRd.setEnabled(false);
zhibaofangshiWutiaojianRd.setEnabled(false);
btnSave.setVisibility(View.GONE);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
EventBus.getDefault().unregister(this);
}
@OnClick({R.id.btn_save})
public void onClick(View view) {
Intent it;
switch (view.getId()) {
case R.id.btn_save:
saveData();
break;
}
}
private void saveData() {
CheckCarData.remark = etRemark.getText().toString().trim();
CheckCarData.jcPrice = etPrice.getText().toString().trim();
if (TextUtils.isEmpty(CheckCarData.jcPrice)) {
shortToast("请输入卖家报价");
return;
}
switch (zhiBaoQiRg.getCheckedRadioButtonId()) {
case R.id.zhibaoqi_wu_rd:
CheckCarData.period = "0";
break;
case R.id.zhibaoqi_1_rd:
CheckCarData.period = "1";
break;
case R.id.zhibaoqi_2_rd:
CheckCarData.period = "2";
break;
}
switch (zhiBaoFangShiRg.getCheckedRadioButtonId()) {
case R.id.zhibaofangshi_baohuan_rd:
CheckCarData.srvMode = "1";
break;
case R.id.zhibaofangshi_youtiaojian_rd:
CheckCarData.srvMode = "2";
break;
case R.id.zhibaofangshi_wutiaojian_rd:
CheckCarData.srvMode = "3";
break;
}
if (ServerUrl.isNetworkConnected(mContext)) {
try {
showProgress();
HashMap<String, String> fields = new HashMap<String, String>();
fields.put("token", myglobal.user.token);
fields.put("orderId", CheckCarData.jcdId);
fields.put("detailId", CheckCarData.detailId);
fields.put("carId", CheckCarData.carId);
fields.put("jcPrice", CheckCarData.jcPrice);
fields.put("period", CheckCarData.period);
fields.put("srvMode", CheckCarData.srvMode);
fields.put("remark", CheckCarData.remark);
postMap(ServerUrl.saveAfterService, fields, saveHandler);
} catch (Exception e) {
e.printStackTrace();
setThread_flag(false);
}
} else {
if (mContext != null)
shortToast("网络连接不可用");
setThread_flag(false);
}
}
private Handler saveHandler = new Handler() {
public void handleMessage(Message msg) {
setThread_flag(false);
hideProgress();
switch (msg.what) {
case 0:
@SuppressWarnings("unchecked")
HashMap<String, Object> result = (HashMap<String, Object>) msg.obj;
try {
String status = result.get("result_code") + "";
if ("200".equals(status)) {
shortToast("已保存~~");
CheckCarData.afterSrvSave = "1";
MessageEvent event = new MessageEvent(MyConstants.SAVE_CHECK_INFO);
postEvent(event);
}else if("401".equals(status)){
String message = result.get("message") + "";
shortToast(message);
goLoginPage();
} else {
String message = result.get("message") + "";
shortToast(message);
}
} catch (Exception e) {
shortToast("抱歉数据异常");
}
break;
default:
shortToast("网络不给力!");
break;
}
}
;
};
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
if (event.isMsgOf(MyConstants.CHECK_ALL)) {
disableAll();
}
}
}
| 9,126 | 0.569567 | 0.565702 | 283 | 31 | 22.461432 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586572 | false | false | 1 |
c448d4de6f114c05bf4080b1eac1684c0be7f269 | 22,531,398,458,141 | 4a0b9427e3634c3540ba41bf5e90673f76b93f57 | /app/src/main/java/org/wilds/quadcontroller/app/communication/UDPProtocol.java | b4c00915aeaa127e80134d7797a5a1b6ab628809 | []
| no_license | guiseco/rpicopter-android-controller | https://github.com/guiseco/rpicopter-android-controller | 8b72eafd83049ba4dc426203504b5293ced2242d | ce34a9b46ecedac0b171a7dcf18e5ba2600f2e53 | refs/heads/master | 2021-01-18T19:07:10.756000 | 2015-03-12T00:37:40 | 2015-03-12T00:37:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2014-2015 Danilo & Ivano Selvaggi
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wilds.quadcontroller.app.communication;
import android.os.Handler;
import android.util.Log;
import org.wilds.quadcontroller.app.communication.packet.HeartBeatPacket;
import org.wilds.quadcontroller.app.communication.packet.HelloPacket;
import org.wilds.quadcontroller.app.communication.packet.Packet;
import org.wilds.quadcontroller.app.communication.packet.QueryStatusPacket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by Wilds on 14/04/2014.
*/
public class UDPProtocol implements Protocol {
protected Handler mHandler = new Handler();
private final static int INTERVAL_HEARTBEAT = 1000 * 2;
private final static int INTERVAL_QUERY_STATUS = 200;
private final static int PACKET_TIMEOUT = 5000;
//
protected DatagramSocket sendSocket;
protected int sendPort = 58000;
protected InetAddress sendTo;
protected int lag;
private final BlockingQueue<Runnable> mQueue = new LinkedBlockingQueue<Runnable>();
protected ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS, mQueue);
protected Map<Long, Packet> waitingForResponse = new ConcurrentHashMap<>();
protected int lostPacket = 0;
protected Runnable mHandlerTaskHeartBeat = new Runnable() {
@Override
public void run() {
sendPacket(new HeartBeatPacket());
}
};
protected Runnable mHandlerTaskQueryStatus = new Runnable() {
@Override
public void run() {
sendPacket(new QueryStatusPacket());
mHandler.postDelayed(mHandlerTaskQueryStatus, INTERVAL_QUERY_STATUS);
}
};
protected Runnable mHandlerTaskCleanWaitingPackets = new Runnable() {
@Override
public void run() {
cleanWaitingPackets();
mHandler.postDelayed(mHandlerTaskQueryStatus, PACKET_TIMEOUT);
}
};
protected OnReceiveListener onReceiveListener;
public UDPProtocol(int sendPort /*, int listenPort*/) {
this.sendPort = sendPort;
try {
sendSocket = new DatagramSocket(sendPort);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void setOnReceiveListener(OnReceiveListener listener) {
this.onReceiveListener = listener;
}
protected void startListening() {
Thread listenThread = new Thread(new Runnable() {
@Override
public void run() {
while (isConnected()) {
byte[] message = new byte[1024];
DatagramPacket p = new DatagramPacket(message, message.length);
try {
sendSocket.receive(p);
if (isFakePacket(p)) {
Log.d("LOGGER", "STOP listening");
return;
}
String text = new String(message, 0, p.getLength());
String par[] = text.split(" ");
if (par.length < 2) {
Log.e("UDPProtocol", "invalid response " + text);
continue;
}
Packet packet = waitingForResponse.remove(Long.parseLong(par[1]));
if (packet == null) {
Log.e("UDPProtocol", "not waiting for response");
continue;
}
lag = (int) ((System.nanoTime() - packet.getId()) / 1000000);
//TODO handle quadcopter response
if (onReceiveListener != null)
onReceiveListener.onReceive(packet.getType(), text);
} catch (IOException ex) {
}
}
}
});
listenThread.start();
}
@Override
public boolean sendPacket(final Packet packet) {
if (!isConnected())
return false;
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
if (packet.waitReply()) {
waitingForResponse.put(packet.getId(), packet);
}
stopHeartBeat();
sendSocket.send(new DatagramPacket(packet.getByte(), packet.getLength(), sendTo, sendPort));
startHeartBeat();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return true;
}
@Override
public void startHeartBeat() {
//mHandlerTask.run();
mHandler.postDelayed(mHandlerTaskHeartBeat, INTERVAL_HEARTBEAT);
}
@Override
public void stopHeartBeat() {
mHandler.removeCallbacks(mHandlerTaskHeartBeat);
}
@Override
public void startQueryStatus() {
mHandlerTaskQueryStatus.run();
}
@Override
public void stopQueryStatus() {
mHandler.removeCallbacks(mHandlerTaskQueryStatus);
}
@Override
public boolean searchForQuadcopter() {
if (isConnected())
close();
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Packet packet = new HelloPacket(InetAddress.getLocalHost().getHostAddress());
DatagramPacket broadcast = new DatagramPacket(packet.getByte(), packet.getLength(), InetAddress.getByName(Utils.getBroadcast()), sendPort);
sendSocket.setBroadcast(true);
sendSocket.send(broadcast);
long t = System.currentTimeMillis();
while (System.currentTimeMillis() - t < 5000) {
byte[] message = new byte[1024];
DatagramPacket p = new DatagramPacket(message, message.length);
sendSocket.receive(p);
String text = new String(message, 0, p.getLength());
Log.d("LOGGER", "RECEIVED: " + text);
// TODO
if (text.contains("OK")) {
if (onReceiveListener != null)
onReceiveListener.onReceive(packet.getType(), p.getAddress());
} else if (text.contains("hello")) {
} else if (isFakePacket(p)) {
Log.d("LOGGER", "STOP");
onConnected();
return;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
return true;
}
@Override
public boolean connectToQuadcopter(String id) {
try {
sendFakePacket();
this.sendTo = InetAddress.getByName(id);
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
}
protected void onConnected() {
lostPacket = 0;
startHeartBeat();
startQueryStatus();
startListening();
startCleanWaitingPackets();
}
public void close() {
sendTo = null;
sendFakePacket(); //interrupt receive
stopHeartBeat();
stopQueryStatus();
stopCleanWaitingPackets();
//sendSocket.close();
}
@Override
public boolean isConnected() {
return sendTo != null;
}
@Override
public String getRemoteAddress() {
return sendTo.getHostAddress();
}
/* this method is used to send fake packet to self and interrupt receive;*/
private void sendFakePacket() {
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
sendSocket.send(new DatagramPacket("".getBytes(), 0, InetAddress.getLocalHost(), sendPort));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
private boolean isFakePacket(DatagramPacket p) {
try {
return p.getLength() == 0 && p.getAddress().equals(InetAddress.getLocalHost());
} catch (UnknownHostException e) {
return false;
}
}
public int getLatency() {
return lag;
}
protected void startCleanWaitingPackets() {
mHandlerTaskQueryStatus.run();
}
protected void stopCleanWaitingPackets() {
mHandler.removeCallbacks(mHandlerTaskCleanWaitingPackets);
}
protected void cleanWaitingPackets() {
for (Long id : waitingForResponse.keySet()) {
if (id / 1000000 > System.currentTimeMillis() + PACKET_TIMEOUT) {
waitingForResponse.remove(id);
++lostPacket;
}
}
}
public int getLostPacket() {
return lostPacket;
}
}
| UTF-8 | Java | 10,228 | java | UDPProtocol.java | Java | [
{
"context": "/*\n * Copyright (C) 2014-2015 Danilo & Ivano Selvaggi\n *\n * This program is free softw",
"end": 36,
"score": 0.9994996190071106,
"start": 30,
"tag": "NAME",
"value": "Danilo"
},
{
"context": "/*\n * Copyright (C) 2014-2015 Danilo & Ivano Selvaggi\n *\n * This program is free software; you can redi",
"end": 53,
"score": 0.9998329281806946,
"start": 39,
"tag": "NAME",
"value": "Ivano Selvaggi"
},
{
"context": " java.util.concurrent.TimeUnit;\n\n/**\n * Created by Wilds on 14/04/2014.\n */\npublic class UDPProtocol imple",
"end": 1561,
"score": 0.9871489405632019,
"start": 1556,
"tag": "USERNAME",
"value": "Wilds"
}
]
| null | []
| /*
* Copyright (C) 2014-2015 Danilo & <NAME>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wilds.quadcontroller.app.communication;
import android.os.Handler;
import android.util.Log;
import org.wilds.quadcontroller.app.communication.packet.HeartBeatPacket;
import org.wilds.quadcontroller.app.communication.packet.HelloPacket;
import org.wilds.quadcontroller.app.communication.packet.Packet;
import org.wilds.quadcontroller.app.communication.packet.QueryStatusPacket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by Wilds on 14/04/2014.
*/
public class UDPProtocol implements Protocol {
protected Handler mHandler = new Handler();
private final static int INTERVAL_HEARTBEAT = 1000 * 2;
private final static int INTERVAL_QUERY_STATUS = 200;
private final static int PACKET_TIMEOUT = 5000;
//
protected DatagramSocket sendSocket;
protected int sendPort = 58000;
protected InetAddress sendTo;
protected int lag;
private final BlockingQueue<Runnable> mQueue = new LinkedBlockingQueue<Runnable>();
protected ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS, mQueue);
protected Map<Long, Packet> waitingForResponse = new ConcurrentHashMap<>();
protected int lostPacket = 0;
protected Runnable mHandlerTaskHeartBeat = new Runnable() {
@Override
public void run() {
sendPacket(new HeartBeatPacket());
}
};
protected Runnable mHandlerTaskQueryStatus = new Runnable() {
@Override
public void run() {
sendPacket(new QueryStatusPacket());
mHandler.postDelayed(mHandlerTaskQueryStatus, INTERVAL_QUERY_STATUS);
}
};
protected Runnable mHandlerTaskCleanWaitingPackets = new Runnable() {
@Override
public void run() {
cleanWaitingPackets();
mHandler.postDelayed(mHandlerTaskQueryStatus, PACKET_TIMEOUT);
}
};
protected OnReceiveListener onReceiveListener;
public UDPProtocol(int sendPort /*, int listenPort*/) {
this.sendPort = sendPort;
try {
sendSocket = new DatagramSocket(sendPort);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void setOnReceiveListener(OnReceiveListener listener) {
this.onReceiveListener = listener;
}
protected void startListening() {
Thread listenThread = new Thread(new Runnable() {
@Override
public void run() {
while (isConnected()) {
byte[] message = new byte[1024];
DatagramPacket p = new DatagramPacket(message, message.length);
try {
sendSocket.receive(p);
if (isFakePacket(p)) {
Log.d("LOGGER", "STOP listening");
return;
}
String text = new String(message, 0, p.getLength());
String par[] = text.split(" ");
if (par.length < 2) {
Log.e("UDPProtocol", "invalid response " + text);
continue;
}
Packet packet = waitingForResponse.remove(Long.parseLong(par[1]));
if (packet == null) {
Log.e("UDPProtocol", "not waiting for response");
continue;
}
lag = (int) ((System.nanoTime() - packet.getId()) / 1000000);
//TODO handle quadcopter response
if (onReceiveListener != null)
onReceiveListener.onReceive(packet.getType(), text);
} catch (IOException ex) {
}
}
}
});
listenThread.start();
}
@Override
public boolean sendPacket(final Packet packet) {
if (!isConnected())
return false;
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
if (packet.waitReply()) {
waitingForResponse.put(packet.getId(), packet);
}
stopHeartBeat();
sendSocket.send(new DatagramPacket(packet.getByte(), packet.getLength(), sendTo, sendPort));
startHeartBeat();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return true;
}
@Override
public void startHeartBeat() {
//mHandlerTask.run();
mHandler.postDelayed(mHandlerTaskHeartBeat, INTERVAL_HEARTBEAT);
}
@Override
public void stopHeartBeat() {
mHandler.removeCallbacks(mHandlerTaskHeartBeat);
}
@Override
public void startQueryStatus() {
mHandlerTaskQueryStatus.run();
}
@Override
public void stopQueryStatus() {
mHandler.removeCallbacks(mHandlerTaskQueryStatus);
}
@Override
public boolean searchForQuadcopter() {
if (isConnected())
close();
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Packet packet = new HelloPacket(InetAddress.getLocalHost().getHostAddress());
DatagramPacket broadcast = new DatagramPacket(packet.getByte(), packet.getLength(), InetAddress.getByName(Utils.getBroadcast()), sendPort);
sendSocket.setBroadcast(true);
sendSocket.send(broadcast);
long t = System.currentTimeMillis();
while (System.currentTimeMillis() - t < 5000) {
byte[] message = new byte[1024];
DatagramPacket p = new DatagramPacket(message, message.length);
sendSocket.receive(p);
String text = new String(message, 0, p.getLength());
Log.d("LOGGER", "RECEIVED: " + text);
// TODO
if (text.contains("OK")) {
if (onReceiveListener != null)
onReceiveListener.onReceive(packet.getType(), p.getAddress());
} else if (text.contains("hello")) {
} else if (isFakePacket(p)) {
Log.d("LOGGER", "STOP");
onConnected();
return;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
return true;
}
@Override
public boolean connectToQuadcopter(String id) {
try {
sendFakePacket();
this.sendTo = InetAddress.getByName(id);
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
}
protected void onConnected() {
lostPacket = 0;
startHeartBeat();
startQueryStatus();
startListening();
startCleanWaitingPackets();
}
public void close() {
sendTo = null;
sendFakePacket(); //interrupt receive
stopHeartBeat();
stopQueryStatus();
stopCleanWaitingPackets();
//sendSocket.close();
}
@Override
public boolean isConnected() {
return sendTo != null;
}
@Override
public String getRemoteAddress() {
return sendTo.getHostAddress();
}
/* this method is used to send fake packet to self and interrupt receive;*/
private void sendFakePacket() {
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
sendSocket.send(new DatagramPacket("".getBytes(), 0, InetAddress.getLocalHost(), sendPort));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
private boolean isFakePacket(DatagramPacket p) {
try {
return p.getLength() == 0 && p.getAddress().equals(InetAddress.getLocalHost());
} catch (UnknownHostException e) {
return false;
}
}
public int getLatency() {
return lag;
}
protected void startCleanWaitingPackets() {
mHandlerTaskQueryStatus.run();
}
protected void stopCleanWaitingPackets() {
mHandler.removeCallbacks(mHandlerTaskCleanWaitingPackets);
}
protected void cleanWaitingPackets() {
for (Long id : waitingForResponse.keySet()) {
if (id / 1000000 > System.currentTimeMillis() + PACKET_TIMEOUT) {
waitingForResponse.remove(id);
++lostPacket;
}
}
}
public int getLostPacket() {
return lostPacket;
}
}
| 10,220 | 0.5614 | 0.554361 | 323 | 30.665634 | 26.641752 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.49226 | false | false | 1 |
3d35ad49b2b2d65872809c6f0afd7f2c0e35b641 | 17,136,919,554,788 | c8091f84f6ad2782b7638685231b518afbcbdeed | /RentalCarcharges/app/src/main/java/com/zybooks/rentalcarcharges/MainActivity.java | e4f27e6c2cbc986d08d3afbaca7fd48ecb2ebc49 | []
| no_license | Janardhen/rental_car_price_App | https://github.com/Janardhen/rental_car_price_App | 2090c0319342ffec1567e8c495a0322a7171178c | 071477dcc2e8e41c812d096072e18171f17a51f3 | refs/heads/main | 2023-03-11T04:40:50.452000 | 2021-02-28T02:11:19 | 2021-02-28T02:11:19 | 343,001,377 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zybooks.rentalcarcharges;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private TextView outputText;
private Spinner typeSpinner;
private EditText days;
private HashMap<String, Double> priceMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
typeSpinner = (Spinner) findViewById(R.id.attendEditText);
days = findViewById(R.id.attendEditText1);
outputText = findViewById(R.id.answerTextView);
addAdapterToSpinner(typeSpinner,R.array.type);
createPriceMap();
}
private void addAdapterToSpinner(Spinner s,int Array) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,
getResources().getStringArray(Array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
}
private void createPriceMap() {
priceMap = new HashMap<String, Double>();
priceMap.put("Economy", 24.99);
priceMap.put("Compact", 29.99);
priceMap.put("Intermediate", 39.99);
priceMap.put("Standard", 44.99);
priceMap.put("Fullsize",49.99);
}
public void calculateClick(View view) {
String type = typeSpinner.getSelectedItem().toString();
String daysString = days.getText().toString();
outputText.setText("Your Total due cost : " + calculateCost());
}
private double calculateCost() {
String serviceString = typeSpinner.getSelectedItem().toString();
String daysString = days.getText().toString();
int days = Integer.parseInt(daysString);
double price = priceMap.get(serviceString);
price *= days;
return price; // TODO
}
}
| UTF-8 | Java | 2,158 | java | MainActivity.java | Java | []
| null | []
| package com.zybooks.rentalcarcharges;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private TextView outputText;
private Spinner typeSpinner;
private EditText days;
private HashMap<String, Double> priceMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
typeSpinner = (Spinner) findViewById(R.id.attendEditText);
days = findViewById(R.id.attendEditText1);
outputText = findViewById(R.id.answerTextView);
addAdapterToSpinner(typeSpinner,R.array.type);
createPriceMap();
}
private void addAdapterToSpinner(Spinner s,int Array) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,
getResources().getStringArray(Array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
}
private void createPriceMap() {
priceMap = new HashMap<String, Double>();
priceMap.put("Economy", 24.99);
priceMap.put("Compact", 29.99);
priceMap.put("Intermediate", 39.99);
priceMap.put("Standard", 44.99);
priceMap.put("Fullsize",49.99);
}
public void calculateClick(View view) {
String type = typeSpinner.getSelectedItem().toString();
String daysString = days.getText().toString();
outputText.setText("Your Total due cost : " + calculateCost());
}
private double calculateCost() {
String serviceString = typeSpinner.getSelectedItem().toString();
String daysString = days.getText().toString();
int days = Integer.parseInt(daysString);
double price = priceMap.get(serviceString);
price *= days;
return price; // TODO
}
}
| 2,158 | 0.68582 | 0.675626 | 70 | 29.828571 | 25.592953 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 1 |
f7560885e9e70e437198ae5ce3bde44241ff1775 | 15,822,659,564,080 | 1707d1199f8110d7cd579f4ee323d8f21f9f682e | /Program_Diagnoser/src/Parsing/Utils.java | ac229686e4f1c1abe7200e7d57e116f69a175744 | []
| no_license | BGU-AiDnD/Debugger | https://github.com/BGU-AiDnD/Debugger | 132a10490571c5605ea5ac0d756e40b6bb346684 | e08f84f1b28cc6f864fdfd83a37f3e9ecfe90d9d | refs/heads/master | 2023-02-25T10:33:38.262000 | 2020-09-09T02:59:27 | 2020-09-09T02:59:27 | 37,018,600 | 5 | 1 | null | false | 2021-02-03T19:27:38 | 2015-06-07T14:01:29 | 2020-09-09T02:59:47 | 2021-02-03T19:27:36 | 76,124 | 1 | 2 | 364 | Java | false | false | package Parsing;
import java.util.Arrays;
public class Utils {
public static String intArrayToString(int[] array){
return Arrays.toString(array);
}
public static int[] stringToIntArray(String arrayAsString){
String[] strings = arrayAsString.replace("[", "").replace("]", "").split(", ");
int result[] = new int[strings.length];
for (int i = 0; i < result.length; i++) {
result[i] = Integer.parseInt(strings[i]);
}
return result;
}
public static String[] stringToStringArray(String arrayAsString){
return arrayAsString.replace("[", "").replace("]", "").split(", ");
}
}
| UTF-8 | Java | 621 | java | Utils.java | Java | []
| null | []
| package Parsing;
import java.util.Arrays;
public class Utils {
public static String intArrayToString(int[] array){
return Arrays.toString(array);
}
public static int[] stringToIntArray(String arrayAsString){
String[] strings = arrayAsString.replace("[", "").replace("]", "").split(", ");
int result[] = new int[strings.length];
for (int i = 0; i < result.length; i++) {
result[i] = Integer.parseInt(strings[i]);
}
return result;
}
public static String[] stringToStringArray(String arrayAsString){
return arrayAsString.replace("[", "").replace("]", "").split(", ");
}
}
| 621 | 0.640902 | 0.639291 | 21 | 28.571428 | 26.54479 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.571429 | false | false | 1 |
8e29bf67430a63e5c600620c5156f8b37fb5e1e3 | 15,822,659,562,117 | 49d3b005580e498c5eb2d5c8151654e1110fa61e | /src/main/java/Animals/Dogs.java | e0efb1ea9a7ab3949c1b06ae7a10cd0272979480 | []
| no_license | jsemenov/traning | https://github.com/jsemenov/traning | 19601e74b4d6ee4f2e54975a3faa9c162cda1990 | 9c374fa86da0ad5bc271086da8f398b79bc4a7d5 | refs/heads/master | 2020-12-24T14:45:05.071000 | 2015-02-24T19:32:36 | 2015-02-24T19:32:36 | 29,866,950 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Animals;
public class Dogs extends Animals{
public Dogs(String string, Integer integer){
name = string;
age = integer;
}
public void bite(){
System.out.println(" I am a dog " + name+ " and i will bite you!!!!");
}
}
| UTF-8 | Java | 278 | java | Dogs.java | Java | []
| null | []
| package Animals;
public class Dogs extends Animals{
public Dogs(String string, Integer integer){
name = string;
age = integer;
}
public void bite(){
System.out.println(" I am a dog " + name+ " and i will bite you!!!!");
}
}
| 278 | 0.557554 | 0.557554 | 24 | 10.583333 | 18.99543 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.208333 | false | false | 1 |
a4514fb6d7d55803908ce788b485125ae9228f6d | 9,405,978,428,657 | 97de788530d54309c751933073eca2449952f1d1 | /concurrent/src/main/java/org/huamuzhen/codewarehouse/concurrent/forkandjoin/FindMaxDoubleTask.java | 24ba015ec9df492991bcdae4a7f02d0e88b20a43 | []
| no_license | sunshycn/codewarehouse | https://github.com/sunshycn/codewarehouse | 7ee78b88ede8481650805597290cbd06396a3d2f | 0010913329880f7c0e6019d01ce0ca929e431505 | refs/heads/master | 2020-03-29T18:00:44.570000 | 2014-10-23T12:59:11 | 2014-10-23T12:59:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.huamuzhen.codewarehouse.concurrent.forkandjoin;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
* Use ForkAndJoin mode to find max number
*
* */
public class FindMaxDoubleTask extends RecursiveTask<Double> {
private final List<Double> list;
private final int numOfTasks;
public FindMaxDoubleTask(List<Double> list, int numOfTasks){
this.list = list;
this.numOfTasks = numOfTasks;
}
private static final long serialVersionUID = 7288369519281340752L;
@Override
protected Double compute() {
int listSize = list.size();
int block = listSize/numOfTasks;
List<RecursiveTask<Double>> forks = new LinkedList<>();
if(listSize > 100){
for(int i= 0; i< numOfTasks;i++){
FindMaxDoubleTask subTask;
if(i == numOfTasks -1 ){
subTask = new FindMaxDoubleTask(list.subList(i*block, listSize),numOfTasks);
}else{
subTask = new FindMaxDoubleTask(list.subList(i*block, (i+1)*block),numOfTasks);
}
forks.add(subTask);
subTask.fork();
}
Double max = 0.0;
for(RecursiveTask<Double> task: forks){
if(task.join() > max){
max = task.join();
}
}
return max;
}else{
Double max = 0.0;
for(Double entry:list){
if(max < entry){
max = entry;
}
}
return max;
}
}
private final static ForkJoinPool forkJoinPool = new ForkJoinPool();
public static void main(String[] args) {
List<Double> list = RandomUtils.getRandomNumericList(0, 1000000, 1000000);
long t1 = System.currentTimeMillis();
Double result = forkJoinPool.invoke(new FindMaxDoubleTask(list,2));
System.out.println(result);
System.out.println(System.currentTimeMillis() - t1);
long t2 = System.currentTimeMillis();
Double max=0.0;
for(Double entry: list){
if (entry > max){
max = entry;
}
}
System.out.println(max);
System.out.println(System.currentTimeMillis() - t2);
}
}
| UTF-8 | Java | 1,981 | java | FindMaxDoubleTask.java | Java | []
| null | []
| package org.huamuzhen.codewarehouse.concurrent.forkandjoin;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
* Use ForkAndJoin mode to find max number
*
* */
public class FindMaxDoubleTask extends RecursiveTask<Double> {
private final List<Double> list;
private final int numOfTasks;
public FindMaxDoubleTask(List<Double> list, int numOfTasks){
this.list = list;
this.numOfTasks = numOfTasks;
}
private static final long serialVersionUID = 7288369519281340752L;
@Override
protected Double compute() {
int listSize = list.size();
int block = listSize/numOfTasks;
List<RecursiveTask<Double>> forks = new LinkedList<>();
if(listSize > 100){
for(int i= 0; i< numOfTasks;i++){
FindMaxDoubleTask subTask;
if(i == numOfTasks -1 ){
subTask = new FindMaxDoubleTask(list.subList(i*block, listSize),numOfTasks);
}else{
subTask = new FindMaxDoubleTask(list.subList(i*block, (i+1)*block),numOfTasks);
}
forks.add(subTask);
subTask.fork();
}
Double max = 0.0;
for(RecursiveTask<Double> task: forks){
if(task.join() > max){
max = task.join();
}
}
return max;
}else{
Double max = 0.0;
for(Double entry:list){
if(max < entry){
max = entry;
}
}
return max;
}
}
private final static ForkJoinPool forkJoinPool = new ForkJoinPool();
public static void main(String[] args) {
List<Double> list = RandomUtils.getRandomNumericList(0, 1000000, 1000000);
long t1 = System.currentTimeMillis();
Double result = forkJoinPool.invoke(new FindMaxDoubleTask(list,2));
System.out.println(result);
System.out.println(System.currentTimeMillis() - t1);
long t2 = System.currentTimeMillis();
Double max=0.0;
for(Double entry: list){
if (entry > max){
max = entry;
}
}
System.out.println(max);
System.out.println(System.currentTimeMillis() - t2);
}
}
| 1,981 | 0.683998 | 0.658253 | 82 | 23.158537 | 22.190676 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.5 | false | false | 1 |
340fcf3c775dbd5e4160abe590079abc63071df1 | 24,094,766,560,362 | d1e75924a43c514acf0b9fb2d70740197f1acb8f | /bodycheck.mgr/src/main/java/com/great/service/impl/OfficeServiceImpl.java | a73b9bc302c117cc411142ef23c59d259ae5280f | []
| no_license | peikun666/bodycheck | https://github.com/peikun666/bodycheck | d9c75fea9a9350002a061bb1c5956ffbf4d8ca23 | bccc646d6bd864b1758432bcf02e36740de81f30 | refs/heads/master | 2020-03-29T04:25:28.191000 | 2018-09-20T01:05:31 | 2018-09-20T01:05:31 | 149,455,855 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.great.service.impl;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.great.dao.OfficeMapper;
import com.great.service.OfficeService;
/**
* @Title : OfficeServiceImpl.java
* @Package : com.great.service.impl
* @DevelopTools : Eclipse EE v4.7.2
* @DevelopSystem: Win10
* @Description : 科室配置的实现类
* @author : DongZiQian
* @date : 2018年4月19日上午10:45:15
* @version : V1.0
*/
@Service
public class OfficeServiceImpl implements OfficeService {
@Autowired
private OfficeMapper officeMapper;
// 获取下拉框的科室
public List<Map<String, Object>> getOfficeOption() {
List<Map<String, Object>> officeOption = officeMapper.getOfficeOption();
return officeOption;
}
// 查询科室
public List<Map<String, Object>> getOffice(Integer currentPage, Integer rowNum, String officeName) {
RowBounds rowBounds = new RowBounds((currentPage - 1) * rowNum, rowNum);
List<Map<String, Object>> office = officeMapper.getOffice(rowBounds, officeName);
return office;
}
// 查询科室数量
public Integer getOfficeCount(String officeName) {
Integer officeCount = officeMapper.getOfficeCount(officeName);
return officeCount;
}
// 添加科室
public Integer addOffice(String officeName) {
Integer addOffice = officeMapper.addOffice(officeName);
return addOffice;
}
// 删除科室
public Integer deleteOffice(Integer officeId) {
Integer deleteOffice = officeMapper.deleteOffice(officeId);
return deleteOffice;
}
// 修改科室
public Integer editOffice(Integer officeId, String officeName) {
Integer editOffice = officeMapper.editOffice(officeId, officeName);
return editOffice;
}
}
| UTF-8 | Java | 1,864 | java | OfficeServiceImpl.java | Java | [
{
"context": "n10\n * @Description : 科室配置的实现类\n * @author : DongZiQian\n * @date : 2018年4月19日上午10:45:15\n * @versi",
"end": 517,
"score": 0.9995718002319336,
"start": 507,
"tag": "NAME",
"value": "DongZiQian"
}
]
| null | []
| package com.great.service.impl;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.great.dao.OfficeMapper;
import com.great.service.OfficeService;
/**
* @Title : OfficeServiceImpl.java
* @Package : com.great.service.impl
* @DevelopTools : Eclipse EE v4.7.2
* @DevelopSystem: Win10
* @Description : 科室配置的实现类
* @author : DongZiQian
* @date : 2018年4月19日上午10:45:15
* @version : V1.0
*/
@Service
public class OfficeServiceImpl implements OfficeService {
@Autowired
private OfficeMapper officeMapper;
// 获取下拉框的科室
public List<Map<String, Object>> getOfficeOption() {
List<Map<String, Object>> officeOption = officeMapper.getOfficeOption();
return officeOption;
}
// 查询科室
public List<Map<String, Object>> getOffice(Integer currentPage, Integer rowNum, String officeName) {
RowBounds rowBounds = new RowBounds((currentPage - 1) * rowNum, rowNum);
List<Map<String, Object>> office = officeMapper.getOffice(rowBounds, officeName);
return office;
}
// 查询科室数量
public Integer getOfficeCount(String officeName) {
Integer officeCount = officeMapper.getOfficeCount(officeName);
return officeCount;
}
// 添加科室
public Integer addOffice(String officeName) {
Integer addOffice = officeMapper.addOffice(officeName);
return addOffice;
}
// 删除科室
public Integer deleteOffice(Integer officeId) {
Integer deleteOffice = officeMapper.deleteOffice(officeId);
return deleteOffice;
}
// 修改科室
public Integer editOffice(Integer officeId, String officeName) {
Integer editOffice = officeMapper.editOffice(officeId, officeName);
return editOffice;
}
}
| 1,864 | 0.745219 | 0.733408 | 68 | 25.147058 | 25.373251 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.176471 | false | false | 1 |
cf630a45e455c649d6a826f45136cf31195b79e8 | 33,603,824,156,643 | 6f084306982f56060697159087654da7e7f4821c | /MVC/src/svc/MovCommentWriteProService.java | efdaee4d399de6e678384c3f775a784b9130dab5 | []
| no_license | ex-obstinacy/MVC | https://github.com/ex-obstinacy/MVC | 1d79a98b6b6a4ff9c282e06d517ba101111587b6 | a842c056a0ba173c900d1092f484f28bdda79fa0 | refs/heads/master | 2023-02-10T08:35:59.561000 | 2021-01-06T05:37:56 | 2021-01-06T05:37:56 | 310,225,008 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package svc;
import static db.JdbcUtil.*;
import java.sql.Connection;
import dao.MovDAO;
import vo.MovCommentBean;
public class MovCommentWriteProService {
public boolean registArticle(MovCommentBean movCommentBean) {
System.out.println("MovCommentWriteProService - registArticle()");
boolean isWriteSuccess = false;
// DB 작업을 위한 비즈니스 로직 수행 준비
Connection con = getConnection();
MovDAO movDAO = MovDAO.getInstance();
movDAO.setConnection(con);
int insertCount = movDAO.insertMovCommentArticle(movCommentBean);
if (insertCount > 0) {
commit(con); // DB 커밋 작업 수행
isWriteSuccess = true; // 리턴할 작업 수행 결과를 true 로 설정
} else {
rollback(con);
}
close(con);
return isWriteSuccess;
}
}
| UTF-8 | Java | 852 | java | MovCommentWriteProService.java | Java | []
| null | []
| package svc;
import static db.JdbcUtil.*;
import java.sql.Connection;
import dao.MovDAO;
import vo.MovCommentBean;
public class MovCommentWriteProService {
public boolean registArticle(MovCommentBean movCommentBean) {
System.out.println("MovCommentWriteProService - registArticle()");
boolean isWriteSuccess = false;
// DB 작업을 위한 비즈니스 로직 수행 준비
Connection con = getConnection();
MovDAO movDAO = MovDAO.getInstance();
movDAO.setConnection(con);
int insertCount = movDAO.insertMovCommentArticle(movCommentBean);
if (insertCount > 0) {
commit(con); // DB 커밋 작업 수행
isWriteSuccess = true; // 리턴할 작업 수행 결과를 true 로 설정
} else {
rollback(con);
}
close(con);
return isWriteSuccess;
}
}
| 852 | 0.665816 | 0.664541 | 39 | 18.102564 | 19.715664 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.820513 | false | false | 1 |
eb6d542f50b4184b910f96eab49dd988e21bf9bd | 23,570,780,548,716 | ef53b4c580cacc103e870c6c1ecb0b47aa0c51a6 | /src/main/java/com/pnc/api/web/controller/BalanceController.java | cfb5a1d949ea2a8d1d3c42a5e691cca0c77c60ae | []
| no_license | julesTchamba/api | https://github.com/julesTchamba/api | bd3e466f5c63bb51ae4566d73a94510e44dbf3f7 | 0759491e6cc8de11c117355baba7e13aae42b276 | refs/heads/master | 2023-03-21T03:28:00.604000 | 2021-03-15T12:42:46 | 2021-03-15T12:42:46 | 347,940,780 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pnc.api.web.controller;
import com.google.common.collect.Iterables;
import com.pnc.api.dao.BalanceDao;
import com.pnc.api.model.Balance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.math.BigDecimal;
import java.net.URI;
import java.util.List;
@RestController
public class BalanceController {
@Autowired
private BalanceDao balanceDao;
//get all balances
@GetMapping(value = "/balances")
public List<Balance> balances() {
return balanceDao.findAll();
}
@GetMapping(value = "/balances/{accountNumber}")
public BigDecimal latestbalances(@PathVariable String accountNumber) {
Balance balanceFound = Iterables.getLast(balanceDao.findByAccountNumber(accountNumber));
if (balanceFound == null)
{
//Todo() we have to manage the case the user send a wrong accountNumber or
// if the accountNumber does not exists
return BigDecimal.valueOf(-1.0);
} else
return balanceFound.getBalance();
}
//add balance
@PostMapping(value = "/balances")
public ResponseEntity<Void> addBalance(@RequestBody Balance balance) {
Balance balanceAdded = balanceDao.save(balance);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{accountNumber}")
.buildAndExpand(balanceAdded.getAccountNumber())
.toUri();
return ResponseEntity.created(location).build();
}
} | UTF-8 | Java | 1,706 | java | BalanceController.java | Java | []
| null | []
| package com.pnc.api.web.controller;
import com.google.common.collect.Iterables;
import com.pnc.api.dao.BalanceDao;
import com.pnc.api.model.Balance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.math.BigDecimal;
import java.net.URI;
import java.util.List;
@RestController
public class BalanceController {
@Autowired
private BalanceDao balanceDao;
//get all balances
@GetMapping(value = "/balances")
public List<Balance> balances() {
return balanceDao.findAll();
}
@GetMapping(value = "/balances/{accountNumber}")
public BigDecimal latestbalances(@PathVariable String accountNumber) {
Balance balanceFound = Iterables.getLast(balanceDao.findByAccountNumber(accountNumber));
if (balanceFound == null)
{
//Todo() we have to manage the case the user send a wrong accountNumber or
// if the accountNumber does not exists
return BigDecimal.valueOf(-1.0);
} else
return balanceFound.getBalance();
}
//add balance
@PostMapping(value = "/balances")
public ResponseEntity<Void> addBalance(@RequestBody Balance balance) {
Balance balanceAdded = balanceDao.save(balance);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{accountNumber}")
.buildAndExpand(balanceAdded.getAccountNumber())
.toUri();
return ResponseEntity.created(location).build();
}
} | 1,706 | 0.690504 | 0.689332 | 53 | 31.207546 | 25.121109 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358491 | false | false | 1 |
8634fb3071c30a5b5aeb7317fea98b7f1d570c87 | 7,919,919,735,486 | e89e05ab422f137fd823a35f829ebd5959750a2d | /app/src/main/java/qtc/project/pos/ui/views/fragment/product/productlist/detail/FragmentProductListDetailView.java | d5d5a23cbf1ef86e7821bbd875b4ec373c5258be | []
| no_license | dinhdeveloper/Admin_POS | https://github.com/dinhdeveloper/Admin_POS | 34d0409a8555fd8c0d7d3792d5b7361e1890ca13 | 346dd41df428d172f95d59663c7b4ef9144f162f | refs/heads/master | 2023-03-29T09:32:36.961000 | 2021-03-31T04:27:42 | 2021-03-31T04:27:42 | 279,499,743 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package qtc.project.pos.ui.views.fragment.product.productlist.detail;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import java.util.ArrayList;
import b.laixuantam.myaarlibrary.base.BaseUiContainer;
import b.laixuantam.myaarlibrary.base.BaseView;
import b.laixuantam.myaarlibrary.helper.KeyboardUtils;
import b.laixuantam.myaarlibrary.widgets.currencyedittext.CurrencyEditText;
import b.laixuantam.myaarlibrary.widgets.popupmenu.ActionItem;
import b.laixuantam.myaarlibrary.widgets.popupmenu.MyCustomPopupMenu;
import b.laixuantam.myaarlibrary.widgets.roundview.RoundTextView;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import qtc.project.pos.R;
import qtc.project.pos.activity.HomeActivity;
import qtc.project.pos.adapter.product.category.ProductItemCategoryAdapter;
import qtc.project.pos.dependency.AppProvider;
import qtc.project.pos.helper.Consts;
import qtc.project.pos.model.ProductCategoryModel;
import qtc.project.pos.model.ProductListModel;
public class FragmentProductListDetailView extends BaseView<FragmentProductListDetailView.UIContainer> implements FragmentProductListDetailViewInterface, ZXingScannerView.ResultHandler {
HomeActivity activity;
FragmentProductListDetailViewCallback callback;
String image_pro;
String id_category = null;
int TYLE_CODE_GEN = 0;
private ZXingScannerView mScannerView;
@Override
public void init(HomeActivity activity, FragmentProductListDetailViewCallback callback) {
this.activity = activity;
this.callback = callback;
KeyboardUtils.setupUI(getView(), activity);
onClick();
}
public void initScanBarcode() {
mScannerView = new ZXingScannerView(activity);
ui.content_frame.addView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.setAutoFocus(true);
mScannerView.startCamera();
}
public void genarateScanBarcode(String resultCode) {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix;
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.CODE_128, 300, 150);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
ui.imv_barcode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
public void genarateScanQrcode(String resultCode) {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix;
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.QR_CODE, 300, 300);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
ui.imv_qrcode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
@Override
public void setProductDetail(ProductListModel model) {
if (model != null) {
AppProvider.getImageHelper().displayImage(Consts.HOST_API + model.getImage(), ui.image_product, null, R.drawable.no_image_full);
ui.title_header.setText(model.getName());
ui.name_product.setText(model.getName());
ui.id_product.setText(model.getId_code());
ui.description_product.setText(model.getDescription());
ui.tonkho.setText(model.getQuantity_safetystock());
ui.qrcode.setText(model.getQr_code());
ui.barcode.setText(model.getBarcode());
ui.gia_ban.setText(model.getPrice_sell());
if (!TextUtils.isEmpty(model.getCost_historical()))
ui.gia_goc.setText(model.getCost_historical());
try {
genarateScanBarcode(model.getBarcode());
genarateScanQrcode(model.getQr_code());
} catch (Exception e) {
Log.e("Ex", e.getMessage());
}
ui.name_product_category.setText(model.getCategory_name());
//cap nhat
ui.layout_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ProductListModel listModel = new ProductListModel();
listModel.setId(model.getId());
listModel.setId_code(ui.id_product.getText().toString());
listModel.setName(ui.name_product.getText().toString());
listModel.setDescription(ui.description_product.getText().toString());
listModel.setCategory_id(id_category);
listModel.setQuantity_safetystock(ui.tonkho.getStringValue());
listModel.setImage(image_pro);
listModel.setBarcode(ui.barcode.getText().toString());
listModel.setQr_code(ui.qrcode.getText().toString());
listModel.setPrice_sell(ui.gia_ban.getStringValue());
String cost_historical = !TextUtils.isEmpty(ui.gia_goc.getStringValue()) ? ui.gia_goc.getStringValue() : "0";
listModel.setCost_historical(cost_historical);
if (callback != null) {
callback.updateProductDetail(listModel);
}
}
});
ui.layout_delete.setOnClickListener(v -> {
if (callback != null)
callback.deleteProduct(model);
});
ui.btnDisable.setOnClickListener(v -> {
if (callback != null)
callback.disableProduct(model.getId());
});
//xoa sp
} else {
ui.layout_delete.setVisibility(View.GONE);
ui.title_header.setText("Tạo mới sản phẩm");
ui.tvTitleUpdate.setText("Tạo mới");
ui.layout_update.setOnClickListener(view -> {
ProductListModel listModel = new ProductListModel();
listModel.setId_code(ui.id_product.getText().toString());
listModel.setName(ui.name_product.getText().toString());
listModel.setDescription(ui.description_product.getText().toString());
listModel.setCategory_id(id_category);
listModel.setQuantity_safetystock(ui.tonkho.getStringValue());
listModel.setImage(image_pro);
listModel.setBarcode(ui.barcode.getText().toString());
listModel.setQr_code(ui.qrcode.getText().toString());
listModel.setPrice_sell(ui.gia_ban.getStringValue());
String cost_historical = !TextUtils.isEmpty(ui.gia_goc.getStringValue()) ? ui.gia_goc.getStringValue() : "0";
listModel.setCost_historical(cost_historical);
if (callback != null) {
callback.updateProductDetail(listModel);
}
});
}
}
@Override
public void clearData() {
ui.id_product.setText(null);
ui.name_product_category.setText(null);
ui.description_product.setText(null);
ui.image_product.setImageResource(R.drawable.imageloading);
}
public void generateCode(String resultCode) {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix;
switch (TYLE_CODE_GEN) {
case 1:
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.CODE_128, 300, 150);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
ui.imv_barcode.setImageBitmap(bitmap);
ui.barcode.setText(resultCode);
break;
case 2:
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.QR_CODE, 250, 250);
BarcodeEncoder barcodeQr = new BarcodeEncoder();
Bitmap bitmapQr = barcodeQr.createBitmap(bitMatrix);
ui.imv_qrcode.setImageBitmap(bitmapQr);
ui.qrcode.setText(resultCode);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void setDataProductImage(String outfile) {
image_pro = outfile;
AppProvider.getImageHelper().displayImage(outfile, ui.image_product, null, R.drawable.no_image_full, false);
}
@Override
public void initViewPopup(ArrayList<ProductCategoryModel> list) {
LayoutInflater layoutInflater = activity.getLayoutInflater();
View popupView = layoutInflater.inflate(R.layout.custom_popup_choose_level_customer, null);
TextView choose_item = popupView.findViewById(R.id.choose_item);
TextView cancel = popupView.findViewById(R.id.cancel);
RecyclerView recycler_view_list = popupView.findViewById(R.id.recycler_view_list);
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setView(popupView);
AlertDialog dialog = alert.create();
//dialog.setCanceledOnTouchOutside(false);
dialog.show();
ProductItemCategoryAdapter chooseAdapter = new ProductItemCategoryAdapter(activity, list);
recycler_view_list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recycler_view_list.setAdapter(chooseAdapter);
chooseAdapter.setOnItemClickListener(new ProductItemCategoryAdapter.onRecyclerViewItemClickListener() {
@Override
public void onItemClickListener(ProductCategoryModel model) {
choose_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
id_category = model.getId();
ui.name_product_category.setText(model.getName());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
@Override
public void showConfirm() {
}
@Override
public void showConfirmDelete() {
}
private void onClick() {
//quet barcode
ui.image_barcode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TYLE_CODE_GEN = 1;
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.CAMERA}, 1101);
} else {
ui.layout_scanbar_code.setVisibility(View.VISIBLE);
initScanBarcode();
}
}
});
//quet qr code
ui.image_qrcode.setOnClickListener(v -> {
TYLE_CODE_GEN = 2;
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.CAMERA}, 1101);
} else {
ui.layout_scanbar_code.setVisibility(View.VISIBLE);
initScanBarcode();
}
});
ui.imageNavLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (callback != null)
callback.onBackprogress();
}
});
//chon file
ui.choose_file_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPopupMenu(v);
}
});
//chon danh muc
ui.choose_category.setOnClickListener(v -> {
if (callback != null)
callback.getAllProductCategory();
});
//dong layout scanbar code
ui.image_close_layout_scan.setOnClickListener(v -> {
mScannerView.stopCamera();
ui.layout_scanbar_code.setVisibility(View.GONE);
});
}
private void showPopupMenu(View view) {
ActionItem change_password = new ActionItem(1, "Chọn ảnh từ camera", null);
ActionItem employee_tracking = new ActionItem(2, "Chọn hình từ thư viện", null);
// int backgroundCustom = ContextCompat.getColor(getContext(), R.color.red);
// int arrowColorCustom = ContextCompat.getColor(getContext(), R.color.red);
MyCustomPopupMenu quickAction = new MyCustomPopupMenu(getContext()/*, backgroundCustom, arrowColorCustom*/);
quickAction.addActionItem(change_password);
quickAction.addActionItem(employee_tracking);
quickAction.setOnActionItemClickListener(new MyCustomPopupMenu.OnActionItemClickListener() {
@Override
public void onItemClick(MyCustomPopupMenu source, int pos, int actionId) {
switch (actionId) {
case 1:
if (callback != null)
callback.onClickOptionSelectImageFromCamera();
break;
case 2:
if (callback != null)
callback.onClickOptionSelectImageFromGallery();
break;
}
}
});
quickAction.show(view);
}
@Override
public BaseUiContainer getUiContainer() {
return new FragmentProductListDetailView.UIContainer();
}
@Override
public int getViewId() {
return R.layout.layout_fragment_product_detail;
}
@Override
public void handleResult(Result rawResult) {
if (rawResult != null) {
Vibrator v = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
// SET RUNG 400 MILLISECONDS
v.vibrate(400);
mScannerView.stopCamera();
mScannerView = null;
ui.layout_scanbar_code.setVisibility(View.GONE);
generateCode(rawResult.getText());
}
}
public static class UIContainer extends BaseUiContainer {
@UiElement(R.id.title_header)
public TextView title_header;
@UiElement(R.id.imageNavLeft)
public ImageView imageNavLeft;
@UiElement(R.id.name_product)
public EditText name_product;
@UiElement(R.id.id_product)
public EditText id_product;
@UiElement(R.id.tonkho)
public CurrencyEditText tonkho;
@UiElement(R.id.barcode)
public EditText barcode;
@UiElement(R.id.qrcode)
public EditText qrcode;
@UiElement(R.id.description_product)
public EditText description_product;
@UiElement(R.id.choose_file_image)
public LinearLayout choose_file_image;
@UiElement(R.id.image_product)
public ImageView image_product;
@UiElement(R.id.image_barcode)
public ImageView image_barcode;
@UiElement(R.id.image_qrcode)
public ImageView image_qrcode;
@UiElement(R.id.layout_update)
public LinearLayout layout_update;
@UiElement(R.id.layout_delete)
public LinearLayout layout_delete;
@UiElement(R.id.choose_category)
public LinearLayout choose_category;
@UiElement(R.id.name_product_category)
public TextView name_product_category;
@UiElement(R.id.content_frame)
public FrameLayout content_frame;
@UiElement(R.id.layout_scanbar_code)
public RelativeLayout layout_scanbar_code;
@UiElement(R.id.image_close_layout_scan)
public View image_close_layout_scan;
@UiElement(R.id.imv_qrcode)
public ImageView imv_qrcode;
@UiElement(R.id.imv_barcode)
public ImageView imv_barcode;
@UiElement(R.id.gia_ban)
public CurrencyEditText gia_ban;
@UiElement(R.id.gia_goc)
public CurrencyEditText gia_goc;
@UiElement(R.id.btnDisable)
public RoundTextView btnDisable;
@UiElement(R.id.tvTitleUpdate)
public TextView tvTitleUpdate;
}
}
| UTF-8 | Java | 17,724 | java | FragmentProductListDetailView.java | Java | [
{
"context": "rary.widgets.roundview.RoundTextView;\nimport me.dm7.barcodescanner.zxing.ZXingScannerView;\nimport qtc",
"end": 1551,
"score": 0.7168150544166565,
"start": 1550,
"tag": "USERNAME",
"value": "7"
}
]
| null | []
| package qtc.project.pos.ui.views.fragment.product.productlist.detail;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import java.util.ArrayList;
import b.laixuantam.myaarlibrary.base.BaseUiContainer;
import b.laixuantam.myaarlibrary.base.BaseView;
import b.laixuantam.myaarlibrary.helper.KeyboardUtils;
import b.laixuantam.myaarlibrary.widgets.currencyedittext.CurrencyEditText;
import b.laixuantam.myaarlibrary.widgets.popupmenu.ActionItem;
import b.laixuantam.myaarlibrary.widgets.popupmenu.MyCustomPopupMenu;
import b.laixuantam.myaarlibrary.widgets.roundview.RoundTextView;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import qtc.project.pos.R;
import qtc.project.pos.activity.HomeActivity;
import qtc.project.pos.adapter.product.category.ProductItemCategoryAdapter;
import qtc.project.pos.dependency.AppProvider;
import qtc.project.pos.helper.Consts;
import qtc.project.pos.model.ProductCategoryModel;
import qtc.project.pos.model.ProductListModel;
public class FragmentProductListDetailView extends BaseView<FragmentProductListDetailView.UIContainer> implements FragmentProductListDetailViewInterface, ZXingScannerView.ResultHandler {
HomeActivity activity;
FragmentProductListDetailViewCallback callback;
String image_pro;
String id_category = null;
int TYLE_CODE_GEN = 0;
private ZXingScannerView mScannerView;
@Override
public void init(HomeActivity activity, FragmentProductListDetailViewCallback callback) {
this.activity = activity;
this.callback = callback;
KeyboardUtils.setupUI(getView(), activity);
onClick();
}
public void initScanBarcode() {
mScannerView = new ZXingScannerView(activity);
ui.content_frame.addView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.setAutoFocus(true);
mScannerView.startCamera();
}
public void genarateScanBarcode(String resultCode) {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix;
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.CODE_128, 300, 150);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
ui.imv_barcode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
public void genarateScanQrcode(String resultCode) {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix;
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.QR_CODE, 300, 300);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
ui.imv_qrcode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
@Override
public void setProductDetail(ProductListModel model) {
if (model != null) {
AppProvider.getImageHelper().displayImage(Consts.HOST_API + model.getImage(), ui.image_product, null, R.drawable.no_image_full);
ui.title_header.setText(model.getName());
ui.name_product.setText(model.getName());
ui.id_product.setText(model.getId_code());
ui.description_product.setText(model.getDescription());
ui.tonkho.setText(model.getQuantity_safetystock());
ui.qrcode.setText(model.getQr_code());
ui.barcode.setText(model.getBarcode());
ui.gia_ban.setText(model.getPrice_sell());
if (!TextUtils.isEmpty(model.getCost_historical()))
ui.gia_goc.setText(model.getCost_historical());
try {
genarateScanBarcode(model.getBarcode());
genarateScanQrcode(model.getQr_code());
} catch (Exception e) {
Log.e("Ex", e.getMessage());
}
ui.name_product_category.setText(model.getCategory_name());
//cap nhat
ui.layout_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ProductListModel listModel = new ProductListModel();
listModel.setId(model.getId());
listModel.setId_code(ui.id_product.getText().toString());
listModel.setName(ui.name_product.getText().toString());
listModel.setDescription(ui.description_product.getText().toString());
listModel.setCategory_id(id_category);
listModel.setQuantity_safetystock(ui.tonkho.getStringValue());
listModel.setImage(image_pro);
listModel.setBarcode(ui.barcode.getText().toString());
listModel.setQr_code(ui.qrcode.getText().toString());
listModel.setPrice_sell(ui.gia_ban.getStringValue());
String cost_historical = !TextUtils.isEmpty(ui.gia_goc.getStringValue()) ? ui.gia_goc.getStringValue() : "0";
listModel.setCost_historical(cost_historical);
if (callback != null) {
callback.updateProductDetail(listModel);
}
}
});
ui.layout_delete.setOnClickListener(v -> {
if (callback != null)
callback.deleteProduct(model);
});
ui.btnDisable.setOnClickListener(v -> {
if (callback != null)
callback.disableProduct(model.getId());
});
//xoa sp
} else {
ui.layout_delete.setVisibility(View.GONE);
ui.title_header.setText("Tạo mới sản phẩm");
ui.tvTitleUpdate.setText("Tạo mới");
ui.layout_update.setOnClickListener(view -> {
ProductListModel listModel = new ProductListModel();
listModel.setId_code(ui.id_product.getText().toString());
listModel.setName(ui.name_product.getText().toString());
listModel.setDescription(ui.description_product.getText().toString());
listModel.setCategory_id(id_category);
listModel.setQuantity_safetystock(ui.tonkho.getStringValue());
listModel.setImage(image_pro);
listModel.setBarcode(ui.barcode.getText().toString());
listModel.setQr_code(ui.qrcode.getText().toString());
listModel.setPrice_sell(ui.gia_ban.getStringValue());
String cost_historical = !TextUtils.isEmpty(ui.gia_goc.getStringValue()) ? ui.gia_goc.getStringValue() : "0";
listModel.setCost_historical(cost_historical);
if (callback != null) {
callback.updateProductDetail(listModel);
}
});
}
}
@Override
public void clearData() {
ui.id_product.setText(null);
ui.name_product_category.setText(null);
ui.description_product.setText(null);
ui.image_product.setImageResource(R.drawable.imageloading);
}
public void generateCode(String resultCode) {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix;
switch (TYLE_CODE_GEN) {
case 1:
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.CODE_128, 300, 150);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
ui.imv_barcode.setImageBitmap(bitmap);
ui.barcode.setText(resultCode);
break;
case 2:
bitMatrix = multiFormatWriter.encode(resultCode, BarcodeFormat.QR_CODE, 250, 250);
BarcodeEncoder barcodeQr = new BarcodeEncoder();
Bitmap bitmapQr = barcodeQr.createBitmap(bitMatrix);
ui.imv_qrcode.setImageBitmap(bitmapQr);
ui.qrcode.setText(resultCode);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void setDataProductImage(String outfile) {
image_pro = outfile;
AppProvider.getImageHelper().displayImage(outfile, ui.image_product, null, R.drawable.no_image_full, false);
}
@Override
public void initViewPopup(ArrayList<ProductCategoryModel> list) {
LayoutInflater layoutInflater = activity.getLayoutInflater();
View popupView = layoutInflater.inflate(R.layout.custom_popup_choose_level_customer, null);
TextView choose_item = popupView.findViewById(R.id.choose_item);
TextView cancel = popupView.findViewById(R.id.cancel);
RecyclerView recycler_view_list = popupView.findViewById(R.id.recycler_view_list);
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setView(popupView);
AlertDialog dialog = alert.create();
//dialog.setCanceledOnTouchOutside(false);
dialog.show();
ProductItemCategoryAdapter chooseAdapter = new ProductItemCategoryAdapter(activity, list);
recycler_view_list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recycler_view_list.setAdapter(chooseAdapter);
chooseAdapter.setOnItemClickListener(new ProductItemCategoryAdapter.onRecyclerViewItemClickListener() {
@Override
public void onItemClickListener(ProductCategoryModel model) {
choose_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
id_category = model.getId();
ui.name_product_category.setText(model.getName());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
@Override
public void showConfirm() {
}
@Override
public void showConfirmDelete() {
}
private void onClick() {
//quet barcode
ui.image_barcode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TYLE_CODE_GEN = 1;
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.CAMERA}, 1101);
} else {
ui.layout_scanbar_code.setVisibility(View.VISIBLE);
initScanBarcode();
}
}
});
//quet qr code
ui.image_qrcode.setOnClickListener(v -> {
TYLE_CODE_GEN = 2;
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.CAMERA}, 1101);
} else {
ui.layout_scanbar_code.setVisibility(View.VISIBLE);
initScanBarcode();
}
});
ui.imageNavLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (callback != null)
callback.onBackprogress();
}
});
//chon file
ui.choose_file_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPopupMenu(v);
}
});
//chon danh muc
ui.choose_category.setOnClickListener(v -> {
if (callback != null)
callback.getAllProductCategory();
});
//dong layout scanbar code
ui.image_close_layout_scan.setOnClickListener(v -> {
mScannerView.stopCamera();
ui.layout_scanbar_code.setVisibility(View.GONE);
});
}
private void showPopupMenu(View view) {
ActionItem change_password = new ActionItem(1, "Chọn ảnh từ camera", null);
ActionItem employee_tracking = new ActionItem(2, "Chọn hình từ thư viện", null);
// int backgroundCustom = ContextCompat.getColor(getContext(), R.color.red);
// int arrowColorCustom = ContextCompat.getColor(getContext(), R.color.red);
MyCustomPopupMenu quickAction = new MyCustomPopupMenu(getContext()/*, backgroundCustom, arrowColorCustom*/);
quickAction.addActionItem(change_password);
quickAction.addActionItem(employee_tracking);
quickAction.setOnActionItemClickListener(new MyCustomPopupMenu.OnActionItemClickListener() {
@Override
public void onItemClick(MyCustomPopupMenu source, int pos, int actionId) {
switch (actionId) {
case 1:
if (callback != null)
callback.onClickOptionSelectImageFromCamera();
break;
case 2:
if (callback != null)
callback.onClickOptionSelectImageFromGallery();
break;
}
}
});
quickAction.show(view);
}
@Override
public BaseUiContainer getUiContainer() {
return new FragmentProductListDetailView.UIContainer();
}
@Override
public int getViewId() {
return R.layout.layout_fragment_product_detail;
}
@Override
public void handleResult(Result rawResult) {
if (rawResult != null) {
Vibrator v = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
// SET RUNG 400 MILLISECONDS
v.vibrate(400);
mScannerView.stopCamera();
mScannerView = null;
ui.layout_scanbar_code.setVisibility(View.GONE);
generateCode(rawResult.getText());
}
}
public static class UIContainer extends BaseUiContainer {
@UiElement(R.id.title_header)
public TextView title_header;
@UiElement(R.id.imageNavLeft)
public ImageView imageNavLeft;
@UiElement(R.id.name_product)
public EditText name_product;
@UiElement(R.id.id_product)
public EditText id_product;
@UiElement(R.id.tonkho)
public CurrencyEditText tonkho;
@UiElement(R.id.barcode)
public EditText barcode;
@UiElement(R.id.qrcode)
public EditText qrcode;
@UiElement(R.id.description_product)
public EditText description_product;
@UiElement(R.id.choose_file_image)
public LinearLayout choose_file_image;
@UiElement(R.id.image_product)
public ImageView image_product;
@UiElement(R.id.image_barcode)
public ImageView image_barcode;
@UiElement(R.id.image_qrcode)
public ImageView image_qrcode;
@UiElement(R.id.layout_update)
public LinearLayout layout_update;
@UiElement(R.id.layout_delete)
public LinearLayout layout_delete;
@UiElement(R.id.choose_category)
public LinearLayout choose_category;
@UiElement(R.id.name_product_category)
public TextView name_product_category;
@UiElement(R.id.content_frame)
public FrameLayout content_frame;
@UiElement(R.id.layout_scanbar_code)
public RelativeLayout layout_scanbar_code;
@UiElement(R.id.image_close_layout_scan)
public View image_close_layout_scan;
@UiElement(R.id.imv_qrcode)
public ImageView imv_qrcode;
@UiElement(R.id.imv_barcode)
public ImageView imv_barcode;
@UiElement(R.id.gia_ban)
public CurrencyEditText gia_ban;
@UiElement(R.id.gia_goc)
public CurrencyEditText gia_goc;
@UiElement(R.id.btnDisable)
public RoundTextView btnDisable;
@UiElement(R.id.tvTitleUpdate)
public TextView tvTitleUpdate;
}
}
| 17,724 | 0.620974 | 0.617527 | 462 | 37.307358 | 28.275253 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588745 | false | false | 1 |
ffe882270562c8e1293cc1137f4aa1d867c4f893 | 214,748,367,887 | 0f971689df84fb688584baf87da7a9f3ca0aaabd | /AI/src/cn/edu/nju/panels/Test.java | 61a6499f17bdcf8b4b37779562b2e98bd5cb3072 | []
| no_license | GY15/Tutorial | https://github.com/GY15/Tutorial | ea9b32d1cb75b53ea7e3a2335c010fa7de29ef0b | 87dab874271e0fa9127f53d05887b22903e07333 | refs/heads/master | 2017-12-02T08:59:33.383000 | 2016-05-07T12:50:56 | 2016-05-07T12:50:56 | 58,263,313 | 0 | 0 | null | true | 2016-05-07T11:36:37 | 2016-05-07T11:36:36 | 2016-05-06T09:02:00 | 2016-05-07T11:34:21 | 724 | 0 | 0 | 0 | null | null | null | package cn.edu.nju.panels;
import javax.swing.JFrame;
public class Test extends JFrame{
GamePanel s = new GamePanel();
public Test(){
super("Test");
this.setSize(960,690);
this.setLocation(100, 3);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(s);
}
public static void main(String[] args) {
new Test();
}
}
| UTF-8 | Java | 377 | java | Test.java | Java | []
| null | []
| package cn.edu.nju.panels;
import javax.swing.JFrame;
public class Test extends JFrame{
GamePanel s = new GamePanel();
public Test(){
super("Test");
this.setSize(960,690);
this.setLocation(100, 3);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(s);
}
public static void main(String[] args) {
new Test();
}
}
| 377 | 0.679045 | 0.65252 | 22 | 16.136364 | 15.142641 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.636364 | false | false | 1 |
5a7f98e8ad8cf888c74e51f09f300d9e2afcd790 | 11,742,440,631,676 | 883c47db7fbaf2901b703f11979e7c5949f2835a | /src/pgoon/java8/test/main/JAVA8_TEST_1.java | 005931729e303294ab933fb41ada4c6ce508e26b | []
| no_license | pgoon/JSYSTEM | https://github.com/pgoon/JSYSTEM | e13c9a0fc812263a1c205fd9c50d418043aa21e1 | 312498875dba9a9a55bcd5503e3e833ca143cd33 | refs/heads/master | 2021-01-21T04:51:00.187000 | 2016-07-10T13:26:03 | 2016-07-10T13:26:03 | 54,002,004 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pgoon.java8.test.main;
import pgoon.java8.test.inter.FUNC_INTERFACE_TEST;
public class JAVA8_TEST_1 {
public static void main(String[] args) {
// 既存
// JAVA8_TEST_1 t = new JAVA8_TEST_1();
// System.out.println(t.getSum(2));
// ラムダ式
FUNC_INTERFACE_TEST t3 = no -> {
System.out.println(no * 2);
return no * 3; };
System.out.println(t3.getSum(100));
}
}
| SHIFT_JIS | Java | 433 | java | JAVA8_TEST_1.java | Java | []
| null | []
| package pgoon.java8.test.main;
import pgoon.java8.test.inter.FUNC_INTERFACE_TEST;
public class JAVA8_TEST_1 {
public static void main(String[] args) {
// 既存
// JAVA8_TEST_1 t = new JAVA8_TEST_1();
// System.out.println(t.getSum(2));
// ラムダ式
FUNC_INTERFACE_TEST t3 = no -> {
System.out.println(no * 2);
return no * 3; };
System.out.println(t3.getSum(100));
}
}
| 433 | 0.589074 | 0.551069 | 21 | 18.047619 | 17.833826 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 1 |
fd30e34f11d6d06480583b077f1ee10d9196f8a4 | 12,618,613,939,418 | 7539cf82fc3a2c5ad57f35f1b9d3379f3fb5b79c | /src/test/java/com/stepDefinition/StepDefinition.java | a3afd89df78e761dcafcc3f7e7ca6845614309ab | []
| no_license | Shambhu4609/PreacticeDemo | https://github.com/Shambhu4609/PreacticeDemo | a78d6460bd0d32f2b4a25c7ae500ac77617b6930 | f3c8ac02ddd77d581bd880c7ed33525da9cce6eb | refs/heads/master | 2022-08-14T18:35:27.104000 | 2020-05-12T07:32:53 | 2020-05-12T07:32:53 | 263,258,855 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinition {
@Given("User should be on facebook home page")
public void user_should_be_on_facebook_home_page() {
}
@When("User enter {string} and {string} in the text box")
public void user_enter_and_in_the_text_box(String string, String string2) {
}
@Then("User click on Login button")
public void user_click_on_Login_button() {
}
@Then("User varify success message")
public void user_varify_success_message() {
}
}
| UTF-8 | Java | 606 | java | StepDefinition.java | Java | []
| null | []
| package com.stepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinition {
@Given("User should be on facebook home page")
public void user_should_be_on_facebook_home_page() {
}
@When("User enter {string} and {string} in the text box")
public void user_enter_and_in_the_text_box(String string, String string2) {
}
@Then("User click on Login button")
public void user_click_on_Login_button() {
}
@Then("User varify success message")
public void user_varify_success_message() {
}
}
| 606 | 0.70132 | 0.69967 | 28 | 20.642857 | 22.11046 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 1 |
d1b81a391c1ddb56e3fd56dfc69d8bac8903c1dc | 1,640,677,515,756 | 5c1e6dd50b7715febec22b994fc264c4463239d2 | /search/indexer/mmm-search-indexer-api/src/main/java/net/sf/mmm/search/indexer/base/state/SearchIndexerStateBean.java | 5f95eccdd231afd4f2642c8240b4085a4cbf553a | [
"Apache-2.0"
]
| permissive | m-m-m/search | https://github.com/m-m-m/search | 7c6720b423d20dea51048df594a6f98ee9a55cd0 | 778bc966f7d443ba6358978e130459d7a09db2a6 | refs/heads/master | 2021-07-22T00:30:15.628000 | 2016-07-07T06:58:02 | 2016-07-07T06:58:02 | 34,912,259 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.search.indexer.base.state;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import net.sf.mmm.search.indexer.api.state.SearchIndexerSourceState;
import net.sf.mmm.search.indexer.api.state.SearchIndexerState;
/**
* This is the implementation of {@link SearchIndexerState} as JAXB-ready Java-Bean.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.0
*/
@XmlRootElement(name = "search-indexer-state")
@XmlAccessorType(XmlAccessType.FIELD)
public class SearchIndexerStateBean implements SearchIndexerState {
/** @see #getIndexingDate() */
@XmlElement(name = "indexing-date")
private Date indexingDate;
/** @see #getSources() */
@XmlElementWrapper(name = "sources")
@XmlElement(name = "source-state")
private List<SearchIndexerSourceStateBean> sources;
/** @see #getSourceStateMap() */
private transient Map<String, SearchIndexerSourceStateBean> sourceStateMap;
/**
* The constructor.
*/
public SearchIndexerStateBean() {
super();
}
/**
* @return the sourceMap
*/
protected Map<String, SearchIndexerSourceStateBean> getSourceStateMap() {
if (this.sourceStateMap == null) {
Map<String, SearchIndexerSourceStateBean> map = new HashMap<String, SearchIndexerSourceStateBean>();
if (this.sources != null) {
for (SearchIndexerSourceStateBean source : this.sources) {
map.put(source.getSource(), source);
}
}
this.sourceStateMap = map;
}
return this.sourceStateMap;
}
/**
* This method gets the {@link List} of {@link SearchIndexerSourceStateBean}. <br>
* <b>ATTENTION:</b><br>
* Do NOT modify this list externally.
*
* @see #getOrCreateSourceState(String)
*
* @return the {@link List} of {@link SearchIndexerSourceStateBean}s.
*/
public List<SearchIndexerSourceStateBean> getSources() {
return this.sources;
}
/**
* @param sources is the sources to set
*/
public void setSources(List<SearchIndexerSourceStateBean> sources) {
this.sources = sources;
}
/**
* {@inheritDoc}
*/
@Override
public SearchIndexerSourceState getSourceState(String source) {
return getSourceStateMap().get(source);
}
/**
* @see #getSourceState(String)
*
* @param source is the source-ID for which the state is requested.
* @return the requested {@link SearchIndexerSourceState}. If it does not exist, it is created and
* associated.
*/
public SearchIndexerSourceStateBean getOrCreateSourceState(String source) {
SearchIndexerSourceStateBean sourceStatus = getSourceStateMap().get(source);
if (sourceStatus == null) {
sourceStatus = new SearchIndexerSourceStateBean();
sourceStatus.setSource(source);
if (this.sources == null) {
this.sources = new ArrayList<SearchIndexerSourceStateBean>();
}
this.sources.add(sourceStatus);
getSourceStateMap().put(source, sourceStatus);
}
return sourceStatus;
}
/**
* {@inheritDoc}
*/
@Override
public Date getIndexingDate() {
return this.indexingDate;
}
/**
* This method sets the {@link #getIndexingDate() indexing-date}.
*
* @param indexingDate is the new indexing-date.
*/
public void setIndexingDate(Date indexingDate) {
this.indexingDate = indexingDate;
}
}
| UTF-8 | Java | 3,794 | java | SearchIndexerStateBean.java | Java | [
{
"context": "exerState} as JAXB-ready Java-Bean.\n * \n * @author Joerg Hohwiller (hohwille at users.sourceforge.net)\n * @since 1.0",
"end": 796,
"score": 0.9998270869255066,
"start": 781,
"tag": "NAME",
"value": "Joerg Hohwiller"
}
]
| null | []
| /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.search.indexer.base.state;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import net.sf.mmm.search.indexer.api.state.SearchIndexerSourceState;
import net.sf.mmm.search.indexer.api.state.SearchIndexerState;
/**
* This is the implementation of {@link SearchIndexerState} as JAXB-ready Java-Bean.
*
* @author <NAME> (hohwille at users.sourceforge.net)
* @since 1.0.0
*/
@XmlRootElement(name = "search-indexer-state")
@XmlAccessorType(XmlAccessType.FIELD)
public class SearchIndexerStateBean implements SearchIndexerState {
/** @see #getIndexingDate() */
@XmlElement(name = "indexing-date")
private Date indexingDate;
/** @see #getSources() */
@XmlElementWrapper(name = "sources")
@XmlElement(name = "source-state")
private List<SearchIndexerSourceStateBean> sources;
/** @see #getSourceStateMap() */
private transient Map<String, SearchIndexerSourceStateBean> sourceStateMap;
/**
* The constructor.
*/
public SearchIndexerStateBean() {
super();
}
/**
* @return the sourceMap
*/
protected Map<String, SearchIndexerSourceStateBean> getSourceStateMap() {
if (this.sourceStateMap == null) {
Map<String, SearchIndexerSourceStateBean> map = new HashMap<String, SearchIndexerSourceStateBean>();
if (this.sources != null) {
for (SearchIndexerSourceStateBean source : this.sources) {
map.put(source.getSource(), source);
}
}
this.sourceStateMap = map;
}
return this.sourceStateMap;
}
/**
* This method gets the {@link List} of {@link SearchIndexerSourceStateBean}. <br>
* <b>ATTENTION:</b><br>
* Do NOT modify this list externally.
*
* @see #getOrCreateSourceState(String)
*
* @return the {@link List} of {@link SearchIndexerSourceStateBean}s.
*/
public List<SearchIndexerSourceStateBean> getSources() {
return this.sources;
}
/**
* @param sources is the sources to set
*/
public void setSources(List<SearchIndexerSourceStateBean> sources) {
this.sources = sources;
}
/**
* {@inheritDoc}
*/
@Override
public SearchIndexerSourceState getSourceState(String source) {
return getSourceStateMap().get(source);
}
/**
* @see #getSourceState(String)
*
* @param source is the source-ID for which the state is requested.
* @return the requested {@link SearchIndexerSourceState}. If it does not exist, it is created and
* associated.
*/
public SearchIndexerSourceStateBean getOrCreateSourceState(String source) {
SearchIndexerSourceStateBean sourceStatus = getSourceStateMap().get(source);
if (sourceStatus == null) {
sourceStatus = new SearchIndexerSourceStateBean();
sourceStatus.setSource(source);
if (this.sources == null) {
this.sources = new ArrayList<SearchIndexerSourceStateBean>();
}
this.sources.add(sourceStatus);
getSourceStateMap().put(source, sourceStatus);
}
return sourceStatus;
}
/**
* {@inheritDoc}
*/
@Override
public Date getIndexingDate() {
return this.indexingDate;
}
/**
* This method sets the {@link #getIndexingDate() indexing-date}.
*
* @param indexingDate is the new indexing-date.
*/
public void setIndexingDate(Date indexingDate) {
this.indexingDate = indexingDate;
}
}
| 3,785 | 0.698998 | 0.697153 | 139 | 26.294964 | 26.242493 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.302158 | false | false | 1 |
7f5bae18be647fe5caacd68a8e9cac9b93ac2595 | 9,809,705,311,017 | 480276acdf4a27e4ed5e7dbeee8cfca44c0dc3c8 | /src/main/java/cn/pompip/androidcontrol/message/FileMessage.java | 73cdd3f05820f6919983c258502c67cf16cacd16 | []
| no_license | houzhenggang/BMTP | https://github.com/houzhenggang/BMTP | d9177ef4791a3535b070064eedab5ae61266344d | fd5b6d4fa20301cfdcd1f855b5a402e22d25ac1a | refs/heads/master | 2020-05-03T13:06:17.198000 | 2019-03-04T18:47:20 | 2019-03-04T18:47:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2019. Edit By pompip.cn
*/
package cn.pompip.androidcontrol.message;
/**
* Created by harry on 2017/5/10.
*/
public class FileMessage extends BinaryMessage {
public String name;
public int filesize;
public int packagesize;
public int offset;
}
| UTF-8 | Java | 286 | java | FileMessage.java | Java | [
{
"context": ".pompip.androidcontrol.message;\n\n/**\n * Created by harry on 2017/5/10.\n */\npublic class FileMessage extend",
"end": 115,
"score": 0.970612645149231,
"start": 110,
"tag": "USERNAME",
"value": "harry"
}
]
| null | []
| /*
* Copyright (c) 2019. Edit By pompip.cn
*/
package cn.pompip.androidcontrol.message;
/**
* Created by harry on 2017/5/10.
*/
public class FileMessage extends BinaryMessage {
public String name;
public int filesize;
public int packagesize;
public int offset;
}
| 286 | 0.688811 | 0.65035 | 16 | 16.875 | 16.710308 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 1 |
4519780e178886e0ff28f19f05fbe8671c79c764 | 9,809,705,310,008 | df49aaabeabb459e8abcc6ed8820c6b579ce7b11 | /PageRankFuyong.java | 313b7908c1b0ef739ebc05f29373163c129da4dd | []
| no_license | edmundxing/cloudComputingStorageAssignmentTwo | https://github.com/edmundxing/cloudComputingStorageAssignmentTwo | ccec92e82c07074b7c107fd6add748d28b652918 | d24aeb47006df98981e124d607ffe31038dcca9b | refs/heads/master | 2021-01-16T17:46:11.513000 | 2014-10-25T02:16:16 | 2014-10-25T02:16:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Fuyong Xing
// Department of Electrical and Computer Engineering
// University of Florida
// This code is for Programming Assignment 2 at the course: Cloud Computing and Storage.
// It implements PageRank given a graph. It is implemented using OpenJDK 6 and Hadoop 0.20.2.
// Usage: $ bin/hadoop jar PageRankFuyong.jar PageRankFuyong inputFolder maximumIteration
import java.io.*;
import java.util.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class PageRankFuyong {
/* Define enum type. */
public static enum DiffPR {
SUM_DIFFPR,
COUNT_NODE
}
/* PageRank Mapper implementation. It splits a line of strings to single strings and then emits a key-value pair of <node, PR>. It also emits the graph structure. */
public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
String lineStr = value.toString();
Text textKey = new Text();
Text textValue = new Text();
if (lineStr.contains("#")) { // non-first iteration
String[] strParts = lineStr.split("#");
String[] strIOPR = strParts[0].split("\\t");
String nodeID = strIOPR[0];
String nodePR = strIOPR[1];
if (strParts.length == 1) {
textKey.set(nodeID);
textValue.set("#");
output.collect(textKey, textValue);
textValue.set(nodePR + "@");
output.collect(textKey, textValue);
} else {
String[] nodeAdjList = strParts[1].split(" ");
int numAdjNode = nodeAdjList.length;
float nodePRV = Float.valueOf(nodePR)/numAdjNode;
textKey.set(nodeID);
textValue.set("#" + strParts[1]);
output.collect(textKey, textValue);
textValue.set(nodePR + "@");
output.collect(textKey, textValue);
for (int i=0; i<numAdjNode; i++) {
textKey.set(nodeAdjList[i]);
textValue.set(Float.toString(nodePRV));
output.collect(textKey, textValue);
}
}
} else { // first iteration
String[] strParts = lineStr.split(" ");
int strLength = strParts.length;
if (strLength < 1) {
return;
} else if (strLength < 2) { // no adjacent nodes
if (!("\\n".equals(strParts[0]) || "".equals(strParts[0]))) {
String nodeID = strParts[0];
textKey.set(nodeID);
textValue.set("#");
output.collect(textKey, textValue);
textValue.set("1.0@");
output.collect(textKey, textValue);
}
}
else { // with adjacent nodes
String nodeID = strParts[0];
String nodePR = "1.0";
int numAdjNode = strParts.length - 1;
StringBuffer strResult = new StringBuffer();
for (int i=1; i<numAdjNode; i++) {
strResult.append(strParts[i] + " ");
}
strResult.append(strParts[numAdjNode]);
String nodeAdjStr = strResult.toString();
float nodePRV = Float.valueOf(nodePR)/numAdjNode;
textKey.set(nodeID);
textValue.set("#" + nodeAdjStr);
output.collect(textKey, textValue);
textValue.set("1.0@");
output.collect(textKey, textValue);
for (int j=1; j<numAdjNode+1; j++) {
textKey.set(strParts[j]);
textValue.set(Float.toString(nodePRV));
output.collect(textKey, textValue);
}
}
}
}
}
/* PageRank Reducer implementation. It sums the values associated with the same key (node ID). */
public static class Reduce extends MapReduceBase implements Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
Float sumPR = 0.0f;
String strM = "";
String str = "";
String[] strPre = new String[2];
while (values.hasNext()) {
str = values.next().toString();
if (str.contains("#")) { // It is a node.
strM = str;
} else if (str.contains("@")) { // Get previous value
strPre = str.split("@");
} else {
sumPR = sumPR + Float.parseFloat(str);
}
}
output.collect(key, new Text(sumPR.toString()+strM));
float diff = (sumPR - Float.valueOf(strPre[0]))*(sumPR - Float.valueOf(strPre[0]));
reporter.getCounter(DiffPR.SUM_DIFFPR).increment((long)(diff*100000000));
reporter.getCounter(DiffPR.COUNT_NODE).increment(1L);
}
}
/* PageRank Job running function. It configures and submits the jobs. */
private long[] runPageRank(String inputFolder, String outputFolder) throws Exception {
/* Create a new job and set up job parameters. */
JobConf conf = new JobConf(PageRankFuyong.class);
conf.setJarByClass(PageRankFuyong.class);
conf.setJobName("PageRankFuyong");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(Map.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
/* Set up input and output file paths. */
FileInputFormat.setInputPaths(conf, new Path(inputFolder));
FileOutputFormat.setOutputPath(conf, new Path(outputFolder));
/* Submit the jobs. */
RunningJob job=JobClient.runJob(conf);
job.waitForCompletion();
Counters countJob = job.getCounters();
long[] countValue = new long[2];
countValue[0] = countJob.findCounter(DiffPR.SUM_DIFFPR).getValue();
countValue[1] = countJob.findCounter(DiffPR.COUNT_NODE).getValue();
return countValue;
}
/* Sorting Mapper: sort the PageRank results. */
public static class SortMap extends MapReduceBase implements Mapper<LongWritable, Text, FloatWritable, Text> {
public void map(LongWritable key, Text value, OutputCollector<FloatWritable, Text> output, Reporter reporter) throws IOException {
String lineStr = value.toString();
if (lineStr.contains("#")) {
String[] strParts = lineStr.split("#");
String[] strIOPR = strParts[0].split("\\t");
float nodeID = Float.parseFloat(strIOPR[1]);
FloatWritable prKey = new FloatWritable(nodeID);
Text textValue = new Text(strIOPR[0]);
output.collect(prKey, textValue);
}
}
}
/* Sorting PageRank Job running function. It configures and submits the jobs. */
private void runSortPageRank(String inputFolder, String outputFolder) throws Exception {
/* Create a new job and set up job parameters. */
JobConf conf = new JobConf(PageRankFuyong.class);
conf.setJarByClass(PageRankFuyong.class);
conf.setJobName("SortPageRankFuyong");
conf.setOutputKeyClass(FloatWritable.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(SortMap.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
/* Set up input and output file paths. */
FileInputFormat.setInputPaths(conf, new Path(inputFolder));
FileOutputFormat.setOutputPath(conf, new Path(outputFolder));
/* Submit the jobs. */
RunningJob job=JobClient.runJob(conf);
job.waitForCompletion();
}
/* Mapper of getting graph properties. It calculates the graph statistics and emits a key-value pair of <Graph, Property>. */
public static class StatMap extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
String lineStr = value.toString();
final Text textKey = new Text("Graph");
Text textValue = new Text();
if (lineStr.contains("#")) {
String[] strParts = lineStr.split("#");
if (strParts.length == 1) {
textValue.set("0");
output.collect(textKey, textValue);
} else {
String[] nodeAdjList = strParts[1].split(" ");
int numAdjNode = nodeAdjList.length;
textValue.set(Integer.toString(numAdjNode));
output.collect(textKey, textValue);
}
}
}
}
/* Reducer of getting graph properties. It computes the statistics of the graph. */
public static class StatReduce extends MapReduceBase implements Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
int numNode = 0;
int numEdge = 0;
int curEdge = 0;
int maxOutDeg = 0;
int minOutDeg = 1000;
while (values.hasNext()) {
curEdge = Integer.parseInt(values.next().toString());
if (maxOutDeg < curEdge) {
maxOutDeg = curEdge;
}
if (minOutDeg > curEdge) {
minOutDeg = curEdge;
}
numNode += 1;
numEdge += curEdge;
}
float aveOutDeg = (float)numEdge/numNode;
String str = "\n\nNumber of nodes = " + Integer.toString(numNode) + "\n" + "Number of edges = " + Integer.toString(numEdge) + "\n";
str = str + "Maximum out-degree = " + Integer.toString(maxOutDeg) + "\n" + "Minimum out-degree = " + Integer.toString(minOutDeg) + "\n";
str = str + "Average out-degree = " + Float.toString(aveOutDeg);
output.collect(new Text("Graph properties:"), new Text(str));
}
}
/* Compute graph property Job running function. It configures and submits the jobs. */
private void runStatPageRank(String inputFolder, String outputFolder) throws Exception {
/* Create a new job and set up job parameters. */
JobConf conf = new JobConf(PageRankFuyong.class);
conf.setJarByClass(PageRankFuyong.class);
conf.setJobName("StatPageRankFuyong");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(StatMap.class);
conf.setReducerClass(StatReduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
/* Set up input and output file paths. */
FileInputFormat.setInputPaths(conf, new Path(inputFolder));
FileOutputFormat.setOutputPath(conf, new Path(outputFolder));
/* Submit the jobs. */
RunningJob job=JobClient.runJob(conf);
job.waitForCompletion();
}
/* Main function. */
public static void main(String[] args) throws Exception {
PageRankFuyong pageRankObj = new PageRankFuyong();
/* Run PageRank job. */
int maxIter = Integer.parseInt(args[1]);
double stopCriterion = 0.001;
double sumdiffprv = 0.0;
long[] countValue = new long[2];
long startTime = 0;
long totalPRtime = 0;
int iter=1;
ArrayList<Long> iterTime = new ArrayList<Long>();
do {
startTime = System.currentTimeMillis();
if (iter == 1) {
countValue = pageRankObj.runPageRank(args[0], args[0]+Integer.toString(iter));
} else {
countValue = pageRankObj.runPageRank(args[0]+Integer.toString(iter-1), args[0]+Integer.toString(iter));
}
sumdiffprv = Math.sqrt((double)countValue[0]/countValue[1]/100000000);
iterTime.add(System.currentTimeMillis() - startTime);
totalPRtime += iterTime.get(iter-1);
iter++;
} while (sumdiffprv > stopCriterion && iter <= maxIter);
/* Run SortPageRank job. */
startTime = System.currentTimeMillis();
pageRankObj.runSortPageRank(args[0]+Integer.toString(iter-1), args[0]+"SortedResults");
long sortTime = System.currentTimeMillis() - startTime;
totalPRtime += sortTime;
/* Run StatPageRank job. */
pageRankObj.runStatPageRank(args[0]+Integer.toString(1), args[0]+"StatResults");
/* Print iteration number and time cost. */
System.out.println("Total iterations of PageRank: " + (iter-1));
System.out.println("Total time (including sorting time): " + totalPRtime + " miliseconds.");
for (int i=0; i<iterTime.size(); i++) {
System.out.println("PageRank time for iteration " + (i+1) + ": " + iterTime.get(i) + " miliseconds.");
}
System.out.println("Sort PageRank time: " + sortTime + " miliseconds.");
}
}
| UTF-8 | Java | 11,678 | java | PageRankFuyong.java | Java | [
{
"context": "// Fuyong Xing\n// Department of Electrical and Computer Engineer",
"end": 14,
"score": 0.9997583627700806,
"start": 3,
"tag": "NAME",
"value": "Fuyong Xing"
}
]
| null | []
| // <NAME>
// Department of Electrical and Computer Engineering
// University of Florida
// This code is for Programming Assignment 2 at the course: Cloud Computing and Storage.
// It implements PageRank given a graph. It is implemented using OpenJDK 6 and Hadoop 0.20.2.
// Usage: $ bin/hadoop jar PageRankFuyong.jar PageRankFuyong inputFolder maximumIteration
import java.io.*;
import java.util.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class PageRankFuyong {
/* Define enum type. */
public static enum DiffPR {
SUM_DIFFPR,
COUNT_NODE
}
/* PageRank Mapper implementation. It splits a line of strings to single strings and then emits a key-value pair of <node, PR>. It also emits the graph structure. */
public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
String lineStr = value.toString();
Text textKey = new Text();
Text textValue = new Text();
if (lineStr.contains("#")) { // non-first iteration
String[] strParts = lineStr.split("#");
String[] strIOPR = strParts[0].split("\\t");
String nodeID = strIOPR[0];
String nodePR = strIOPR[1];
if (strParts.length == 1) {
textKey.set(nodeID);
textValue.set("#");
output.collect(textKey, textValue);
textValue.set(nodePR + "@");
output.collect(textKey, textValue);
} else {
String[] nodeAdjList = strParts[1].split(" ");
int numAdjNode = nodeAdjList.length;
float nodePRV = Float.valueOf(nodePR)/numAdjNode;
textKey.set(nodeID);
textValue.set("#" + strParts[1]);
output.collect(textKey, textValue);
textValue.set(nodePR + "@");
output.collect(textKey, textValue);
for (int i=0; i<numAdjNode; i++) {
textKey.set(nodeAdjList[i]);
textValue.set(Float.toString(nodePRV));
output.collect(textKey, textValue);
}
}
} else { // first iteration
String[] strParts = lineStr.split(" ");
int strLength = strParts.length;
if (strLength < 1) {
return;
} else if (strLength < 2) { // no adjacent nodes
if (!("\\n".equals(strParts[0]) || "".equals(strParts[0]))) {
String nodeID = strParts[0];
textKey.set(nodeID);
textValue.set("#");
output.collect(textKey, textValue);
textValue.set("1.0@");
output.collect(textKey, textValue);
}
}
else { // with adjacent nodes
String nodeID = strParts[0];
String nodePR = "1.0";
int numAdjNode = strParts.length - 1;
StringBuffer strResult = new StringBuffer();
for (int i=1; i<numAdjNode; i++) {
strResult.append(strParts[i] + " ");
}
strResult.append(strParts[numAdjNode]);
String nodeAdjStr = strResult.toString();
float nodePRV = Float.valueOf(nodePR)/numAdjNode;
textKey.set(nodeID);
textValue.set("#" + nodeAdjStr);
output.collect(textKey, textValue);
textValue.set("1.0@");
output.collect(textKey, textValue);
for (int j=1; j<numAdjNode+1; j++) {
textKey.set(strParts[j]);
textValue.set(Float.toString(nodePRV));
output.collect(textKey, textValue);
}
}
}
}
}
/* PageRank Reducer implementation. It sums the values associated with the same key (node ID). */
public static class Reduce extends MapReduceBase implements Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
Float sumPR = 0.0f;
String strM = "";
String str = "";
String[] strPre = new String[2];
while (values.hasNext()) {
str = values.next().toString();
if (str.contains("#")) { // It is a node.
strM = str;
} else if (str.contains("@")) { // Get previous value
strPre = str.split("@");
} else {
sumPR = sumPR + Float.parseFloat(str);
}
}
output.collect(key, new Text(sumPR.toString()+strM));
float diff = (sumPR - Float.valueOf(strPre[0]))*(sumPR - Float.valueOf(strPre[0]));
reporter.getCounter(DiffPR.SUM_DIFFPR).increment((long)(diff*100000000));
reporter.getCounter(DiffPR.COUNT_NODE).increment(1L);
}
}
/* PageRank Job running function. It configures and submits the jobs. */
private long[] runPageRank(String inputFolder, String outputFolder) throws Exception {
/* Create a new job and set up job parameters. */
JobConf conf = new JobConf(PageRankFuyong.class);
conf.setJarByClass(PageRankFuyong.class);
conf.setJobName("PageRankFuyong");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(Map.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
/* Set up input and output file paths. */
FileInputFormat.setInputPaths(conf, new Path(inputFolder));
FileOutputFormat.setOutputPath(conf, new Path(outputFolder));
/* Submit the jobs. */
RunningJob job=JobClient.runJob(conf);
job.waitForCompletion();
Counters countJob = job.getCounters();
long[] countValue = new long[2];
countValue[0] = countJob.findCounter(DiffPR.SUM_DIFFPR).getValue();
countValue[1] = countJob.findCounter(DiffPR.COUNT_NODE).getValue();
return countValue;
}
/* Sorting Mapper: sort the PageRank results. */
public static class SortMap extends MapReduceBase implements Mapper<LongWritable, Text, FloatWritable, Text> {
public void map(LongWritable key, Text value, OutputCollector<FloatWritable, Text> output, Reporter reporter) throws IOException {
String lineStr = value.toString();
if (lineStr.contains("#")) {
String[] strParts = lineStr.split("#");
String[] strIOPR = strParts[0].split("\\t");
float nodeID = Float.parseFloat(strIOPR[1]);
FloatWritable prKey = new FloatWritable(nodeID);
Text textValue = new Text(strIOPR[0]);
output.collect(prKey, textValue);
}
}
}
/* Sorting PageRank Job running function. It configures and submits the jobs. */
private void runSortPageRank(String inputFolder, String outputFolder) throws Exception {
/* Create a new job and set up job parameters. */
JobConf conf = new JobConf(PageRankFuyong.class);
conf.setJarByClass(PageRankFuyong.class);
conf.setJobName("SortPageRankFuyong");
conf.setOutputKeyClass(FloatWritable.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(SortMap.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
/* Set up input and output file paths. */
FileInputFormat.setInputPaths(conf, new Path(inputFolder));
FileOutputFormat.setOutputPath(conf, new Path(outputFolder));
/* Submit the jobs. */
RunningJob job=JobClient.runJob(conf);
job.waitForCompletion();
}
/* Mapper of getting graph properties. It calculates the graph statistics and emits a key-value pair of <Graph, Property>. */
public static class StatMap extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
String lineStr = value.toString();
final Text textKey = new Text("Graph");
Text textValue = new Text();
if (lineStr.contains("#")) {
String[] strParts = lineStr.split("#");
if (strParts.length == 1) {
textValue.set("0");
output.collect(textKey, textValue);
} else {
String[] nodeAdjList = strParts[1].split(" ");
int numAdjNode = nodeAdjList.length;
textValue.set(Integer.toString(numAdjNode));
output.collect(textKey, textValue);
}
}
}
}
/* Reducer of getting graph properties. It computes the statistics of the graph. */
public static class StatReduce extends MapReduceBase implements Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
int numNode = 0;
int numEdge = 0;
int curEdge = 0;
int maxOutDeg = 0;
int minOutDeg = 1000;
while (values.hasNext()) {
curEdge = Integer.parseInt(values.next().toString());
if (maxOutDeg < curEdge) {
maxOutDeg = curEdge;
}
if (minOutDeg > curEdge) {
minOutDeg = curEdge;
}
numNode += 1;
numEdge += curEdge;
}
float aveOutDeg = (float)numEdge/numNode;
String str = "\n\nNumber of nodes = " + Integer.toString(numNode) + "\n" + "Number of edges = " + Integer.toString(numEdge) + "\n";
str = str + "Maximum out-degree = " + Integer.toString(maxOutDeg) + "\n" + "Minimum out-degree = " + Integer.toString(minOutDeg) + "\n";
str = str + "Average out-degree = " + Float.toString(aveOutDeg);
output.collect(new Text("Graph properties:"), new Text(str));
}
}
/* Compute graph property Job running function. It configures and submits the jobs. */
private void runStatPageRank(String inputFolder, String outputFolder) throws Exception {
/* Create a new job and set up job parameters. */
JobConf conf = new JobConf(PageRankFuyong.class);
conf.setJarByClass(PageRankFuyong.class);
conf.setJobName("StatPageRankFuyong");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(StatMap.class);
conf.setReducerClass(StatReduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
/* Set up input and output file paths. */
FileInputFormat.setInputPaths(conf, new Path(inputFolder));
FileOutputFormat.setOutputPath(conf, new Path(outputFolder));
/* Submit the jobs. */
RunningJob job=JobClient.runJob(conf);
job.waitForCompletion();
}
/* Main function. */
public static void main(String[] args) throws Exception {
PageRankFuyong pageRankObj = new PageRankFuyong();
/* Run PageRank job. */
int maxIter = Integer.parseInt(args[1]);
double stopCriterion = 0.001;
double sumdiffprv = 0.0;
long[] countValue = new long[2];
long startTime = 0;
long totalPRtime = 0;
int iter=1;
ArrayList<Long> iterTime = new ArrayList<Long>();
do {
startTime = System.currentTimeMillis();
if (iter == 1) {
countValue = pageRankObj.runPageRank(args[0], args[0]+Integer.toString(iter));
} else {
countValue = pageRankObj.runPageRank(args[0]+Integer.toString(iter-1), args[0]+Integer.toString(iter));
}
sumdiffprv = Math.sqrt((double)countValue[0]/countValue[1]/100000000);
iterTime.add(System.currentTimeMillis() - startTime);
totalPRtime += iterTime.get(iter-1);
iter++;
} while (sumdiffprv > stopCriterion && iter <= maxIter);
/* Run SortPageRank job. */
startTime = System.currentTimeMillis();
pageRankObj.runSortPageRank(args[0]+Integer.toString(iter-1), args[0]+"SortedResults");
long sortTime = System.currentTimeMillis() - startTime;
totalPRtime += sortTime;
/* Run StatPageRank job. */
pageRankObj.runStatPageRank(args[0]+Integer.toString(1), args[0]+"StatResults");
/* Print iteration number and time cost. */
System.out.println("Total iterations of PageRank: " + (iter-1));
System.out.println("Total time (including sorting time): " + totalPRtime + " miliseconds.");
for (int i=0; i<iterTime.size(); i++) {
System.out.println("PageRank time for iteration " + (i+1) + ": " + iterTime.get(i) + " miliseconds.");
}
System.out.println("Sort PageRank time: " + sortTime + " miliseconds.");
}
}
| 11,673 | 0.690358 | 0.681795 | 315 | 36.073017 | 30.333349 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.209524 | false | false | 1 |
5001a90d2942f5d06fbddf4e742b43f8a7062bd3 | 15,710,990,375,066 | 35ff0ea28cf1edba99ab9fcc34a929f14d3641db | /Hillel/src/database/SingletonExample.java | d112d5eb93b00d8a7ecdadcfcfb6ee4c8365203c | []
| no_license | RMysholovka/hillelJava | https://github.com/RMysholovka/hillelJava | 5cdedb5c23b06284b17a746c49c1ec643d5b94e3 | d4c6d76017b43adc7df0bb1686e56dd72a42166a | refs/heads/master | 2021-01-17T08:59:33.572000 | 2016-04-24T11:00:18 | 2016-04-24T11:00:18 | 42,669,442 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package database;
import java.util.ArrayList;
/**
* Created by RMysholovka on 21.12.2015.
*/
public class SingletonExample {
private static SingletonExample instance = new SingletonExample();
public String someValue;
private SingletonExample() {
}
public static SingletonExample getInstance() {
if (instance == null) {
synchronized (SingletonExample.class) {
if (instance == null) {
instance = new SingletonExample();
}
}
}
return instance;
}
public static void clear() {
instance = null;
}
public static void main(String[] args) throws InterruptedException {
ArrayList<SingletonExample> singletonExamples = new ArrayList<>();
singletonExamples.add(null);
singletonExamples.add(null);
int i = 0;
while (true) {
i++;
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
SingletonExample singletonExample = SingletonExample.getInstance();
singletonExamples.set(0, singletonExample);
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
SingletonExample singletonExample = SingletonExample.getInstance();
singletonExamples.set(1, singletonExample);
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
if (singletonExamples.get(0) != singletonExamples.get(1)) {
break;
}
clear();
}
}
}
| UTF-8 | Java | 1,804 | java | SingletonExample.java | Java | [
{
"context": "e;\n\nimport java.util.ArrayList;\n\n/**\n * Created by RMysholovka on 21.12.2015.\n */\npublic class SingletonExample ",
"end": 77,
"score": 0.9641404747962952,
"start": 66,
"tag": "USERNAME",
"value": "RMysholovka"
}
]
| null | []
| package database;
import java.util.ArrayList;
/**
* Created by RMysholovka on 21.12.2015.
*/
public class SingletonExample {
private static SingletonExample instance = new SingletonExample();
public String someValue;
private SingletonExample() {
}
public static SingletonExample getInstance() {
if (instance == null) {
synchronized (SingletonExample.class) {
if (instance == null) {
instance = new SingletonExample();
}
}
}
return instance;
}
public static void clear() {
instance = null;
}
public static void main(String[] args) throws InterruptedException {
ArrayList<SingletonExample> singletonExamples = new ArrayList<>();
singletonExamples.add(null);
singletonExamples.add(null);
int i = 0;
while (true) {
i++;
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
SingletonExample singletonExample = SingletonExample.getInstance();
singletonExamples.set(0, singletonExample);
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
SingletonExample singletonExample = SingletonExample.getInstance();
singletonExamples.set(1, singletonExample);
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
if (singletonExamples.get(0) != singletonExamples.get(1)) {
break;
}
clear();
}
}
}
| 1,804 | 0.522173 | 0.511641 | 73 | 23.712328 | 23.457031 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.356164 | false | false | 1 |
7843671a24d6b398e104ad3725c958045ed0edf8 | 24,026,047,060,748 | 9da7db5620474e5caf15dc8dcf81180722fd9b43 | /src/org/kyupi/data/parser/Stil.java | e4f2e5282c2b091488f1502f4614cf2cd0f1e592 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
]
| permissive | s-holst/kyupi | https://github.com/s-holst/kyupi | 2ab8f08c871badb01330bfd83b8b87b89b4f584b | bb74ac95d026c373ba110901875ab6f9cf9e5597 | refs/heads/master | 2021-01-13T17:27:43.513000 | 2018-11-24T02:02:38 | 2018-11-24T02:02:38 | 11,678,192 | 3 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Generated By:JavaCC: Do not edit this line. Stil.java */
package org.kyupi.data.parser;
import java.util.*;
import java.io.*;
import org.apache.log4j.Logger;
@SuppressWarnings("all")
public class Stil implements StilConstants {
protected static Logger log = Logger.getLogger(Stil.class);
private static String getLocation(String sf_, Token token_) {
if (token_ != null)
return sf_ + ":" + token_.beginLine + ":" + token_.beginColumn;
return sf_;
}
public static Stil load (InputStream is, File f) throws IOException {
String sf_ = f.getPath();
Reader reader = new InputStreamReader(is);
Stil parser = new Stil(reader);
try {
parser.stil_file ();
} catch (ParseException e3) {
e3.printStackTrace();
throw new IOException("Parse error at " + getLocation(sf_,e3.currentToken) + ": " + e3.getMessage());
} catch (TokenMgrError e4) {
throw new IOException("Token error in " + sf_.toString() + ": " + e4.getMessage());
}
return parser;
}
private String unquote(String s)
{
return s.substring(1,s.length()-1);
}
public ArrayList<String> primary_inputs;
public ArrayList<String> primary_outputs;
public ArrayList<String> chain_names;
public ArrayList<ArrayList<String>> chain_cells;
public ArrayList<Operation> ops;
public String clock;
public class Operation {
public String pi,po,scanin,scanout;
}
final public void stil_file() throws ParseException {
jj_consume_token(STIL);
jj_consume_token(number_float);
ignored_block();
label_1:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case HEADER:
jj_consume_token(HEADER);
ignored_block();
break;
case SIGNALS:
jj_consume_token(SIGNALS);
ignored_block();
break;
case SIGNALGROUPS:
jj_consume_token(SIGNALGROUPS);
signal_groups();
break;
case TIMING:
jj_consume_token(TIMING);
ignored_block();
break;
case SCANSTRUCTURES:
jj_consume_token(SCANSTRUCTURES);
scan_structures();
break;
case PATTERNBURST:
jj_consume_token(PATTERNBURST);
jj_consume_token(string);
ignored_block();
break;
case PATTERNEXEC:
jj_consume_token(PATTERNEXEC);
ignored_block();
break;
case PROCEDURES:
jj_consume_token(PROCEDURES);
ignored_block();
break;
case MACRODEFS:
jj_consume_token(MACRODEFS);
ignored_block();
break;
case PATTERN:
jj_consume_token(PATTERN);
jj_consume_token(string);
pattern();
break;
default:
jj_la1[0] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case HEADER:
case SIGNALS:
case SIGNALGROUPS:
case TIMING:
case SCANSTRUCTURES:
case PATTERNBURST:
case PATTERNEXEC:
case PROCEDURES:
case MACRODEFS:
case PATTERN:
;
break;
default:
jj_la1[1] = jj_gen;
break label_1;
}
}
jj_consume_token(0);
}
final public void signal_groups() throws ParseException {
Token t;
ArrayList<String> arr;
jj_consume_token(bopen);
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[2] = jj_gen;
break label_2;
}
t = jj_consume_token(string);
jj_consume_token(equals);
jj_consume_token(quote);
arr = string_plus_array();
jj_consume_token(quote);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case semicolon:
jj_consume_token(semicolon);
break;
case bopen:
ignored_block();
break;
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
String s = unquote(t.image);
if (s.equals("_pi"))
primary_inputs = arr;
if (s.equals("_po"))
primary_outputs = arr;
}
jj_consume_token(bclose);
}
final public void scan_structures() throws ParseException {
Token t;
ArrayList<String> cells;
jj_consume_token(bopen);
chain_names = new ArrayList<String>();
chain_cells = new ArrayList<ArrayList<String>>();
label_3:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SCANCHAIN:
;
break;
default:
jj_la1[4] = jj_gen;
break label_3;
}
jj_consume_token(SCANCHAIN);
t = jj_consume_token(string);
chain_names.add(unquote(t.image));
cells = scan_chain();
chain_cells.add(cells);
}
jj_consume_token(bclose);
}
final public ArrayList<String> scan_chain() throws ParseException {
ArrayList<String> cells = null;
Token t;
jj_consume_token(bopen);
label_4:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SCANLENGTH:
case SCANIN:
case SCANOUT:
case SCANINVERSION:
case SCANCELLS:
case SCANMASTERCLOCK:
;
break;
default:
jj_la1[5] = jj_gen;
break label_4;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SCANLENGTH:
jj_consume_token(SCANLENGTH);
jj_consume_token(number_integer);
jj_consume_token(semicolon);
break;
case SCANIN:
jj_consume_token(SCANIN);
jj_consume_token(string);
jj_consume_token(semicolon);
break;
case SCANOUT:
jj_consume_token(SCANOUT);
jj_consume_token(string);
jj_consume_token(semicolon);
break;
case SCANINVERSION:
jj_consume_token(SCANINVERSION);
jj_consume_token(number_integer);
jj_consume_token(semicolon);
break;
case SCANCELLS:
jj_consume_token(SCANCELLS);
cells = string_array();
jj_consume_token(semicolon);
break;
case SCANMASTERCLOCK:
jj_consume_token(SCANMASTERCLOCK);
t = jj_consume_token(string);
jj_consume_token(semicolon);
clock = unquote(t.image);
break;
default:
jj_la1[6] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
jj_consume_token(bclose);
{if (true) return cells;}
throw new Error("Missing return statement in function");
}
final public void pattern() throws ParseException {
Operation op;
ops = new ArrayList<Operation>();
jj_consume_token(bopen);
label_5:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case CALL:
case identifier:
case semicolon:
case bopen:
case nonbrace_character:
case string:
;
break;
default:
jj_la1[7] = jj_gen;
break label_5;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case identifier:
jj_consume_token(identifier);
break;
case string:
jj_consume_token(string);
break;
case semicolon:
jj_consume_token(semicolon);
break;
case nonbrace_character:
jj_consume_token(nonbrace_character);
break;
case bopen:
ignored_block();
break;
case CALL:
jj_consume_token(CALL);
jj_consume_token(string);
op = pattern_record();
ops.add(op);
break;
default:
jj_la1[8] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
jj_consume_token(bclose);
}
final public Operation pattern_record() throws ParseException {
Operation op = new Operation();
String pat;
String id;
Token t;
jj_consume_token(bopen);
label_6:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[9] = jj_gen;
break label_6;
}
t = jj_consume_token(string);
jj_consume_token(equals);
pat = read_pattern();
jj_consume_token(semicolon);
id=unquote(t.image);
if (id.equals("_pi"))
op.pi = pat;
if (id.equals("_po"))
op.po = pat;
if (id.equals("Scan_In"))
op.scanin = pat;
if (id.equals("Scan_Out"))
op.scanout = pat;
}
jj_consume_token(bclose);
{if (true) return op;}
throw new Error("Missing return statement in function");
}
final public ArrayList<String> string_plus_array() throws ParseException {
Token t;
ArrayList<String> arr = new ArrayList<String>();
label_7:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[10] = jj_gen;
break label_7;
}
t = jj_consume_token(string);
arr.add(unquote(t.image));
label_8:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case plus:
;
break;
default:
jj_la1[11] = jj_gen;
break label_8;
}
jj_consume_token(plus);
t = jj_consume_token(string);
arr.add(unquote(t.image));
}
}
{if (true) return arr;}
throw new Error("Missing return statement in function");
}
final public ArrayList<String> string_array() throws ParseException {
Token t;
ArrayList<String> arr = new ArrayList<String>();
label_9:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[12] = jj_gen;
break label_9;
}
t = jj_consume_token(string);
arr.add(unquote(t.image));
}
{if (true) return arr;}
throw new Error("Missing return statement in function");
}
final public void ignored_block() throws ParseException {
jj_consume_token(bopen);
skip_to_matching_brace();
jj_consume_token(bclose);
}
void skip_to_matching_brace() throws ParseException {
Token tok;
int nesting = 1;
while (true) {
tok = getToken(1);
if (tok.kind == bopen) nesting++;
if (tok.kind == bclose) {
nesting--;
if (nesting == 0) break;
}
tok = getNextToken();
}
}
String read_pattern() throws ParseException {
StringBuffer buf = new StringBuffer();
Token tok;
while (true) {
tok = getToken(1);
if (tok.kind == semicolon) break;
buf.append(tok.image);
tok = getNextToken();
}
return buf.toString();
}
/** Generated Token Manager. */
public StilTokenManager token_source;
SimpleCharStream jj_input_stream;
/** Current token. */
public Token token;
/** Next token. */
public Token jj_nt;
private int jj_ntk;
private int jj_gen;
final private int[] jj_la1 = new int[13];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static {
jj_la1_init_0();
jj_la1_init_1();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {0x1ff80,0x1ff80,0x0,0x0,0x20000,0xfc0000,0xfc0000,0x81000000,0x81000000,0x0,0x0,0x0,0x0,};
}
private static void jj_la1_init_1() {
jj_la1_1 = new int[] {0x0,0x0,0x80,0x18,0x0,0x0,0x0,0xd8,0xd8,0x80,0x80,0x4,0x80,};
}
/** Constructor with InputStream. */
public Stil(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public Stil(java.io.InputStream stream, String encoding) {
try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source = new StilTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Constructor. */
public Stil(java.io.Reader stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new StilTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Constructor with generated Token Manager. */
public Stil(StilTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(StilTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
/** Get the next Token. */
final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
/** Get the specific Token. */
final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private int jj_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
private int[] jj_expentry;
private int jj_kind = -1;
/** Generate ParseException. */
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[40];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 13; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 40; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
/** Enable tracing. */
final public void enable_tracing() {
}
/** Disable tracing. */
final public void disable_tracing() {
}
}
| UTF-8 | Java | 16,083 | java | Stil.java | Java | []
| null | []
| /* Generated By:JavaCC: Do not edit this line. Stil.java */
package org.kyupi.data.parser;
import java.util.*;
import java.io.*;
import org.apache.log4j.Logger;
@SuppressWarnings("all")
public class Stil implements StilConstants {
protected static Logger log = Logger.getLogger(Stil.class);
private static String getLocation(String sf_, Token token_) {
if (token_ != null)
return sf_ + ":" + token_.beginLine + ":" + token_.beginColumn;
return sf_;
}
public static Stil load (InputStream is, File f) throws IOException {
String sf_ = f.getPath();
Reader reader = new InputStreamReader(is);
Stil parser = new Stil(reader);
try {
parser.stil_file ();
} catch (ParseException e3) {
e3.printStackTrace();
throw new IOException("Parse error at " + getLocation(sf_,e3.currentToken) + ": " + e3.getMessage());
} catch (TokenMgrError e4) {
throw new IOException("Token error in " + sf_.toString() + ": " + e4.getMessage());
}
return parser;
}
private String unquote(String s)
{
return s.substring(1,s.length()-1);
}
public ArrayList<String> primary_inputs;
public ArrayList<String> primary_outputs;
public ArrayList<String> chain_names;
public ArrayList<ArrayList<String>> chain_cells;
public ArrayList<Operation> ops;
public String clock;
public class Operation {
public String pi,po,scanin,scanout;
}
final public void stil_file() throws ParseException {
jj_consume_token(STIL);
jj_consume_token(number_float);
ignored_block();
label_1:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case HEADER:
jj_consume_token(HEADER);
ignored_block();
break;
case SIGNALS:
jj_consume_token(SIGNALS);
ignored_block();
break;
case SIGNALGROUPS:
jj_consume_token(SIGNALGROUPS);
signal_groups();
break;
case TIMING:
jj_consume_token(TIMING);
ignored_block();
break;
case SCANSTRUCTURES:
jj_consume_token(SCANSTRUCTURES);
scan_structures();
break;
case PATTERNBURST:
jj_consume_token(PATTERNBURST);
jj_consume_token(string);
ignored_block();
break;
case PATTERNEXEC:
jj_consume_token(PATTERNEXEC);
ignored_block();
break;
case PROCEDURES:
jj_consume_token(PROCEDURES);
ignored_block();
break;
case MACRODEFS:
jj_consume_token(MACRODEFS);
ignored_block();
break;
case PATTERN:
jj_consume_token(PATTERN);
jj_consume_token(string);
pattern();
break;
default:
jj_la1[0] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case HEADER:
case SIGNALS:
case SIGNALGROUPS:
case TIMING:
case SCANSTRUCTURES:
case PATTERNBURST:
case PATTERNEXEC:
case PROCEDURES:
case MACRODEFS:
case PATTERN:
;
break;
default:
jj_la1[1] = jj_gen;
break label_1;
}
}
jj_consume_token(0);
}
final public void signal_groups() throws ParseException {
Token t;
ArrayList<String> arr;
jj_consume_token(bopen);
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[2] = jj_gen;
break label_2;
}
t = jj_consume_token(string);
jj_consume_token(equals);
jj_consume_token(quote);
arr = string_plus_array();
jj_consume_token(quote);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case semicolon:
jj_consume_token(semicolon);
break;
case bopen:
ignored_block();
break;
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
String s = unquote(t.image);
if (s.equals("_pi"))
primary_inputs = arr;
if (s.equals("_po"))
primary_outputs = arr;
}
jj_consume_token(bclose);
}
final public void scan_structures() throws ParseException {
Token t;
ArrayList<String> cells;
jj_consume_token(bopen);
chain_names = new ArrayList<String>();
chain_cells = new ArrayList<ArrayList<String>>();
label_3:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SCANCHAIN:
;
break;
default:
jj_la1[4] = jj_gen;
break label_3;
}
jj_consume_token(SCANCHAIN);
t = jj_consume_token(string);
chain_names.add(unquote(t.image));
cells = scan_chain();
chain_cells.add(cells);
}
jj_consume_token(bclose);
}
final public ArrayList<String> scan_chain() throws ParseException {
ArrayList<String> cells = null;
Token t;
jj_consume_token(bopen);
label_4:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SCANLENGTH:
case SCANIN:
case SCANOUT:
case SCANINVERSION:
case SCANCELLS:
case SCANMASTERCLOCK:
;
break;
default:
jj_la1[5] = jj_gen;
break label_4;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SCANLENGTH:
jj_consume_token(SCANLENGTH);
jj_consume_token(number_integer);
jj_consume_token(semicolon);
break;
case SCANIN:
jj_consume_token(SCANIN);
jj_consume_token(string);
jj_consume_token(semicolon);
break;
case SCANOUT:
jj_consume_token(SCANOUT);
jj_consume_token(string);
jj_consume_token(semicolon);
break;
case SCANINVERSION:
jj_consume_token(SCANINVERSION);
jj_consume_token(number_integer);
jj_consume_token(semicolon);
break;
case SCANCELLS:
jj_consume_token(SCANCELLS);
cells = string_array();
jj_consume_token(semicolon);
break;
case SCANMASTERCLOCK:
jj_consume_token(SCANMASTERCLOCK);
t = jj_consume_token(string);
jj_consume_token(semicolon);
clock = unquote(t.image);
break;
default:
jj_la1[6] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
jj_consume_token(bclose);
{if (true) return cells;}
throw new Error("Missing return statement in function");
}
final public void pattern() throws ParseException {
Operation op;
ops = new ArrayList<Operation>();
jj_consume_token(bopen);
label_5:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case CALL:
case identifier:
case semicolon:
case bopen:
case nonbrace_character:
case string:
;
break;
default:
jj_la1[7] = jj_gen;
break label_5;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case identifier:
jj_consume_token(identifier);
break;
case string:
jj_consume_token(string);
break;
case semicolon:
jj_consume_token(semicolon);
break;
case nonbrace_character:
jj_consume_token(nonbrace_character);
break;
case bopen:
ignored_block();
break;
case CALL:
jj_consume_token(CALL);
jj_consume_token(string);
op = pattern_record();
ops.add(op);
break;
default:
jj_la1[8] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
jj_consume_token(bclose);
}
final public Operation pattern_record() throws ParseException {
Operation op = new Operation();
String pat;
String id;
Token t;
jj_consume_token(bopen);
label_6:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[9] = jj_gen;
break label_6;
}
t = jj_consume_token(string);
jj_consume_token(equals);
pat = read_pattern();
jj_consume_token(semicolon);
id=unquote(t.image);
if (id.equals("_pi"))
op.pi = pat;
if (id.equals("_po"))
op.po = pat;
if (id.equals("Scan_In"))
op.scanin = pat;
if (id.equals("Scan_Out"))
op.scanout = pat;
}
jj_consume_token(bclose);
{if (true) return op;}
throw new Error("Missing return statement in function");
}
final public ArrayList<String> string_plus_array() throws ParseException {
Token t;
ArrayList<String> arr = new ArrayList<String>();
label_7:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[10] = jj_gen;
break label_7;
}
t = jj_consume_token(string);
arr.add(unquote(t.image));
label_8:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case plus:
;
break;
default:
jj_la1[11] = jj_gen;
break label_8;
}
jj_consume_token(plus);
t = jj_consume_token(string);
arr.add(unquote(t.image));
}
}
{if (true) return arr;}
throw new Error("Missing return statement in function");
}
final public ArrayList<String> string_array() throws ParseException {
Token t;
ArrayList<String> arr = new ArrayList<String>();
label_9:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case string:
;
break;
default:
jj_la1[12] = jj_gen;
break label_9;
}
t = jj_consume_token(string);
arr.add(unquote(t.image));
}
{if (true) return arr;}
throw new Error("Missing return statement in function");
}
final public void ignored_block() throws ParseException {
jj_consume_token(bopen);
skip_to_matching_brace();
jj_consume_token(bclose);
}
void skip_to_matching_brace() throws ParseException {
Token tok;
int nesting = 1;
while (true) {
tok = getToken(1);
if (tok.kind == bopen) nesting++;
if (tok.kind == bclose) {
nesting--;
if (nesting == 0) break;
}
tok = getNextToken();
}
}
String read_pattern() throws ParseException {
StringBuffer buf = new StringBuffer();
Token tok;
while (true) {
tok = getToken(1);
if (tok.kind == semicolon) break;
buf.append(tok.image);
tok = getNextToken();
}
return buf.toString();
}
/** Generated Token Manager. */
public StilTokenManager token_source;
SimpleCharStream jj_input_stream;
/** Current token. */
public Token token;
/** Next token. */
public Token jj_nt;
private int jj_ntk;
private int jj_gen;
final private int[] jj_la1 = new int[13];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static {
jj_la1_init_0();
jj_la1_init_1();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {0x1ff80,0x1ff80,0x0,0x0,0x20000,0xfc0000,0xfc0000,0x81000000,0x81000000,0x0,0x0,0x0,0x0,};
}
private static void jj_la1_init_1() {
jj_la1_1 = new int[] {0x0,0x0,0x80,0x18,0x0,0x0,0x0,0xd8,0xd8,0x80,0x80,0x4,0x80,};
}
/** Constructor with InputStream. */
public Stil(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public Stil(java.io.InputStream stream, String encoding) {
try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source = new StilTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Constructor. */
public Stil(java.io.Reader stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new StilTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Constructor with generated Token Manager. */
public Stil(StilTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(StilTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 13; i++) jj_la1[i] = -1;
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
/** Get the next Token. */
final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
/** Get the specific Token. */
final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private int jj_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
private int[] jj_expentry;
private int jj_kind = -1;
/** Generate ParseException. */
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[40];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 13; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 40; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
/** Enable tracing. */
final public void enable_tracing() {
}
/** Disable tracing. */
final public void disable_tracing() {
}
}
| 16,083 | 0.551763 | 0.535099 | 602 | 25.715946 | 19.018982 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647841 | false | false | 1 |
8f038d0f9d4c263ef0f87241ee0c334ff8d701e1 | 29,231,547,423,784 | 8fd4529de13944ea3a76b1dbf6be4cb686b6dc4b | /app/src/main/java/com/limitip/mm/mark_movie/util/GetActivity.java | 3fb33e85b555d2b5e12c162a66fa11109710461c | []
| no_license | hokitlee/Mark_Movie-Android | https://github.com/hokitlee/Mark_Movie-Android | df0c98be84267c8a98a80171935bd80fe6bc9120 | 5f460eaf689df204fd41f0e1c46784d60d3dcc18 | refs/heads/master | 2020-03-16T14:05:05.870000 | 2018-07-09T12:14:34 | 2018-07-09T12:14:34 | 132,707,093 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.limitip.mm.mark_movie.util;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.view.View;
public class GetActivity {
public static Activity getActivityFromView(View view) {
Context context = view.getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
}
| UTF-8 | Java | 562 | java | GetActivity.java | Java | []
| null | []
| package com.limitip.mm.mark_movie.util;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.view.View;
public class GetActivity {
public static Activity getActivityFromView(View view) {
Context context = view.getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
}
| 562 | 0.660142 | 0.660142 | 19 | 28.578947 | 19.765244 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 1 |
57002edcf79dcda0ec7ff4af55f1b60185764249 | 8,770,323,229,575 | 24f6909042d5f2f506ef70901567b31a3d0720af | /src/org/itstep/enam/Command.java | 23ee4ff8637977b75c1f062cdf851ba84abaf796 | []
| no_license | Cemen093/exeamOop | https://github.com/Cemen093/exeamOop | 7d83519e15ef0de256d93494709e07e4dc89b165 | 0a738a8a53dccb9dd0ec9dc358b51855caef2422 | refs/heads/master | 2023-02-08T23:48:19.210000 | 2021-01-01T21:01:39 | 2021-01-01T21:01:39 | 325,877,930 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.itstep.enam;
public enum Command {
ADD_NEW_EMPLOYEE("добавить нового сотрудника"), TO_FIRE_EMPLOYEE("уволить сотрудника"),
CHANGE_INFORMATION_EMPLOYEE("изменить информацию о сотруднике"), FIND_EMPLOYEES("найти сотрудников"),
PRINT_REPORT("распечатать отчет"), EXIT("выход"), ADD_NEW_DEPARTMENT("добавить новый департамент"), COMMAND_NOT_FOUND("");
String name;
Command(String name) {
this.name = name;
}
public String getName() {
return name;
}
} | UTF-8 | Java | 641 | java | Command.java | Java | []
| null | []
| package org.itstep.enam;
public enum Command {
ADD_NEW_EMPLOYEE("добавить нового сотрудника"), TO_FIRE_EMPLOYEE("уволить сотрудника"),
CHANGE_INFORMATION_EMPLOYEE("изменить информацию о сотруднике"), FIND_EMPLOYEES("найти сотрудников"),
PRINT_REPORT("распечатать отчет"), EXIT("выход"), ADD_NEW_DEPARTMENT("добавить новый департамент"), COMMAND_NOT_FOUND("");
String name;
Command(String name) {
this.name = name;
}
public String getName() {
return name;
}
} | 641 | 0.682353 | 0.682353 | 17 | 29.058823 | 38.112019 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false | 1 |
eeef0cabf890c9fbe97d50cc785dffa962bdb8c6 | 8,615,704,409,772 | a5d01febfd8d45a61f815b6f5ed447e25fad4959 | /Source Code/5.5.1/sources/com/iqoption/d/bt.java | 1338138b792153a0fd4a38f5b04837e49c4fcfbd | []
| no_license | kkagill/Decompiler-IQ-Option | https://github.com/kkagill/Decompiler-IQ-Option | 7fe5911f90ed2490687f5d216cb2940f07b57194 | c2a9dbbe79a959aa1ab8bb7a89c735e8f9dbc5a6 | refs/heads/master | 2020-09-14T20:44:49.115000 | 2019-11-04T06:58:55 | 2019-11-04T06:58:55 | 223,236,327 | 1 | 0 | null | true | 2019-11-21T18:17:17 | 2019-11-21T18:17:16 | 2019-11-04T07:03:15 | 2019-11-04T07:02:38 | 104,586 | 0 | 0 | 0 | null | false | false | package com.iqoption.d;
import android.databinding.DataBindingComponent;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.iqoption.core.ui.widget.MaxSizeLinearLayout;
import com.iqoption.view.RobotoTextView;
import com.iqoption.x.R;
/* compiled from: BuyNewDialogViewBindingImpl */
public class bt extends bs {
@Nullable
private static final IncludedLayouts awU = null;
@Nullable
private static final SparseIntArray awV = new SparseIntArray();
private long awW;
@NonNull
private final LinearLayout axx;
@NonNull
private final MaxSizeLinearLayout blM;
protected boolean onFieldChange(int i, Object obj, int i2) {
return false;
}
public boolean setVariable(int i, @Nullable Object obj) {
return true;
}
static {
awV.put(R.id.timeToClose, 2);
awV.put(R.id.newOptionButton, 3);
}
public bt(@Nullable DataBindingComponent dataBindingComponent, @NonNull View[] viewArr) {
this(dataBindingComponent, viewArr, ViewDataBinding.mapBindings(dataBindingComponent, viewArr, 4, awU, awV));
}
private bt(DataBindingComponent dataBindingComponent, View[] viewArr, Object[] objArr) {
super(dataBindingComponent, viewArr[0], 0, (RobotoTextView) objArr[3], (TextView) objArr[2]);
this.awW = -1;
this.axx = (LinearLayout) objArr[0];
this.axx.setTag(null);
this.blM = (MaxSizeLinearLayout) objArr[1];
this.blM.setTag(null);
setRootTag(viewArr);
invalidateAll();
}
public void invalidateAll() {
synchronized (this) {
this.awW = 1;
}
requestRebind();
}
public boolean hasPendingBindings() {
synchronized (this) {
if (this.awW != 0) {
return true;
}
return false;
}
}
protected void executeBindings() {
synchronized (this) {
long j = this.awW;
this.awW = 0;
}
}
}
| UTF-8 | Java | 2,221 | java | bt.java | Java | []
| null | []
| package com.iqoption.d;
import android.databinding.DataBindingComponent;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.iqoption.core.ui.widget.MaxSizeLinearLayout;
import com.iqoption.view.RobotoTextView;
import com.iqoption.x.R;
/* compiled from: BuyNewDialogViewBindingImpl */
public class bt extends bs {
@Nullable
private static final IncludedLayouts awU = null;
@Nullable
private static final SparseIntArray awV = new SparseIntArray();
private long awW;
@NonNull
private final LinearLayout axx;
@NonNull
private final MaxSizeLinearLayout blM;
protected boolean onFieldChange(int i, Object obj, int i2) {
return false;
}
public boolean setVariable(int i, @Nullable Object obj) {
return true;
}
static {
awV.put(R.id.timeToClose, 2);
awV.put(R.id.newOptionButton, 3);
}
public bt(@Nullable DataBindingComponent dataBindingComponent, @NonNull View[] viewArr) {
this(dataBindingComponent, viewArr, ViewDataBinding.mapBindings(dataBindingComponent, viewArr, 4, awU, awV));
}
private bt(DataBindingComponent dataBindingComponent, View[] viewArr, Object[] objArr) {
super(dataBindingComponent, viewArr[0], 0, (RobotoTextView) objArr[3], (TextView) objArr[2]);
this.awW = -1;
this.axx = (LinearLayout) objArr[0];
this.axx.setTag(null);
this.blM = (MaxSizeLinearLayout) objArr[1];
this.blM.setTag(null);
setRootTag(viewArr);
invalidateAll();
}
public void invalidateAll() {
synchronized (this) {
this.awW = 1;
}
requestRebind();
}
public boolean hasPendingBindings() {
synchronized (this) {
if (this.awW != 0) {
return true;
}
return false;
}
}
protected void executeBindings() {
synchronized (this) {
long j = this.awW;
this.awW = 0;
}
}
}
| 2,221 | 0.65376 | 0.647456 | 77 | 27.844156 | 24.366287 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.701299 | false | false | 1 |
3a6ea2aa496709b0b4cdf54d1100a1a178f8bfb8 | 1,803,886,279,657 | 63025c86419f93ab4f757ba39ab98145b4e078be | /src/main/java/com/eureka/test/algorithmsv2/array/medium/Combine.java | eb7bd3062b999c654e73cd6fb8c3d66b2fca27df | []
| no_license | ykkssb/algorithms | https://github.com/ykkssb/algorithms | 0018cd0573619bf7e1e7df6a720131dc5bb6b82d | c99e6f3581fb5c2a5527a58355abf8d422c721e3 | refs/heads/master | 2022-10-14T15:29:58.856000 | 2022-10-11T07:06:12 | 2022-10-12T06:53:57 | 245,316,588 | 0 | 0 | null | false | 2021-12-14T21:42:21 | 2020-03-06T02:54:53 | 2021-09-23T06:23:51 | 2021-12-14T21:42:20 | 409 | 0 | 0 | 3 | Java | false | false | package com.eureka.test.algorithmsv2.array.medium;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* <p>组合</p>
* https://leetcode-cn.com/problems/combinations/
* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
*
* @Author : Eric
* @Date: 2020-06-03 19:42
*/
public class Combine {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
if (n == 0 || k == 0) {
return res;
}
Stack<Integer> st = new Stack<>();
fill(n, k, 1, st);
return res;
}
/**
* todo v1
* @param n
* @param k
* @param index
* @param st
*/
public void fill(int n, int k, int index, Stack<Integer> st) {
if (st.size() == k) {
res.add(new ArrayList<>(st));
return;
}
for (int i = index; i <= n - k + st.size()+1; i++) {
st.push(i);
fill(n, k, i + 1, st);
st.pop();
}
}
public static void main(String[] args) {
Combine c = new Combine();
// 1,2,3,4
System.out.println(c.combine(4, 2));
}
}
| UTF-8 | Java | 1,214 | java | Combine.java | Java | [
{
"context": "数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。\n *\n * @Author : Eric\n * @Date: 2020-06-03 19:42\n */\npublic class Combi",
"end": 258,
"score": 0.9927915334701538,
"start": 254,
"tag": "NAME",
"value": "Eric"
}
]
| null | []
| package com.eureka.test.algorithmsv2.array.medium;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* <p>组合</p>
* https://leetcode-cn.com/problems/combinations/
* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
*
* @Author : Eric
* @Date: 2020-06-03 19:42
*/
public class Combine {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
if (n == 0 || k == 0) {
return res;
}
Stack<Integer> st = new Stack<>();
fill(n, k, 1, st);
return res;
}
/**
* todo v1
* @param n
* @param k
* @param index
* @param st
*/
public void fill(int n, int k, int index, Stack<Integer> st) {
if (st.size() == k) {
res.add(new ArrayList<>(st));
return;
}
for (int i = index; i <= n - k + st.size()+1; i++) {
st.push(i);
fill(n, k, i + 1, st);
st.pop();
}
}
public static void main(String[] args) {
Combine c = new Combine();
// 1,2,3,4
System.out.println(c.combine(4, 2));
}
}
| 1,214 | 0.490566 | 0.468268 | 56 | 19.821428 | 17.691914 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607143 | false | false | 1 |
9290ce9c7ba5cb2e82b7f4763138ec68fa0c6bab | 35,175,782,188,051 | 7031a6cf3cc842907f93f0894bc74b1a325e0c7e | /src/main/java/com/wind/service/impl/RelationService.java | 1f900c4a681e45238287dcf5b9e55ad1381eef02 | []
| no_license | wind27/portal_moment | https://github.com/wind27/portal_moment | b432a2fd69255449e7b5418f6dfc6a759d71bb6e | b43311d5c864076dd743714e1d82462f47f47d4e | refs/heads/master | 2021-01-10T02:18:36.347000 | 2016-03-18T12:24:26 | 2016-03-18T12:24:26 | 50,831,217 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wind.service.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.wind.commons.DataSourceSwitch;
import com.wind.dao.IRelationDao;
import com.wind.entity.Relation;
import com.wind.exception.RollBackException;
import com.wind.service.IRelationService;
/**
* TokenService 实现
*
* @author qianchun
* @date 2016年2月19日 下午2:59:33
*/
@Service
public class RelationService implements IRelationService {
public RelationService() {
DataSourceSwitch.setDataSourceType("userDataSource");
}
@Resource
IRelationDao relationDao;
// @Override
// public Relation add(Relation relation) {
// return relationDao.insert(relation);
// }
@Override
public List<Relation> findByUid(long uid) {
return relationDao.findByUid(uid);
}
@Override
public List<Relation> findByTargetUid(long targetUid) {
return relationDao.findByTargetUid(targetUid);
}
@Override
public boolean update(Relation relation) {
return relationDao.update(relation);
}
@Override
public boolean updateByParams(Map<String, Object> params) {
return relationDao.updateByParams(params);
}
@Override
public Relation findByUidAndTargetUid(long uid, long targetUid) {
return relationDao.findByUidAndTargetUid(uid, targetUid);
}
@Override
public boolean batchAdd(List<Relation> relationList) {
return relationDao.batchAdd(relationList);
}
@Override
public boolean batchUpdate(List<Relation> relationList) {
boolean flag = true;
if(relationList==null || relationList.size()!=2) {
return false;
}
for(int i=0; i<relationList.size(); i++) {
Relation r = relationList.get(i);
if(r!=null) {
flag = relationDao.update(r);
}
if(flag == false) {
new RollBackException("添加关注异常,事务回滚!!!");
return false;
}
}
return flag;
}
}
| UTF-8 | Java | 2,162 | java | RelationService.java | Java | [
{
"context": "ionService;\n\n/**\n * TokenService 实现\n * \n * @author qianchun\n * @date 2016年2月19日 下午2:59:33\n */\n@Service\npublic",
"end": 404,
"score": 0.9993293881416321,
"start": 396,
"tag": "USERNAME",
"value": "qianchun"
}
]
| null | []
| package com.wind.service.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.wind.commons.DataSourceSwitch;
import com.wind.dao.IRelationDao;
import com.wind.entity.Relation;
import com.wind.exception.RollBackException;
import com.wind.service.IRelationService;
/**
* TokenService 实现
*
* @author qianchun
* @date 2016年2月19日 下午2:59:33
*/
@Service
public class RelationService implements IRelationService {
public RelationService() {
DataSourceSwitch.setDataSourceType("userDataSource");
}
@Resource
IRelationDao relationDao;
// @Override
// public Relation add(Relation relation) {
// return relationDao.insert(relation);
// }
@Override
public List<Relation> findByUid(long uid) {
return relationDao.findByUid(uid);
}
@Override
public List<Relation> findByTargetUid(long targetUid) {
return relationDao.findByTargetUid(targetUid);
}
@Override
public boolean update(Relation relation) {
return relationDao.update(relation);
}
@Override
public boolean updateByParams(Map<String, Object> params) {
return relationDao.updateByParams(params);
}
@Override
public Relation findByUidAndTargetUid(long uid, long targetUid) {
return relationDao.findByUidAndTargetUid(uid, targetUid);
}
@Override
public boolean batchAdd(List<Relation> relationList) {
return relationDao.batchAdd(relationList);
}
@Override
public boolean batchUpdate(List<Relation> relationList) {
boolean flag = true;
if(relationList==null || relationList.size()!=2) {
return false;
}
for(int i=0; i<relationList.size(); i++) {
Relation r = relationList.get(i);
if(r!=null) {
flag = relationDao.update(r);
}
if(flag == false) {
new RollBackException("添加关注异常,事务回滚!!!");
return false;
}
}
return flag;
}
}
| 2,162 | 0.646226 | 0.639623 | 85 | 23.941177 | 21.004959 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388235 | false | false | 1 |
74b618beab1f356cf0d300a004364c13321d199e | 8,641,474,249,969 | 2fbb920555d82dc6fdadc129749acf6c632fb7d4 | /gdsap-framework/src/main/java/uk/co/quidos/gdsap/evaluation/services/StandardRecommendationServiceMgr.java | edea8bc8185354112308ec99852858aa7fda1d4c | [
"Apache-2.0"
]
| permissive | ZhangPeng1990/crm | https://github.com/ZhangPeng1990/crm | 3cd31b6a121418c47032979354af0886a236a0cf | c5b176718924c024a13cc6ceccb2e737e70cedd3 | refs/heads/master | 2020-06-05T18:25:41.600000 | 2015-04-29T10:38:01 | 2015-04-29T10:38:01 | 34,787,517 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package uk.co.quidos.gdsap.evaluation.services;
import java.util.List;
import uk.co.quidos.gdsap.evaluation.Report;
import uk.co.quidos.gdsap.evaluation.StandardOption;
import uk.co.quidos.gdsap.evaluation.StandardRecommendation;
import uk.co.quidos.gdsap.evaluation.StandardRecommendationWrap;
import uk.co.quidos.gdsap.evaluation.StandardValue;
import uk.co.quidos.gdsap.evaluation.enums.SolutionType;
import uk.co.quidos.gdsap.framework.enums.EpcVersion;
import uk.co.quidos.gdsap.framework.sys.business.BusinessObjectServiceMgr;
/**
* @author peng.shi
*/
public interface StandardRecommendationServiceMgr extends BusinessObjectServiceMgr
{
public static final String SERVICE_NAME = "standardRecommendationServiceMgr";
/**
* @param code
* @return
*/
StandardRecommendation getStandardRecommendation(int code, Report report);
/**
* 获取 StandardOption 选项
* @param sr
* @param standardOptionCode
* @return
*/
StandardOption getStandardOption(StandardRecommendation sr,String standardOptionCode);
/**
*
* @param sr
* @param name
* @return
*/
StandardValue getStandardValue(StandardRecommendation sr, String name);
/**
* 添加RecommendationWrap
* @param wrap
* @return
*/
List<StandardRecommendationWrap> addStandardRecommendation(long reportId, List<StandardRecommendation> recommendations);
/**
* 通过ReportId 获取 StandardRecommendation
* @param reportId
* @return
*/
List<StandardRecommendationWrap> getStandardRecommendationWraps(long reportId, SolutionType recommendationType);
/**
* 通过id获取StandardRecommendationWrap
* @param id
* @return
*/
StandardRecommendationWrap getStandardRecommendationWrap(long id);
/**
* report 可为null
* 根据对应report的GDAR LIG, 加工返回到GDP用的GDIP的改进,根据GDAR LIG 的改进勾选情况来勾选GDP用的GDIP的改进
* @param report
* @param nodataWraps
* @return
*/
List<StandardRecommendationWrap> processNodataWraps(Report report, List<StandardRecommendationWrap> nodataWraps);
}
| UTF-8 | Java | 2,148 | java | StandardRecommendationServiceMgr.java | Java | [
{
"context": "iness.BusinessObjectServiceMgr;\r\n\r\n/**\r\n * @author peng.shi\r\n */\r\npublic interface StandardRecommendation",
"end": 584,
"score": 0.8982325196266174,
"start": 580,
"tag": "NAME",
"value": "peng"
},
{
"context": ".BusinessObjectServiceMgr;\r\n\r\n/**\r\n * @author peng.shi\r\n */\r\npublic interface StandardRecommendationServ",
"end": 588,
"score": 0.7668460607528687,
"start": 585,
"tag": "USERNAME",
"value": "shi"
}
]
| null | []
| /**
*
*/
package uk.co.quidos.gdsap.evaluation.services;
import java.util.List;
import uk.co.quidos.gdsap.evaluation.Report;
import uk.co.quidos.gdsap.evaluation.StandardOption;
import uk.co.quidos.gdsap.evaluation.StandardRecommendation;
import uk.co.quidos.gdsap.evaluation.StandardRecommendationWrap;
import uk.co.quidos.gdsap.evaluation.StandardValue;
import uk.co.quidos.gdsap.evaluation.enums.SolutionType;
import uk.co.quidos.gdsap.framework.enums.EpcVersion;
import uk.co.quidos.gdsap.framework.sys.business.BusinessObjectServiceMgr;
/**
* @author peng.shi
*/
public interface StandardRecommendationServiceMgr extends BusinessObjectServiceMgr
{
public static final String SERVICE_NAME = "standardRecommendationServiceMgr";
/**
* @param code
* @return
*/
StandardRecommendation getStandardRecommendation(int code, Report report);
/**
* 获取 StandardOption 选项
* @param sr
* @param standardOptionCode
* @return
*/
StandardOption getStandardOption(StandardRecommendation sr,String standardOptionCode);
/**
*
* @param sr
* @param name
* @return
*/
StandardValue getStandardValue(StandardRecommendation sr, String name);
/**
* 添加RecommendationWrap
* @param wrap
* @return
*/
List<StandardRecommendationWrap> addStandardRecommendation(long reportId, List<StandardRecommendation> recommendations);
/**
* 通过ReportId 获取 StandardRecommendation
* @param reportId
* @return
*/
List<StandardRecommendationWrap> getStandardRecommendationWraps(long reportId, SolutionType recommendationType);
/**
* 通过id获取StandardRecommendationWrap
* @param id
* @return
*/
StandardRecommendationWrap getStandardRecommendationWrap(long id);
/**
* report 可为null
* 根据对应report的GDAR LIG, 加工返回到GDP用的GDIP的改进,根据GDAR LIG 的改进勾选情况来勾选GDP用的GDIP的改进
* @param report
* @param nodataWraps
* @return
*/
List<StandardRecommendationWrap> processNodataWraps(Report report, List<StandardRecommendationWrap> nodataWraps);
}
| 2,148 | 0.743415 | 0.743415 | 75 | 25.333334 | 30.934483 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.04 | false | false | 1 |
df302ec160cccfb7f242118041e7e8981e72f860 | 25,967,372,330,044 | a4ced7cc2d3406849a9a91a302df267ed698b8f7 | /command.line.test/src/com/jetbrains/teamcity/resources/TCWorkspaceTest.java | eb9d02f3dcc3305c4d9f8d2d3f36cc361ed20f98 | [
"Apache-2.0"
]
| permissive | JetBrains/teamcity-commandline | https://github.com/JetBrains/teamcity-commandline | f6460c79349ff5e89aebd23e7db008aad815a9e5 | f2ce5238909bda19d41ddd779239f64ea20d12c8 | refs/heads/master | 2023-08-28T08:15:50.046000 | 2023-08-07T08:10:07 | 2023-08-07T08:53:43 | 162,288,286 | 3 | 6 | Apache-2.0 | false | 2023-08-07T08:53:45 | 2018-12-18T12:55:20 | 2022-11-18T10:37:38 | 2023-08-07T08:53:44 | 19,490 | 2 | 5 | 2 | Java | false | false | package com.jetbrains.teamcity.resources;
import com.jetbrains.teamcity.TestingUtil;
import java.io.File;
import java.io.IOException;
import jetbrains.buildServer.util.FileUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class TCWorkspaceTest {
private static TCWorkspace ourTestWorkspace;
private File root;
@BeforeClass
public static void setup() {
ourTestWorkspace = new TCWorkspace();
}
@Before
public void setUp() throws IOException {
root = TestingUtil.createFS();
File file = new File(TCWorkspace.TCC_GLOBAL_ADMIN_FILE + ".test");
file.mkdirs();
FileUtil.delete(file);
}
@After
public void tearDown() {
TestingUtil.releaseFS(root);
}
@Test
public void getAdminFileFor_error_handling() throws Exception {
//root
File root = TestingUtil.getFSRoot();
assertNull(TCWorkspace.getMatcherFor(root));
//file in root
TCWorkspace.getMatcherFor(new File(root, "file.txt"));// no exception
}
@Test
public void getAdminFileFor_functionality() throws Exception {
File file = new File(root, "java/resources/java.resources");
assertNull("Admin file found for: " + file, TCWorkspace.getMatcherFor(file));// still_not_created
final File rootAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE);
FileUtil.writeFileAndReportErrors(rootAdminFile, ".=//depo/test/\n");
File java = new File(root, "1.java");
assertNotNull("No Admin file found for: " + java, TCWorkspace.getMatcherFor(java));// the_same_place
File javaResource = new File(root, "java/resources/java.resources");
assertNotNull("No Admin file found for: " + javaResource, TCWorkspace.getMatcherFor(javaResource));// in_hierarchy
}
@Test
public void getMatching_relative() throws Exception {
final File globalAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE + ".test.admin." + System.currentTimeMillis());
try{
//create global Admin
FileUtil.writeFileAndReportErrors(globalAdminFile, ".=//depo/test/dot\n" +
"cpp=//depo/test/cpp_root\n" +
"cpp/resources=//depo/test/cpp_resources\n");
final ITCResourceMatcher admin = new FileBasedMatcher(globalAdminFile);
//overriding
File cpp = new File(root, "cpp/1.cpp");
File cppResource = new File(root, "cpp/resources/cpp.resources");
ITCResourceMatcher.Matching cppMatching = admin.getMatching(cpp);
ITCResourceMatcher.Matching resCppMatching = admin.getMatching(cppResource);
assertNotNull(cppMatching);
assertEquals("//depo/test/cpp_root", cppMatching.getTCID());// in_hierarchy
assertNotNull(resCppMatching);
assertEquals("//depo/test/cpp_resources", resCppMatching.getTCID());// in_hierarchy
} finally {
globalAdminFile.deleteOnExit();
}
}
@Test
public void testNPE_when_matching_TW_58901() throws IOException {
FileUtil.writeFileAndReportErrors(new File(root, TCWorkspace.TCC_ADMIN_FILE),
"u-boot=perforce://perforce:1666:////Products/TRUNK/3800Core/u-boot-3802\n");
final File local = new File(root, "u-boot");
local.mkdir();
final ITCResource tcResource = new TCWorkspace().getTCResource(local);
assertEquals(tcResource.getLocal().getAbsoluteFile(), local.getAbsoluteFile());
assertEquals(tcResource.getRepositoryPath(), "perforce://perforce:1666:////Products/TRUNK/3800Core/u-boot-3802/");
}
@Test
public void testNPE_when_matching_TW_58901_noMatch() throws IOException {
FileUtil.writeFileAndReportErrors(new File(root, TCWorkspace.TCC_ADMIN_FILE),
"u-boot=perforce://perforce:1666:////Products/TRUNK/3800Core/u-boot-3802\n");
final File local = new File(root, "u-boot1");
local.mkdir();
assertNull(new TCWorkspace().getTCResource(local));
}
@Test
public void getResource_per_folder_relative_path() throws Exception {
final File rootAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE);
FileUtil.writeFileAndReportErrors(rootAdminFile, ".=//depo/test/\n");
getResource_test_paths(root);
}
@Test
public void getResource_per_folder_absolute_path() throws Exception {
final File rootAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE);
FileUtil.writeFileAndReportErrors(rootAdminFile, root.getCanonicalFile().getAbsolutePath() + "=//depo/test/\n");
getResource_test_paths(root);
}
private void getResource_test_paths(final File root) throws Exception {
//simple
File java = new File(root, "1.java");
ITCResource itcResource = ourTestWorkspace.getTCResource(java);
assertNotNull("No ITCResource created for: " + java, itcResource);
assertEquals("//depo/test/1.java", itcResource.getRepositoryPath());
//in hierarchy
File javaResource = new File(root, "java/resources/java.resources");
itcResource = ourTestWorkspace.getTCResource(javaResource);
assertNotNull("No ITCResource created for: " + javaResource, itcResource);// in_hierarchy
assertEquals("//depo/test/java/resources/java.resources", itcResource.getRepositoryPath());// in_hierarchy
//overriding
final File cppRootAdminFile = new File(root, "cpp/" + TCWorkspace.TCC_ADMIN_FILE).getAbsoluteFile();
FileUtil.writeFileAndReportErrors(cppRootAdminFile, ".=//depo/test/CPLUSPLUS/src\n");
File cppResource = new File(root, "cpp/resources/cpp.resources");
itcResource = ourTestWorkspace.getTCResource(cppResource);
assertNotNull("No ITCResource created for: " + cppResource, itcResource);// in_hierarchy
assertEquals("//depo/test/CPLUSPLUS/src/resources/cpp.resources", itcResource.getRepositoryPath());// in_hierarchy
}
@Test
public void getResource_global_absolute_path() throws Exception {
final File testGlobalAdminFile = new File(TCWorkspace.TCC_GLOBAL_ADMIN_FILE + ".test");
try{
//create global Admin
final File testRootFolder = root.getCanonicalFile();
FileUtil.writeFileAndReportErrors(testGlobalAdminFile, testRootFolder.getAbsolutePath() + "=//depo/test/\n");
final TCWorkspace workspace = new TCWorkspace(null/*new FileBasedMatcher(globalAdminFile)*/){
@Override
protected File getGlobalAdminFile() {
return testGlobalAdminFile;
}
};
//simple
File java = new File(root, "1.java");
ITCResource itcResource = workspace.getTCResource(java);
assertNotNull("No ITCResource created for: " + java, itcResource);
assertEquals("//depo/test/1.java", itcResource.getRepositoryPath());
//in hierarchy
File javaResource = new File(root, "java/resources/java.resources");
itcResource = workspace.getTCResource(javaResource);
assertNotNull("No ITCResource created for: " + javaResource, itcResource);// in_hierarchy
assertEquals("//depo/test/java/resources/java.resources", itcResource.getRepositoryPath());// in_hierarchy
} finally {
testGlobalAdminFile.deleteOnExit();
}
}
@Test
public void getResource_global_overrided_with_per_folder() throws Exception {
final File testGlobalAdminFile = new File(TCWorkspace.TCC_GLOBAL_ADMIN_FILE + ".test");
try{
//create global Admin
FileUtil.writeFileAndReportErrors(testGlobalAdminFile, root.getCanonicalFile().getAbsolutePath() + "=//depo/test/\n");
final TCWorkspace workspace = new TCWorkspace(null){
@Override
protected File getGlobalAdminFile() {
return testGlobalAdminFile;
}
};
//overriding
final File cppRootAdminFile = new File(root, "cpp/" + TCWorkspace.TCC_ADMIN_FILE).getAbsoluteFile();
FileUtil.writeFileAndReportErrors(cppRootAdminFile, ".=//depo/test/CPLUSPLUS/src\n");
File cppResource = new File(root, "cpp/resources/cpp.resources");
ITCResource itcResource = workspace.getTCResource(cppResource);
assertNotNull("No ITCResource created for: " + cppResource, itcResource);// in_hierarchy
assertEquals("//depo/test/CPLUSPLUS/src/resources/cpp.resources", itcResource.getRepositoryPath());// in_hierarchy
} finally {
testGlobalAdminFile.deleteOnExit();
}
}
}
| UTF-8 | Java | 8,143 | java | TCWorkspaceTest.java | Java | []
| null | []
| package com.jetbrains.teamcity.resources;
import com.jetbrains.teamcity.TestingUtil;
import java.io.File;
import java.io.IOException;
import jetbrains.buildServer.util.FileUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class TCWorkspaceTest {
private static TCWorkspace ourTestWorkspace;
private File root;
@BeforeClass
public static void setup() {
ourTestWorkspace = new TCWorkspace();
}
@Before
public void setUp() throws IOException {
root = TestingUtil.createFS();
File file = new File(TCWorkspace.TCC_GLOBAL_ADMIN_FILE + ".test");
file.mkdirs();
FileUtil.delete(file);
}
@After
public void tearDown() {
TestingUtil.releaseFS(root);
}
@Test
public void getAdminFileFor_error_handling() throws Exception {
//root
File root = TestingUtil.getFSRoot();
assertNull(TCWorkspace.getMatcherFor(root));
//file in root
TCWorkspace.getMatcherFor(new File(root, "file.txt"));// no exception
}
@Test
public void getAdminFileFor_functionality() throws Exception {
File file = new File(root, "java/resources/java.resources");
assertNull("Admin file found for: " + file, TCWorkspace.getMatcherFor(file));// still_not_created
final File rootAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE);
FileUtil.writeFileAndReportErrors(rootAdminFile, ".=//depo/test/\n");
File java = new File(root, "1.java");
assertNotNull("No Admin file found for: " + java, TCWorkspace.getMatcherFor(java));// the_same_place
File javaResource = new File(root, "java/resources/java.resources");
assertNotNull("No Admin file found for: " + javaResource, TCWorkspace.getMatcherFor(javaResource));// in_hierarchy
}
@Test
public void getMatching_relative() throws Exception {
final File globalAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE + ".test.admin." + System.currentTimeMillis());
try{
//create global Admin
FileUtil.writeFileAndReportErrors(globalAdminFile, ".=//depo/test/dot\n" +
"cpp=//depo/test/cpp_root\n" +
"cpp/resources=//depo/test/cpp_resources\n");
final ITCResourceMatcher admin = new FileBasedMatcher(globalAdminFile);
//overriding
File cpp = new File(root, "cpp/1.cpp");
File cppResource = new File(root, "cpp/resources/cpp.resources");
ITCResourceMatcher.Matching cppMatching = admin.getMatching(cpp);
ITCResourceMatcher.Matching resCppMatching = admin.getMatching(cppResource);
assertNotNull(cppMatching);
assertEquals("//depo/test/cpp_root", cppMatching.getTCID());// in_hierarchy
assertNotNull(resCppMatching);
assertEquals("//depo/test/cpp_resources", resCppMatching.getTCID());// in_hierarchy
} finally {
globalAdminFile.deleteOnExit();
}
}
@Test
public void testNPE_when_matching_TW_58901() throws IOException {
FileUtil.writeFileAndReportErrors(new File(root, TCWorkspace.TCC_ADMIN_FILE),
"u-boot=perforce://perforce:1666:////Products/TRUNK/3800Core/u-boot-3802\n");
final File local = new File(root, "u-boot");
local.mkdir();
final ITCResource tcResource = new TCWorkspace().getTCResource(local);
assertEquals(tcResource.getLocal().getAbsoluteFile(), local.getAbsoluteFile());
assertEquals(tcResource.getRepositoryPath(), "perforce://perforce:1666:////Products/TRUNK/3800Core/u-boot-3802/");
}
@Test
public void testNPE_when_matching_TW_58901_noMatch() throws IOException {
FileUtil.writeFileAndReportErrors(new File(root, TCWorkspace.TCC_ADMIN_FILE),
"u-boot=perforce://perforce:1666:////Products/TRUNK/3800Core/u-boot-3802\n");
final File local = new File(root, "u-boot1");
local.mkdir();
assertNull(new TCWorkspace().getTCResource(local));
}
@Test
public void getResource_per_folder_relative_path() throws Exception {
final File rootAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE);
FileUtil.writeFileAndReportErrors(rootAdminFile, ".=//depo/test/\n");
getResource_test_paths(root);
}
@Test
public void getResource_per_folder_absolute_path() throws Exception {
final File rootAdminFile = new File(root, TCWorkspace.TCC_ADMIN_FILE);
FileUtil.writeFileAndReportErrors(rootAdminFile, root.getCanonicalFile().getAbsolutePath() + "=//depo/test/\n");
getResource_test_paths(root);
}
private void getResource_test_paths(final File root) throws Exception {
//simple
File java = new File(root, "1.java");
ITCResource itcResource = ourTestWorkspace.getTCResource(java);
assertNotNull("No ITCResource created for: " + java, itcResource);
assertEquals("//depo/test/1.java", itcResource.getRepositoryPath());
//in hierarchy
File javaResource = new File(root, "java/resources/java.resources");
itcResource = ourTestWorkspace.getTCResource(javaResource);
assertNotNull("No ITCResource created for: " + javaResource, itcResource);// in_hierarchy
assertEquals("//depo/test/java/resources/java.resources", itcResource.getRepositoryPath());// in_hierarchy
//overriding
final File cppRootAdminFile = new File(root, "cpp/" + TCWorkspace.TCC_ADMIN_FILE).getAbsoluteFile();
FileUtil.writeFileAndReportErrors(cppRootAdminFile, ".=//depo/test/CPLUSPLUS/src\n");
File cppResource = new File(root, "cpp/resources/cpp.resources");
itcResource = ourTestWorkspace.getTCResource(cppResource);
assertNotNull("No ITCResource created for: " + cppResource, itcResource);// in_hierarchy
assertEquals("//depo/test/CPLUSPLUS/src/resources/cpp.resources", itcResource.getRepositoryPath());// in_hierarchy
}
@Test
public void getResource_global_absolute_path() throws Exception {
final File testGlobalAdminFile = new File(TCWorkspace.TCC_GLOBAL_ADMIN_FILE + ".test");
try{
//create global Admin
final File testRootFolder = root.getCanonicalFile();
FileUtil.writeFileAndReportErrors(testGlobalAdminFile, testRootFolder.getAbsolutePath() + "=//depo/test/\n");
final TCWorkspace workspace = new TCWorkspace(null/*new FileBasedMatcher(globalAdminFile)*/){
@Override
protected File getGlobalAdminFile() {
return testGlobalAdminFile;
}
};
//simple
File java = new File(root, "1.java");
ITCResource itcResource = workspace.getTCResource(java);
assertNotNull("No ITCResource created for: " + java, itcResource);
assertEquals("//depo/test/1.java", itcResource.getRepositoryPath());
//in hierarchy
File javaResource = new File(root, "java/resources/java.resources");
itcResource = workspace.getTCResource(javaResource);
assertNotNull("No ITCResource created for: " + javaResource, itcResource);// in_hierarchy
assertEquals("//depo/test/java/resources/java.resources", itcResource.getRepositoryPath());// in_hierarchy
} finally {
testGlobalAdminFile.deleteOnExit();
}
}
@Test
public void getResource_global_overrided_with_per_folder() throws Exception {
final File testGlobalAdminFile = new File(TCWorkspace.TCC_GLOBAL_ADMIN_FILE + ".test");
try{
//create global Admin
FileUtil.writeFileAndReportErrors(testGlobalAdminFile, root.getCanonicalFile().getAbsolutePath() + "=//depo/test/\n");
final TCWorkspace workspace = new TCWorkspace(null){
@Override
protected File getGlobalAdminFile() {
return testGlobalAdminFile;
}
};
//overriding
final File cppRootAdminFile = new File(root, "cpp/" + TCWorkspace.TCC_ADMIN_FILE).getAbsoluteFile();
FileUtil.writeFileAndReportErrors(cppRootAdminFile, ".=//depo/test/CPLUSPLUS/src\n");
File cppResource = new File(root, "cpp/resources/cpp.resources");
ITCResource itcResource = workspace.getTCResource(cppResource);
assertNotNull("No ITCResource created for: " + cppResource, itcResource);// in_hierarchy
assertEquals("//depo/test/CPLUSPLUS/src/resources/cpp.resources", itcResource.getRepositoryPath());// in_hierarchy
} finally {
testGlobalAdminFile.deleteOnExit();
}
}
}
| 8,143 | 0.716198 | 0.709689 | 212 | 37.410378 | 36.65554 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.537736 | false | false | 1 |
587bce454d1f9b9b27fa0e20f1ce1e829fd58065 | 18,451,179,556,195 | 95da42376fe8fcdec4952e6b8175b6dc03c9149f | /src/main/java/one/ua/services/registerManager/RegisterManager.java | 6b6c2b1d822f040879b788a26df904bc9ddb5abe | []
| no_license | ivandemydko/Conference | https://github.com/ivandemydko/Conference | ae33c046a7ebf18406a1dfd0c95c7f0fb2a7b131 | f4dc25a0e243c70bf5b83551895fef8b7e59108b | refs/heads/master | 2022-07-30T04:27:21.269000 | 2019-10-09T14:42:34 | 2019-10-09T14:42:34 | 205,219,072 | 0 | 0 | null | false | 2022-06-21T01:46:27 | 2019-08-29T17:45:55 | 2019-10-09T14:42:54 | 2022-06-21T01:46:23 | 849 | 0 | 0 | 2 | Java | false | false | package one.ua.services.registerManager;
import one.ua.databaseLogic.dao.RegisterDao;
import one.ua.databaseLogic.factory.DaoFactory;
import one.ua.entity.Report;
import one.ua.entity.User;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class encapsulated some methods from {@link RegisterDao}
*/
public class RegisterManager {
private RegisterDao registerDao;
public List<Long> getReportsIdByUserId(User user) {
registerDao = DaoFactory.getRegisterDao();
List<Long> registerList = registerDao.getReportsIdByUserId(user.getId());
registerDao.closeConnection();
return registerList;
}
public void checkRegistrationForUser(List<Report> reportList, List<Long> registerList) {
for (Long id : registerList) {
for (Report report : reportList) {
if (report.getId().equals(id)) {
report.setIsUserRegistered(true);
}
}
}
}
public Map<Long, Integer> getCountOfVisitors(List<Report> reportList) {
int count;
Map<Long, Integer> countOfVisitors = new HashMap<>();
RegisterDao registerDao = DaoFactory.getRegisterDao();
for (Report report : reportList) {
count = registerDao.getCountOfVisitors(report.getId());
countOfVisitors.put(report.getId(), count);
}
registerDao.closeConnection();
return countOfVisitors;
}
public int userRegister(Long userId, Long reportId) {
registerDao = DaoFactory.getRegisterDao();
int result = registerDao.userRegister(userId, reportId);
registerDao.closeConnection();
return result;
}
/**
* Sets registration for certain {@link User}
* @param report is a <code>Report</code> where user will be register.
*/
public void makeUserRegistered(Report report) {
report.setIsUserRegistered(true);
}
public List<User> getAllRegisteredUsers(Long reportId) {
RegisterDao registerDao = DaoFactory.getRegisterDao();
List<User> userList = registerDao.getAllRegisteredUsers(reportId);
registerDao.closeConnection();
return userList;
}
}
| UTF-8 | Java | 2,234 | java | RegisterManager.java | Java | []
| null | []
| package one.ua.services.registerManager;
import one.ua.databaseLogic.dao.RegisterDao;
import one.ua.databaseLogic.factory.DaoFactory;
import one.ua.entity.Report;
import one.ua.entity.User;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class encapsulated some methods from {@link RegisterDao}
*/
public class RegisterManager {
private RegisterDao registerDao;
public List<Long> getReportsIdByUserId(User user) {
registerDao = DaoFactory.getRegisterDao();
List<Long> registerList = registerDao.getReportsIdByUserId(user.getId());
registerDao.closeConnection();
return registerList;
}
public void checkRegistrationForUser(List<Report> reportList, List<Long> registerList) {
for (Long id : registerList) {
for (Report report : reportList) {
if (report.getId().equals(id)) {
report.setIsUserRegistered(true);
}
}
}
}
public Map<Long, Integer> getCountOfVisitors(List<Report> reportList) {
int count;
Map<Long, Integer> countOfVisitors = new HashMap<>();
RegisterDao registerDao = DaoFactory.getRegisterDao();
for (Report report : reportList) {
count = registerDao.getCountOfVisitors(report.getId());
countOfVisitors.put(report.getId(), count);
}
registerDao.closeConnection();
return countOfVisitors;
}
public int userRegister(Long userId, Long reportId) {
registerDao = DaoFactory.getRegisterDao();
int result = registerDao.userRegister(userId, reportId);
registerDao.closeConnection();
return result;
}
/**
* Sets registration for certain {@link User}
* @param report is a <code>Report</code> where user will be register.
*/
public void makeUserRegistered(Report report) {
report.setIsUserRegistered(true);
}
public List<User> getAllRegisteredUsers(Long reportId) {
RegisterDao registerDao = DaoFactory.getRegisterDao();
List<User> userList = registerDao.getAllRegisteredUsers(reportId);
registerDao.closeConnection();
return userList;
}
}
| 2,234 | 0.661594 | 0.661594 | 70 | 30.914286 | 25.22909 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514286 | false | false | 1 |
26ebc55697afa9602cee872f007364a2ca596e7c | 10,505,490,050,569 | 577f496c02bc54bacc921fedcedbb86cde778f40 | /src/dao/MD5Hashing.java | 8ddd7122148ef22f4866c1cd5e05dc9be5576e23 | []
| no_license | giang1599-nguyen/ParkingLot | https://github.com/giang1599-nguyen/ParkingLot | efca03656decedef368a368f3e8e861f39fd2b8c | f5d9ff80a333b8c0bdbd02ecf1821e94d09a31e2 | refs/heads/master | 2022-12-02T14:21:49.366000 | 2020-08-12T19:09:20 | 2020-08-12T19:09:20 | 280,071,678 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class MD5Hashing {
public static void main(String[] args) throws Exception {
System.out.println(MD5Hashing.getRandomString(10));
}
public static String getMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
return convertByteToHex(messageDigest);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static String convertByteToHex(byte[] data) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
sb.append(Integer.toString((data[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
// 5.getRandomString(int lenght)
public static String getRandomString(int length) {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < length) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String randomString = salt.toString();
return randomString;
}
}
| UTF-8 | Java | 1,480 | java | MD5Hashing.java | Java | []
| null | []
| package dao;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class MD5Hashing {
public static void main(String[] args) throws Exception {
System.out.println(MD5Hashing.getRandomString(10));
}
public static String getMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
return convertByteToHex(messageDigest);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static String convertByteToHex(byte[] data) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
sb.append(Integer.toString((data[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
// 5.getRandomString(int lenght)
public static String getRandomString(int length) {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < length) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String randomString = salt.toString();
return randomString;
}
}
| 1,480 | 0.611486 | 0.593919 | 41 | 34.097561 | 24.137619 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536585 | false | false | 1 |
11783ac5473cd4f967d7816a051c7af6c99f833a | 10,608,569,256,138 | 1c4a510f2af125727af479a426c0823da4d18486 | /Blueprint/app/src/main/java/com/manhattan/blueprint/View/ControlledViewPager.java | b6d28064feb47e5f56d2aace55e72c4d74ea7611 | []
| no_license | manhattan-blueprint/Manhattan-Mobile | https://github.com/manhattan-blueprint/Manhattan-Mobile | 9812e814e650fc3e2fe1bce7316b23fd50c0cb23 | cd4774cc637b7f2152836a5aa5b14b94d6eef1c3 | refs/heads/develop | 2020-03-31T12:49:45.388000 | 2019-11-02T13:55:39 | 2019-11-02T13:55:39 | 152,231,063 | 1 | 0 | null | false | 2019-11-02T13:55:40 | 2018-10-09T10:18:04 | 2019-10-31T19:02:40 | 2019-11-02T13:55:40 | 120,812 | 1 | 0 | 1 | Java | false | false | package com.manhattan.blueprint.View;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class ControlledViewPager extends ViewPager {
public ControlledViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return false;
}
}
| UTF-8 | Java | 545 | java | ControlledViewPager.java | Java | []
| null | []
| package com.manhattan.blueprint.View;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class ControlledViewPager extends ViewPager {
public ControlledViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return false;
}
}
| 545 | 0.73211 | 0.730275 | 23 | 22.695652 | 21.226387 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 1 |
4e37adc565af59013f95cd6712c261b1ec961798 | 13,958,643,780,901 | b1c749dafa2a0783244f0cec42f4adc71a2e60ab | /app/src/main/java/com/example/andrew/softtecodemo/GridFragment.java | a13dc1e8776b5f9dc1c24bc0b28b1c4c44ca34e6 | []
| no_license | AndySharou/SoftTecoDemo | https://github.com/AndySharou/SoftTecoDemo | 039ea1ff1255dc0b9ce1901a5fb2125f8c92ada8 | 53be5a77cee0178efaffc7cf6d1dd7aad408be44 | refs/heads/master | 2021-01-12T01:12:22.071000 | 2017-01-08T16:50:17 | 2017-01-08T16:50:17 | 78,356,385 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.andrew.softtecodemo;
/**
* Created by Andrew on 06.01.2017.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
@SuppressLint("ValidFragment")
public class GridFragment extends Fragment {
private GridView mGridView;
private GridAdapter mGridAdapter;
GridItems[] gridItems = {};
private Activity activity;
public GridFragment(GridItems[] gridItems, Activity activity) {
this.gridItems = gridItems;
this.activity = activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.grid, container, false);
mGridView = (GridView) view.findViewById(R.id.gridView);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (activity != null) {
mGridAdapter = new GridAdapter(activity, gridItems);
if (mGridView != null) {
mGridView.setAdapter(mGridAdapter);
}
mGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
onGridItemClick((GridView) parent, view, position, id);
}
});
}
}
public void onGridItemClick(GridView g, View v, int position, long id) {
// Toast.makeText(
// activity,
// "User ID is: "
// + gridItems[position].userId, Toast.LENGTH_LONG).show();
Log.i("TAG", "User ID CLICKED " + gridItems[position].userId);
Intent intent = new Intent(getActivity(), ContactActivity.class);
intent.putExtra("userId",gridItems[position].userId);
intent.putExtra("postId",gridItems[position].postId);
startActivity(intent);
}
} | UTF-8 | Java | 2,425 | java | GridFragment.java | Java | [
{
"context": "package com.example.andrew.softtecodemo;\n\n/**\n * Created by Andrew on 06.",
"end": 23,
"score": 0.6205959320068359,
"start": 20,
"tag": "USERNAME",
"value": "and"
},
{
"context": "om.example.andrew.softtecodemo;\n\n/**\n * Created by Andrew on 06.01.2017.\n */\n\nimport android.annotation.Sup",
"end": 66,
"score": 0.9995021224021912,
"start": 60,
"tag": "NAME",
"value": "Andrew"
}
]
| null | []
| package com.example.andrew.softtecodemo;
/**
* Created by Andrew on 06.01.2017.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
@SuppressLint("ValidFragment")
public class GridFragment extends Fragment {
private GridView mGridView;
private GridAdapter mGridAdapter;
GridItems[] gridItems = {};
private Activity activity;
public GridFragment(GridItems[] gridItems, Activity activity) {
this.gridItems = gridItems;
this.activity = activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.grid, container, false);
mGridView = (GridView) view.findViewById(R.id.gridView);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (activity != null) {
mGridAdapter = new GridAdapter(activity, gridItems);
if (mGridView != null) {
mGridView.setAdapter(mGridAdapter);
}
mGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
onGridItemClick((GridView) parent, view, position, id);
}
});
}
}
public void onGridItemClick(GridView g, View v, int position, long id) {
// Toast.makeText(
// activity,
// "User ID is: "
// + gridItems[position].userId, Toast.LENGTH_LONG).show();
Log.i("TAG", "User ID CLICKED " + gridItems[position].userId);
Intent intent = new Intent(getActivity(), ContactActivity.class);
intent.putExtra("userId",gridItems[position].userId);
intent.putExtra("postId",gridItems[position].postId);
startActivity(intent);
}
} | 2,425 | 0.639588 | 0.635876 | 75 | 31.346666 | 24.50605 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 1 |
805aaa3178ea4c095511b20898c32002559851e0 | 11,948,599,019,778 | 56ed316103d76d44e5e1651bf185aac216db9252 | /TimeTracker/app/src/main/java/core/DS/timetracker/CVisitorFormatterText.java | 2aecfbcce20bb86fc4c3cc6fcc76fd602b619036 | []
| no_license | Wardo82/TimeTracker | https://github.com/Wardo82/TimeTracker | 5ef42cd20dc1416497782b35680529c5a8f3b9a7 | eeef5147ea4bb458ba2f44ecc7be4e5131c10d28 | refs/heads/master | 2020-08-04T09:17:32.066000 | 2020-01-08T04:41:37 | 2020-01-08T04:41:37 | 212,087,090 | 0 | 0 | null | false | 2020-01-08T04:41:38 | 2019-10-01T12:11:53 | 2020-01-07T18:35:21 | 2020-01-08T04:41:38 | 11,863 | 0 | 0 | 0 | Java | false | false | package core.ds.TimeTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* Visitor Subclass of <code>CVisitorFormatter</code> that implements
* the text format.
*/
public class CVisitorFormatterText extends CVisitorFormatter {
/** Initialize start and end of the period for this report.
* @param start Start of the report period (left bound).
* @param end End of the report period (right bound). */
public CVisitorFormatterText(final long start, final long end) {
super(start, end); // Calls superclass constructor
}
public void visitProject(final CProject project) {
if (logger.isDebugEnabled()) {
logger.debug("Visiting {}", project.getName());
}
long start = project.getStartTime(); // Get project initial time
if (m_startTime > start) { // If the project is previous to the report
start = m_startTime;
}
long end = project.getEndTime(); // Get project finished time
if (m_endTime < end) { // If the project is not finished
end = m_endTime;
}
String parent = "";
// If it's not root project
if (project.getProjectParentName() != null) {
parent = project.getProjectParentName() + " ";
m_subProjectsTable = m_subProjectsTable + project.getName() + " " + parent
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(project.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
} else {
m_mainProjectsTable = m_mainProjectsTable + project.getName() + " " + parent
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(project.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
}
}
public void visitTask(final CTask task) {
if (logger.isDebugEnabled()) {
logger.debug("Visiting {}", task.getName());
}
long start = task.getStartTime(); // Get project initial time
if (m_startTime > start) { // If the project is previous to the report
start = m_startTime;
}
long end = task.getEndTime(); // Get project finished time
if (m_endTime < end) { // If the project is not finished
end = m_endTime;
}
m_tasksTable = m_tasksTable + task.getName() + " "
+ task.getProjectParentName() + " "
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(task.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
};
public void visitInterval(final CInterval interval) {
if (logger.isDebugEnabled()) {
logger.debug("Visiting {}", interval.getName());
}
long start = interval.getStartTime(); // Get project initial time
if (m_startTime > start) { // If the project is previous to the report
start = m_startTime;
}
long end = interval.getEndTime(); // Get project finished time
if (m_endTime < end) { // If the project is not finished
end = m_endTime;
}
m_intervalsTable = m_intervalsTable + interval.getTaskParentName() + " "
+ interval.getProjectName() + " "
+ interval.getName() + " "
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(interval.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
}
@Override
public void appendLineSeparator() {
m_document = m_document
+ "-------------------------------------------------------------------------\n";
}
@Override
public void appendHeader() {
appendLineSeparator(); // Line
m_document = m_document + "Report\n"; // Main title
appendLineSeparator(); // Line
m_document = m_document + "Period:\n";
m_document = m_document + "Since: "
+ Day.format(new Date(m_startTime)) + "\n";
m_document = m_document + "Until: "
+ Day.format(new Date(m_endTime)) + "\n";
m_document = m_document + "Current Date: "
+ Day.format(new Date(m_currentTime)) + "\n";
appendLineSeparator(); // Line
}
@Override
public void appendProjectsHeader() {
m_document = m_document + "First level projects: \n";
m_document = m_document + "Name | Start date |"
+ " Finish date | Total Time \n";
}
@Override
public void appendProjectsData() {
m_document = m_document + m_mainProjectsTable;
}
@Override
public void appendSubProjectsHeader() {
m_document = m_document + "Sub-projects: \n";
m_document = m_document + "Name | Belongs to |"
+ " Start date | Finish date | Total Time \n";
}
@Override
public void appendSubProjectsData() {
m_document = m_document + m_subProjectsTable;
}
@Override
public void appendTasksHeader() {
m_document = m_document + "Tasks: \n";
m_document = m_document + "Name | Parent project |"
+ " Start date | Finish date | Total Time \n";
}
@Override
public void appendTasksData() {
m_document = m_document + m_tasksTable;
}
@Override
public void appendIntervalsHeader() {
m_document = m_document + "Intervals: \n";
m_document = m_document + "Name | In task | ID |"
+ " Start date | Finish date | Total Time \n";
}
@Override
public void appendIntervalsData() {
m_document = m_document + m_intervalsTable;
}
@Override
public void generateReport() {
System.out.println(m_document);
}
/** String used to compile the whole document before generating
* the report. */
private String m_document = "";
// Tables for each important chunk of information.
private String m_mainProjectsTable = new String();
private String m_subProjectsTable = new String();
private String m_tasksTable = new String();
private String m_intervalsTable = new String();
private static Logger logger = LoggerFactory.getLogger(CVisitorFormatterText.class);
}
| UTF-8 | Java | 7,105 | java | CVisitorFormatterText.java | Java | []
| null | []
| package core.ds.TimeTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* Visitor Subclass of <code>CVisitorFormatter</code> that implements
* the text format.
*/
public class CVisitorFormatterText extends CVisitorFormatter {
/** Initialize start and end of the period for this report.
* @param start Start of the report period (left bound).
* @param end End of the report period (right bound). */
public CVisitorFormatterText(final long start, final long end) {
super(start, end); // Calls superclass constructor
}
public void visitProject(final CProject project) {
if (logger.isDebugEnabled()) {
logger.debug("Visiting {}", project.getName());
}
long start = project.getStartTime(); // Get project initial time
if (m_startTime > start) { // If the project is previous to the report
start = m_startTime;
}
long end = project.getEndTime(); // Get project finished time
if (m_endTime < end) { // If the project is not finished
end = m_endTime;
}
String parent = "";
// If it's not root project
if (project.getProjectParentName() != null) {
parent = project.getProjectParentName() + " ";
m_subProjectsTable = m_subProjectsTable + project.getName() + " " + parent
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(project.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
} else {
m_mainProjectsTable = m_mainProjectsTable + project.getName() + " " + parent
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(project.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
}
}
public void visitTask(final CTask task) {
if (logger.isDebugEnabled()) {
logger.debug("Visiting {}", task.getName());
}
long start = task.getStartTime(); // Get project initial time
if (m_startTime > start) { // If the project is previous to the report
start = m_startTime;
}
long end = task.getEndTime(); // Get project finished time
if (m_endTime < end) { // If the project is not finished
end = m_endTime;
}
m_tasksTable = m_tasksTable + task.getName() + " "
+ task.getProjectParentName() + " "
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(task.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
};
public void visitInterval(final CInterval interval) {
if (logger.isDebugEnabled()) {
logger.debug("Visiting {}", interval.getName());
}
long start = interval.getStartTime(); // Get project initial time
if (m_startTime > start) { // If the project is previous to the report
start = m_startTime;
}
long end = interval.getEndTime(); // Get project finished time
if (m_endTime < end) { // If the project is not finished
end = m_endTime;
}
m_intervalsTable = m_intervalsTable + interval.getTaskParentName() + " "
+ interval.getProjectName() + " "
+ interval.getName() + " "
+ Day.format(new Date(start)) + ", "
+ hour.format(new Date(start)) + " "
+ Day.format(new Date(end)) + ", "
+ hour.format(new Date(end)) + " "
+ duration.format(
new Date(interval.getTotalTimeWithin(m_startTime, m_endTime)))
+ "\n";
}
@Override
public void appendLineSeparator() {
m_document = m_document
+ "-------------------------------------------------------------------------\n";
}
@Override
public void appendHeader() {
appendLineSeparator(); // Line
m_document = m_document + "Report\n"; // Main title
appendLineSeparator(); // Line
m_document = m_document + "Period:\n";
m_document = m_document + "Since: "
+ Day.format(new Date(m_startTime)) + "\n";
m_document = m_document + "Until: "
+ Day.format(new Date(m_endTime)) + "\n";
m_document = m_document + "Current Date: "
+ Day.format(new Date(m_currentTime)) + "\n";
appendLineSeparator(); // Line
}
@Override
public void appendProjectsHeader() {
m_document = m_document + "First level projects: \n";
m_document = m_document + "Name | Start date |"
+ " Finish date | Total Time \n";
}
@Override
public void appendProjectsData() {
m_document = m_document + m_mainProjectsTable;
}
@Override
public void appendSubProjectsHeader() {
m_document = m_document + "Sub-projects: \n";
m_document = m_document + "Name | Belongs to |"
+ " Start date | Finish date | Total Time \n";
}
@Override
public void appendSubProjectsData() {
m_document = m_document + m_subProjectsTable;
}
@Override
public void appendTasksHeader() {
m_document = m_document + "Tasks: \n";
m_document = m_document + "Name | Parent project |"
+ " Start date | Finish date | Total Time \n";
}
@Override
public void appendTasksData() {
m_document = m_document + m_tasksTable;
}
@Override
public void appendIntervalsHeader() {
m_document = m_document + "Intervals: \n";
m_document = m_document + "Name | In task | ID |"
+ " Start date | Finish date | Total Time \n";
}
@Override
public void appendIntervalsData() {
m_document = m_document + m_intervalsTable;
}
@Override
public void generateReport() {
System.out.println(m_document);
}
/** String used to compile the whole document before generating
* the report. */
private String m_document = "";
// Tables for each important chunk of information.
private String m_mainProjectsTable = new String();
private String m_subProjectsTable = new String();
private String m_tasksTable = new String();
private String m_intervalsTable = new String();
private static Logger logger = LoggerFactory.getLogger(CVisitorFormatterText.class);
}
| 7,105 | 0.540042 | 0.539761 | 197 | 35.06599 | 26.037083 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446701 | false | false | 1 |
5284c00949acb48232e14335056df4ded606927f | 9,320,079,058,162 | 9a6ea6087367965359d644665b8d244982d1b8b6 | /src/main/java/X/C50162Tq.java | 3b764b004c945f42ddf0b80f82c40dd10ad12ae5 | []
| no_license | technocode/com.wa_2.21.2 | https://github.com/technocode/com.wa_2.21.2 | a3dd842758ff54f207f1640531374d3da132b1d2 | 3c4b6f3c7bdef7c1523c06d5bd9a90b83acc80f9 | refs/heads/master | 2023-02-12T11:20:28.666000 | 2021-01-14T10:22:21 | 2021-01-14T10:22:21 | 329,578,591 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package X;
/* renamed from: X.2Tq reason: invalid class name and case insensitive filesystem */
public class C50162Tq {
public AnonymousClass2U2 A00;
public AnonymousClass2U5 A01;
public Boolean A02;
public Boolean A03;
public Boolean A04;
public Float A05;
public Integer A06;
public Integer A07;
public Long A08;
public Long A09;
public Long A0A;
public Long A0B;
public Long A0C;
public Long A0D;
public Long A0E;
public Long A0F;
public Long A0G;
public String A0H;
public String A0I;
public String A0J;
public String A0K;
public void A00(long j) {
this.A0E = Long.valueOf(j);
}
}
| UTF-8 | Java | 688 | java | C50162Tq.java | Java | []
| null | []
| package X;
/* renamed from: X.2Tq reason: invalid class name and case insensitive filesystem */
public class C50162Tq {
public AnonymousClass2U2 A00;
public AnonymousClass2U5 A01;
public Boolean A02;
public Boolean A03;
public Boolean A04;
public Float A05;
public Integer A06;
public Integer A07;
public Long A08;
public Long A09;
public Long A0A;
public Long A0B;
public Long A0C;
public Long A0D;
public Long A0E;
public Long A0F;
public Long A0G;
public String A0H;
public String A0I;
public String A0J;
public String A0K;
public void A00(long j) {
this.A0E = Long.valueOf(j);
}
}
| 688 | 0.656977 | 0.593023 | 30 | 21.933332 | 14.507317 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766667 | false | false | 1 |
fb35685037f804bd3957add87ac0c80f4c424f8d | 19,473,381,759,865 | 848cf0c48c27097f06d560fddd4c5ff00dff3a61 | /java/limax/src/limax/switcher/LmkInfo.java | 6f933d299ee863abe786d32149035152f83cce96 | [
"MIT"
]
| permissive | k896152374/limax_5.16 | https://github.com/k896152374/limax_5.16 | 7e76d1ff3c0f5640cfa109a18490e17d60f04655 | cb243c50bbce5720da733ba913a271a5452fec04 | refs/heads/main | 2023-07-09T10:06:55.557000 | 2021-08-20T08:19:26 | 2021-08-20T08:19:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package limax.switcher;
import limax.codec.MarshalException;
import limax.codec.Octets;
import limax.codec.OctetsStream;
public final class LmkInfo {
private final String uid;
private final Octets lmkdata;
LmkInfo(String uid, Octets lmkData) {
this.uid = uid;
this.lmkdata = lmkData;
}
public LmkInfo(String uid) {
this(uid, new Octets());
}
public LmkInfo(Octets binary) throws MarshalException {
OctetsStream os = OctetsStream.wrap(binary);
this.uid = os.unmarshal_String();
this.lmkdata = os.unmarshal_Octets();
}
public Octets encode() {
return new OctetsStream().marshal(uid).marshal(lmkdata);
}
public String getUid() {
return uid;
}
public Octets getLmkData() {
return lmkdata;
}
}
| UTF-8 | Java | 766 | java | LmkInfo.java | Java | []
| null | []
| package limax.switcher;
import limax.codec.MarshalException;
import limax.codec.Octets;
import limax.codec.OctetsStream;
public final class LmkInfo {
private final String uid;
private final Octets lmkdata;
LmkInfo(String uid, Octets lmkData) {
this.uid = uid;
this.lmkdata = lmkData;
}
public LmkInfo(String uid) {
this(uid, new Octets());
}
public LmkInfo(Octets binary) throws MarshalException {
OctetsStream os = OctetsStream.wrap(binary);
this.uid = os.unmarshal_String();
this.lmkdata = os.unmarshal_Octets();
}
public Octets encode() {
return new OctetsStream().marshal(uid).marshal(lmkdata);
}
public String getUid() {
return uid;
}
public Octets getLmkData() {
return lmkdata;
}
}
| 766 | 0.686684 | 0.686684 | 37 | 18.702703 | 17.048206 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.324324 | false | false | 1 |
31a609c6969230a508f0e9407f63b4c74ff20390 | 8,022,998,966,894 | 8b2642e7fb69d7c4c2b88c67e0d7ffd8135976d0 | /sys.dao/src/core/entity/Flujo.java | 307347da2691caa15500472b73dbc322ad5cc830 | []
| no_license | jpretel/sys.core | https://github.com/jpretel/sys.core | d9de9b27d16455afac0de9be03036451dbd9e7bb | 117706942460bd243f17a06535394edabbf3f2ab | refs/heads/master | 2021-01-16T19:32:36.626000 | 2014-12-08T03:35:33 | 2014-12-08T03:35:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package core.entity;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@NamedQuery(name="Flujo.findAll", query="SELECT f FROM Flujo f")
public class Flujo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable=false, length=3)
private String idflujo;
@Column(nullable=false, length=75)
private String descripcion;
public Flujo() {
}
public String getIdflujo() {
return this.idflujo;
}
public void setIdflujo(String idflujo) {
this.idflujo = idflujo;
}
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
} | UTF-8 | Java | 728 | java | Flujo.java | Java | []
| null | []
| package core.entity;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@NamedQuery(name="Flujo.findAll", query="SELECT f FROM Flujo f")
public class Flujo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable=false, length=3)
private String idflujo;
@Column(nullable=false, length=75)
private String descripcion;
public Flujo() {
}
public String getIdflujo() {
return this.idflujo;
}
public void setIdflujo(String idflujo) {
this.idflujo = idflujo;
}
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
} | 728 | 0.699176 | 0.693681 | 39 | 16.717949 | 17.868391 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 1 |
68d79086870a20ae27bd780538974e8b3da28193 | 4,346,506,948,173 | 599b0e2208a4d7f6c101dc2f0009a0a8714e2245 | /src/main/java/com/purusottam/softwarecatalogue/bean/LicenseBean.java | a72a3153a94ddda1a1d29dc36537f0020023a451 | []
| no_license | purusottam11/software-catalogue | https://github.com/purusottam11/software-catalogue | 9058385d429ae80c39ada9f602eea7563a76ba9b | 4121a91aad6b4220d9846e02c89ed37634002fc9 | refs/heads/master | 2023-02-10T15:05:30.014000 | 2021-01-05T12:42:32 | 2021-01-05T12:42:32 | 274,862,793 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.purusottam.softwarecatalogue.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class LicenseBean {
private Long productId;
private Long versionId;
private Long productEditionId;
private String licenseType;
private Boolean trail;
private Integer period;
private Boolean production;
private Boolean test;
private Boolean development;
private Boolean training;
private Boolean otherRestrictions;
private String licenseCategory;
private String licenseCategoryDescription;
private String licenseTypeDescription;
private String licenseMetricType;
private String licenseMetricTypeDescription;
private String licenseMetricCategory;
private String licenseMetricCategoryDescription;
}
| UTF-8 | Java | 960 | java | LicenseBean.java | Java | []
| null | []
| package com.purusottam.softwarecatalogue.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class LicenseBean {
private Long productId;
private Long versionId;
private Long productEditionId;
private String licenseType;
private Boolean trail;
private Integer period;
private Boolean production;
private Boolean test;
private Boolean development;
private Boolean training;
private Boolean otherRestrictions;
private String licenseCategory;
private String licenseCategoryDescription;
private String licenseTypeDescription;
private String licenseMetricType;
private String licenseMetricTypeDescription;
private String licenseMetricCategory;
private String licenseMetricCategoryDescription;
}
| 960 | 0.736458 | 0.736458 | 50 | 17.200001 | 17.254564 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46 | false | false | 1 |
863aa62aae739446c863469995f0aaa551791868 | 3,710,851,807,711 | fb82d1be40342378fcfdb0ac3185f19f27fb0e84 | /src/main/java/StepProjectBooking/service/UserService.java | 85233905483b62812d547f828c64524dc97d1f7f | []
| no_license | shahsevil/StepProjectBooking | https://github.com/shahsevil/StepProjectBooking | 92bfb18ea728ac035eab626772206f55ca616fcd | 1ba5d52f247b983f6f6a7ab6a9a158f76210c24e | refs/heads/master | 2021-12-27T22:07:41.845000 | 2020-06-14T20:49:23 | 2020-06-14T20:49:23 | 248,303,403 | 0 | 1 | null | false | 2020-03-19T23:01:36 | 2020-03-18T17:50:40 | 2020-03-19T20:34:03 | 2020-03-19T23:01:35 | 13 | 0 | 1 | 0 | Java | false | false | package StepProjectBooking.service;
import StepProjectBooking.DAO.DAOUser;
import StepProjectBooking.database.DAOUserFileText;
import StepProjectBooking.entity.User;
import java.util.List;
public class UserService implements DAOUser<User> {
private DAOUser<User> userDAO = new DAOUserFileText();
@Override
public List<User> getAll() {
return userDAO.getAll();
}
public void save(User user) {
if (!user.getName().equals("") && !user.getPassword().equals("")) {
userDAO.save(user);
} else {
new IllegalArgumentException();
}
}
@Override
public boolean delete(String name) {
userDAO.delete(name);
return false;
}
@Override
public User get(int id) {
return null;
}
public void SaveData(String fileName) {
userDAO.SaveData(fileName);
}
public void ReadData(String fileName) {
userDAO.ReadData(fileName);
}
@Override
public void LoadData(List<User> users) {
}
}
| UTF-8 | Java | 1,040 | java | UserService.java | Java | []
| null | []
| package StepProjectBooking.service;
import StepProjectBooking.DAO.DAOUser;
import StepProjectBooking.database.DAOUserFileText;
import StepProjectBooking.entity.User;
import java.util.List;
public class UserService implements DAOUser<User> {
private DAOUser<User> userDAO = new DAOUserFileText();
@Override
public List<User> getAll() {
return userDAO.getAll();
}
public void save(User user) {
if (!user.getName().equals("") && !user.getPassword().equals("")) {
userDAO.save(user);
} else {
new IllegalArgumentException();
}
}
@Override
public boolean delete(String name) {
userDAO.delete(name);
return false;
}
@Override
public User get(int id) {
return null;
}
public void SaveData(String fileName) {
userDAO.SaveData(fileName);
}
public void ReadData(String fileName) {
userDAO.ReadData(fileName);
}
@Override
public void LoadData(List<User> users) {
}
}
| 1,040 | 0.630769 | 0.630769 | 49 | 20.224489 | 19.213373 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 1 |
07bc298c01db53c5d1779111e4f6e559bfb5c7b9 | 3,066,606,696,453 | cfe30f9f6ae678ea5899410f2add91762967144d | /msg/esper/src/main/java/com/demo/event/Header.java | e133f2e29f3fc13c939345158199107cee3562fe | []
| no_license | pingpangkuangmo/framework | https://github.com/pingpangkuangmo/framework | da46012244839e70bb314acdef5a2aa5c356b848 | 76164673e7049474887d175e095616d5dd67e489 | refs/heads/master | 2020-05-21T20:18:25.505000 | 2017-06-10T03:07:49 | 2017-06-10T03:07:49 | 35,748,076 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.event;
/**
* @author lg
* Date: 4/13/17
* Time: 3:08 PM
*/
public class Header {
private String entry;
private String appId;
private String hostIp;
private String hostName;
private String id;
private String msg;
private String cluster;
private String ezone;
private String idc;
private String requestId;
private String addition;
private int rpcLevel;
public String getEntry() {
return entry;
}
public void setEntry(String entry) {
this.entry = entry;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getHostIp() {
return hostIp;
}
public void setHostIp(String hostIp) {
this.hostIp = hostIp;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getEzone() {
return ezone;
}
public void setEzone(String ezone) {
this.ezone = ezone;
}
public String getIdc() {
return idc;
}
public void setIdc(String idc) {
this.idc = idc;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getAddition() {
return addition;
}
public void setAddition(String addition) {
this.addition = addition;
}
public int getRpcLevel() {
return rpcLevel;
}
public void setRpcLevel(int rpcLevel) {
this.rpcLevel = rpcLevel;
}
}
| UTF-8 | Java | 2,120 | java | Header.java | Java | [
{
"context": "package com.demo.event;\n\n/**\n * @author lg\n * Date: 4/13/17\n * Time: 3:08 PM",
"end": 42,
"score": 0.9948427081108093,
"start": 40,
"tag": "USERNAME",
"value": "lg"
}
]
| null | []
| package com.demo.event;
/**
* @author lg
* Date: 4/13/17
* Time: 3:08 PM
*/
public class Header {
private String entry;
private String appId;
private String hostIp;
private String hostName;
private String id;
private String msg;
private String cluster;
private String ezone;
private String idc;
private String requestId;
private String addition;
private int rpcLevel;
public String getEntry() {
return entry;
}
public void setEntry(String entry) {
this.entry = entry;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getHostIp() {
return hostIp;
}
public void setHostIp(String hostIp) {
this.hostIp = hostIp;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getEzone() {
return ezone;
}
public void setEzone(String ezone) {
this.ezone = ezone;
}
public String getIdc() {
return idc;
}
public void setIdc(String idc) {
this.idc = idc;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getAddition() {
return addition;
}
public void setAddition(String addition) {
this.addition = addition;
}
public int getRpcLevel() {
return rpcLevel;
}
public void setRpcLevel(int rpcLevel) {
this.rpcLevel = rpcLevel;
}
}
| 2,120 | 0.575472 | 0.571698 | 118 | 16.966103 | 14.369184 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.313559 | false | false | 1 |
8e0155e2601c17a0db28179a36c12c0277cc1fbd | 3,066,606,698,886 | a852d14809a089e69bf8cf83a4c5589d2989100f | /AAPL/src/com/pwc/in/aapl/web/action/registration/TerminationMemberDetailsAction.java | 254ee86099f53089ec04ff0cc0001e72ee5d15ce | []
| no_license | s-a-n-d-y/Chain_Business_Monitor | https://github.com/s-a-n-d-y/Chain_Business_Monitor | 8fdc9c72bfcf4a7b1d4920d4104669b5930a0c08 | eeac126ea7400e5406154ca116cc0207c31b2e94 | refs/heads/master | 2017-12-08T09:28:57.192000 | 2017-01-16T19:31:12 | 2017-01-16T19:31:12 | 79,151,866 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pwc.in.aapl.web.action.registration;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import com.pwc.in.aapl.app.business.dto.user.AAPLMemberDto;
import com.pwc.in.aapl.app.business.dto.user.TerminateMemberDto;
import com.pwc.in.aapl.app.business.facade.admin.IRankMasterBusiness;
import com.pwc.in.aapl.app.business.facade.claim.IClaimBusiness;
import com.pwc.in.aapl.app.business.facade.commission.ICommissionDistributionSearchBusiness;
import com.pwc.in.aapl.app.business.facade.common.IMemberSearchBusiness;
import com.pwc.in.aapl.app.business.facade.registration.IRegistrationBusiness;
import com.pwc.in.aapl.app.data.dataAccessor.commission.CommissionDistributionSearchDataAccessor;
import com.pwc.in.aapl.app.exception.AAPLException;
import com.pwc.in.aapl.web.action.common.AAPLAction;
import com.pwc.in.aapl.web.action.common.CustomerSearchAction;
import com.pwc.in.aapl.web.forms.commission.CommissionDistributionSearchForm;
import com.pwc.in.aapl.web.forms.registration.EditExistingMember;
import com.pwc.in.aapl.web.utils.AAPLConstants;
public class TerminationMemberDetailsAction extends AAPLAction {
private Logger logger = Logger.getLogger(EditExistingmemberAction.class);
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("inside TerminationMemberDetailsAction :: start ");
String path = "";
ApplicationContext context = getWebApplicationContext();
List<TerminateMemberDto> terminateMemberList = null;
IClaimBusiness claimBusiness = (IClaimBusiness) context.getBean(AAPLConstants.CLAIM_ACCESSOR);
try{
terminateMemberList =claimBusiness.getTerminateMemberDetails(context);
System.out.println("terminateMemberList Size in TerminationMemberDetailsAction "+terminateMemberList.size());
if(terminateMemberList!=null && terminateMemberList.size()>0)
{
request.setAttribute("terminateMemberList", terminateMemberList);
}
else
{
request.setAttribute("DATA_NOT_FOUND", "No Data");
}
path = "getTerminatedMemberInput";
}catch(AAPLException e)
{
System.err.println(" TerminationMemberDetailsAction AAPLException " + e);
logger.error("TerminationMemberDetailsAction AAPLException ", e);
e.printStackTrace();
path = "global.aapl.error";
}
System.out.println("inside TerminationMemberDetailsAction :: end forwarding " + path);
return mapping.findForward(path);
}
}
| UTF-8 | Java | 3,024 | java | TerminationMemberDetailsAction.java | Java | []
| null | []
| package com.pwc.in.aapl.web.action.registration;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import com.pwc.in.aapl.app.business.dto.user.AAPLMemberDto;
import com.pwc.in.aapl.app.business.dto.user.TerminateMemberDto;
import com.pwc.in.aapl.app.business.facade.admin.IRankMasterBusiness;
import com.pwc.in.aapl.app.business.facade.claim.IClaimBusiness;
import com.pwc.in.aapl.app.business.facade.commission.ICommissionDistributionSearchBusiness;
import com.pwc.in.aapl.app.business.facade.common.IMemberSearchBusiness;
import com.pwc.in.aapl.app.business.facade.registration.IRegistrationBusiness;
import com.pwc.in.aapl.app.data.dataAccessor.commission.CommissionDistributionSearchDataAccessor;
import com.pwc.in.aapl.app.exception.AAPLException;
import com.pwc.in.aapl.web.action.common.AAPLAction;
import com.pwc.in.aapl.web.action.common.CustomerSearchAction;
import com.pwc.in.aapl.web.forms.commission.CommissionDistributionSearchForm;
import com.pwc.in.aapl.web.forms.registration.EditExistingMember;
import com.pwc.in.aapl.web.utils.AAPLConstants;
public class TerminationMemberDetailsAction extends AAPLAction {
private Logger logger = Logger.getLogger(EditExistingmemberAction.class);
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("inside TerminationMemberDetailsAction :: start ");
String path = "";
ApplicationContext context = getWebApplicationContext();
List<TerminateMemberDto> terminateMemberList = null;
IClaimBusiness claimBusiness = (IClaimBusiness) context.getBean(AAPLConstants.CLAIM_ACCESSOR);
try{
terminateMemberList =claimBusiness.getTerminateMemberDetails(context);
System.out.println("terminateMemberList Size in TerminationMemberDetailsAction "+terminateMemberList.size());
if(terminateMemberList!=null && terminateMemberList.size()>0)
{
request.setAttribute("terminateMemberList", terminateMemberList);
}
else
{
request.setAttribute("DATA_NOT_FOUND", "No Data");
}
path = "getTerminatedMemberInput";
}catch(AAPLException e)
{
System.err.println(" TerminationMemberDetailsAction AAPLException " + e);
logger.error("TerminationMemberDetailsAction AAPLException ", e);
e.printStackTrace();
path = "global.aapl.error";
}
System.out.println("inside TerminationMemberDetailsAction :: end forwarding " + path);
return mapping.findForward(path);
}
}
| 3,024 | 0.780093 | 0.779431 | 76 | 37.763157 | 30.853588 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.881579 | false | false | 1 |
5eedad97cce72892bd30db13f1d1239cf81476ee | 5,892,695,193,386 | 9d360588130e71be5435fab071ef876cbe482f6b | /Student/src/cn/com/zjf/model/PageModel.java | 20b53b13cbec3a818e78ceaa4dc879d1ecb807d9 | []
| no_license | poai/struts2_demo | https://github.com/poai/struts2_demo | 3502a80efad77dc2e7830b8dd5b65474b567247e | 18425e9cca665aa93165ea55993dbdaae2e73c8f | refs/heads/master | 2020-02-26T15:28:13.078000 | 2016-06-04T05:31:54 | 2016-06-04T05:31:54 | 60,394,898 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.com.zjf.model;
import java.io.Serializable;
import java.util.List;
/**/
public class PageModel<T> implements Serializable{
private static final long serialVersionUID = 1L;
private int page;
private int total;
private List<T> data;
private int size;
private String sql;
public PageModel() {
}
public PageModel(int page, int size, String sql) {
super();
this.page = page;
this.size = size;
this.sql = sql;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "PageModel [page=" + page + ", total=" + total + ", data=" + data + ", size=" + size + ", sql=" + sql
+ "]";
}
}
| UTF-8 | Java | 1,256 | java | PageModel.java | Java | []
| null | []
| package cn.com.zjf.model;
import java.io.Serializable;
import java.util.List;
/**/
public class PageModel<T> implements Serializable{
private static final long serialVersionUID = 1L;
private int page;
private int total;
private List<T> data;
private int size;
private String sql;
public PageModel() {
}
public PageModel(int page, int size, String sql) {
super();
this.page = page;
this.size = size;
this.sql = sql;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "PageModel [page=" + page + ", total=" + total + ", data=" + data + ", size=" + size + ", sql=" + sql
+ "]";
}
}
| 1,256 | 0.61465 | 0.613854 | 65 | 17.323076 | 17.689726 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.646154 | false | false | 1 |
7498451904a2d50113d38369bc5a12df13e697c0 | 31,430,570,735,652 | e22ac9cdc7b65d98f44919a7dfe8f33275d7c659 | /SelfBinarySearchTree.java | 63f0b6d7df1f409a5f0f24511936e1b6efa30665 | []
| no_license | Ashitosh-Godse/Leetcode_Problems | https://github.com/Ashitosh-Godse/Leetcode_Problems | 32e241190963631cb0e1ec4d2d32559b1982cf73 | 96934b0c5d4d10fef977641799e3fde4764f7361 | refs/heads/main | 2023-08-10T18:44:50.173000 | 2021-09-26T14:32:34 | 2021-09-26T14:32:34 | 410,567,667 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
class BST{
static BSTNode createNode(int val) {
BSTNode a=new BSTNode(val);
a.left=null;
a.right=null;
return a;
}
static BSTNode insert( BSTNode root,int val) {
if(root==null) {
return createNode(val);
}
else if(val<root.data) {
root.left=insert(root.left,val);
}else {
root.right=insert(root.right,val);
}
return root;
}
}
public class SelfBinarySearchTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
BST t=new BST();
BSTNode root=null;
t.insert(root, 8);
t.insert(root, 3);
t.insert(root, 9);
}
}
class BSTNode{
BSTNode left,right;
int data;
BSTNode(int data){
this.data=data;
this.left=this.right=null;
}
}
| UTF-8 | Java | 746 | java | SelfBinarySearchTree.java | Java | []
| null | []
| package leetcode;
class BST{
static BSTNode createNode(int val) {
BSTNode a=new BSTNode(val);
a.left=null;
a.right=null;
return a;
}
static BSTNode insert( BSTNode root,int val) {
if(root==null) {
return createNode(val);
}
else if(val<root.data) {
root.left=insert(root.left,val);
}else {
root.right=insert(root.right,val);
}
return root;
}
}
public class SelfBinarySearchTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
BST t=new BST();
BSTNode root=null;
t.insert(root, 8);
t.insert(root, 3);
t.insert(root, 9);
}
}
class BSTNode{
BSTNode left,right;
int data;
BSTNode(int data){
this.data=data;
this.left=this.right=null;
}
}
| 746 | 0.640751 | 0.636729 | 49 | 14.22449 | 13.130841 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.918367 | false | false | 1 |
684a677f9749a5b0f71924a8c97d706b3bb95fe0 | 24,627,342,533,696 | 241596e4382318140565699a871241a76910de2a | /day10_01_session/src/com/heima/car/servlet/CarServlet.java | c0fba8beb7654cfed8d51596c5115db6bc66dd18 | [
"Apache-2.0"
]
| permissive | weiwenqiang/MyEclipse_DarkHorse | https://github.com/weiwenqiang/MyEclipse_DarkHorse | ff7eb59cdf6476e369e02b62cde97f8ea30c9e5b | c7729803b5e4f49ffc5cb7e3389df2581fa38595 | refs/heads/master | 2021-08-11T03:18:53.676000 | 2017-11-13T05:25:39 | 2017-11-13T05:25:39 | 107,613,325 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.heima.car.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.heima.car.bean.Book;
//显示购物车中的内容
public class CarServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8") ;
response.setContentType("text/html;charset=UTF-8") ;
PrintWriter out = response.getWriter() ;
HttpSession session = request.getSession() ;
//如果用户直接在地址栏中输入地址访问此servlet,那此时session是一个新创建的对象
if(session.isNew()){
//直接返回主页面
response.sendRedirect(request.getContextPath() + "/servlet/ShowAllBookServlet") ;
return ;
}
//先从session拿到购物车
List<Book> list = (List<Book>)session.getAttribute("carlist") ;
//如果用户直接从主页面上点击查看购物车过来,此时还没有购买任何书籍呢,所以提示用户会主页
if(list == null){
//用户首次访问购物车
out.write("你还没有购买任何书籍呢,看个鸟啊,2秒后转向主页") ;
response.setHeader("Refresh", "2;url="+ request.getContextPath() + "/servlet/ShowAllBookServlet") ;
return ;
}
//说明购买了书籍
out.write("你购买的书籍如下:<br> ") ;
out.write("书名\t数量\t总价格<br>") ;
for (int i = 0; i < list.size(); i++) {
Book b = list.get(i) ;
out.write(b.getBookName() + "\t" + b.getCount() + "\t" + b.getPrice() * b.getCount() + "<br>") ;
}
out.write("<br><br><a href = '" +request.getContextPath()+ "/servlet/ShowAllBookServlet'>返回主页面</a>") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
| GB18030 | Java | 2,084 | java | CarServlet.java | Java | []
| null | []
| package com.heima.car.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.heima.car.bean.Book;
//显示购物车中的内容
public class CarServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8") ;
response.setContentType("text/html;charset=UTF-8") ;
PrintWriter out = response.getWriter() ;
HttpSession session = request.getSession() ;
//如果用户直接在地址栏中输入地址访问此servlet,那此时session是一个新创建的对象
if(session.isNew()){
//直接返回主页面
response.sendRedirect(request.getContextPath() + "/servlet/ShowAllBookServlet") ;
return ;
}
//先从session拿到购物车
List<Book> list = (List<Book>)session.getAttribute("carlist") ;
//如果用户直接从主页面上点击查看购物车过来,此时还没有购买任何书籍呢,所以提示用户会主页
if(list == null){
//用户首次访问购物车
out.write("你还没有购买任何书籍呢,看个鸟啊,2秒后转向主页") ;
response.setHeader("Refresh", "2;url="+ request.getContextPath() + "/servlet/ShowAllBookServlet") ;
return ;
}
//说明购买了书籍
out.write("你购买的书籍如下:<br> ") ;
out.write("书名\t数量\t总价格<br>") ;
for (int i = 0; i < list.size(); i++) {
Book b = list.get(i) ;
out.write(b.getBookName() + "\t" + b.getCount() + "\t" + b.getPrice() * b.getCount() + "<br>") ;
}
out.write("<br><br><a href = '" +request.getContextPath()+ "/servlet/ShowAllBookServlet'>返回主页面</a>") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
| 2,084 | 0.711712 | 0.708896 | 59 | 29.101694 | 27.34878 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.135593 | false | false | 1 |
97a0f73e1f48ca8649cac676127696b2852f22d4 | 8,839,042,759,533 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/22/22_a19492dbf2ad31247202a80bf64bfb54e0b765db/RedexAlter/22_a19492dbf2ad31247202a80bf64bfb54e0b765db_RedexAlter_s.java | dd4501ffa291b926adf602807e29f5d0ac08b164 | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | /*
* Copyright (c) 2012. Redex Scripting - Unauthorized use prohibited by author.
*/
package RedexAlter;
import org.powerbot.game.api.ActiveScript;
import org.powerbot.game.bot.event.listener.PaintListener;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: 0xe9
* Date: 6/23/12
* Time: 4:45 PM
*/
public class RedexAlter extends ActiveScript implements PaintListener {
@Override
protected void setup() {
}
@Override
public void onRepaint(Graphics g) {
}
}
| UTF-8 | Java | 532 | java | 22_a19492dbf2ad31247202a80bf64bfb54e0b765db_RedexAlter_s.java | Java | [
{
"context": "*;\n \n /**\n * Created by IntelliJ IDEA.\n * User: 0xe9\n * Date: 6/23/12\n * Time: 4:45 PM\n */\n public ",
"end": 292,
"score": 0.9992453455924988,
"start": 288,
"tag": "USERNAME",
"value": "0xe9"
}
]
| null | []
| /*
* Copyright (c) 2012. Redex Scripting - Unauthorized use prohibited by author.
*/
package RedexAlter;
import org.powerbot.game.api.ActiveScript;
import org.powerbot.game.bot.event.listener.PaintListener;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: 0xe9
* Date: 6/23/12
* Time: 4:45 PM
*/
public class RedexAlter extends ActiveScript implements PaintListener {
@Override
protected void setup() {
}
@Override
public void onRepaint(Graphics g) {
}
}
| 532 | 0.656015 | 0.629699 | 29 | 17.310345 | 21.630285 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.137931 | false | false | 1 |
04a7f6c2647bbc122d8b4936e9feada3b0d587b9 | 23,742,579,269,214 | 6f356af61b6a00bbd3064882ad16f77b814edecc | /common-api/src/main/java/cn/stylefeng/guns/cloud/api/product/model/params/GunsProQueryParam.java | 9e82f4083844f98520142f230ec4df04dadd1367 | []
| no_license | xwb666666/sp_server | https://github.com/xwb666666/sp_server | 7ebc34b0ea991aca0786520207fedfa69ac17de2 | a8ed11913586cafa80778d0e9900b55bfc540e2b | refs/heads/master | 2023-06-25T07:41:48.280000 | 2021-05-31T01:36:03 | 2021-05-31T01:37:30 | 387,706,227 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.stylefeng.guns.cloud.api.product.model.params;
import lombok.Data;
/**
* 查询商品列表请求参数
*/
@Data
public class GunsProQueryParam {
private String name;
private String code;
private Integer status;
private Long cateId;
private Long groupId;
private Long pageSize=20l;
private Long page=1l;
}
| UTF-8 | Java | 350 | java | GunsProQueryParam.java | Java | []
| null | []
| package cn.stylefeng.guns.cloud.api.product.model.params;
import lombok.Data;
/**
* 查询商品列表请求参数
*/
@Data
public class GunsProQueryParam {
private String name;
private String code;
private Integer status;
private Long cateId;
private Long groupId;
private Long pageSize=20l;
private Long page=1l;
}
| 350 | 0.709091 | 0.7 | 18 | 17.333334 | 14.992591 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
46b6e78f3c04d9efe61e0b73001599d281a33d42 | 22,359,599,795,936 | eec09d07a4196c6a0d7261ec91a219b65da148a4 | /05-jaxws-client-wsimport/src/main/java/pl/pg/asobecki/wai/jaxws/Main.java | ed3c35617577391064b19f48e4108a570964c390 | []
| no_license | asobecki/wai-pg | https://github.com/asobecki/wai-pg | 176fa64cdef7844be89c709b3c7a2947378d6648 | b40b1dde12288db81601e34dce2e30c197596c42 | refs/heads/master | 2023-01-24T17:28:43.994000 | 2022-03-03T14:32:21 | 2022-03-03T14:32:21 | 86,552,591 | 5 | 1 | null | false | 2023-01-07T05:52:12 | 2017-03-29T07:39:18 | 2022-06-06T16:21:54 | 2023-01-07T05:52:12 | 11,096 | 3 | 0 | 20 | C# | false | false | package pl.pg.asobecki.wai.jaxws;
public class Main {
public static void main(String[] args) {
FirstWebServiceImplService firstWebServiceImplService = new FirstWebServiceImplService();
FirstWebService service = firstWebServiceImplService.getFirstWebServiceImplPort();
System.out.println(service.getFirstWebServiceAsString("test string"));
}
}
| UTF-8 | Java | 374 | java | Main.java | Java | []
| null | []
| package pl.pg.asobecki.wai.jaxws;
public class Main {
public static void main(String[] args) {
FirstWebServiceImplService firstWebServiceImplService = new FirstWebServiceImplService();
FirstWebService service = firstWebServiceImplService.getFirstWebServiceImplPort();
System.out.println(service.getFirstWebServiceAsString("test string"));
}
}
| 374 | 0.764706 | 0.764706 | 10 | 36.400002 | 36.307575 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
9e255db020c9bc13e204d0ed9676a4b82307ff0b | 274,877,975,699 | fd8ff90309352fc46d6d7e57ed390d33f57c185c | /backend/src/test/java/br/com/basis/abaco/web/rest/AlrResourceIT.java | fe9ace1c15f894c4b558b7d8ae0287a81d368c86 | []
| no_license | BasisTI/abaco | https://github.com/BasisTI/abaco | 2c30d5f67317b0df424517bd8029e4c02119d523 | 057058aebd8820c0ff2329d5517c20cadee52196 | refs/heads/master | 2021-12-03T02:55:18.623000 | 2021-11-27T03:15:01 | 2021-11-27T03:15:01 | 432,338,982 | 2 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.basis.abaco.web.rest;
import br.com.basis.abaco.AbacoApp;
import br.com.basis.abaco.domain.Alr;
import br.com.basis.abaco.repository.AlrRepository;
import br.com.basis.abaco.repository.search.AlrSearchRepository;
import br.com.basis.abaco.service.AlrService;
import br.com.basis.abaco.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AlrResource REST controller.
*
* @see AlrResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AbacoApp.class)
public class AlrResourceIT {
@Autowired
private AlrRepository alrRepository;
@Autowired
private AlrSearchRepository alrSearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restAlrMockMvc;
private Alr alr;
@Autowired
private AlrService alrService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
AlrResource alrResource = new AlrResource(alrRepository, alrSearchRepository, alrService);
this.restAlrMockMvc = MockMvcBuilders.standaloneSetup(alrResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Alr createEntity(EntityManager em) {
Alr alr = new Alr();
return alr;
}
@Before
public void initTest() {
alrSearchRepository.deleteAll();
alr = createEntity(em);
}
@Test
@Transactional
public void createAlr() throws Exception {
int databaseSizeBeforeCreate = alrRepository.findAll().size();
// Create the Alr
restAlrMockMvc.perform(post("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(alr)))
.andExpect(status().isCreated());
// Validate the Alr in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeCreate + 1);
Alr testAlr = alrList.get(alrList.size() - 1);
// Validate the Alr in Elasticsearch
Alr alrEs = alrSearchRepository.findOne(testAlr.getId());
assertThat(alrEs).isEqualToComparingFieldByField(testAlr);
}
@Test
@Transactional
public void createAlrWithExistingId() throws Exception {
int databaseSizeBeforeCreate = alrRepository.findAll().size();
// Create the Alr with an existing ID
Alr existingAlr = new Alr();
existingAlr.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restAlrMockMvc.perform(post("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(existingAlr)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllAlrs() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
// Get all the alrList
restAlrMockMvc.perform(get("/api/alrs?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(alr.getId().intValue())));
}
@Test
@Transactional
public void getAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
// Get the alr
restAlrMockMvc.perform(get("/api/alrs/{id}", alr.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(alr.getId().intValue()));
}
@Test
@Transactional
public void getNonExistingAlr() throws Exception {
// Get the alr
restAlrMockMvc.perform(get("/api/alrs/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
alrSearchRepository.save(alr);
int databaseSizeBeforeUpdate = alrRepository.findAll().size();
// Update the alr
Alr updatedAlr = alrRepository.findOne(alr.getId());
restAlrMockMvc.perform(put("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedAlr)))
.andExpect(status().isOk());
// Validate the Alr in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeUpdate);
Alr testAlr = alrList.get(alrList.size() - 1);
// Validate the Alr in Elasticsearch
Alr alrEs = alrSearchRepository.findOne(testAlr.getId());
assertThat(alrEs).isEqualToComparingFieldByField(testAlr);
}
@Test
@Transactional
public void updateNonExistingAlr() throws Exception {
int databaseSizeBeforeUpdate = alrRepository.findAll().size();
// Create the Alr
// If the entity doesn't have an ID, it will be created instead of just being updated
restAlrMockMvc.perform(put("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(alr)))
.andExpect(status().isCreated());
// Validate the Alr in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
alrSearchRepository.save(alr);
int databaseSizeBeforeDelete = alrRepository.findAll().size();
// Get the alr
restAlrMockMvc.perform(delete("/api/alrs/{id}", alr.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean alrExistsInEs = alrSearchRepository.exists(alr.getId());
assertThat(alrExistsInEs).isFalse();
// Validate the database is empty
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
alrSearchRepository.save(alr);
// Search the alr
restAlrMockMvc.perform(get("/api/_search/alrs?query=id:" + alr.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(alr.getId().intValue())));
}
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Alr.class);
}
}
| UTF-8 | Java | 8,715 | java | AlrResourceIT.java | Java | []
| null | []
| package br.com.basis.abaco.web.rest;
import br.com.basis.abaco.AbacoApp;
import br.com.basis.abaco.domain.Alr;
import br.com.basis.abaco.repository.AlrRepository;
import br.com.basis.abaco.repository.search.AlrSearchRepository;
import br.com.basis.abaco.service.AlrService;
import br.com.basis.abaco.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AlrResource REST controller.
*
* @see AlrResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AbacoApp.class)
public class AlrResourceIT {
@Autowired
private AlrRepository alrRepository;
@Autowired
private AlrSearchRepository alrSearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restAlrMockMvc;
private Alr alr;
@Autowired
private AlrService alrService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
AlrResource alrResource = new AlrResource(alrRepository, alrSearchRepository, alrService);
this.restAlrMockMvc = MockMvcBuilders.standaloneSetup(alrResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Alr createEntity(EntityManager em) {
Alr alr = new Alr();
return alr;
}
@Before
public void initTest() {
alrSearchRepository.deleteAll();
alr = createEntity(em);
}
@Test
@Transactional
public void createAlr() throws Exception {
int databaseSizeBeforeCreate = alrRepository.findAll().size();
// Create the Alr
restAlrMockMvc.perform(post("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(alr)))
.andExpect(status().isCreated());
// Validate the Alr in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeCreate + 1);
Alr testAlr = alrList.get(alrList.size() - 1);
// Validate the Alr in Elasticsearch
Alr alrEs = alrSearchRepository.findOne(testAlr.getId());
assertThat(alrEs).isEqualToComparingFieldByField(testAlr);
}
@Test
@Transactional
public void createAlrWithExistingId() throws Exception {
int databaseSizeBeforeCreate = alrRepository.findAll().size();
// Create the Alr with an existing ID
Alr existingAlr = new Alr();
existingAlr.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restAlrMockMvc.perform(post("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(existingAlr)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllAlrs() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
// Get all the alrList
restAlrMockMvc.perform(get("/api/alrs?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(alr.getId().intValue())));
}
@Test
@Transactional
public void getAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
// Get the alr
restAlrMockMvc.perform(get("/api/alrs/{id}", alr.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(alr.getId().intValue()));
}
@Test
@Transactional
public void getNonExistingAlr() throws Exception {
// Get the alr
restAlrMockMvc.perform(get("/api/alrs/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
alrSearchRepository.save(alr);
int databaseSizeBeforeUpdate = alrRepository.findAll().size();
// Update the alr
Alr updatedAlr = alrRepository.findOne(alr.getId());
restAlrMockMvc.perform(put("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedAlr)))
.andExpect(status().isOk());
// Validate the Alr in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeUpdate);
Alr testAlr = alrList.get(alrList.size() - 1);
// Validate the Alr in Elasticsearch
Alr alrEs = alrSearchRepository.findOne(testAlr.getId());
assertThat(alrEs).isEqualToComparingFieldByField(testAlr);
}
@Test
@Transactional
public void updateNonExistingAlr() throws Exception {
int databaseSizeBeforeUpdate = alrRepository.findAll().size();
// Create the Alr
// If the entity doesn't have an ID, it will be created instead of just being updated
restAlrMockMvc.perform(put("/api/alrs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(alr)))
.andExpect(status().isCreated());
// Validate the Alr in the database
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
alrSearchRepository.save(alr);
int databaseSizeBeforeDelete = alrRepository.findAll().size();
// Get the alr
restAlrMockMvc.perform(delete("/api/alrs/{id}", alr.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean alrExistsInEs = alrSearchRepository.exists(alr.getId());
assertThat(alrExistsInEs).isFalse();
// Validate the database is empty
List<Alr> alrList = alrRepository.findAll();
assertThat(alrList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchAlr() throws Exception {
// Initialize the database
alrRepository.saveAndFlush(alr);
alrSearchRepository.save(alr);
// Search the alr
restAlrMockMvc.perform(get("/api/_search/alrs?query=id:" + alr.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(alr.getId().intValue())));
}
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Alr.class);
}
}
| 8,715 | 0.684337 | 0.682387 | 254 | 33.311024 | 26.378262 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.377953 | false | false | 1 |
d1cdf286fb28450d16cf7b5069f08631dcbfadc8 | 20,736,102,170,267 | 5c3e134352f5bbe08291611db22d5ff8fb58b90d | /Triangle/AbstractSyntaxTrees/RunCommand.java | 9c1264461cd923ce2fbbec0b68e394f7be0ebcdc | []
| no_license | RachitVargas/Triangulo | https://github.com/RachitVargas/Triangulo | 2ad4da14f73b21d2aca6b87378efd3f27893fcc8 | 95b3dbcb4c234a1924cb787f90ce844ef18aafeb | refs/heads/feature/parteRachit | 2023-04-08T02:23:16.715000 | 2021-04-20T18:08:29 | 2021-04-20T18:08:29 | 345,252,396 | 0 | 0 | null | false | 2021-04-20T18:08:30 | 2021-03-07T03:47:01 | 2021-04-20T00:55:58 | 2021-04-20T18:08:29 | 72 | 0 | 0 | 0 | Java | false | false | package Triangle.AbstractSyntaxTrees;
import Triangle.SyntacticAnalyzer.SourcePosition;
public class RunCommand extends Command{
public IntegerLiteral I;
public Command C;
public RunCommand(IntegerLiteral ilAST,Command cAST, SourcePosition sourcePosition){
super(sourcePosition);
I = ilAST;
C = cAST;
}
public Object visit(Visitor v, Object o){
return v.visitRunCommand(this,o);
}
}
| UTF-8 | Java | 443 | java | RunCommand.java | Java | []
| null | []
| package Triangle.AbstractSyntaxTrees;
import Triangle.SyntacticAnalyzer.SourcePosition;
public class RunCommand extends Command{
public IntegerLiteral I;
public Command C;
public RunCommand(IntegerLiteral ilAST,Command cAST, SourcePosition sourcePosition){
super(sourcePosition);
I = ilAST;
C = cAST;
}
public Object visit(Visitor v, Object o){
return v.visitRunCommand(this,o);
}
}
| 443 | 0.704289 | 0.704289 | 18 | 23.611111 | 23.063051 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 1 |
f5ba49c0d859a1d430cc293187443a81787d2f67 | 25,005,299,616,428 | df2345b0c6dbdefaad1520a9966e2cac2c590f31 | /java/src/jsrl/net/NeighborWatchListener.java | c6256c31ae2a62296455b3beb84345b5bc12bc29 | [
"MIT"
]
| permissive | 311labs/SRL | https://github.com/311labs/SRL | 7f02fda6fb742cb1b30a61cc6cee655babb7d4e8 | c3f0069270ada3784f2a81d9ec9e390e31e53a59 | refs/heads/master | 2021-03-13T00:00:14.908000 | 2014-08-03T16:19:12 | 2014-08-03T16:19:12 | 22,578,454 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jsrl.net;
import java.util.List;
/**
* @author ians
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public interface NeighborWatchListener
{
public void neighbor_change(List<String> available_list);
}
| UTF-8 | Java | 302 | java | NeighborWatchListener.java | Java | [
{
"context": " jsrl.net;\n\nimport java.util.List;\n\n/**\n * @author ians\n *\n * TODO To change the template for this genera",
"end": 62,
"score": 0.9983494281768799,
"start": 58,
"tag": "USERNAME",
"value": "ians"
}
]
| null | []
| package jsrl.net;
import java.util.List;
/**
* @author ians
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public interface NeighborWatchListener
{
public void neighbor_change(List<String> available_list);
}
| 302 | 0.735099 | 0.735099 | 14 | 20.571428 | 24.097168 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 1 |
5b3c881315a48c9d734357447d2b8770ec09cad0 | 27,101,243,672,258 | 3433ae5352c44930ff2bd4cb410b4d140f48d048 | /src/main/java/ac/za/cput/chapter5/stuctural/composite/Person.java | edb9cada63de1681f9df256caa2ced4d35bb79a5 | []
| no_license | K-Otto/chapter5 | https://github.com/K-Otto/chapter5 | c6c230d9b0da4bf310258b01a63b9f9bad2487f0 | 85d3d29fe55e426c22fda33f37abf6c0a9911399 | refs/heads/master | 2020-11-26T14:01:29.638000 | 2015-03-13T17:21:03 | 2015-03-13T17:21:03 | 32,170,010 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ac.za.cput.chapter5.stuctural.composite;
/**
* Created by student on 2015/03/13.
*/
public class Person implements Component{
String name;
public Person(String name) {
this.name = name;
}
public void sayHello() {
System.out.println(name + " person says hello");
}
public void sayGoodbye() {
System.out.println(name + " person says goodbye");
}
} | UTF-8 | Java | 419 | java | Person.java | Java | [
{
"context": "t.chapter5.stuctural.composite;\n\n/**\n * Created by student on 2015/03/13.\n */\npublic class Person implement",
"end": 75,
"score": 0.9187465310096741,
"start": 68,
"tag": "USERNAME",
"value": "student"
}
]
| null | []
| package ac.za.cput.chapter5.stuctural.composite;
/**
* Created by student on 2015/03/13.
*/
public class Person implements Component{
String name;
public Person(String name) {
this.name = name;
}
public void sayHello() {
System.out.println(name + " person says hello");
}
public void sayGoodbye() {
System.out.println(name + " person says goodbye");
}
} | 419 | 0.613365 | 0.591885 | 27 | 14.555555 | 19.07749 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.185185 | false | false | 1 |
a40507bbf7dc3c7115e0aa6776e1da60b87dc0ab | 7,567,732,399,536 | 5e83f1705741d4cc4ef13c4a7e2131ad5a98039e | /app/src/main/java/com/juhezi/citymemory/data/module/User.java | 3c1303ca16cfada2407aa71dce7e4ec305fb38e9 | []
| no_license | qiaoyunrui/CityMemory | https://github.com/qiaoyunrui/CityMemory | 5525fa3aca937b5e398f0246d893154ce98ea92c | dab84540a86b4bbf4fc706db87849975af74ba50 | refs/heads/master | 2020-07-10T18:03:32.591000 | 2016-10-03T13:29:14 | 2016-10-03T13:29:14 | 66,413,825 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.juhezi.citymemory.data.module;
import com.avos.avoscloud.AVUser;
import com.juhezi.citymemory.other.Config;
import java.io.Serializable;
import java.util.List;
/**
* Created by qiaoyunrui on 16-8-26.
*/
public class User implements Serializable {
public static final int USER_TYPE_PERSON = 1;
public static final int USER_TYPE_GROUP = 2;
private String username; //用户名
private String pickName; //昵称
private String mail; //邮箱
private String avatar; //头像
private int userType; //账户类型
private int ownCount;
private int pipCount;
private List<String> ownMemories; //创建的记忆
private List<String> pipMemories; //参与的记忆
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPickName() {
return pickName;
}
public void setPickName(String pickName) {
this.pickName = pickName;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getUserType() {
return userType;
}
public void setUserType(int userType) {
this.userType = userType;
}
public List<String> getOwnMemories() {
return ownMemories;
}
public void setOwnMemories(List<String> ownMemories) {
this.ownMemories = ownMemories;
}
public List<String> getPipMemories() {
return pipMemories;
}
public void setPipMemories(List<String> pipMemories) {
this.pipMemories = pipMemories;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getOwnCount() {
return ownCount;
}
public void setOwnCount(int ownCount) {
this.ownCount = ownCount;
}
public int getPipCount() {
return pipCount;
}
public void setPipCount(int pipCount) {
this.pipCount = pipCount;
}
public static User parseUser(AVUser avUserser) {
User user = new User();
user.username = avUserser.getUsername();
user.pickName = avUserser.getString(Config.USER_PICK_NAME);
user.avatar = avUserser.getString(Config.USER_AVATAR);
user.mail = avUserser.getEmail();
user.userType = avUserser.getInt(Config.USER_TYPE);
user.ownCount = avUserser.getInt(Config.USER_OWN);
user.pipCount = avUserser.getInt(Config.USER_PIP);
return user;
}
}
| UTF-8 | Java | 2,645 | java | User.java | Java | [
{
"context": "lizable;\nimport java.util.List;\n\n/**\n * Created by qiaoyunrui on 16-8-26.\n */\npublic class User implements Seri",
"end": 203,
"score": 0.9989827871322632,
"start": 193,
"tag": "USERNAME",
"value": "qiaoyunrui"
},
{
"context": "YPE_GROUP = 2;\n\n private String username; //用户名\n private String pickName; //昵称\n private ",
"end": 402,
"score": 0.9946846961975098,
"start": 399,
"tag": "USERNAME",
"value": "用户名"
},
{
"context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna",
"end": 750,
"score": 0.9770022630691528,
"start": 742,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public String getPickName() {\n ",
"end": 838,
"score": 0.9889199733734131,
"start": 830,
"tag": "USERNAME",
"value": "username"
},
{
"context": " User user = new User();\n user.username = avUserser.getUsername();\n user.pickName = avUserse",
"end": 2201,
"score": 0.8509330153465271,
"start": 2194,
"tag": "USERNAME",
"value": "avUsers"
}
]
| null | []
| package com.juhezi.citymemory.data.module;
import com.avos.avoscloud.AVUser;
import com.juhezi.citymemory.other.Config;
import java.io.Serializable;
import java.util.List;
/**
* Created by qiaoyunrui on 16-8-26.
*/
public class User implements Serializable {
public static final int USER_TYPE_PERSON = 1;
public static final int USER_TYPE_GROUP = 2;
private String username; //用户名
private String pickName; //昵称
private String mail; //邮箱
private String avatar; //头像
private int userType; //账户类型
private int ownCount;
private int pipCount;
private List<String> ownMemories; //创建的记忆
private List<String> pipMemories; //参与的记忆
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPickName() {
return pickName;
}
public void setPickName(String pickName) {
this.pickName = pickName;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getUserType() {
return userType;
}
public void setUserType(int userType) {
this.userType = userType;
}
public List<String> getOwnMemories() {
return ownMemories;
}
public void setOwnMemories(List<String> ownMemories) {
this.ownMemories = ownMemories;
}
public List<String> getPipMemories() {
return pipMemories;
}
public void setPipMemories(List<String> pipMemories) {
this.pipMemories = pipMemories;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getOwnCount() {
return ownCount;
}
public void setOwnCount(int ownCount) {
this.ownCount = ownCount;
}
public int getPipCount() {
return pipCount;
}
public void setPipCount(int pipCount) {
this.pipCount = pipCount;
}
public static User parseUser(AVUser avUserser) {
User user = new User();
user.username = avUserser.getUsername();
user.pickName = avUserser.getString(Config.USER_PICK_NAME);
user.avatar = avUserser.getString(Config.USER_AVATAR);
user.mail = avUserser.getEmail();
user.userType = avUserser.getInt(Config.USER_TYPE);
user.ownCount = avUserser.getInt(Config.USER_OWN);
user.pipCount = avUserser.getInt(Config.USER_PIP);
return user;
}
}
| 2,645 | 0.633321 | 0.630627 | 113 | 22 | 19.453598 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380531 | false | false | 1 |
3c32fd8029346e69e24cb2bc8f9e98c9f18a2a49 | 7,567,732,397,705 | 5746c5bcda3e55cef640dc4f10dec19a5b14898c | /SpaceExplorer/src/GUI/WelcomeFrame.java | 8c9d48c76b353c2904b504ae70246a7e7acc5444 | []
| no_license | bachvuviet/SENG201 | https://github.com/bachvuviet/SENG201 | ecd2c0b00f6f30e3ca51ec1da12e7a0b4bb0a691 | fe92a277d31b4762b0ff8123dff989a04609f35e | refs/heads/master | 2023-01-29T23:46:45.517000 | 2020-11-29T22:12:06 | 2020-11-29T22:12:06 | 181,090,939 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* GUI package contain all Graphical Implement of the game, upgrade from commandline game
*/
package GUI;
import CustomUIELmt.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Image;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import Backend.Galaxy;
import java.awt.Color;
/**
* Class Intro:
* This is the First and Begin Frame, player choose New game, Load game or view Credits.
* This take user to different frames.
* @author Bach Vu
* @version 0.30
*/
public class WelcomeFrame {
/** Field Intro:
* First frame
*/
public JFrame frame;
/** Method Intro:
* Create controls in the frame
*/
public WelcomeFrame() {
frame = new JFrame();
frame.setTitle("SENG");
frame.setResizable(false);
frame.getContentPane().setFont(new Font("Cambria", Font.BOLD | Font.ITALIC, 19));
frame.setBounds(100, 100, 635, 414);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setIconImage(StaticObjects.SelfResizeImage("/Celestial/Earth1.png", this, 40, 40));
frame.getContentPane().setLayout(null);
JLabel lblWelcome = new JLabel("IMPERIAL BATTLEFLEET HEADQUARTER");
lblWelcome.setBackground(new Color(75, 0, 130));
lblWelcome.setHorizontalAlignment(SwingConstants.CENTER);
lblWelcome.setToolTipText("");
lblWelcome.setFont(new Font("Cambria Math", lblWelcome.getFont().getStyle() | Font.BOLD, 21));
lblWelcome.setBounds(0, 0, 631, 72);
frame.getContentPane().add(lblWelcome);
JButton btnCreateSpaceship = new TranslucentButton("Receive new Mission");
btnCreateSpaceship.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnCreateSpaceship.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//newGame.frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
MissionFrame newGame = new MissionFrame();
newGame.frame.setUndecorated(true);//no control box
newGame.frame.setVisible(true);
newGame.frame.setLocationRelativeTo(null);
frame.dispose();
}
});
btnCreateSpaceship.setBounds(180, 174, 270, 57);
frame.getContentPane().add(btnCreateSpaceship);
JButton btnLoadMission = new TranslucentButton("Load Mission");
btnLoadMission.setAlignmentX(.5f);
btnLoadMission.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnLoadMission.setBounds(180, 241, 270, 57);
btnLoadMission.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Galaxy gala;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(false);;
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("SpaceExplorer Saves (.starman)", "starman"));
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
try {
FileInputStream fileInputStream = new FileInputStream(fileChooser.getSelectedFile());
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
gala = (Galaxy) objectInputStream.readObject();
objectInputStream.close();
//newGame.frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
LoadingFrame loadGame = new LoadingFrame(gala, true);
loadGame.frame.setUndecorated(true);//no control box
loadGame.frame.setVisible(true);
loadGame.frame.setLocationRelativeTo(null);
frame.dispose();
} catch(Exception ex) {
StaticObjects.MessBox(ex.getMessage(),"Can't load selected save", "Open Error");
ex.printStackTrace();
return;
}
} else {
}
}
});
frame.getContentPane().add(btnLoadMission);
JButton btnCredits = new TranslucentButton("Credits");
String Credits = "<html>"
+ "<p> Developers: Bach and Linh"
+ "<p> Animation: Bach and Linh"
+ "<p> Graphics: Bach and Linh"
+ "<p> Soundtrack: Bach and Linh"
+ "<p> Design: Bach and Linh"
+ "<p> Storyline: Bach and Linh"
+ "<p> Testers: Bach and Linh"
+ "</html>";
btnCredits.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StaticObjects.MessBox(Credits, "Game Credits", "");
}
});
btnCredits.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnCredits.setBounds(180, 308, 270, 57);
frame.getContentPane().add(btnCredits);
JLabel lblBackground = new JLabel("");
lblBackground.setVerticalAlignment(SwingConstants.BOTTOM);
Image backImg = new ImageIcon(this.getClass().getResource("/Background/Welcome.jpg")).getImage();
lblBackground.setBounds(0, 0, 631, 386);
lblBackground.setIcon(new ImageIcon(backImg));
frame.getContentPane().add(lblBackground);
}
/**
* Game Entry point, create a Welcome page which is the first page of the game
* @param args Initial argument (potential save)
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WelcomeFrame window = new WelcomeFrame();
window.frame.setLocationRelativeTo(null);
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| UTF-8 | Java | 5,420 | java | WelcomeFrame.java | Java | [
{
"context": "\n * This take user to different frames.\n * @author Bach Vu\n * @version 0.30\n */\n\npublic class WelcomeFrame {",
"end": 802,
"score": 0.9997935891151428,
"start": 795,
"tag": "NAME",
"value": "Bach Vu"
},
{
"context": "\t\tString Credits = \"<html>\"\n\t\t\t\t+ \"<p> Developers: Bach and Linh\"\n\t\t\t\t+ \"<p> Animation: Bach and Linh\"\n\t\t\t\t+ \"<p> ",
"end": 4053,
"score": 0.9890204668045044,
"start": 4040,
"tag": "NAME",
"value": "Bach and Linh"
},
{
"context": "\"<p> Storyline: Bach and Linh\"\n\t\t\t\t+ \"<p> Testers: Bach and Linh\"\n\t\t\t\t+ \"</html>\";\n\t\tbtnCredits.addAct",
"end": 4258,
"score": 0.590474009513855,
"start": 4257,
"tag": "NAME",
"value": "B"
},
{
"context": "yline: Bach and Linh\"\n\t\t\t\t+ \"<p> Testers: Bach and Linh\"\n\t\t\t\t+ \"</html>\";\n\t\tbtnCredits.addActionListener(",
"end": 4270,
"score": 0.7527093887329102,
"start": 4266,
"tag": "NAME",
"value": "Linh"
}
]
| null | []
| /**
* GUI package contain all Graphical Implement of the game, upgrade from commandline game
*/
package GUI;
import CustomUIELmt.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Image;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import Backend.Galaxy;
import java.awt.Color;
/**
* Class Intro:
* This is the First and Begin Frame, player choose New game, Load game or view Credits.
* This take user to different frames.
* @author <NAME>
* @version 0.30
*/
public class WelcomeFrame {
/** Field Intro:
* First frame
*/
public JFrame frame;
/** Method Intro:
* Create controls in the frame
*/
public WelcomeFrame() {
frame = new JFrame();
frame.setTitle("SENG");
frame.setResizable(false);
frame.getContentPane().setFont(new Font("Cambria", Font.BOLD | Font.ITALIC, 19));
frame.setBounds(100, 100, 635, 414);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setIconImage(StaticObjects.SelfResizeImage("/Celestial/Earth1.png", this, 40, 40));
frame.getContentPane().setLayout(null);
JLabel lblWelcome = new JLabel("IMPERIAL BATTLEFLEET HEADQUARTER");
lblWelcome.setBackground(new Color(75, 0, 130));
lblWelcome.setHorizontalAlignment(SwingConstants.CENTER);
lblWelcome.setToolTipText("");
lblWelcome.setFont(new Font("Cambria Math", lblWelcome.getFont().getStyle() | Font.BOLD, 21));
lblWelcome.setBounds(0, 0, 631, 72);
frame.getContentPane().add(lblWelcome);
JButton btnCreateSpaceship = new TranslucentButton("Receive new Mission");
btnCreateSpaceship.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnCreateSpaceship.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//newGame.frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
MissionFrame newGame = new MissionFrame();
newGame.frame.setUndecorated(true);//no control box
newGame.frame.setVisible(true);
newGame.frame.setLocationRelativeTo(null);
frame.dispose();
}
});
btnCreateSpaceship.setBounds(180, 174, 270, 57);
frame.getContentPane().add(btnCreateSpaceship);
JButton btnLoadMission = new TranslucentButton("Load Mission");
btnLoadMission.setAlignmentX(.5f);
btnLoadMission.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnLoadMission.setBounds(180, 241, 270, 57);
btnLoadMission.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Galaxy gala;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(false);;
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("SpaceExplorer Saves (.starman)", "starman"));
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
try {
FileInputStream fileInputStream = new FileInputStream(fileChooser.getSelectedFile());
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
gala = (Galaxy) objectInputStream.readObject();
objectInputStream.close();
//newGame.frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
LoadingFrame loadGame = new LoadingFrame(gala, true);
loadGame.frame.setUndecorated(true);//no control box
loadGame.frame.setVisible(true);
loadGame.frame.setLocationRelativeTo(null);
frame.dispose();
} catch(Exception ex) {
StaticObjects.MessBox(ex.getMessage(),"Can't load selected save", "Open Error");
ex.printStackTrace();
return;
}
} else {
}
}
});
frame.getContentPane().add(btnLoadMission);
JButton btnCredits = new TranslucentButton("Credits");
String Credits = "<html>"
+ "<p> Developers: <NAME>"
+ "<p> Animation: Bach and Linh"
+ "<p> Graphics: Bach and Linh"
+ "<p> Soundtrack: Bach and Linh"
+ "<p> Design: Bach and Linh"
+ "<p> Storyline: Bach and Linh"
+ "<p> Testers: Bach and Linh"
+ "</html>";
btnCredits.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StaticObjects.MessBox(Credits, "Game Credits", "");
}
});
btnCredits.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnCredits.setBounds(180, 308, 270, 57);
frame.getContentPane().add(btnCredits);
JLabel lblBackground = new JLabel("");
lblBackground.setVerticalAlignment(SwingConstants.BOTTOM);
Image backImg = new ImageIcon(this.getClass().getResource("/Background/Welcome.jpg")).getImage();
lblBackground.setBounds(0, 0, 631, 386);
lblBackground.setIcon(new ImageIcon(backImg));
frame.getContentPane().add(lblBackground);
}
/**
* Game Entry point, create a Welcome page which is the first page of the game
* @param args Initial argument (potential save)
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WelcomeFrame window = new WelcomeFrame();
window.frame.setLocationRelativeTo(null);
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| 5,412 | 0.712177 | 0.696494 | 162 | 32.456791 | 25.882713 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.12963 | false | false | 1 |
86ef91899d7cd9a10849b76ca899c38d7ddbd831 | 23,845,658,449,459 | 9c9e8f2e37da6f9340ba8b442c266e4ac6dd0c64 | /CuttingCottrill_EspionageAPI/src/main/java/edu/neumont/csc380/espionage/model/MyKeyPair.java | e4e9c7eb6bb2c2403d995e2049601f732c031575 | []
| no_license | wes-cutting/Espionage | https://github.com/wes-cutting/Espionage | 56160e18843d21f7135923906d10ef8848c67367 | beddfafcf6baf06ef2a29e95e7c8facf0bc1de0f | refs/heads/master | 2021-01-01T10:36:55.059000 | 2013-04-30T03:20:37 | 2013-04-30T03:20:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.neumont.csc380.espionage.model;
public class MyKeyPair {
MyPublicKey publicKey;
MyPrivateKey privateKey;
public MyKeyPair(MyPublicKey publicKey, MyPrivateKey privateKey){
this.publicKey = publicKey;
this.privateKey = privateKey;
}
}
| UTF-8 | Java | 254 | java | MyKeyPair.java | Java | []
| null | []
| package edu.neumont.csc380.espionage.model;
public class MyKeyPair {
MyPublicKey publicKey;
MyPrivateKey privateKey;
public MyKeyPair(MyPublicKey publicKey, MyPrivateKey privateKey){
this.publicKey = publicKey;
this.privateKey = privateKey;
}
}
| 254 | 0.795276 | 0.783465 | 10 | 24.4 | 19.463812 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 1 |
ddee3863525fd3351b8fa9b8c5a5b2a0881c3008 | 3,427,383,965,605 | 3a17a5108173531b963ba4b7d9fbbbebe89cd3dd | /src/main/java/pl/obrazkarnia/build/controller/SearchController.java | 8c2a82c3a76c12b9cf5d657d8eac83a579602430 | []
| no_license | poozone/obrazkarnia_final | https://github.com/poozone/obrazkarnia_final | bf36facdc06c6aafb574b07182a44f90124a3a15 | 186d1c34745d45580ee19b1447c3f1500646992b | refs/heads/master | 2021-01-10T04:36:54.286000 | 2016-01-23T17:44:45 | 2016-01-23T18:27:48 | 50,202,138 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.obrazkarnia.build.controller;
import java.security.Principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import pl.obrazkarnia.build.service.HistoryService;
import pl.obrazkarnia.build.service.SearchService;
import com.tumblr.jumblr.types.Photo;
@Controller
public class SearchController {
@Autowired
SearchService searchService;
@Autowired
HistoryService historyService;
@RequestMapping("/search")
public String doSearch(Model model, @RequestParam(name = "tag") String tag,
Principal principal) {
if (!tag.isEmpty()) {
List<Photo> results = searchService.searchByTag(tag);
model.addAttribute("photos", results);
if(principal!=null) {
historyService.addHistory(principal, results);
}
return "search-results";
} else
return "redirect:index.html";
}
}
| UTF-8 | Java | 1,124 | java | SearchController.java | Java | []
| null | []
| package pl.obrazkarnia.build.controller;
import java.security.Principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import pl.obrazkarnia.build.service.HistoryService;
import pl.obrazkarnia.build.service.SearchService;
import com.tumblr.jumblr.types.Photo;
@Controller
public class SearchController {
@Autowired
SearchService searchService;
@Autowired
HistoryService historyService;
@RequestMapping("/search")
public String doSearch(Model model, @RequestParam(name = "tag") String tag,
Principal principal) {
if (!tag.isEmpty()) {
List<Photo> results = searchService.searchByTag(tag);
model.addAttribute("photos", results);
if(principal!=null) {
historyService.addHistory(principal, results);
}
return "search-results";
} else
return "redirect:index.html";
}
}
| 1,124 | 0.737544 | 0.737544 | 44 | 23.545454 | 21.883425 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.681818 | false | false | 1 |
0807fc787c2723a00df87d6f59cb4e1eb46082e7 | 27,831,388,092,256 | 6efb757c8291cac98703b3d5b8cc718900ac7824 | /client/src/Connection/SenderImpl.java | 55d2c2f4fd8b66aefb3b69e9d30ad0505a4c514a | []
| no_license | trueOlZay/lab6_4 | https://github.com/trueOlZay/lab6_4 | f273382a9ce6fb1ea73a97d97ef8fef7be6ab33b | 8b3c112819dcfb7443ed3af9ba2a40fdecdc589a | refs/heads/master | 2023-05-07T02:16:35.903000 | 2021-06-13T16:30:33 | 2021-06-13T16:30:33 | 376,590,620 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Connection;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
@Singleton
public class SenderImpl implements Sender{
private final SocketChannel socketChannel;
@Inject
public SenderImpl(ClientConnectionManagerImpl clientConnectionManagerImpl) {
this.socketChannel = clientConnectionManagerImpl.getSocketChannel();
}
public void send(Object serializedObject) throws IOException {
System.out.println("sender 1");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(serializedObject);
byte [] data = byteArrayOutputStream.toByteArray();
System.out.println("sender 2");
socketChannel.write(ByteBuffer.wrap(data));
}
}
| UTF-8 | Java | 1,044 | java | SenderImpl.java | Java | []
| null | []
| package Connection;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
@Singleton
public class SenderImpl implements Sender{
private final SocketChannel socketChannel;
@Inject
public SenderImpl(ClientConnectionManagerImpl clientConnectionManagerImpl) {
this.socketChannel = clientConnectionManagerImpl.getSocketChannel();
}
public void send(Object serializedObject) throws IOException {
System.out.println("sender 1");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(serializedObject);
byte [] data = byteArrayOutputStream.toByteArray();
System.out.println("sender 2");
socketChannel.write(ByteBuffer.wrap(data));
}
}
| 1,044 | 0.767241 | 0.765326 | 31 | 32.677418 | 27.608305 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 1 |
f3dddaacc760f75c7502acfa74b09e40e85260da | 24,352,464,601,184 | e891924e3367de5937b449fa3839a4453522cb82 | /SFM/src/test/java/CurrencyManagerTest.java | 06250dc81c4da01a6dbac2f232970b75aa650a27 | []
| no_license | bzsol/Tobacco-Shop-SFM | https://github.com/bzsol/Tobacco-Shop-SFM | 99839af25876821656aad314049dcab83395bc53 | 6df41671f1d3ec74f24be87e390eec050bd79136 | refs/heads/main | 2023-05-02T16:24:26.799000 | 2021-05-11T20:17:54 | 2021-05-11T20:17:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import hu.sfm.utils.CurrencyManager;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import org.junit.jupiter.params.provider.CsvSource;
public class CurrencyManagerTest {
@ParameterizedTest
@CsvFileSource(resources = "/testfile/currency.csv")
void IsCreatePatternPass(String number,String pattern){
Assertions.assertEquals(CurrencyManager.createPattern(number),pattern);
}
@ParameterizedTest
@CsvFileSource(resources = "/testfile/currency.csv")
void IsRemoveTextFieldPatternPass(String result,String value){
Assertions.assertEquals(CurrencyManager.removeTextFieldPattern(value),result);
}
}
| UTF-8 | Java | 780 | java | CurrencyManagerTest.java | Java | []
| null | []
| import hu.sfm.utils.CurrencyManager;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import org.junit.jupiter.params.provider.CsvSource;
public class CurrencyManagerTest {
@ParameterizedTest
@CsvFileSource(resources = "/testfile/currency.csv")
void IsCreatePatternPass(String number,String pattern){
Assertions.assertEquals(CurrencyManager.createPattern(number),pattern);
}
@ParameterizedTest
@CsvFileSource(resources = "/testfile/currency.csv")
void IsRemoveTextFieldPatternPass(String result,String value){
Assertions.assertEquals(CurrencyManager.removeTextFieldPattern(value),result);
}
}
| 780 | 0.783333 | 0.783333 | 23 | 32.913044 | 27.333548 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 1 |
3dd087ac1d195d4d1f985482ef8f6ed9258ada42 | 11,398,843,237,889 | 0dd4c8ae6a0d459b2d6d3f2dbb8f4ae404abacac | /app/src/main/java/palma/felipe/com/br/jobshub/adapter/LineAdapter.java | 8a3193a5bd578a13b9e6260dde08228babfc774e | []
| no_license | felipepalma14/jobshub | https://github.com/felipepalma14/jobshub | 82d8a0830b555183d061de25c34feffd7e16cbff | cb4bf799fba00feacec43dd085a2bdab046e40cd | refs/heads/master | 2020-04-26T01:49:53.407000 | 2019-03-11T01:39:19 | 2019-03-11T01:39:19 | 173,216,110 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package palma.felipe.com.br.jobshub.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
import palma.felipe.com.br.jobshub.R;
import palma.felipe.com.br.jobshub.model.Issue;
public class LineAdapter extends RecyclerView.Adapter<LineAdapter.LineHolder> {
private List<Issue> mListIssues;
private ItemListener mItemListener;
public LineAdapter(List<Issue> mListIssues, ItemListener itemListener) {
setListIssues(mListIssues);
this.mItemListener = itemListener;
}
@NonNull
@Override
public LineHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View issueView = inflater.inflate(R.layout.main_line_view, viewGroup, false);
return new LineHolder(issueView, mItemListener);
}
@Override
public void onBindViewHolder(@NonNull LineHolder lineHolder, int i) {
lineHolder.txtIssueTitle.setText(mListIssues.get(i).getTitle());
lineHolder.txtIssueJobLocal.setText(mListIssues.get(i).getState());
lineHolder.txtIssueJobOpenedAt.setText(mListIssues.get(i).getCreatedAt());
Glide
.with(lineHolder.imgProfile.getContext())
.load(mListIssues.get(i).getUser().getAvatarUrl())
.into(lineHolder.imgProfile);
}
@Override
public int getItemCount() {
return mListIssues != null ? mListIssues.size() : 0;
}
private void setListIssues(List<Issue> issues) {
this.mListIssues = issues;
}
public void replaceData(List<Issue> issues) {
setListIssues(issues);
notifyDataSetChanged();
}
public Issue getItem(int position) {
return mListIssues.get(position);
}
public class LineHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtIssueTitle, txtIssueJobLocal, txtIssueJobOpenedAt;
public ImageView imgProfile;
private ItemListener mItemListener;
public LineHolder(View itemView, ItemListener listener) {
super(itemView);
this.mItemListener = listener;
txtIssueTitle = (TextView) itemView.findViewById(R.id.txt_job_title);
txtIssueJobLocal = (TextView) itemView.findViewById(R.id.txt_job_local);
txtIssueJobOpenedAt = (TextView) itemView.findViewById(R.id.txt_issue_opened_at);
imgProfile = (ImageView) itemView.findViewById(R.id.img_github_profile);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int position = getAdapterPosition();
Issue mIssue = getItem(position);
mItemListener.onIssueClick(mIssue);
}
}
public interface ItemListener {
void onIssueClick(Issue clickedIssue);
}
}
| UTF-8 | Java | 3,131 | java | LineAdapter.java | Java | []
| null | []
| package palma.felipe.com.br.jobshub.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
import palma.felipe.com.br.jobshub.R;
import palma.felipe.com.br.jobshub.model.Issue;
public class LineAdapter extends RecyclerView.Adapter<LineAdapter.LineHolder> {
private List<Issue> mListIssues;
private ItemListener mItemListener;
public LineAdapter(List<Issue> mListIssues, ItemListener itemListener) {
setListIssues(mListIssues);
this.mItemListener = itemListener;
}
@NonNull
@Override
public LineHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View issueView = inflater.inflate(R.layout.main_line_view, viewGroup, false);
return new LineHolder(issueView, mItemListener);
}
@Override
public void onBindViewHolder(@NonNull LineHolder lineHolder, int i) {
lineHolder.txtIssueTitle.setText(mListIssues.get(i).getTitle());
lineHolder.txtIssueJobLocal.setText(mListIssues.get(i).getState());
lineHolder.txtIssueJobOpenedAt.setText(mListIssues.get(i).getCreatedAt());
Glide
.with(lineHolder.imgProfile.getContext())
.load(mListIssues.get(i).getUser().getAvatarUrl())
.into(lineHolder.imgProfile);
}
@Override
public int getItemCount() {
return mListIssues != null ? mListIssues.size() : 0;
}
private void setListIssues(List<Issue> issues) {
this.mListIssues = issues;
}
public void replaceData(List<Issue> issues) {
setListIssues(issues);
notifyDataSetChanged();
}
public Issue getItem(int position) {
return mListIssues.get(position);
}
public class LineHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtIssueTitle, txtIssueJobLocal, txtIssueJobOpenedAt;
public ImageView imgProfile;
private ItemListener mItemListener;
public LineHolder(View itemView, ItemListener listener) {
super(itemView);
this.mItemListener = listener;
txtIssueTitle = (TextView) itemView.findViewById(R.id.txt_job_title);
txtIssueJobLocal = (TextView) itemView.findViewById(R.id.txt_job_local);
txtIssueJobOpenedAt = (TextView) itemView.findViewById(R.id.txt_issue_opened_at);
imgProfile = (ImageView) itemView.findViewById(R.id.img_github_profile);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int position = getAdapterPosition();
Issue mIssue = getItem(position);
mItemListener.onIssueClick(mIssue);
}
}
public interface ItemListener {
void onIssueClick(Issue clickedIssue);
}
}
| 3,131 | 0.692431 | 0.691792 | 98 | 30.938776 | 28.286009 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520408 | false | false | 1 |
b2404fbfb58382496aa21f6fdeaaa0968f03180f | 11,570,641,922,397 | c5627725a439ec40f12eac5b4da23da88bc0d2aa | /src/main/java/com/dhcc/cn/framework/utlis/LineCharts.java | 0fa164c66cb423bcf11dd34f612e53d5dfebfa55 | [
"MIT"
]
| permissive | denghang1989/spring_framework | https://github.com/denghang1989/spring_framework | 3351e81c4121041ef43a95430f41c6c346ebd0f3 | 1e61e2f5c8b21328223834f6eab4c3d680f441bb | refs/heads/master | 2022-07-15T06:06:45.972000 | 2020-01-29T06:32:45 | 2020-01-29T06:32:45 | 214,618,063 | 0 | 0 | MIT | false | 2022-06-21T02:01:58 | 2019-10-12T09:24:00 | 2020-01-29T06:32:47 | 2022-06-21T02:01:58 | 2,442 | 0 | 0 | 3 | CSS | false | false | package com.dhcc.cn.framework.utlis;
import com.github.abel533.echarts.Option;
public class LineCharts {
public static Option getLineOption(){
Option option = new Option();
option.title("line");
return option;
}
}
| UTF-8 | Java | 250 | java | LineCharts.java | Java | [
{
"context": "e com.dhcc.cn.framework.utlis;\n\nimport com.github.abel533.echarts.Option;\n\npublic class LineCharts {\n\n p",
"end": 63,
"score": 0.9986003041267395,
"start": 56,
"tag": "USERNAME",
"value": "abel533"
}
]
| null | []
| package com.dhcc.cn.framework.utlis;
import com.github.abel533.echarts.Option;
public class LineCharts {
public static Option getLineOption(){
Option option = new Option();
option.title("line");
return option;
}
}
| 250 | 0.66 | 0.648 | 13 | 18.23077 | 16.830164 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 1 |
bb6048e2bcd7441493b2a44bfa77810ec6943bf6 | 8,323,646,655,732 | 67f7bfce5467203d54d697ea2a138e1d8bf43810 | /QueueProgram/src/Program6.java | 98e2a058b25c17f7ca0217cdb48a0072a72d37fc | []
| no_license | aslamamaan3/Design-Patterns | https://github.com/aslamamaan3/Design-Patterns | 9dcb3b759796d6816dfd59ae4bb60d905fde11c6 | f8af3bc1326e9cce6ab0312d6c474c4d3d82daba | refs/heads/master | 2020-04-29T08:56:29.694000 | 2019-03-16T17:56:00 | 2019-03-16T17:56:00 | 176,005,089 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Program6 {
public static void main(String[] args) {
MyQueue q = new MyQueue();
Thread p = new Thread(new Producer(q));
Thread c = new Thread(new Consumer(q));
p.start();
c.start();
}
}
| UTF-8 | Java | 219 | java | Program6.java | Java | []
| null | []
|
public class Program6 {
public static void main(String[] args) {
MyQueue q = new MyQueue();
Thread p = new Thread(new Producer(q));
Thread c = new Thread(new Consumer(q));
p.start();
c.start();
}
}
| 219 | 0.616438 | 0.611872 | 13 | 15.769231 | 16.229858 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false | 1 |
605f828b93256d967dfb6d41282dd419a308b9cc | 12,833,362,290,658 | ffb22a1abfeef692b2b927012b1ec2dd000e4550 | /src/main/java/net/minecraft/src/CJB_GLTextureBufferedImage.java | 26a5c1d1b260b6459b2711b09f90598a35025fb7 | []
| no_license | Cat7373/cjb-deux | https://github.com/Cat7373/cjb-deux | 5672b51c8322a48e418478b67918422b3c7727d9 | 778f1028e42718552d3c114bda0f540346090131 | refs/heads/master | 2021-01-22T14:25:49.259000 | 2013-01-11T05:46:09 | 2013-01-11T05:46:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.minecraft.src;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBufferByte;
import java.awt.image.ImageObserver;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.minecraft.client.renderer.GLAllocation;
import org.lwjgl.opengl.GL11;
public class CJB_GLTextureBufferedImage extends BufferedImage
{
private static final ByteBuffer buffer = GLAllocation.createDirectByteBuffer(262144);
private static final HashMap registerImage = new HashMap();
private static final Lock lock = new ReentrantLock();
public byte[] data;
private int register;
private boolean magFiltering;
private boolean minFiltering;
private boolean clampTexture;
private CJB_GLTextureBufferedImage(ColorModel var1, WritableRaster var2, boolean var3, Hashtable var4)
{
super(var1, var2, var3, var4);
this.data = ((DataBufferByte)var2.getDataBuffer()).getData();
}
public static CJB_GLTextureBufferedImage create(int var0, int var1)
{
ColorSpace var2 = ColorSpace.getInstance(1000);
int[] var3 = new int[] {8, 8, 8, 8};
int[] var4 = new int[] {0, 1, 2, 3};
ComponentColorModel var5 = new ComponentColorModel(var2, var3, true, false, 3, 0);
WritableRaster var6 = Raster.createInterleavedRaster(0, var0, var1, var0 * 4, 4, var4, (Point)null);
return new CJB_GLTextureBufferedImage(var5, var6, false, (Hashtable)null);
}
public static CJB_GLTextureBufferedImage create(BufferedImage var0)
{
CJB_GLTextureBufferedImage var1 = create(var0.getWidth(), var0.getHeight());
Graphics var2 = var1.getGraphics();
var2.drawImage(var0, 0, 0, (ImageObserver)null);
var2.dispose();
return var1;
}
public int register()
{
lock.lock();
int var2;
try
{
int var1;
if (this.register == 0)
{
this.register = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.register);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, this.minFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, this.magFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
var1 = this.clampTexture ? 10496 : 10497;
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, var1);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, var1);
buffer.clear();
buffer.put(this.data);
buffer.flip();
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.getWidth(), this.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
registerImage.put(Integer.valueOf(this.register), this);
var2 = this.register;
return var2;
}
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.register);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, this.minFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, this.magFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
var1 = this.clampTexture ? 10496 : 10497;
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, var1);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, var1);
buffer.clear();
buffer.put(this.data);
buffer.flip();
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, this.getWidth(), this.getHeight(), GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
var2 = this.register;
}
finally
{
lock.unlock();
}
return var2;
}
public boolean bind()
{
lock.lock();
boolean var1;
try
{
if (this.register == 0)
{
var1 = false;
return var1;
}
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.register);
var1 = true;
}
finally
{
lock.unlock();
}
return var1;
}
public void unregister()
{
lock.lock();
try
{
if (this.register == 0)
{
return;
}
GL11.glDeleteTextures(this.register);
this.register = 0;
registerImage.remove(Integer.valueOf(this.register));
}
finally
{
lock.unlock();
}
}
public static void unregister(int var0)
{
lock.lock();
try
{
CJB_GLTextureBufferedImage var1 = (CJB_GLTextureBufferedImage)registerImage.get(Integer.valueOf(var0));
if (var1 != null)
{
var1.unregister();
}
}
finally
{
lock.unlock();
}
}
public void setMagFilter(boolean var1)
{
this.magFiltering = var1;
}
public void setMinFilter(boolean var1)
{
this.minFiltering = var1;
}
public int getId()
{
return this.register;
}
public boolean getMagFilter()
{
return this.magFiltering;
}
public boolean getMinFilter()
{
return this.minFiltering;
}
public void setClampTexture(boolean var1)
{
this.clampTexture = var1;
}
public boolean isClampTexture()
{
return this.clampTexture;
}
public void setRGBA(int var1, int var2, byte var3, byte var4, byte var5, byte var6)
{
int var7 = (var2 * this.getWidth() + var1) * 4;
this.data[var7++] = var3;
this.data[var7++] = var4;
this.data[var7++] = var5;
this.data[var7] = var6;
}
public void setRGB(int var1, int var2, byte var3, byte var4, byte var5)
{
int var6 = (var2 * this.getWidth() + var1) * 4;
this.data[var6++] = var3;
this.data[var6++] = var4;
this.data[var6++] = var5;
this.data[var6] = -1;
}
public void setRGB(int var1, int var2, int var3)
{
int var4 = (var2 * this.getWidth() + var1) * 4;
this.data[var4++] = (byte)(var3 >> 16);
this.data[var4++] = (byte)(var3 >> 8);
this.data[var4++] = (byte)(var3 >> 0);
this.data[var4] = (byte)(var3 >> 24);
}
public static void createTexture(int[] var0, int var1, int var2, int var3, boolean var4, boolean var5)
{
byte[] var6 = new byte[var1 * var2 * 4];
int var7 = 0;
int var8 = var0.length;
for (int var9 = 0; var7 < var8; ++var7)
{
int var10 = var0[var7];
var6[var9++] = (byte)(var10 >> 16);
var6[var9++] = (byte)(var10 >> 8);
var6[var9++] = (byte)(var10 >> 0);
var6[var9++] = (byte)(var10 >> 24);
}
createTexture(var6, var1, var2, var3, var4, var5);
}
public static void createTexture(byte[] var0, int var1, int var2, int var3, boolean var4, boolean var5)
{
GL11.glBindTexture(GL11.GL_TEXTURE_2D, var3);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, var4 ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, var4 ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, var5 ? GL11.GL_CLAMP : GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, var5 ? GL11.GL_CLAMP : GL11.GL_REPEAT);
buffer.clear();
buffer.put(var0);
buffer.flip();
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, var1, var2, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
}
}
| UTF-8 | Java | 8,587 | java | CJB_GLTextureBufferedImage.java | Java | []
| null | []
| package net.minecraft.src;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBufferByte;
import java.awt.image.ImageObserver;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.minecraft.client.renderer.GLAllocation;
import org.lwjgl.opengl.GL11;
public class CJB_GLTextureBufferedImage extends BufferedImage
{
private static final ByteBuffer buffer = GLAllocation.createDirectByteBuffer(262144);
private static final HashMap registerImage = new HashMap();
private static final Lock lock = new ReentrantLock();
public byte[] data;
private int register;
private boolean magFiltering;
private boolean minFiltering;
private boolean clampTexture;
private CJB_GLTextureBufferedImage(ColorModel var1, WritableRaster var2, boolean var3, Hashtable var4)
{
super(var1, var2, var3, var4);
this.data = ((DataBufferByte)var2.getDataBuffer()).getData();
}
public static CJB_GLTextureBufferedImage create(int var0, int var1)
{
ColorSpace var2 = ColorSpace.getInstance(1000);
int[] var3 = new int[] {8, 8, 8, 8};
int[] var4 = new int[] {0, 1, 2, 3};
ComponentColorModel var5 = new ComponentColorModel(var2, var3, true, false, 3, 0);
WritableRaster var6 = Raster.createInterleavedRaster(0, var0, var1, var0 * 4, 4, var4, (Point)null);
return new CJB_GLTextureBufferedImage(var5, var6, false, (Hashtable)null);
}
public static CJB_GLTextureBufferedImage create(BufferedImage var0)
{
CJB_GLTextureBufferedImage var1 = create(var0.getWidth(), var0.getHeight());
Graphics var2 = var1.getGraphics();
var2.drawImage(var0, 0, 0, (ImageObserver)null);
var2.dispose();
return var1;
}
public int register()
{
lock.lock();
int var2;
try
{
int var1;
if (this.register == 0)
{
this.register = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.register);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, this.minFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, this.magFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
var1 = this.clampTexture ? 10496 : 10497;
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, var1);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, var1);
buffer.clear();
buffer.put(this.data);
buffer.flip();
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.getWidth(), this.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
registerImage.put(Integer.valueOf(this.register), this);
var2 = this.register;
return var2;
}
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.register);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, this.minFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, this.magFiltering ? GL11.GL_LINEAR : GL11.GL_NEAREST);
var1 = this.clampTexture ? 10496 : 10497;
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, var1);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, var1);
buffer.clear();
buffer.put(this.data);
buffer.flip();
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, this.getWidth(), this.getHeight(), GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
var2 = this.register;
}
finally
{
lock.unlock();
}
return var2;
}
public boolean bind()
{
lock.lock();
boolean var1;
try
{
if (this.register == 0)
{
var1 = false;
return var1;
}
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.register);
var1 = true;
}
finally
{
lock.unlock();
}
return var1;
}
public void unregister()
{
lock.lock();
try
{
if (this.register == 0)
{
return;
}
GL11.glDeleteTextures(this.register);
this.register = 0;
registerImage.remove(Integer.valueOf(this.register));
}
finally
{
lock.unlock();
}
}
public static void unregister(int var0)
{
lock.lock();
try
{
CJB_GLTextureBufferedImage var1 = (CJB_GLTextureBufferedImage)registerImage.get(Integer.valueOf(var0));
if (var1 != null)
{
var1.unregister();
}
}
finally
{
lock.unlock();
}
}
public void setMagFilter(boolean var1)
{
this.magFiltering = var1;
}
public void setMinFilter(boolean var1)
{
this.minFiltering = var1;
}
public int getId()
{
return this.register;
}
public boolean getMagFilter()
{
return this.magFiltering;
}
public boolean getMinFilter()
{
return this.minFiltering;
}
public void setClampTexture(boolean var1)
{
this.clampTexture = var1;
}
public boolean isClampTexture()
{
return this.clampTexture;
}
public void setRGBA(int var1, int var2, byte var3, byte var4, byte var5, byte var6)
{
int var7 = (var2 * this.getWidth() + var1) * 4;
this.data[var7++] = var3;
this.data[var7++] = var4;
this.data[var7++] = var5;
this.data[var7] = var6;
}
public void setRGB(int var1, int var2, byte var3, byte var4, byte var5)
{
int var6 = (var2 * this.getWidth() + var1) * 4;
this.data[var6++] = var3;
this.data[var6++] = var4;
this.data[var6++] = var5;
this.data[var6] = -1;
}
public void setRGB(int var1, int var2, int var3)
{
int var4 = (var2 * this.getWidth() + var1) * 4;
this.data[var4++] = (byte)(var3 >> 16);
this.data[var4++] = (byte)(var3 >> 8);
this.data[var4++] = (byte)(var3 >> 0);
this.data[var4] = (byte)(var3 >> 24);
}
public static void createTexture(int[] var0, int var1, int var2, int var3, boolean var4, boolean var5)
{
byte[] var6 = new byte[var1 * var2 * 4];
int var7 = 0;
int var8 = var0.length;
for (int var9 = 0; var7 < var8; ++var7)
{
int var10 = var0[var7];
var6[var9++] = (byte)(var10 >> 16);
var6[var9++] = (byte)(var10 >> 8);
var6[var9++] = (byte)(var10 >> 0);
var6[var9++] = (byte)(var10 >> 24);
}
createTexture(var6, var1, var2, var3, var4, var5);
}
public static void createTexture(byte[] var0, int var1, int var2, int var3, boolean var4, boolean var5)
{
GL11.glBindTexture(GL11.GL_TEXTURE_2D, var3);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, var4 ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, var4 ? GL11.GL_LINEAR : GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, var5 ? GL11.GL_CLAMP : GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, var5 ? GL11.GL_CLAMP : GL11.GL_REPEAT);
buffer.clear();
buffer.put(var0);
buffer.flip();
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, var1, var2, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
}
}
| 8,587 | 0.568068 | 0.519739 | 262 | 30.774809 | 32.16428 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.919847 | false | false | 1 |
2c1458ddfcee6358009cef4ca750a8db45d7489c | 19,722,489,881,362 | 883e808eb835436bfccb513b93cd3ffbf48d1a45 | /src/com/shop/servlet/shopcart/AddShopCart.java | 482837683cc0d8fc590ba1dab4caf75bf075aec8 | []
| no_license | danerlt/ShopSystem | https://github.com/danerlt/ShopSystem | eed8a4e684cf2062db229b79856d944f98309c67 | 5f3239547411cdd9e02f28fc6f01bbc8f25ebbeb | refs/heads/master | 2021-09-20T21:30:22.653000 | 2018-08-15T13:52:22 | 2018-08-15T13:52:22 | 76,842,620 | 32 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shop.servlet.shopcart;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.shop.dao.ProductDao;
import com.shop.domain.Product;
import com.shop.domain.ShopCart;
import com.shop.utils.DBUtil;
@WebServlet("/AddShopCart")
public class AddShopCart extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddShopCart() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
PrintWriter out = response.getWriter();
int id = 0;
String cid = request.getParameter("cId");
int pId = Integer.parseInt(request.getParameter("pId"));
int count = Integer.parseInt(request.getParameter("count"));
String isBuy = request.getParameter("isBuy");
//计算总价
BigDecimal totolPrice ;
BigDecimal unitPrice;//商品单价
ProductDao pd = new ProductDao();
Product p = new Product();
p = pd.find(pId);
unitPrice = p.getiPrice();
totolPrice = unitPrice.multiply(new BigDecimal(Integer.valueOf(count)));
request.getSession().setAttribute("product", p);
int cId = 0;//用户未登录时设置购物车id为0,cId为0
if(cid != null || cid.equals("")){
//用户已登录
cId = Integer.parseInt(cid);
DBUtil db = new DBUtil();
String sql = "insert into shopcart(cId,pId,count,isBuy,totalPrice) values(?,?,?,?,?)";
Object[] params = {cId,pId,count,isBuy,totolPrice};
int n = db.doUpdate(sql, params);
if(n > 0){
//添加购物车成功
out.println("<script>alert('添加成功!')</script>");
}else {
//添加购物车失败
out.println("<script>alert('添加成功!')</script>");
}
}else {
ShopCart sc = new ShopCart();
sc.setId(id);
sc.setcId(cId);
sc.setpId(pId);
sc.setCount(count);
sc.setIsBuy(isBuy);
sc.setTotolPrice(totolPrice);
request.getSession().setAttribute("shopcart", sc);
}
response.sendRedirect("/ShopSystem/cart.jsp");
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| UTF-8 | Java | 2,610 | java | AddShopCart.java | Java | []
| null | []
| package com.shop.servlet.shopcart;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.shop.dao.ProductDao;
import com.shop.domain.Product;
import com.shop.domain.ShopCart;
import com.shop.utils.DBUtil;
@WebServlet("/AddShopCart")
public class AddShopCart extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddShopCart() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
PrintWriter out = response.getWriter();
int id = 0;
String cid = request.getParameter("cId");
int pId = Integer.parseInt(request.getParameter("pId"));
int count = Integer.parseInt(request.getParameter("count"));
String isBuy = request.getParameter("isBuy");
//计算总价
BigDecimal totolPrice ;
BigDecimal unitPrice;//商品单价
ProductDao pd = new ProductDao();
Product p = new Product();
p = pd.find(pId);
unitPrice = p.getiPrice();
totolPrice = unitPrice.multiply(new BigDecimal(Integer.valueOf(count)));
request.getSession().setAttribute("product", p);
int cId = 0;//用户未登录时设置购物车id为0,cId为0
if(cid != null || cid.equals("")){
//用户已登录
cId = Integer.parseInt(cid);
DBUtil db = new DBUtil();
String sql = "insert into shopcart(cId,pId,count,isBuy,totalPrice) values(?,?,?,?,?)";
Object[] params = {cId,pId,count,isBuy,totolPrice};
int n = db.doUpdate(sql, params);
if(n > 0){
//添加购物车成功
out.println("<script>alert('添加成功!')</script>");
}else {
//添加购物车失败
out.println("<script>alert('添加成功!')</script>");
}
}else {
ShopCart sc = new ShopCart();
sc.setId(id);
sc.setcId(cId);
sc.setpId(pId);
sc.setCount(count);
sc.setIsBuy(isBuy);
sc.setTotolPrice(totolPrice);
request.getSession().setAttribute("shopcart", sc);
}
response.sendRedirect("/ShopSystem/cart.jsp");
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| 2,610 | 0.664673 | 0.662281 | 79 | 29.746836 | 23.848928 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.012658 | false | false | 1 |
951501473819301fe4f791834bb01db815977eb6 | 9,302,899,200,079 | ade3e11a79ae2724ea6216e1bfae9f6af6094143 | /Framework/src/main/java/com/pixshow/framework/ext/struts/JSONResult.java | fe2e66167408cda3d3cbf1b732ce7674b43b6697 | []
| no_license | yanchao86/oldtoolbox | https://github.com/yanchao86/oldtoolbox | f2d10a9c0d97a8f7556c120e52aa85def6afadd5 | f5add876c847b4f1fe61d46016692eda42596c77 | refs/heads/master | 2020-04-06T15:00:02.398000 | 2016-09-29T03:50:49 | 2016-09-29T03:50:49 | 49,851,467 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2010-2013 www.pixshow.net All Rights Reserved
*
* File:JSONResult.java Project: LvFramework
*
* Creator:<a href="mailto:jifangliang@163.com">Time</a>
* Date:Jan 18, 2013 2:15:48 PM
*
*/
package com.pixshow.framework.ext.struts;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
import com.pixshow.framework.abbr.api.annotation.Abbr;
import com.pixshow.framework.config.Config;
import com.pixshow.framework.utils.AnnotationUtility;
import com.pixshow.framework.utils.ClassUtility;
/**
*
*
*
* @author <a href="mailto:jifangliang@163.com">Time</a>
* @author $Author:$
* @version $Revision:$ $Date:$
* @since Jan 18, 2013
*
*/
public class JSONResult extends org.apache.struts2.json.JSONResult {
private static final long serialVersionUID = 1L;
protected Object findRootObject(ActionInvocation invocation) {
Object rootObject;
if (getRoot() != null) {
ValueStack stack = invocation.getStack();
rootObject = stack.findValue(getRoot());
} else {
rootObject = invocation.getStack().peek(); // model overrides action
}
return rootObject;
}
protected Object readRootObject(ActionInvocation invocation) {
if (isEnableSMD()) {
return buildSMDObject(invocation);
}
return findRootObject(invocation);
}
protected boolean enableGzip(HttpServletRequest request) {
return isEnableGZIP() && JSONUtil.isGzipInRequest(request);
}
@Override
public void execute(ActionInvocation invocation) throws Exception {
ActionContext actionContext = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
boolean enableAbbr = false;
boolean excludeEmpty = false;
Class<?> actionClass = ClassUtility.getUserClass(invocation.getAction().getClass());
Abbr abbr = AnnotationUtility.findAnnotation(actionClass, Abbr.class);
if (abbr == null) {
enableAbbr = Config.getInstance().getBoolean("abbr.setting.enable.defalut", enableAbbr);
excludeEmpty = Config.getInstance().getBoolean("abbr.setting.excludeEmpty.defalut", enableAbbr);
} else {
enableAbbr = abbr.enable();
excludeEmpty = abbr.excludeEmpty();
}
try {
Object rootObject;
rootObject = readRootObject(invocation);
writeToResponse(response, createJSONString(request, rootObject, enableAbbr, excludeEmpty), enableGzip(request));
} catch (IOException exception) {
throw exception;
}
}
private String createJSONString(HttpServletRequest request, Object rootObject, boolean enableAbbr, boolean excludeEmpty) throws JSONException {
String json;
JSONWriter writer = new JSONWriter();
writer.setIgnoreHierarchy(isIgnoreHierarchy());
writer.setEnumAsBean(isEnumAsBean());
writer.setEnableAbbr(enableAbbr);
writer.setExcludeEmpty(excludeEmpty);
json = writer.write(rootObject, getExcludePropertiesList(), getIncludePropertiesList(), isExcludeNullProperties());
// json = JSONUtil.serialize(rootObject, getExcludePropertiesList(), getIncludePropertiesList(), isIgnoreHierarchy(), isEnumAsBean(), isExcludeNullProperties());
json = "{\"result\":0,\"data\":" + json + "}";
json = addCallbackIfApplicable(request, json);
return json;
}
}
| UTF-8 | Java | 3,982 | java | JSONResult.java | Java | [
{
"context": "oject: LvFramework\n * \n * Creator:<a href=\"mailto:jifangliang@163.com\">Time</a> \n * Date:Jan 18, 2013 2:15:48 PM\n * \n *",
"end": 164,
"score": 0.9999278783798218,
"start": 145,
"tag": "EMAIL",
"value": "jifangliang@163.com"
},
{
"context": "lity;\n\n/**\n * \n * \n * \n * @author <a href=\"mailto:jifangliang@163.com\">Time</a>\n * @author $Author:$\n * @version $Revis",
"end": 919,
"score": 0.9999275803565979,
"start": 900,
"tag": "EMAIL",
"value": "jifangliang@163.com"
}
]
| null | []
| /*
* Copyright (c) 2010-2013 www.pixshow.net All Rights Reserved
*
* File:JSONResult.java Project: LvFramework
*
* Creator:<a href="mailto:<EMAIL>">Time</a>
* Date:Jan 18, 2013 2:15:48 PM
*
*/
package com.pixshow.framework.ext.struts;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
import com.pixshow.framework.abbr.api.annotation.Abbr;
import com.pixshow.framework.config.Config;
import com.pixshow.framework.utils.AnnotationUtility;
import com.pixshow.framework.utils.ClassUtility;
/**
*
*
*
* @author <a href="mailto:<EMAIL>">Time</a>
* @author $Author:$
* @version $Revision:$ $Date:$
* @since Jan 18, 2013
*
*/
public class JSONResult extends org.apache.struts2.json.JSONResult {
private static final long serialVersionUID = 1L;
protected Object findRootObject(ActionInvocation invocation) {
Object rootObject;
if (getRoot() != null) {
ValueStack stack = invocation.getStack();
rootObject = stack.findValue(getRoot());
} else {
rootObject = invocation.getStack().peek(); // model overrides action
}
return rootObject;
}
protected Object readRootObject(ActionInvocation invocation) {
if (isEnableSMD()) {
return buildSMDObject(invocation);
}
return findRootObject(invocation);
}
protected boolean enableGzip(HttpServletRequest request) {
return isEnableGZIP() && JSONUtil.isGzipInRequest(request);
}
@Override
public void execute(ActionInvocation invocation) throws Exception {
ActionContext actionContext = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
boolean enableAbbr = false;
boolean excludeEmpty = false;
Class<?> actionClass = ClassUtility.getUserClass(invocation.getAction().getClass());
Abbr abbr = AnnotationUtility.findAnnotation(actionClass, Abbr.class);
if (abbr == null) {
enableAbbr = Config.getInstance().getBoolean("abbr.setting.enable.defalut", enableAbbr);
excludeEmpty = Config.getInstance().getBoolean("abbr.setting.excludeEmpty.defalut", enableAbbr);
} else {
enableAbbr = abbr.enable();
excludeEmpty = abbr.excludeEmpty();
}
try {
Object rootObject;
rootObject = readRootObject(invocation);
writeToResponse(response, createJSONString(request, rootObject, enableAbbr, excludeEmpty), enableGzip(request));
} catch (IOException exception) {
throw exception;
}
}
private String createJSONString(HttpServletRequest request, Object rootObject, boolean enableAbbr, boolean excludeEmpty) throws JSONException {
String json;
JSONWriter writer = new JSONWriter();
writer.setIgnoreHierarchy(isIgnoreHierarchy());
writer.setEnumAsBean(isEnumAsBean());
writer.setEnableAbbr(enableAbbr);
writer.setExcludeEmpty(excludeEmpty);
json = writer.write(rootObject, getExcludePropertiesList(), getIncludePropertiesList(), isExcludeNullProperties());
// json = JSONUtil.serialize(rootObject, getExcludePropertiesList(), getIncludePropertiesList(), isIgnoreHierarchy(), isEnumAsBean(), isExcludeNullProperties());
json = "{\"result\":0,\"data\":" + json + "}";
json = addCallbackIfApplicable(request, json);
return json;
}
}
| 3,958 | 0.695881 | 0.685836 | 107 | 36.214954 | 34.565399 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672897 | false | false | 1 |
61769cf536b6c9643429ae7fc1f6c8809c5e1b00 | 23,175,643,569,121 | 8ac95a6fb566d62110198aa7f14399586091787e | /results/Epidemic_Manhattan_40hosts/RunOn_2020_12_18_16.00.05.755_mapmanhattan_host40_protepidemic_BestIndividual_98.java | a82ff82ef0702b89bac2bcdd33cc8222f3c7a271 | []
| no_license | tsume82/evolution_routing_protocol | https://github.com/tsume82/evolution_routing_protocol | da02f5af391749d1c918713eb6f1e0270a6e9a34 | b1f2730f58def0e3d6cc4a303b369002bdce1017 | refs/heads/main | 2023-03-16T06:24:32.184000 | 2021-03-10T10:12:22 | 2021-03-10T10:12:22 | 330,688,716 | 1 | 0 | null | true | 2021-03-10T10:12:23 | 2021-01-18T14:18:23 | 2021-03-05T17:35:04 | 2021-03-10T10:12:22 | 2,991 | 0 | 0 | 0 | Java | false | false | package routing;
import core.Settings;
public class BestIndividual_98 extends ActiveRouter{
public BestIndividual_98(Settings s) {
super(s);
}
protected BestIndividual_98(BestIndividual_98 r) {
super(r);
}
@Override
public void update() {
super.update();
if((!!isTransferring() || canStartTransfer())){if((!(isTransferring() || isTransferring()) || isTransferring())){if(!(canStartTransfer() != canStartTransfer())){if(isTransferring()){this.tryAllMessagesToAllConnections();}
exchangeDeliverableMessages();
exchangeDeliverableMessages();
this.tryAllMessagesToAllConnections();}}} }
@Override
public BestIndividual_98 replicate() {
return new BestIndividual_98(this);
}
} | UTF-8 | Java | 691 | java | RunOn_2020_12_18_16.00.05.755_mapmanhattan_host40_protepidemic_BestIndividual_98.java | Java | []
| null | []
| package routing;
import core.Settings;
public class BestIndividual_98 extends ActiveRouter{
public BestIndividual_98(Settings s) {
super(s);
}
protected BestIndividual_98(BestIndividual_98 r) {
super(r);
}
@Override
public void update() {
super.update();
if((!!isTransferring() || canStartTransfer())){if((!(isTransferring() || isTransferring()) || isTransferring())){if(!(canStartTransfer() != canStartTransfer())){if(isTransferring()){this.tryAllMessagesToAllConnections();}
exchangeDeliverableMessages();
exchangeDeliverableMessages();
this.tryAllMessagesToAllConnections();}}} }
@Override
public BestIndividual_98 replicate() {
return new BestIndividual_98(this);
}
} | 691 | 0.74385 | 0.726483 | 23 | 29.086956 | 44.144932 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.478261 | false | false | 1 |
7723dcd571a8f58cf64ef53a05d96600bee01f41 | 30,940,944,440,905 | 1b2c20f57c15b41f9f94394686c58996b57c9200 | /src/com/leetcode/medium/NumPow16_1.java | e24be795206eabb197adae6c0cf45268b589e4ae | []
| no_license | zhaozhixin853859234/study | https://github.com/zhaozhixin853859234/study | 15679940bab482c6965c1ede2f19f686e151782f | 9ffa7d87ee55447a0c781e47100946d173e737f8 | refs/heads/master | 2023-02-05T23:48:56.127000 | 2020-12-29T02:30:59 | 2020-12-29T02:30:59 | 318,099,002 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.leetcode.medium;
/**
* <h3>study</h3>
*
* @author : zhao
* @version :
* @date : 2020-06-02 14:06
*/
public class NumPow16_1 {
public static void main(String[] args) {
System.out.println(myPow(2,-2));
}
// 超时,n/2+1次相乘
public static double myPow(double x, int n) {
if (n==0)
return 1;
double res = 1.0;
if (n>0){
for (int i = 0; i <n/2; i++) {
res *= x;
}
return n%2==0 ? res*res : res*res*x;
}
else {
for (int j = 0; j < (n*(-1))/2 ; j++) {
res*=(1/x);
}
return n%2==0? res*res: res*res*(1/x);
}
}
}
| UTF-8 | Java | 717 | java | NumPow16_1.java | Java | [
{
"context": "ode.medium;\n\n/**\n * <h3>study</h3>\n *\n * @author : zhao\n * @version :\n * @date : 2020-06-02 14:06\n */\npub",
"end": 72,
"score": 0.7170445919036865,
"start": 68,
"tag": "USERNAME",
"value": "zhao"
}
]
| null | []
| package com.leetcode.medium;
/**
* <h3>study</h3>
*
* @author : zhao
* @version :
* @date : 2020-06-02 14:06
*/
public class NumPow16_1 {
public static void main(String[] args) {
System.out.println(myPow(2,-2));
}
// 超时,n/2+1次相乘
public static double myPow(double x, int n) {
if (n==0)
return 1;
double res = 1.0;
if (n>0){
for (int i = 0; i <n/2; i++) {
res *= x;
}
return n%2==0 ? res*res : res*res*x;
}
else {
for (int j = 0; j < (n*(-1))/2 ; j++) {
res*=(1/x);
}
return n%2==0? res*res: res*res*(1/x);
}
}
}
| 717 | 0.410184 | 0.35785 | 33 | 20.424242 | 15.851643 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 1 |
a20d9def7bf6913522e16887a1df976dd1a485e1 | 18,537,078,881,064 | db19b20222c920953fd9b20a41ebfd76cabc1756 | /src/entities/Receipt.java | 7f598ffe1417a403d91797731b3475652026d03a | []
| no_license | jphrmartins/pucrs-poo | https://github.com/jphrmartins/pucrs-poo | 08f29e8d7f94ef9431da5a1d624ce9f801cc52f4 | ed4dac3517a39721c53edb91c1f174310e2d8f15 | refs/heads/master | 2022-11-15T02:07:39.966000 | 2020-07-06T22:32:17 | 2020-07-06T22:32:17 | 273,100,407 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package entities;
import java.util.List;
public class Receipt {
private int id;
private double totalPrice;
private double discount;
private double tax;
private double total;
private List<Product> list;
public Receipt(int id, double totalPrice, double discount, double tax, double total, List<Product> list) {
this.id = id;
this.totalPrice = round(totalPrice);
this.discount = discount;
this.tax = round(tax);
this.total = round(total);
this.list = list;
}
public double getTax() {
return tax;
}
public double getTotal() {
return total;
}
@Override
public String toString() {
StringBuilder stringBuilder;
stringBuilder = new StringBuilder("=====================================\n");
stringBuilder.append("Recibo de venda número: ").append(this.id).append("\n");
stringBuilder.append("Numero do item | Código | Descricão | Preço unitário | Quantidade | Valor do item \n");
for (int i = 0; i < list.size(); i++) {
stringBuilder.append(i + 1).append(" | ")
.append(list.get(i).getBarCode()).append(" | ")
.append(list.get(i).getDescription()).append(" | ")
.append(list.get(i).getPrice()).append(" | ")
.append(list.get(i).getAmount()).append(" | ")
.append((round(list.get(i).getAmount() * list.get(i).getPrice()))).append("\n");
}
stringBuilder.append("\t\t\t\tTotal | ").append(this.totalPrice).append("\n")
.append("\t\t\t\tDesconto | ").append(this.discount).append("\n")
.append("\t\t\t\tImposto | ").append(this.tax).append("\n")
.append("\t\t\t\tValor da venda | ").append(this.total);
stringBuilder.append("\n=====================================\n");
return stringBuilder.toString();
}
private double round(double price) {
double roundedPrice = price * 100;
roundedPrice = Math.ceil(roundedPrice);
return roundedPrice / 100;
}
}
| UTF-8 | Java | 2,144 | java | Receipt.java | Java | []
| null | []
| package entities;
import java.util.List;
public class Receipt {
private int id;
private double totalPrice;
private double discount;
private double tax;
private double total;
private List<Product> list;
public Receipt(int id, double totalPrice, double discount, double tax, double total, List<Product> list) {
this.id = id;
this.totalPrice = round(totalPrice);
this.discount = discount;
this.tax = round(tax);
this.total = round(total);
this.list = list;
}
public double getTax() {
return tax;
}
public double getTotal() {
return total;
}
@Override
public String toString() {
StringBuilder stringBuilder;
stringBuilder = new StringBuilder("=====================================\n");
stringBuilder.append("Recibo de venda número: ").append(this.id).append("\n");
stringBuilder.append("Numero do item | Código | Descricão | Preço unitário | Quantidade | Valor do item \n");
for (int i = 0; i < list.size(); i++) {
stringBuilder.append(i + 1).append(" | ")
.append(list.get(i).getBarCode()).append(" | ")
.append(list.get(i).getDescription()).append(" | ")
.append(list.get(i).getPrice()).append(" | ")
.append(list.get(i).getAmount()).append(" | ")
.append((round(list.get(i).getAmount() * list.get(i).getPrice()))).append("\n");
}
stringBuilder.append("\t\t\t\tTotal | ").append(this.totalPrice).append("\n")
.append("\t\t\t\tDesconto | ").append(this.discount).append("\n")
.append("\t\t\t\tImposto | ").append(this.tax).append("\n")
.append("\t\t\t\tValor da venda | ").append(this.total);
stringBuilder.append("\n=====================================\n");
return stringBuilder.toString();
}
private double round(double price) {
double roundedPrice = price * 100;
roundedPrice = Math.ceil(roundedPrice);
return roundedPrice / 100;
}
}
| 2,144 | 0.548855 | 0.545115 | 57 | 36.526318 | 30.761736 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.842105 | false | false | 1 |
c9df01c92f67a8d2ca2add886bd48b1c3f83fe43 | 22,677,427,355,767 | 5f60a6de05fd72ce263e434e216df68cb3bff071 | /src/main/java/com/jlab/customermanagement/service/CustomerService.java | 8d74eb1e98eeb06496c1f764abc36cf056fc0bea | [
"Apache-2.0"
]
| permissive | jac-gt/customer-management-app | https://github.com/jac-gt/customer-management-app | ea0920cff914ef6f49ca4b873fa2726e2f53ded1 | 9343b878112d2282416e6abfee3be34dba4b9c68 | refs/heads/master | 2020-04-26T07:07:51.184000 | 2019-03-03T21:28:41 | 2019-03-03T21:28:41 | 173,385,188 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jlab.customermanagement.service;
import java.util.List;
import java.util.Optional;
import com.jlab.customermanagement.model.Customer;
public interface CustomerService {
public Customer save(Customer customer);
public List<Customer> all();
public Customer one(long id);
public void delete(long customerId);
}
| UTF-8 | Java | 351 | java | CustomerService.java | Java | []
| null | []
| package com.jlab.customermanagement.service;
import java.util.List;
import java.util.Optional;
import com.jlab.customermanagement.model.Customer;
public interface CustomerService {
public Customer save(Customer customer);
public List<Customer> all();
public Customer one(long id);
public void delete(long customerId);
}
| 351 | 0.74359 | 0.74359 | 18 | 17.5 | 18.306799 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 3 |
5058db1f0c506dc572c6fb94ee2ac0007baa0222 | 21,758,304,355,342 | 8bcfea9936a4ca147948a2a77be435ac1bfa2566 | /src/main/java/dataAccess/FollowingTraingAcces.java | 329d32e0e01571e960ac549681ab3b9c839046d2 | []
| no_license | SoftwareProjectIIGroep4/java | https://github.com/SoftwareProjectIIGroep4/java | 8e0d5d037a993bb283717a9b63dd7b4aa0fd180f | 51f623a49dffe5b8c0b86f470def0eccd00e45b9 | refs/heads/master | 2021-05-15T09:29:55.952000 | 2017-12-24T11:59:57 | 2017-12-24T11:59:57 | 108,137,863 | 0 | 0 | null | false | 2017-12-25T07:05:04 | 2017-10-24T14:22:56 | 2017-10-24T14:31:28 | 2017-12-25T07:05:04 | 795 | 0 | 0 | 0 | Java | false | null | package dataAccess;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import models.Address;
import models.FollowingTraining;
public class FollowingTraingAcces extends RestRequest {
public static FollowingTraining get(Integer id) throws IOException, URISyntaxException {
String JSONFollowingt = getAllOrOne(new URI(Constants.FOLLOWING_TRAINING_SOURCE + id));
FollowingTraining followingTraining = mapper.readValue(JSONFollowingt, FollowingTraining.class);
return followingTraining;
}
public static HashMap<Integer, FollowingTraining> getAll() throws IOException, URISyntaxException {
String JSONFollowingt = getAllOrOne(new URI(Constants.FOLLOWING_TRAINING_SOURCE));
List<FollowingTraining> followingTrainings = mapper.readValue(JSONFollowingt, new TypeReference<List<FollowingTraining>>() {
});
HashMap<Integer, FollowingTraining> followingTrainingsMap = new HashMap<Integer, FollowingTraining>();
for (FollowingTraining followingTraining : followingTrainings) {
followingTrainingsMap.put(followingTraining.getTraingSessionId(), followingTraining);
}
return followingTrainingsMap;
}
public static FollowingTraining add(FollowingTraining followingTraining) throws IOException, URISyntaxException {
String JSONFollowingt = postObject(followingTraining, new URI(Constants.FOLLOWING_TRAINING_SOURCE));
return mapper.readValue(JSONFollowingt, FollowingTraining.class);
}
public static void update(FollowingTraining followingTraining) throws URISyntaxException, IOException {
putObject(followingTraining, new URI(Constants.FOLLOWING_TRAINING_SOURCE + followingTraining.getTraingSessionId()));
}
}
| UTF-8 | Java | 1,801 | java | FollowingTraingAcces.java | Java | []
| null | []
| package dataAccess;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import models.Address;
import models.FollowingTraining;
public class FollowingTraingAcces extends RestRequest {
public static FollowingTraining get(Integer id) throws IOException, URISyntaxException {
String JSONFollowingt = getAllOrOne(new URI(Constants.FOLLOWING_TRAINING_SOURCE + id));
FollowingTraining followingTraining = mapper.readValue(JSONFollowingt, FollowingTraining.class);
return followingTraining;
}
public static HashMap<Integer, FollowingTraining> getAll() throws IOException, URISyntaxException {
String JSONFollowingt = getAllOrOne(new URI(Constants.FOLLOWING_TRAINING_SOURCE));
List<FollowingTraining> followingTrainings = mapper.readValue(JSONFollowingt, new TypeReference<List<FollowingTraining>>() {
});
HashMap<Integer, FollowingTraining> followingTrainingsMap = new HashMap<Integer, FollowingTraining>();
for (FollowingTraining followingTraining : followingTrainings) {
followingTrainingsMap.put(followingTraining.getTraingSessionId(), followingTraining);
}
return followingTrainingsMap;
}
public static FollowingTraining add(FollowingTraining followingTraining) throws IOException, URISyntaxException {
String JSONFollowingt = postObject(followingTraining, new URI(Constants.FOLLOWING_TRAINING_SOURCE));
return mapper.readValue(JSONFollowingt, FollowingTraining.class);
}
public static void update(FollowingTraining followingTraining) throws URISyntaxException, IOException {
putObject(followingTraining, new URI(Constants.FOLLOWING_TRAINING_SOURCE + followingTraining.getTraingSessionId()));
}
}
| 1,801 | 0.810106 | 0.810106 | 43 | 40.88372 | 42.496628 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.534884 | false | false | 3 |
8093af03dbe386a8f91a788dc39382b1e90010c8 | 16,724,602,672,043 | 5745e586d9ea2efa8815cce83951dbfe686282db | /src/assignment4/DessertShop.java | be128f9a7fcd6e67274aa0cf60a7d1e907dd0f00 | []
| no_license | dustfreer/INFO5100assignment | https://github.com/dustfreer/INFO5100assignment | 56a3e95efea6f95cfb2ac881bf763295243c44d1 | 77f690282a6c399315324ad13c19d7051f43bba3 | refs/heads/master | 2020-07-22T11:25:36.494000 | 2019-11-10T22:49:14 | 2019-11-10T22:49:14 | 207,183,724 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package assignment4;
import java.util.ArrayList;
import java.util.List;
public class DessertShop {
public static final double taxRate = 0.065;
static int maxImumSizeOfName = 35;
static String cents2dollarsAndCentsmethod(int dollar){
String dol = "" + dollar / 100;
String cent = "." + dollar % 100;
return dol + cent;
}
static String setSpace(String line, String cost){
int spaceNum = maxImumSizeOfName - line.length() - cost.length();
for ( int i = 0 ; i < spaceNum; i++)
line = line + " ";
line = line + cost +"\n";
return line;
}
public static abstract class DessertItem{
protected String name;
public DessertItem() {
}
public DessertItem(String name) {
}
public String getName() {
return name;
}
public abstract int getCost();
}
public static class Checkout{
protected List<DessertItem> dessertItems = new ArrayList<DessertItem>();
public Checkout(){;
}
public int numberOfItems() {
return dessertItems.size();
}
public void enterItem(DessertItem item) {
dessertItems.add(item);
}
public void clear() {
dessertItems.removeAll(dessertItems);
}
public int totalCost() {
int totalcost = 0;
for ( DessertItem d : dessertItems) {
//System.out.println(d.getCost());
totalcost += d.getCost();
}
return totalcost;
}
public int totalTax() {
int totaltax = Math.round((float)(this.totalCost() * taxRate));
return totaltax;
}
public String toString() {
String receipt = "";
receipt += " M & M Dessert Shoppen\n";
receipt += " ---------------------\n\n";
String line = "" ;
for( DessertItem d : dessertItems) {
line = d.getName();
if ( d.getClass().getSimpleName().equals("Sundae")) {
String[] n= d.getName().split("\n", 0);
receipt += n[0]+ "\n";
line = n[1];
}else if ( d.getClass().getSimpleName().equals("Candy")) {
receipt += "2.25 lbs. @ 3.99 /lb.\n";
}else if ( d.getClass().getSimpleName().equals("Cookie")) {
receipt += "4 @ 3.99 /dz.\n";
}
String cost = cents2dollarsAndCentsmethod(d.getCost());
line = setSpace(line, cost);
receipt += line;
}
String taxLine = setSpace("Tax", cents2dollarsAndCentsmethod(this.totalTax()));
receipt += taxLine;
String totalCostLine = setSpace("Total Cost", cents2dollarsAndCentsmethod(this.totalCost()+this.totalTax()));
receipt += totalCostLine;
return receipt;
}
}
}
| UTF-8 | Java | 2,487 | java | DessertShop.java | Java | []
| null | []
| package assignment4;
import java.util.ArrayList;
import java.util.List;
public class DessertShop {
public static final double taxRate = 0.065;
static int maxImumSizeOfName = 35;
static String cents2dollarsAndCentsmethod(int dollar){
String dol = "" + dollar / 100;
String cent = "." + dollar % 100;
return dol + cent;
}
static String setSpace(String line, String cost){
int spaceNum = maxImumSizeOfName - line.length() - cost.length();
for ( int i = 0 ; i < spaceNum; i++)
line = line + " ";
line = line + cost +"\n";
return line;
}
public static abstract class DessertItem{
protected String name;
public DessertItem() {
}
public DessertItem(String name) {
}
public String getName() {
return name;
}
public abstract int getCost();
}
public static class Checkout{
protected List<DessertItem> dessertItems = new ArrayList<DessertItem>();
public Checkout(){;
}
public int numberOfItems() {
return dessertItems.size();
}
public void enterItem(DessertItem item) {
dessertItems.add(item);
}
public void clear() {
dessertItems.removeAll(dessertItems);
}
public int totalCost() {
int totalcost = 0;
for ( DessertItem d : dessertItems) {
//System.out.println(d.getCost());
totalcost += d.getCost();
}
return totalcost;
}
public int totalTax() {
int totaltax = Math.round((float)(this.totalCost() * taxRate));
return totaltax;
}
public String toString() {
String receipt = "";
receipt += " M & M Dessert Shoppen\n";
receipt += " ---------------------\n\n";
String line = "" ;
for( DessertItem d : dessertItems) {
line = d.getName();
if ( d.getClass().getSimpleName().equals("Sundae")) {
String[] n= d.getName().split("\n", 0);
receipt += n[0]+ "\n";
line = n[1];
}else if ( d.getClass().getSimpleName().equals("Candy")) {
receipt += "2.25 lbs. @ 3.99 /lb.\n";
}else if ( d.getClass().getSimpleName().equals("Cookie")) {
receipt += "4 @ 3.99 /dz.\n";
}
String cost = cents2dollarsAndCentsmethod(d.getCost());
line = setSpace(line, cost);
receipt += line;
}
String taxLine = setSpace("Tax", cents2dollarsAndCentsmethod(this.totalTax()));
receipt += taxLine;
String totalCostLine = setSpace("Total Cost", cents2dollarsAndCentsmethod(this.totalCost()+this.totalTax()));
receipt += totalCostLine;
return receipt;
}
}
}
| 2,487 | 0.618416 | 0.605549 | 106 | 22.462265 | 21.518827 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.867924 | false | false | 3 |
098a1f818c866467f8c05f140793188681ba7da6 | 33,225,867,025,901 | 0f6e7b83c8cd851ff9e72b7444f821c16844dd17 | /libraries/AIRSResponseExecutor/src/airs/responses/executor/FixedParamsFormatter.java | 54c3417511c6ebaeabed54725834095b3fd07896 | []
| no_license | lvazquez-ditupm/ProyectoRECLAMO | https://github.com/lvazquez-ditupm/ProyectoRECLAMO | cbc47023263a3fe2c3836e2092e7d4da78c5f9e2 | 6983d5d98b8571767b603204fe719678a63aa522 | refs/heads/master | 2021-01-21T04:46:45.662000 | 2016-06-08T11:01:59 | 2016-06-08T11:01:59 | 54,195,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* "FixedParamsFormatter" Java class is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version always keeping
* the additional terms specified in this license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
*
* Additional Terms of this License
* --------------------------------
*
* 1. It is Required the preservation of specified reasonable legal notices
* and author attributions in that material and in the Appropriate Legal
* Notices displayed by works containing it.
*
* 2. It is limited the use for publicity purposes of names of licensors or
* authors of the material.
*
* 3. It is Required indemnification of licensors and authors of that material
* by anyone who conveys the material (or modified versions of it) with
* contractual assumptions of liability to the recipient, for any liability
* that these contractual assumptions directly impose on those licensors
* and authors.
*
* 4. It is Prohibited misrepresentation of the origin of that material, and it is
* required that modified versions of such material be marked in reasonable
* ways as different from the original version.
*
* 5. It is Declined to grant rights under trademark law for use of some trade
* names, trademarks, or service marks.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (lgpl.txt). If not, see <http://www.gnu.org/licenses/>
*/
package airs.responses.executor;
import airs.responses.executor.utils.PropsUtil;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* This class parses the config files of the responses executor module:
* airsResponseExecutor.conf and plugin-number.conf.
*
* @author UPM (member of RECLAMO Development Team)(http://reclamo.inf.um.es)
* @version 1.0
*/
public class FixedParamsFormatter {
private ExecutorAgentList _executorAgentList;
private GroupExecutorAgentsList _groupExecutorList;
private SidsGroupList _sidsGroupList;
private ResponseActionList _responseActionList;
private PluginList _pluginList;
private PropsUtil props = new PropsUtil();
public FixedParamsFormatter() throws IOException {
_executorAgentList = new ExecutorAgentList();
_groupExecutorList = new GroupExecutorAgentsList();
_sidsGroupList = new SidsGroupList();
_responseActionList = new ResponseActionList();
_pluginList = new PluginList();
}
public void ParseConfigFile(String fileName) {
try {
BufferedReader buff = new BufferedReader(new FileReader(fileName));
String line;
ExecutorAgent agent;
String configLine[];
String handler;
String params;
GroupExecutorAgents group;
SidsGroup sids;
ResponseAction response;
int numberLine = 1;
while ((line = buff.readLine()) != null) {
configLine = ParseLine(line, numberLine);
if (configLine != null) {
handler = configLine[0];
params = configLine[1];
if (handler.equalsIgnoreCase("executor_agent")) {
//It's because the executor agent could be defined with port param and it uses ':'
if (configLine.length > 2) {
params = configLine[1] + ":" + configLine[2];
}
agent = ParseExecutorAgent(params, numberLine);
if (agent != null) {
getExecutorAgentList().AddExecutorAgent(agent);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new executor agent:"+agent.toString());
}
}
} else if (handler.equalsIgnoreCase("group")) {
group = ParseGroupExecutors(params, numberLine);
if (group != null) {
getGroupExecutorList().AddGroupExecutorAgent(group);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.print("Debug:[MCER] Parsing a new group of executor agents:");
group.PrintExecutorGroup();
}
}
} else if (handler.equalsIgnoreCase("sid_group")) {
sids = ParseSidsGroup(params, numberLine);
if (sids != null) {
getSidsGroupList().AddSidsGroup(sids);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new SIDS group:"+ sids.toString());
}
}
} else if (handler.equalsIgnoreCase("response_action")) {
response = ParseResponseAction(params, numberLine);
if (response != null) {
getResponseActionList().AddsResponseAction(response);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new response action:"+ response.toString());
}
}
} else if (handler.equalsIgnoreCase("composed")) {
//Configline[2] contains defines sids group composed:name>r1,r2,r3:sid-group
response = ParseComposed(params, configLine[2].trim(), numberLine);
if (response != null){
getResponseActionList().AddsResponseAction(response);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new response action:"+ response.toString());
}
}
} else if (handler.equalsIgnoreCase("logfile")) {
PropsUtil.logFile = PropsUtil.removeSpaces(params);
} else if (handler.equalsIgnoreCase("loglevel")) {
PropsUtil.logLevel = Integer.parseInt(PropsUtil.removeSpaces(params));
} else {
PropsUtil.LoggMessage(1, "Error:[ParseConfigFile]["+props.CONF_FILE +
":"+numberLine+"] "+handler+" unknown option", "AIRSResponseExecutor");
}
}
numberLine++;
}
} catch (IOException e) {
PropsUtil.LoggMessage(1, "Error:[ParseConfigFile] "+fileName+" can't be read or found.", "AIRSResponseExecutor");
}
}
/***
*This function ignores comment and blank lines. Returns only configuration lines.
* @param line.- Configuration line.
* @param numberLine .- Number line in the configuration file.
* @return An String vector (size=2) which contains a handler word and its parameters. Return NULL when
* line is a comment or blank.
*/
public String[] ParseLine(String line, int numberLine) {
try{
if (line != null && !line.isEmpty()) {
String options[];
String option;
options = line.split(":");
option = PropsUtil.removeSpaces(options[0]);
if (option.charAt(0) != '#') {
options[0] = PropsUtil.removeSpaces(options[0]);
return options;
} else {
return null;
}
} else {
return null;
}
}catch(StringIndexOutOfBoundsException ex){ //It's used to control the empty lines in configuration file
return null;
}
}
public ExecutorAgent ParseExecutorAgent(String line, int numberLine) {
ExecutorAgent executor = new ExecutorAgent();
String params[];
String hostport[];
params = line.split(",");
if(params.length >= 2){
executor.setId(params[0].trim());
hostport=params[1].split(":");
executor.setHost(hostport[0].trim());
if(hostport.length==2){
executor.setPort(Integer.parseInt(hostport[1].trim()));
}
if(params.length >=3){
executor.setKey(params[2].trim());
}
}else{
PropsUtil.LoggMessage(1, "Error:[ParseExecutorAgent]["+props.CONF_FILE+":"+numberLine+"] Undefined hostname or IP parameter.", "AIRSResponseExecutor");
return null;
}
return executor;
}
public GroupExecutorAgents ParseGroupExecutors(String line, int numberLine) {
GroupExecutorAgents group = new GroupExecutorAgents();
String params[];
String agents[];
String idExecutor;
params=line.split(">");
if(params.length==2){
group.setId(params[0].trim());
agents=params[1].split(",");
for(int i=0; i<agents.length;i++){
idExecutor=agents[i].trim();
if (group.checkExistExecutor(idExecutor) == null) {
ExecutorAgent executor = getExecutorAgentList().getExistExecutorbyid(idExecutor);
if (executor != null) {
group.AddExecutorAgent(executor);
} else {
PropsUtil.LoggMessage(1, "Error:[ParseGroupExecutors]["+props.CONF_FILE+":"+numberLine+"] "
+idExecutor + " executor agent doesn't exists.", "AIRSResponseExecutor");
}
} else {
PropsUtil.LoggMessage(3, "Info:[ParseGroupExecutors]["+props.CONF_FILE+":"+numberLine+"] Skipping "
+idExecutor + " executor agent, it already exists.", "AIRSResponseExecutor");
}
}
}else{
PropsUtil.LoggMessage(1, "Error:[ParseGroupExecutors["+props.CONF_FILE+":"+numberLine+"] Invalid number of parameters.", "AIRSExecutorAgent");
return null;
}
return group;
}
public SidsGroup ParseSidsGroup(String line, int numberLine) {
SidsGroup sidsgroup = new SidsGroup();
String params[];
String sids[];
params=line.split(">");
if(params.length==2){
sidsgroup.setNameSidsGroup(params[0].trim());
sids=params[1].split(",");
for(int i=0; i<sids.length;i++){
sidsgroup.getSidsList().add(Integer.parseInt(sids[i].trim()));
}
}else{
PropsUtil.LoggMessage(1, "Error:[ParseSidsGroup["+props.CONF_FILE+":"+numberLine+"] Invalid number of parameters.", "AIRSExecutorAgent");
return null;
}
return sidsgroup;
}
public ResponseAction ParseResponseAction(String line, int numberLine) throws IOException {
ResponseAction response = new ResponseAction();
GroupExecutorAgents group;
String groupId = new String();
Plugin plugin;
String sidsname;
SidsGroup sidsgroup;
String handlerplugin;
String params[] = line.split(",");
if (params.length == 8) {
response.setName(PropsUtil.removeSpaces(params[0]));
groupId = PropsUtil.removeSpaces(params[1]);
if (groupId.equalsIgnoreCase("THIS")) {
group = new GroupExecutorAgents();
} else {
group = getGroupExecutorList().getExistGroup(groupId);
if (group == null) {
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined group of executor agents.", "AIRSResponseExecutor");
return null;
}
}
response.setGroupExecutorAgents(group);
handlerplugin = PropsUtil.removeSpaces(params[2]);
if (handlerplugin.equalsIgnoreCase("ALL")) {
plugin = new Plugin();
response.setPlugin(plugin);
} else {
plugin = getPluginList().getExistPlugin(handlerplugin);
if (plugin != null) {
response.setPlugin(plugin);
} else {
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined plugin handler.", "AIRSResponseExecutor");
return null;
}
}
response.setWho(PropsUtil.removeSpaces(params[3]));
response.setExecuteFlag(PropsUtil.removeSpaces(params[4]));
response.setDuration(PropsUtil.removeSpaces(params[5]));
response.setMode(PropsUtil.removeSpaces(params[6]));
sidsname=params[7].trim();
if(sidsname.equalsIgnoreCase("ALL")){
response.setSids(new SidsGroup());
response.getSids().getSidsList().add(0,0);
}else{
sidsgroup = this.getSidsGroupList().getExistSid(sidsname);
if(sidsgroup != null){
response.setSids(sidsgroup);
}else{
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined SIDs group.", "AIRSResponseExecutor");
return null;
}
}
return response;
} else {
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Invalid number of parameters.", "AIRSResponseExecutor");
return null;
}
}
public void ParsePlugin(String fileName) throws IOException {
BufferedReader buff;
String line;
Plugin plugin;
String params[];
int numberLine = 1;
try {
buff = new BufferedReader(new FileReader(fileName));
while ((line = buff.readLine()) != null) {
params = ParseLine(line, numberLine);
if (params != null) {
if (params.length == 2) {
plugin = new Plugin(PropsUtil.removeSpaces(params[0]), Integer.parseInt(PropsUtil.removeSpaces(params[1])));
getPluginList().AddsPlugin(plugin);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Adding a new plugin handler: "+plugin.toString());
}
} else {
PropsUtil.LoggMessage(1,"Error:[ParsePlugin]["+props.PLUGIN_NUMBERS_FILE+":"+numberLine+"]"
+ "Incorrect number of params.","AIRSResponseExecutor");
}
}
numberLine++;
}
} catch (FileNotFoundException ex) {
PropsUtil.LoggMessage(1, "Error:[ParsePlugin] "+fileName +" can't read or found.", "AIRSResponseExecutor");
}
}
public ResponseAction ParseComposed (String line, String sidsname, int numberLine) throws IOException{
ResponseAction response;
String params[];
String components[];
String name_response;
String name_composed;
ArrayList<String> response_composed;
SidsGroup sidsgroup;
if(sidsname!=null){
params = line.split(">");
if(params.length != 2){
PropsUtil.LoggMessage(1,"Error: [ParseComposed] ["+props.CONF_FILE+":"+numberLine+"]"
+ "Invalid number of params.","AIRSResponseExecutor");
return null;
}
if(!params[1].isEmpty()){
components=params[1].split(",");
}else {
PropsUtil.LoggMessage(1,"Error: [ParseComposed] ["+props.CONF_FILE+":"+numberLine+"]"
+ "Undefined response actions.","AIRSResponseExecutor");
return null;
}
name_composed=PropsUtil.removeSpaces(params[0]);
response_composed=new ArrayList<String>();
for(int i=0; i<components.length; i++){
name_response = PropsUtil.removeSpaces(components[i]);
if(this.getResponseActionList().getExistResponseActions(name_response)==null){
PropsUtil.LoggMessage(1,"Error: [ParseComposed] ["+props.CONF_FILE+":"+numberLine+"]"
+ " Undefined \""+ name_response +"\" response action.","AIRSResponseExecutor");
return null;
}else{
response_composed.add(name_response);
}
}
if(sidsname.equalsIgnoreCase("ALL")){
sidsgroup = new SidsGroup();
sidsgroup.getSidsList().add(0,0);
}else{
sidsgroup = this.getSidsGroupList().getExistSid(sidsname);
if(sidsgroup == null){
PropsUtil.LoggMessage(1, "Error:[ParseComposed]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined SIDs group.", "AIRSResponseExecutor");
return null;
}
}
response=new ResponseAction(name_composed,null,null,null,null,null,null,true,response_composed,sidsgroup);
return response;
}else{
PropsUtil.LoggMessage(1, "Error:[ParseComposed]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined SIDs group parameter.", "AIRSResponseExecutor");
return null;
}
}
//Auxiliar functions
/**
*
* @param parameter
* @return
*/
//Properties
public ExecutorAgentList getExecutorAgentList() {
return _executorAgentList;
}
public GroupExecutorAgentsList getGroupExecutorList() {
return _groupExecutorList;
}
public SidsGroupList getSidsGroupList() {
return _sidsGroupList;
}
public ResponseActionList getResponseActionList() {
return _responseActionList;
}
public PluginList getPluginList() {
return _pluginList;
}
public void setGroupExecutorList(GroupExecutorAgentsList value) {
_groupExecutorList = value;
}
public void setExecutorAgentList(ExecutorAgentList value) {
_executorAgentList = value;
}
public void setSidsGroupList(SidsGroupList _sidsGroupList) {
this._sidsGroupList = _sidsGroupList;
}
public void setResponseActionList(ResponseActionList value) {
_responseActionList = value;
}
public void setPluginList(PluginList value) {
_pluginList = value;
}
} | UTF-8 | Java | 19,980 | java | FixedParamsFormatter.java | Java | [
{
"context": "cutor.conf and plugin-number.conf.\n * \n * @author UPM (member of RECLAMO Development Team)(http://recla",
"end": 2208,
"score": 0.9994809627532959,
"start": 2205,
"tag": "USERNAME",
"value": "UPM"
}
]
| null | []
| /**
* "FixedParamsFormatter" Java class is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version always keeping
* the additional terms specified in this license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
*
* Additional Terms of this License
* --------------------------------
*
* 1. It is Required the preservation of specified reasonable legal notices
* and author attributions in that material and in the Appropriate Legal
* Notices displayed by works containing it.
*
* 2. It is limited the use for publicity purposes of names of licensors or
* authors of the material.
*
* 3. It is Required indemnification of licensors and authors of that material
* by anyone who conveys the material (or modified versions of it) with
* contractual assumptions of liability to the recipient, for any liability
* that these contractual assumptions directly impose on those licensors
* and authors.
*
* 4. It is Prohibited misrepresentation of the origin of that material, and it is
* required that modified versions of such material be marked in reasonable
* ways as different from the original version.
*
* 5. It is Declined to grant rights under trademark law for use of some trade
* names, trademarks, or service marks.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (lgpl.txt). If not, see <http://www.gnu.org/licenses/>
*/
package airs.responses.executor;
import airs.responses.executor.utils.PropsUtil;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* This class parses the config files of the responses executor module:
* airsResponseExecutor.conf and plugin-number.conf.
*
* @author UPM (member of RECLAMO Development Team)(http://reclamo.inf.um.es)
* @version 1.0
*/
public class FixedParamsFormatter {
private ExecutorAgentList _executorAgentList;
private GroupExecutorAgentsList _groupExecutorList;
private SidsGroupList _sidsGroupList;
private ResponseActionList _responseActionList;
private PluginList _pluginList;
private PropsUtil props = new PropsUtil();
public FixedParamsFormatter() throws IOException {
_executorAgentList = new ExecutorAgentList();
_groupExecutorList = new GroupExecutorAgentsList();
_sidsGroupList = new SidsGroupList();
_responseActionList = new ResponseActionList();
_pluginList = new PluginList();
}
public void ParseConfigFile(String fileName) {
try {
BufferedReader buff = new BufferedReader(new FileReader(fileName));
String line;
ExecutorAgent agent;
String configLine[];
String handler;
String params;
GroupExecutorAgents group;
SidsGroup sids;
ResponseAction response;
int numberLine = 1;
while ((line = buff.readLine()) != null) {
configLine = ParseLine(line, numberLine);
if (configLine != null) {
handler = configLine[0];
params = configLine[1];
if (handler.equalsIgnoreCase("executor_agent")) {
//It's because the executor agent could be defined with port param and it uses ':'
if (configLine.length > 2) {
params = configLine[1] + ":" + configLine[2];
}
agent = ParseExecutorAgent(params, numberLine);
if (agent != null) {
getExecutorAgentList().AddExecutorAgent(agent);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new executor agent:"+agent.toString());
}
}
} else if (handler.equalsIgnoreCase("group")) {
group = ParseGroupExecutors(params, numberLine);
if (group != null) {
getGroupExecutorList().AddGroupExecutorAgent(group);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.print("Debug:[MCER] Parsing a new group of executor agents:");
group.PrintExecutorGroup();
}
}
} else if (handler.equalsIgnoreCase("sid_group")) {
sids = ParseSidsGroup(params, numberLine);
if (sids != null) {
getSidsGroupList().AddSidsGroup(sids);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new SIDS group:"+ sids.toString());
}
}
} else if (handler.equalsIgnoreCase("response_action")) {
response = ParseResponseAction(params, numberLine);
if (response != null) {
getResponseActionList().AddsResponseAction(response);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new response action:"+ response.toString());
}
}
} else if (handler.equalsIgnoreCase("composed")) {
//Configline[2] contains defines sids group composed:name>r1,r2,r3:sid-group
response = ParseComposed(params, configLine[2].trim(), numberLine);
if (response != null){
getResponseActionList().AddsResponseAction(response);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Parsing a new response action:"+ response.toString());
}
}
} else if (handler.equalsIgnoreCase("logfile")) {
PropsUtil.logFile = PropsUtil.removeSpaces(params);
} else if (handler.equalsIgnoreCase("loglevel")) {
PropsUtil.logLevel = Integer.parseInt(PropsUtil.removeSpaces(params));
} else {
PropsUtil.LoggMessage(1, "Error:[ParseConfigFile]["+props.CONF_FILE +
":"+numberLine+"] "+handler+" unknown option", "AIRSResponseExecutor");
}
}
numberLine++;
}
} catch (IOException e) {
PropsUtil.LoggMessage(1, "Error:[ParseConfigFile] "+fileName+" can't be read or found.", "AIRSResponseExecutor");
}
}
/***
*This function ignores comment and blank lines. Returns only configuration lines.
* @param line.- Configuration line.
* @param numberLine .- Number line in the configuration file.
* @return An String vector (size=2) which contains a handler word and its parameters. Return NULL when
* line is a comment or blank.
*/
public String[] ParseLine(String line, int numberLine) {
try{
if (line != null && !line.isEmpty()) {
String options[];
String option;
options = line.split(":");
option = PropsUtil.removeSpaces(options[0]);
if (option.charAt(0) != '#') {
options[0] = PropsUtil.removeSpaces(options[0]);
return options;
} else {
return null;
}
} else {
return null;
}
}catch(StringIndexOutOfBoundsException ex){ //It's used to control the empty lines in configuration file
return null;
}
}
public ExecutorAgent ParseExecutorAgent(String line, int numberLine) {
ExecutorAgent executor = new ExecutorAgent();
String params[];
String hostport[];
params = line.split(",");
if(params.length >= 2){
executor.setId(params[0].trim());
hostport=params[1].split(":");
executor.setHost(hostport[0].trim());
if(hostport.length==2){
executor.setPort(Integer.parseInt(hostport[1].trim()));
}
if(params.length >=3){
executor.setKey(params[2].trim());
}
}else{
PropsUtil.LoggMessage(1, "Error:[ParseExecutorAgent]["+props.CONF_FILE+":"+numberLine+"] Undefined hostname or IP parameter.", "AIRSResponseExecutor");
return null;
}
return executor;
}
public GroupExecutorAgents ParseGroupExecutors(String line, int numberLine) {
GroupExecutorAgents group = new GroupExecutorAgents();
String params[];
String agents[];
String idExecutor;
params=line.split(">");
if(params.length==2){
group.setId(params[0].trim());
agents=params[1].split(",");
for(int i=0; i<agents.length;i++){
idExecutor=agents[i].trim();
if (group.checkExistExecutor(idExecutor) == null) {
ExecutorAgent executor = getExecutorAgentList().getExistExecutorbyid(idExecutor);
if (executor != null) {
group.AddExecutorAgent(executor);
} else {
PropsUtil.LoggMessage(1, "Error:[ParseGroupExecutors]["+props.CONF_FILE+":"+numberLine+"] "
+idExecutor + " executor agent doesn't exists.", "AIRSResponseExecutor");
}
} else {
PropsUtil.LoggMessage(3, "Info:[ParseGroupExecutors]["+props.CONF_FILE+":"+numberLine+"] Skipping "
+idExecutor + " executor agent, it already exists.", "AIRSResponseExecutor");
}
}
}else{
PropsUtil.LoggMessage(1, "Error:[ParseGroupExecutors["+props.CONF_FILE+":"+numberLine+"] Invalid number of parameters.", "AIRSExecutorAgent");
return null;
}
return group;
}
public SidsGroup ParseSidsGroup(String line, int numberLine) {
SidsGroup sidsgroup = new SidsGroup();
String params[];
String sids[];
params=line.split(">");
if(params.length==2){
sidsgroup.setNameSidsGroup(params[0].trim());
sids=params[1].split(",");
for(int i=0; i<sids.length;i++){
sidsgroup.getSidsList().add(Integer.parseInt(sids[i].trim()));
}
}else{
PropsUtil.LoggMessage(1, "Error:[ParseSidsGroup["+props.CONF_FILE+":"+numberLine+"] Invalid number of parameters.", "AIRSExecutorAgent");
return null;
}
return sidsgroup;
}
public ResponseAction ParseResponseAction(String line, int numberLine) throws IOException {
ResponseAction response = new ResponseAction();
GroupExecutorAgents group;
String groupId = new String();
Plugin plugin;
String sidsname;
SidsGroup sidsgroup;
String handlerplugin;
String params[] = line.split(",");
if (params.length == 8) {
response.setName(PropsUtil.removeSpaces(params[0]));
groupId = PropsUtil.removeSpaces(params[1]);
if (groupId.equalsIgnoreCase("THIS")) {
group = new GroupExecutorAgents();
} else {
group = getGroupExecutorList().getExistGroup(groupId);
if (group == null) {
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined group of executor agents.", "AIRSResponseExecutor");
return null;
}
}
response.setGroupExecutorAgents(group);
handlerplugin = PropsUtil.removeSpaces(params[2]);
if (handlerplugin.equalsIgnoreCase("ALL")) {
plugin = new Plugin();
response.setPlugin(plugin);
} else {
plugin = getPluginList().getExistPlugin(handlerplugin);
if (plugin != null) {
response.setPlugin(plugin);
} else {
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined plugin handler.", "AIRSResponseExecutor");
return null;
}
}
response.setWho(PropsUtil.removeSpaces(params[3]));
response.setExecuteFlag(PropsUtil.removeSpaces(params[4]));
response.setDuration(PropsUtil.removeSpaces(params[5]));
response.setMode(PropsUtil.removeSpaces(params[6]));
sidsname=params[7].trim();
if(sidsname.equalsIgnoreCase("ALL")){
response.setSids(new SidsGroup());
response.getSids().getSidsList().add(0,0);
}else{
sidsgroup = this.getSidsGroupList().getExistSid(sidsname);
if(sidsgroup != null){
response.setSids(sidsgroup);
}else{
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined SIDs group.", "AIRSResponseExecutor");
return null;
}
}
return response;
} else {
PropsUtil.LoggMessage(1, "Error:[ParseResponseAction]["+props.CONF_FILE+ ":"+ numberLine +
"] Invalid number of parameters.", "AIRSResponseExecutor");
return null;
}
}
public void ParsePlugin(String fileName) throws IOException {
BufferedReader buff;
String line;
Plugin plugin;
String params[];
int numberLine = 1;
try {
buff = new BufferedReader(new FileReader(fileName));
while ((line = buff.readLine()) != null) {
params = ParseLine(line, numberLine);
if (params != null) {
if (params.length == 2) {
plugin = new Plugin(PropsUtil.removeSpaces(params[0]), Integer.parseInt(PropsUtil.removeSpaces(params[1])));
getPluginList().AddsPlugin(plugin);
if(PropsUtil.DEBUG_AIRS_EXE){
System.out.println("Debug:[MCER] Adding a new plugin handler: "+plugin.toString());
}
} else {
PropsUtil.LoggMessage(1,"Error:[ParsePlugin]["+props.PLUGIN_NUMBERS_FILE+":"+numberLine+"]"
+ "Incorrect number of params.","AIRSResponseExecutor");
}
}
numberLine++;
}
} catch (FileNotFoundException ex) {
PropsUtil.LoggMessage(1, "Error:[ParsePlugin] "+fileName +" can't read or found.", "AIRSResponseExecutor");
}
}
public ResponseAction ParseComposed (String line, String sidsname, int numberLine) throws IOException{
ResponseAction response;
String params[];
String components[];
String name_response;
String name_composed;
ArrayList<String> response_composed;
SidsGroup sidsgroup;
if(sidsname!=null){
params = line.split(">");
if(params.length != 2){
PropsUtil.LoggMessage(1,"Error: [ParseComposed] ["+props.CONF_FILE+":"+numberLine+"]"
+ "Invalid number of params.","AIRSResponseExecutor");
return null;
}
if(!params[1].isEmpty()){
components=params[1].split(",");
}else {
PropsUtil.LoggMessage(1,"Error: [ParseComposed] ["+props.CONF_FILE+":"+numberLine+"]"
+ "Undefined response actions.","AIRSResponseExecutor");
return null;
}
name_composed=PropsUtil.removeSpaces(params[0]);
response_composed=new ArrayList<String>();
for(int i=0; i<components.length; i++){
name_response = PropsUtil.removeSpaces(components[i]);
if(this.getResponseActionList().getExistResponseActions(name_response)==null){
PropsUtil.LoggMessage(1,"Error: [ParseComposed] ["+props.CONF_FILE+":"+numberLine+"]"
+ " Undefined \""+ name_response +"\" response action.","AIRSResponseExecutor");
return null;
}else{
response_composed.add(name_response);
}
}
if(sidsname.equalsIgnoreCase("ALL")){
sidsgroup = new SidsGroup();
sidsgroup.getSidsList().add(0,0);
}else{
sidsgroup = this.getSidsGroupList().getExistSid(sidsname);
if(sidsgroup == null){
PropsUtil.LoggMessage(1, "Error:[ParseComposed]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined SIDs group.", "AIRSResponseExecutor");
return null;
}
}
response=new ResponseAction(name_composed,null,null,null,null,null,null,true,response_composed,sidsgroup);
return response;
}else{
PropsUtil.LoggMessage(1, "Error:[ParseComposed]["+props.CONF_FILE+ ":"+ numberLine +
"] Undefined SIDs group parameter.", "AIRSResponseExecutor");
return null;
}
}
//Auxiliar functions
/**
*
* @param parameter
* @return
*/
//Properties
public ExecutorAgentList getExecutorAgentList() {
return _executorAgentList;
}
public GroupExecutorAgentsList getGroupExecutorList() {
return _groupExecutorList;
}
public SidsGroupList getSidsGroupList() {
return _sidsGroupList;
}
public ResponseActionList getResponseActionList() {
return _responseActionList;
}
public PluginList getPluginList() {
return _pluginList;
}
public void setGroupExecutorList(GroupExecutorAgentsList value) {
_groupExecutorList = value;
}
public void setExecutorAgentList(ExecutorAgentList value) {
_executorAgentList = value;
}
public void setSidsGroupList(SidsGroupList _sidsGroupList) {
this._sidsGroupList = _sidsGroupList;
}
public void setResponseActionList(ResponseActionList value) {
_responseActionList = value;
}
public void setPluginList(PluginList value) {
_pluginList = value;
}
} | 19,980 | 0.541642 | 0.537638 | 453 | 43.10817 | 32.107014 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.600442 | false | false | 3 |
9128c840a5656b7229c23e9a2d1392b05644a845 | 29,815,662,995,034 | 62984e78069a83730ab9404841d4de9c6c1b238b | /app/src/main/java/com/example/immortal/clock_seller/fragments/SignUpFragment.java | 009303d333a2adbd0f9a50287697b476ef7c3883 | []
| no_license | tranhoangnhi95/clock_seller | https://github.com/tranhoangnhi95/clock_seller | 571773b381ee22652b300bf294975dc918e7fdcb | e097998317148255d7dfc1fbcb5e2d9a9af75474 | refs/heads/master | 2020-03-19T08:13:00.718000 | 2018-11-15T17:19:16 | 2018-11-15T17:19:16 | 136,185,093 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.immortal.clock_seller.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.immortal.clock_seller.activity.SignInActivity;
import com.example.immortal.clock_seller.R;
import com.example.immortal.clock_seller.model.User;
import com.example.immortal.clock_seller.utils.DrawableClickListener;
import com.example.immortal.clock_seller.utils.TextChangeListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.concurrent.Executor;
public class SignUpFragment extends Fragment {
public EditText txtName, txtPhone, txtEmail, txtAddress, txtPass;
public Button btnSignUp;
public FragmentCommuniCation fragmentCommuniCation;
public DatabaseReference mDatabase;
public FirebaseAuth mAuth;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_signup_fragment, container, false);
inits(view);
signUpEvents();
return view;
}
/**
* Ánh xạ các view và tạo sự kiện
*
* @param view điều khiển
*/
private void inits(View view) {
btnSignUp = view.findViewById(R.id.btn_SUSignUp);
txtName = view.findViewById(R.id.txt_SUName);
txtPhone = view.findViewById(R.id.txt_SUPhone);
txtEmail = view.findViewById(R.id.txt_SUEmail);
txtAddress = view.findViewById(R.id.txt_SUAddress);
txtPass = view.findViewById(R.id.txt_SUPass);
//thêm các sự kiện rightDrawableClick
rightDrawableClick(txtName, R.drawable.person_24dp);
rightDrawableClick(txtPhone, R.drawable.phone_24dp);
rightDrawableClick(txtEmail, R.drawable.email_24dp);
rightDrawableClick(txtAddress, R.drawable.location24dp);
txtPass.setOnTouchListener(new DrawableClickListener.RightDrawableClickListener(txtPass) {
@Override
public boolean onDrawableClick() {
if (txtPass.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
txtPass.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
txtPass.setCompoundDrawablesWithIntrinsicBounds(R.drawable.lock_24dp, 0, R.drawable.visibility_off_24dp, 0);
} else {
txtPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
txtPass.setCompoundDrawablesWithIntrinsicBounds(R.drawable.lock_24dp, 0, R.drawable.visibility_24dp, 0);
}
return true;
}
});
}
//Sự kiện
private void signUpEvents() {
//sự kiên click button đăng nhập
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
String Name, Phone, Email, Address, Pass;
Name = txtName.getText().toString();
Phone = txtPhone.getText().toString();
Email = txtEmail.getText().toString().toLowerCase();
Address = txtAddress.getText().toString();
Pass = txtPass.getText().toString();
SignInActivity activity = (SignInActivity) getActivity();
activity.signUpFragment(Name, Phone, Email, Address, Pass);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getContext(), "Vui lòng nhập dầy đủ thông tin trước khi đăng ký", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onPause() {
super.onPause();
}
//Interface hỗ trợ giao tiếp fragment
public interface FragmentCommuniCation {
void PassingEmail(String Email); //Hàm hỗ trợ truyền email
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
fragmentCommuniCation = (FragmentCommuniCation) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
/**
* Thêm sự kiện rightDrawableClick xóa nội dung editText
*
* @param editText edit text cần thêm sự kiện
* @param drawaleLeft drawable bên trái
*/
private void rightDrawableClick(final EditText editText, final int drawaleLeft) {
//sự kiện RightDrawableClick xóa nội dung edittext
editText.setOnTouchListener(new DrawableClickListener.RightDrawableClickListener(editText) {
@Override
public boolean onDrawableClick() {
editText.setText("");
return true;
}
});
//Sự kiện khi chuỗi của editText thay đổi
editText.addTextChangedListener(new TextChangeListener() {
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//nếu chuỗi rỗng sẽ ẩn drawable
if (charSequence.length() == 0) {
editText.setCompoundDrawablesWithIntrinsicBounds(drawaleLeft, 0, 0, 0);
} else {
//ngược lại hiển thị drawable
editText.setCompoundDrawablesWithIntrinsicBounds(drawaleLeft, 0, R.drawable.cancel_24dp, 0);
}
super.onTextChanged(charSequence, i, i1, i2);
}
});
editText.setCompoundDrawablesWithIntrinsicBounds(drawaleLeft, 0, 0, 0);
}
}
| UTF-8 | Java | 6,718 | java | SignUpFragment.java | Java | []
| null | []
| package com.example.immortal.clock_seller.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.immortal.clock_seller.activity.SignInActivity;
import com.example.immortal.clock_seller.R;
import com.example.immortal.clock_seller.model.User;
import com.example.immortal.clock_seller.utils.DrawableClickListener;
import com.example.immortal.clock_seller.utils.TextChangeListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.concurrent.Executor;
public class SignUpFragment extends Fragment {
public EditText txtName, txtPhone, txtEmail, txtAddress, txtPass;
public Button btnSignUp;
public FragmentCommuniCation fragmentCommuniCation;
public DatabaseReference mDatabase;
public FirebaseAuth mAuth;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_signup_fragment, container, false);
inits(view);
signUpEvents();
return view;
}
/**
* Ánh xạ các view và tạo sự kiện
*
* @param view điều khiển
*/
private void inits(View view) {
btnSignUp = view.findViewById(R.id.btn_SUSignUp);
txtName = view.findViewById(R.id.txt_SUName);
txtPhone = view.findViewById(R.id.txt_SUPhone);
txtEmail = view.findViewById(R.id.txt_SUEmail);
txtAddress = view.findViewById(R.id.txt_SUAddress);
txtPass = view.findViewById(R.id.txt_SUPass);
//thêm các sự kiện rightDrawableClick
rightDrawableClick(txtName, R.drawable.person_24dp);
rightDrawableClick(txtPhone, R.drawable.phone_24dp);
rightDrawableClick(txtEmail, R.drawable.email_24dp);
rightDrawableClick(txtAddress, R.drawable.location24dp);
txtPass.setOnTouchListener(new DrawableClickListener.RightDrawableClickListener(txtPass) {
@Override
public boolean onDrawableClick() {
if (txtPass.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
txtPass.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
txtPass.setCompoundDrawablesWithIntrinsicBounds(R.drawable.lock_24dp, 0, R.drawable.visibility_off_24dp, 0);
} else {
txtPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
txtPass.setCompoundDrawablesWithIntrinsicBounds(R.drawable.lock_24dp, 0, R.drawable.visibility_24dp, 0);
}
return true;
}
});
}
//Sự kiện
private void signUpEvents() {
//sự kiên click button đăng nhập
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
String Name, Phone, Email, Address, Pass;
Name = txtName.getText().toString();
Phone = txtPhone.getText().toString();
Email = txtEmail.getText().toString().toLowerCase();
Address = txtAddress.getText().toString();
Pass = txtPass.getText().toString();
SignInActivity activity = (SignInActivity) getActivity();
activity.signUpFragment(Name, Phone, Email, Address, Pass);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getContext(), "Vui lòng nhập dầy đủ thông tin trước khi đăng ký", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onPause() {
super.onPause();
}
//Interface hỗ trợ giao tiếp fragment
public interface FragmentCommuniCation {
void PassingEmail(String Email); //Hàm hỗ trợ truyền email
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
fragmentCommuniCation = (FragmentCommuniCation) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
/**
* Thêm sự kiện rightDrawableClick xóa nội dung editText
*
* @param editText edit text cần thêm sự kiện
* @param drawaleLeft drawable bên trái
*/
private void rightDrawableClick(final EditText editText, final int drawaleLeft) {
//sự kiện RightDrawableClick xóa nội dung edittext
editText.setOnTouchListener(new DrawableClickListener.RightDrawableClickListener(editText) {
@Override
public boolean onDrawableClick() {
editText.setText("");
return true;
}
});
//Sự kiện khi chuỗi của editText thay đổi
editText.addTextChangedListener(new TextChangeListener() {
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//nếu chuỗi rỗng sẽ ẩn drawable
if (charSequence.length() == 0) {
editText.setCompoundDrawablesWithIntrinsicBounds(drawaleLeft, 0, 0, 0);
} else {
//ngược lại hiển thị drawable
editText.setCompoundDrawablesWithIntrinsicBounds(drawaleLeft, 0, R.drawable.cancel_24dp, 0);
}
super.onTextChanged(charSequence, i, i1, i2);
}
});
editText.setCompoundDrawablesWithIntrinsicBounds(drawaleLeft, 0, 0, 0);
}
}
| 6,718 | 0.654551 | 0.649099 | 170 | 37.841175 | 30.031425 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735294 | false | false | 3 |
d057ce0041023449b09f8cda964a6954ccaa9391 | 29,815,662,996,224 | 02a958673df833e5f3bbee311983d07caca1bd0e | /macula-engine-commons/deleted/org/macula/cloud/core/utils/HttpRequestUtils.java | b5234e8ed8312cb5336ea096e6ae4def24236357 | [
"MIT"
]
| permissive | macula-cloud/macula-cloud-starters | https://github.com/macula-cloud/macula-cloud-starters | e7b2c10570ccc1c28e8f8689ae224190de52a0d0 | cbb7722cfff967cfcfe5ca8b4a9acc14b8b2395f | refs/heads/main | 2023-01-01T14:42:09.640000 | 2022-07-05T09:17:42 | 2022-07-05T09:17:42 | 306,774,211 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.macula.cloud.core.utils;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.util.UriUtils;
public final class HttpRequestUtils {
private static final String AJAX_MARK_UP = "isAjaxRequest";
public static final String AJAX_REQUEST_HEADER = "X-Requested-With";
public static final String AJAX_REQUEST_VALUE = "XMLHttpRequest";
public static final String API_REQUEST_VALUE = "OpenAPIRequest";
public static final String FEIGN_REQUEST_VALUE = "FeignRequest";
public static final String GATEWAY_USER_REQUEST_VALUE = "GatewayUserRequest";
public static final String GATEWAY_OPEN_SERVICE_REQUEST_VALUE = "GatewayOpenServiceRequest";
public static final String REDIRECT_TO_PARAMETER = "redirect_to_url";
public static final String OAUTH2_TOKEN_COOKIE = "OAUTH2-TOKEN";
public static boolean isAjaxOrOpenAPIRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return AJAX_REQUEST_VALUE.equals(requestType) || API_REQUEST_VALUE.equals(requestType);
}
public static boolean isAjaxRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return AJAX_REQUEST_VALUE.equals(requestType);
}
public static boolean isOpenAPIRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return API_REQUEST_VALUE.equals(requestType);
}
public static boolean isFeignRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return FEIGN_REQUEST_VALUE.equals(requestType);
}
public static boolean isGatewayUserRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return GATEWAY_USER_REQUEST_VALUE.equals(requestType);
}
public static boolean isGatewayOpenServiceRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return GATEWAY_OPEN_SERVICE_REQUEST_VALUE.equals(requestType);
}
public static void markAsAjaxRequest(HttpServletRequest request) {
if (request.getAttribute(AJAX_MARK_UP) == null) {
request.setAttribute(AJAX_MARK_UP, Boolean.TRUE);
}
}
public static boolean isMarkAsAjaxRequest(HttpServletRequest request) {
return Boolean.TRUE == request.getAttribute(AJAX_MARK_UP);
}
public static String getRequestBrowser(HttpServletRequest request) {
return request.getHeader("User-Agent");
}
public static String getRequestAddress(HttpServletRequest request) {
String[] headNames = new String[] {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP" };
String ip = null;
for (int i = 0; i < headNames.length; i++) {
ip = request.getHeader(headNames[i]);
if (StringUtils.isNotBlank(ip)) {
break;
}
}
return StringUtils.isEmpty(ip) ? request.getRemoteAddr() : ip;
}
public static Map<String, String> getOpenApiRequestParams(HttpServletRequest request) {
TreeMap<String, String> params = new TreeMap<String, String>();
Enumeration<?> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (!"SIGN".equalsIgnoreCase(name)) {
String[] values = request.getParameterValues(name);
if (values != null) {
StringBuffer str = new StringBuffer(values[0]);
// 多值合并
for (int i = 1; i < values.length; i++) {
str.append(name).append(values[i]);
}
params.put(name, str.toString());
}
}
}
return params;
}
public static boolean isLoginRequest(HttpServletRequest request) {
AntPathMatcher pathMather = new AntPathMatcher();
return pathMather.match("/login/**", request.getRequestURI());
}
public static boolean isLoginRedirectLocation(String location) {
return StringUtils.contains(location, "/login");
}
public static void setRedirectToAttribute(HttpServletRequest request, String url) {
request.setAttribute(REDIRECT_TO_PARAMETER, url);
}
public static String createRedirectToParam(String url) {
String redirect = UriUtils.encode(url, "UTF-8");
return new StringBuilder(REDIRECT_TO_PARAMETER).append("=").append(redirect).toString();
}
public static String getRedirectToValue(HttpServletRequest request) {
String targetUrl = request.getParameter(REDIRECT_TO_PARAMETER);
if (targetUrl == null) {
String state = request.getParameter("state");
if (state != null) {
// TODO targetUrl = J2CacheUtils.get("state", state);
}
}
if (targetUrl == null) {
targetUrl = (String) request.getAttribute(REDIRECT_TO_PARAMETER);
}
return targetUrl;
}
public static void clearRedirectToValue(HttpServletRequest request) {
String state = request.getParameter("state");
if (state != null) {
// TODO 2CacheUtils.evict("state", state);
}
}
}
| UTF-8 | Java | 4,935 | java | HttpRequestUtils.java | Java | []
| null | []
| package org.macula.cloud.core.utils;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.util.UriUtils;
public final class HttpRequestUtils {
private static final String AJAX_MARK_UP = "isAjaxRequest";
public static final String AJAX_REQUEST_HEADER = "X-Requested-With";
public static final String AJAX_REQUEST_VALUE = "XMLHttpRequest";
public static final String API_REQUEST_VALUE = "OpenAPIRequest";
public static final String FEIGN_REQUEST_VALUE = "FeignRequest";
public static final String GATEWAY_USER_REQUEST_VALUE = "GatewayUserRequest";
public static final String GATEWAY_OPEN_SERVICE_REQUEST_VALUE = "GatewayOpenServiceRequest";
public static final String REDIRECT_TO_PARAMETER = "redirect_to_url";
public static final String OAUTH2_TOKEN_COOKIE = "OAUTH2-TOKEN";
public static boolean isAjaxOrOpenAPIRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return AJAX_REQUEST_VALUE.equals(requestType) || API_REQUEST_VALUE.equals(requestType);
}
public static boolean isAjaxRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return AJAX_REQUEST_VALUE.equals(requestType);
}
public static boolean isOpenAPIRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return API_REQUEST_VALUE.equals(requestType);
}
public static boolean isFeignRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return FEIGN_REQUEST_VALUE.equals(requestType);
}
public static boolean isGatewayUserRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return GATEWAY_USER_REQUEST_VALUE.equals(requestType);
}
public static boolean isGatewayOpenServiceRequest(HttpServletRequest request) {
String requestType = request.getHeader(AJAX_REQUEST_HEADER);
return GATEWAY_OPEN_SERVICE_REQUEST_VALUE.equals(requestType);
}
public static void markAsAjaxRequest(HttpServletRequest request) {
if (request.getAttribute(AJAX_MARK_UP) == null) {
request.setAttribute(AJAX_MARK_UP, Boolean.TRUE);
}
}
public static boolean isMarkAsAjaxRequest(HttpServletRequest request) {
return Boolean.TRUE == request.getAttribute(AJAX_MARK_UP);
}
public static String getRequestBrowser(HttpServletRequest request) {
return request.getHeader("User-Agent");
}
public static String getRequestAddress(HttpServletRequest request) {
String[] headNames = new String[] {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP" };
String ip = null;
for (int i = 0; i < headNames.length; i++) {
ip = request.getHeader(headNames[i]);
if (StringUtils.isNotBlank(ip)) {
break;
}
}
return StringUtils.isEmpty(ip) ? request.getRemoteAddr() : ip;
}
public static Map<String, String> getOpenApiRequestParams(HttpServletRequest request) {
TreeMap<String, String> params = new TreeMap<String, String>();
Enumeration<?> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (!"SIGN".equalsIgnoreCase(name)) {
String[] values = request.getParameterValues(name);
if (values != null) {
StringBuffer str = new StringBuffer(values[0]);
// 多值合并
for (int i = 1; i < values.length; i++) {
str.append(name).append(values[i]);
}
params.put(name, str.toString());
}
}
}
return params;
}
public static boolean isLoginRequest(HttpServletRequest request) {
AntPathMatcher pathMather = new AntPathMatcher();
return pathMather.match("/login/**", request.getRequestURI());
}
public static boolean isLoginRedirectLocation(String location) {
return StringUtils.contains(location, "/login");
}
public static void setRedirectToAttribute(HttpServletRequest request, String url) {
request.setAttribute(REDIRECT_TO_PARAMETER, url);
}
public static String createRedirectToParam(String url) {
String redirect = UriUtils.encode(url, "UTF-8");
return new StringBuilder(REDIRECT_TO_PARAMETER).append("=").append(redirect).toString();
}
public static String getRedirectToValue(HttpServletRequest request) {
String targetUrl = request.getParameter(REDIRECT_TO_PARAMETER);
if (targetUrl == null) {
String state = request.getParameter("state");
if (state != null) {
// TODO targetUrl = J2CacheUtils.get("state", state);
}
}
if (targetUrl == null) {
targetUrl = (String) request.getAttribute(REDIRECT_TO_PARAMETER);
}
return targetUrl;
}
public static void clearRedirectToValue(HttpServletRequest request) {
String state = request.getParameter("state");
if (state != null) {
// TODO 2CacheUtils.evict("state", state);
}
}
}
| 4,935 | 0.746093 | 0.744469 | 149 | 32.067116 | 29.041897 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.020134 | false | false | 3 |
fe6a498a22adcd2189b9e1cc7d4dd42689355d28 | 17,480,516,922,867 | 11a67d6c48f9012179834885233c79186c998fe0 | /src/main/java/ru/bona/guice/vaadin/mvp/addressbook/ui/event/NewContactEvent.java | 1a51a84c0c8224a937af69e9ce943766191f03fe | []
| no_license | alex-kontcur/guice-vaadin-addressbook | https://github.com/alex-kontcur/guice-vaadin-addressbook | d1d589779529465db783d42832d9202d98c8fffb | 64036e00514ff9acad54fb662fd958cb093d9bad | refs/heads/master | 2016-08-12T06:38:58.337000 | 2016-03-22T14:46:51 | 2016-03-22T14:46:51 | 54,482,862 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.bona.guice.vaadin.mvp.addressbook.ui.event;
/**
* NewContactEvent
*
* @author Kontsur Alex
* @since 24.01.13
*/
public class NewContactEvent {
}
| UTF-8 | Java | 162 | java | NewContactEvent.java | Java | [
{
"context": "ok.ui.event;\n\n/**\n * NewContactEvent\n *\n * @author Kontsur Alex\n * @since 24.01.13\n */\npublic class NewContactEve",
"end": 105,
"score": 0.9968506693840027,
"start": 93,
"tag": "NAME",
"value": "Kontsur Alex"
}
]
| null | []
| package ru.bona.guice.vaadin.mvp.addressbook.ui.event;
/**
* NewContactEvent
*
* @author <NAME>
* @since 24.01.13
*/
public class NewContactEvent {
}
| 156 | 0.703704 | 0.666667 | 10 | 15.2 | 16.448708 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 3 |
146c92e4c20a6f4b484c30d99db8fe801eaa5cf5 | 20,040,317,427,197 | 008e36b8328909c10deb72a6ce6c951d648498c7 | /tracker-storm/src/main/java/com/tracker/storm/drpc/drpcprocess/HBaseProcess.java | 69aa154944553960f3692f31cb4d8ed402dc32ce | []
| no_license | luxr123/UserAnalysis | https://github.com/luxr123/UserAnalysis | 3f090e32c35da31fd98412df673db5607a95b32c | e2c5740d5ba0db69bf6d9908714e2c3425702506 | refs/heads/master | 2021-01-10T19:58:49.544000 | 2014-10-31T02:04:22 | 2014-10-31T02:04:22 | 25,714,894 | 0 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tracker.storm.drpc.drpcprocess;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.hadoop.hbase.util.Bytes;
import scala.actors.threadpool.Arrays;
import com.tracker.common.utils.StringUtil;
import com.tracker.db.hbase.HbaseCRUD;
import com.tracker.db.hbase.HbaseCRUD.HbaseParam;
import com.tracker.db.hbase.HbaseCRUD.HbaseResult;
import com.tracker.db.hbase.HbaseUtils;
import com.tracker.storm.data.DataService;
import com.tracker.storm.drpc.drpcresult.DrpcResult;
import com.tracker.storm.drpc.drpcresult.SearchValueResult;
import com.tracker.storm.drpc.drpcresult.SearchValueResult.ValueItem;
import com.tracker.storm.drpc.spottype.DynamicConstruct;
/**
*
* 文件名:HBaseProcess
* 创建人:zhifeng.zheng
* 创建日期:2014年10月22日 下午5:23:39
* 功能描述:访问hbase功能的drpcProcess类,实现了DynamicConstruct接口用于动态创建hbase连接对象.
*
*/
public class HBaseProcess extends DrpcProcess implements Serializable,DynamicConstruct{
/**
*
*/
private static final long serialVersionUID = -517360849307802366L;
protected HbaseCRUD m_crud;
public static String ProcessFunc = "";
protected DataService dataService;
public static long parseTimeToLong(String original) {
try {
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return dateFormat.parse(original).getTime();
} catch (ParseException e) {
}
return System.currentTimeMillis();
}
public HBaseProcess(){
m_crud = null;
}
public HBaseProcess(String tableName,String zookeeper){
m_crud = null;
Object[] tmp = new Object[2];
tmp[0] = tableName;
tmp[1] = zookeeper;
init(tmp);
}
@Override
public void init(Object[] args) {
// TODO Auto-generated method stub
String tableName = (String)args[0];
String zookeeper = (String)args[1];
if(tableName != null && zookeeper != null){
m_crud = new HbaseCRUD(tableName, zookeeper);
}
dataService = new DataService(HbaseUtils.getHConnection(zookeeper));
}
@Override
public boolean isProcessable(String input) {
// TODO Auto-generated method stub
//topsearchvalue:engine:searchtype:startindex:endindex
return true;
}
@Override
public DrpcResult process(String input, Object localbuff) {
// TODO Auto-generated method stub
//input engine:searchtype:field:startindex:endindex:partlist
// String splits[] = input.split(StringUtil.ARUGEMENT_SPLIT);
// Calendar cal = Calendar.getInstance();
// String prefixKey = (cal.get(Calendar.MONTH) + 1) + StringUtil.ARUGEMENT_SPLIT
// + cal.get(Calendar.DAY_OF_MONTH) + StringUtil.ARUGEMENT_SPLIT;
// String field[] = {"count"};
// for(int i = 1;i<4;i++){
// prefixKey += splits[i] + StringUtil.ARUGEMENT_SPLIT;
// }
// List<ValueItem> listInt = new ArrayList<ValueItem>();
// Integer startIndex = Integer.parseInt(splits[4]);
// Integer endIndex = Integer.parseInt(splits[5]) + startIndex;
// String partitionList[] = splits[6].split(StringUtil.KEY_VALUE_SPLIT);
// for(String element : partitionList){
// String startKey = prefixKey + element + StringUtil.ARUGEMENT_SPLIT;
// String endKey = prefixKey + element + ".";
// HbaseParam hp = new HbaseParam();
// HbaseResult hr = new HbaseResult();
// hp.setColumns(Arrays.asList(field));
// String nextKey = null;
// //get all result from a startKey
// do{
// nextKey = m_crud.readRange(hp, hr, startKey,endKey);
// for(int i=0;i<hr.size();i++){
// String name = hr.getRowKey(i).replaceAll(startKey, "");
// listInt.add(new ValueItem(name, Bytes.toLong(
// hr.getRawValue(i, "infomation", field[0]))));
// }
// startKey = nextKey;
// }while(nextKey != null);
// }
// Collections.sort(listInt, new Comparator<ValueItem>() {
// @Override
// public int compare(ValueItem o1, ValueItem o2) {
// // TODO Auto-generated method stub
// if(o2.getCount() > o1.getCount())
// return 1;
// else if(o2 == o1)
// return 0;
// else
// return -1;
// }
// });
// if(startIndex >= listInt.size() || startIndex < 0)
// return null;
// else if (endIndex >= listInt.size())
// endIndex = listInt.size() ;
// SearchValueResult svr = new SearchValueResult(new ArrayList<ValueItem>(
// listInt.subList(startIndex, endIndex)),listInt.size());
// return svr;
return null;
}
}
| UTF-8 | Java | 4,543 | java | HBaseProcess.java | Java | [
{
"context": "amicConstruct;\n/**\n * \n * 文件名:HBaseProcess\n * 创建人:zhifeng.zheng\n * 创建日期:2014年10月22日 下午5:23:39\n * 功能描述:",
"end": 937,
"score": 0.5596873164176941,
"start": 935,
"tag": "NAME",
"value": "zh"
},
{
"context": "icConstruct;\n/**\n * \n * 文件名:HBaseProcess\n * 创建人:zhifeng.zheng\n * 创建日期:2014年10月22日 下午5:23:39\n * 功能描述:访问hbase功能的d",
"end": 948,
"score": 0.7760958075523376,
"start": 937,
"tag": "USERNAME",
"value": "ifeng.zheng"
}
]
| null | []
| package com.tracker.storm.drpc.drpcprocess;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.hadoop.hbase.util.Bytes;
import scala.actors.threadpool.Arrays;
import com.tracker.common.utils.StringUtil;
import com.tracker.db.hbase.HbaseCRUD;
import com.tracker.db.hbase.HbaseCRUD.HbaseParam;
import com.tracker.db.hbase.HbaseCRUD.HbaseResult;
import com.tracker.db.hbase.HbaseUtils;
import com.tracker.storm.data.DataService;
import com.tracker.storm.drpc.drpcresult.DrpcResult;
import com.tracker.storm.drpc.drpcresult.SearchValueResult;
import com.tracker.storm.drpc.drpcresult.SearchValueResult.ValueItem;
import com.tracker.storm.drpc.spottype.DynamicConstruct;
/**
*
* 文件名:HBaseProcess
* 创建人:zhifeng.zheng
* 创建日期:2014年10月22日 下午5:23:39
* 功能描述:访问hbase功能的drpcProcess类,实现了DynamicConstruct接口用于动态创建hbase连接对象.
*
*/
public class HBaseProcess extends DrpcProcess implements Serializable,DynamicConstruct{
/**
*
*/
private static final long serialVersionUID = -517360849307802366L;
protected HbaseCRUD m_crud;
public static String ProcessFunc = "";
protected DataService dataService;
public static long parseTimeToLong(String original) {
try {
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return dateFormat.parse(original).getTime();
} catch (ParseException e) {
}
return System.currentTimeMillis();
}
public HBaseProcess(){
m_crud = null;
}
public HBaseProcess(String tableName,String zookeeper){
m_crud = null;
Object[] tmp = new Object[2];
tmp[0] = tableName;
tmp[1] = zookeeper;
init(tmp);
}
@Override
public void init(Object[] args) {
// TODO Auto-generated method stub
String tableName = (String)args[0];
String zookeeper = (String)args[1];
if(tableName != null && zookeeper != null){
m_crud = new HbaseCRUD(tableName, zookeeper);
}
dataService = new DataService(HbaseUtils.getHConnection(zookeeper));
}
@Override
public boolean isProcessable(String input) {
// TODO Auto-generated method stub
//topsearchvalue:engine:searchtype:startindex:endindex
return true;
}
@Override
public DrpcResult process(String input, Object localbuff) {
// TODO Auto-generated method stub
//input engine:searchtype:field:startindex:endindex:partlist
// String splits[] = input.split(StringUtil.ARUGEMENT_SPLIT);
// Calendar cal = Calendar.getInstance();
// String prefixKey = (cal.get(Calendar.MONTH) + 1) + StringUtil.ARUGEMENT_SPLIT
// + cal.get(Calendar.DAY_OF_MONTH) + StringUtil.ARUGEMENT_SPLIT;
// String field[] = {"count"};
// for(int i = 1;i<4;i++){
// prefixKey += splits[i] + StringUtil.ARUGEMENT_SPLIT;
// }
// List<ValueItem> listInt = new ArrayList<ValueItem>();
// Integer startIndex = Integer.parseInt(splits[4]);
// Integer endIndex = Integer.parseInt(splits[5]) + startIndex;
// String partitionList[] = splits[6].split(StringUtil.KEY_VALUE_SPLIT);
// for(String element : partitionList){
// String startKey = prefixKey + element + StringUtil.ARUGEMENT_SPLIT;
// String endKey = prefixKey + element + ".";
// HbaseParam hp = new HbaseParam();
// HbaseResult hr = new HbaseResult();
// hp.setColumns(Arrays.asList(field));
// String nextKey = null;
// //get all result from a startKey
// do{
// nextKey = m_crud.readRange(hp, hr, startKey,endKey);
// for(int i=0;i<hr.size();i++){
// String name = hr.getRowKey(i).replaceAll(startKey, "");
// listInt.add(new ValueItem(name, Bytes.toLong(
// hr.getRawValue(i, "infomation", field[0]))));
// }
// startKey = nextKey;
// }while(nextKey != null);
// }
// Collections.sort(listInt, new Comparator<ValueItem>() {
// @Override
// public int compare(ValueItem o1, ValueItem o2) {
// // TODO Auto-generated method stub
// if(o2.getCount() > o1.getCount())
// return 1;
// else if(o2 == o1)
// return 0;
// else
// return -1;
// }
// });
// if(startIndex >= listInt.size() || startIndex < 0)
// return null;
// else if (endIndex >= listInt.size())
// endIndex = listInt.size() ;
// SearchValueResult svr = new SearchValueResult(new ArrayList<ValueItem>(
// listInt.subList(startIndex, endIndex)),listInt.size());
// return svr;
return null;
}
}
| 4,543 | 0.707295 | 0.695174 | 140 | 30.821428 | 22.313759 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.35 | false | false | 3 |
22b125f9d9b0775c17bfb72c89cf5e48dde7b927 | 13,357,348,329,062 | d8899a969c06824ba20258f3b26feb906e0d9419 | /银行系统(第一次修改)/functions4_query/Query.java | 7c901f125c1382111dcc25535b250e236eda3d34 | []
| no_license | x-iaoxiao/gggggggggggggggggg | https://github.com/x-iaoxiao/gggggggggggggggggg | a9182db2c402c5bf7c9ee46f70a83b819456c269 | 3318d80219045200d1bc9c61169979729e2ccf40 | refs/heads/master | 2021-08-23T18:24:00.878000 | 2017-12-06T02:00:38 | 2017-12-06T02:00:38 | 104,295,228 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package functions4_query;
import basic.Account;
public interface Query {
public void show_account(Account user);
}
| UTF-8 | Java | 126 | java | Query.java | Java | []
| null | []
| package functions4_query;
import basic.Account;
public interface Query {
public void show_account(Account user);
}
| 126 | 0.730159 | 0.722222 | 10 | 11.3 | 14.028899 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
16dd8b3a659736d300ef3ae448730ccccf4bb17c | 11,957,188,985,612 | 7597193a190fcb9642a24a839a1c59f8821e84f1 | /src/test/java/com/example/demo/service/UserServiceTest.java | 62fe831842ebe681546c959481634813bc516c15 | []
| no_license | HamzaHaddada1/SpringProject | https://github.com/HamzaHaddada1/SpringProject | a51622091c414a9af6d7660f3a07d9940d992189 | 68aac8d04f1b301f5af52ce9826eb9808fd9fa8f | refs/heads/master | 2020-12-07T01:08:55.106000 | 2020-01-16T14:37:57 | 2020-01-16T14:37:57 | 232,598,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.service;
import com.example.demo.DAO.UserRepository;
import com.example.demo.entity.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
class UserServiceTest {
@InjectMocks
private UserService userService;
@Mock
private UserRepository userRepository;
@BeforeEach
void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
}
@Test
void ajouterUserTest() throws Exception{
User userTest=new User(Long.valueOf(12),"hamza","123");
when(userRepository.save(userTest)).thenReturn(userTest);
assertEquals(userService.ajouterUser(userTest),userTest);
}
@Test
void authentificationtest() throws Exception{
User userTest=new User(Long.valueOf(12),"hamza","123");
User userTest1=new User();
userTest1=null;
when(userRepository.findUserByName(anyString())).thenReturn(userTest1);
assertTrue(userTest!=null,"user must be defined");
assertTrue(userTest.getPassword().equals("123")&&userTest.getName().equals("hamza"),"the user must be defined");
}
@Test
void correctUserPass() throws Exception{
User userTest=new User(Long.valueOf(12),"hamza","123");
assertTrue(userTest.getPassword().equals("123"),"Correct userPassword");
}
} | UTF-8 | Java | 1,646 | java | UserServiceTest.java | Java | [
{
"context": "\n User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n when(userRepository.save(userTe",
"end": 838,
"score": 0.6653285026550293,
"start": 835,
"tag": "USERNAME",
"value": "ham"
},
{
"context": " User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n when(userRepository.save(userTest",
"end": 840,
"score": 0.5062556862831116,
"start": 838,
"tag": "NAME",
"value": "za"
},
{
"context": " User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n when(userRepository.save(userTest)).the",
"end": 846,
"score": 0.633830726146698,
"start": 843,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "\n User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n User userTest1=new User();\n ",
"end": 1099,
"score": 0.430203378200531,
"start": 1096,
"tag": "USERNAME",
"value": "ham"
},
{
"context": " User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n User userTest1=new User();\n ",
"end": 1101,
"score": 0.7422580122947693,
"start": 1099,
"tag": "NAME",
"value": "za"
},
{
"context": "User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n User userTest1=new User();\n use",
"end": 1107,
"score": 0.5364299416542053,
"start": 1105,
"tag": "PASSWORD",
"value": "23"
},
{
"context": " assertTrue(userTest.getPassword().equals(\"123\")&&userTest.getName().equals(\"hamza\"),\"the user m",
"end": 1362,
"score": 0.9897308349609375,
"start": 1359,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "sword().equals(\"123\")&&userTest.getName().equals(\"hamza\"),\"the user must be defined\");\n\n\n }\n @Test\n",
"end": 1398,
"score": 0.9375147819519043,
"start": 1393,
"tag": "USERNAME",
"value": "hamza"
},
{
"context": "\n User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n assertTrue(userTest.getPasswor",
"end": 1545,
"score": 0.5085170269012451,
"start": 1542,
"tag": "USERNAME",
"value": "ham"
},
{
"context": " User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n assertTrue(userTest.getPassword(",
"end": 1547,
"score": 0.5134873390197754,
"start": 1545,
"tag": "NAME",
"value": "za"
},
{
"context": " User userTest=new User(Long.valueOf(12),\"hamza\",\"123\");\n assertTrue(userTest.getPassword().equa",
"end": 1553,
"score": 0.8941240310668945,
"start": 1550,
"tag": "PASSWORD",
"value": "123"
},
{
"context": " assertTrue(userTest.getPassword().equals(\"123\"),\"Correct userPassword\");\n }\n\n}",
"end": 1610,
"score": 0.9615718722343445,
"start": 1607,
"tag": "PASSWORD",
"value": "123"
}
]
| null | []
| package com.example.demo.service;
import com.example.demo.DAO.UserRepository;
import com.example.demo.entity.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
class UserServiceTest {
@InjectMocks
private UserService userService;
@Mock
private UserRepository userRepository;
@BeforeEach
void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
}
@Test
void ajouterUserTest() throws Exception{
User userTest=new User(Long.valueOf(12),"hamza","123");
when(userRepository.save(userTest)).thenReturn(userTest);
assertEquals(userService.ajouterUser(userTest),userTest);
}
@Test
void authentificationtest() throws Exception{
User userTest=new User(Long.valueOf(12),"hamza","123");
User userTest1=new User();
userTest1=null;
when(userRepository.findUserByName(anyString())).thenReturn(userTest1);
assertTrue(userTest!=null,"user must be defined");
assertTrue(userTest.getPassword().equals("123")&&userTest.getName().equals("hamza"),"the user must be defined");
}
@Test
void correctUserPass() throws Exception{
User userTest=new User(Long.valueOf(12),"hamza","123");
assertTrue(userTest.getPassword().equals("123"),"Correct userPassword");
}
} | 1,646 | 0.721142 | 0.706561 | 50 | 31.940001 | 26.694126 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72 | false | false | 3 |
85d9c65faa43ca8b7231b65be289fe9f80cd68e0 | 13,030,930,806,959 | 4c3f1a0db97202232e2585aac11590855486ee95 | /src/main/java/pl/windykacjasamochodowa/store/services/AdressService.java | 00e154900c571b854cee6a56dfe95c313b79ac86 | [
"MIT"
]
| permissive | woolke/WINapp | https://github.com/woolke/WINapp | 58f8628fa6d390eeaa55559c6d09107cbfc04ee2 | d6d2c0c86c0cdb3e0cb055798485a311be07dfd8 | HEAD | 2018-12-23T00:52:34.884000 | 2018-10-24T16:18:20 | 2018-10-24T16:18:20 | 149,910,488 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.windykacjasamochodowa.store.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;
import pl.windykacjasamochodowa.store.components.StaticFunc;
import pl.windykacjasamochodowa.store.model._enums.debtorData.AdressSOURCE;
import pl.windykacjasamochodowa.store.model._enums.debtorData.AdressTYPE;
import pl.windykacjasamochodowa.store.model._enums.debtorData.AdressVERIFIED;
import pl.windykacjasamochodowa.store.model.debt.debitors.Adress;
import pl.windykacjasamochodowa.store.model.debt.debitors.Location;
import pl.windykacjasamochodowa.store.model.debt.debitors.Subject;
import pl.windykacjasamochodowa.store.respositories.debt.debitors.AdressRepository;
import java.time.LocalDate;
import java.util.Date;
@Service
public class AdressService {
private final AdressRepository adressRepository;
private final LocationService locationService;
@Autowired
public AdressService(AdressRepository adressRepository, LocationService locationService) {
this.adressRepository = adressRepository;
this.locationService = locationService;
}
public Adress buildAdress(String adressString, AdressTYPE adressTYPE, AdressSOURCE adressSOURCE) {
return Adress.builder()
.adressFull(adressString)
.adressTYPE(adressTYPE)
.adressSOURCE(adressSOURCE).build();
}
public Adress getById(String subject) {
return adressRepository.findById(StaticFunc.intFromStringID(subject)).orElse(null);
}
public Adress getById(Integer subject) {
return adressRepository.findById(subject).orElse(null);
}
public boolean addAdressToSubject (Subject subject, Adress adress) {
Point adressGeoPoint = LocationService.getGeoPointFromAddress(adress.printFullAdress());
if (subject.getAdresses().stream()
.anyMatch(l -> l.getLocation().getId().equals(adressGeoPoint))) { //todo sprawdzić porównanie dwuch punktów
if (subject.getAdresses().stream().noneMatch(n -> n.getAdressFull().equals(adress.getAdressFull()))) {
Location adressLocation = locationService.getByPoint(adressGeoPoint);
adress.setToMap(false);
adress.setAdressVERIFIED(AdressVERIFIED.ND);
adress.setComment((new Date()).toString() + " - adres zdeaktywowany automatycznie przy dodawania z bazy -inny adres w tej samej lokalizacji");
adress.setLocation(adressLocation);
subject.getAdresses().add(adress);
adress.setSubject(subject);
return true;
} else {
return false;
}
}
Location adressLocation = locationService.addByPoint(adressGeoPoint);
adress.setLocation(adressLocation);
adress.setAdressVERIFIED(AdressVERIFIED.NIEZWERYFIKOWANY);
adress.setComment((new Date()).toString() + " - import");
adress.setToMap(true);
subject.getAdresses().add(adress);
adress.setSubject(subject);
return true;
}
}
| UTF-8 | Java | 3,156 | java | AdressService.java | Java | []
| null | []
| package pl.windykacjasamochodowa.store.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;
import pl.windykacjasamochodowa.store.components.StaticFunc;
import pl.windykacjasamochodowa.store.model._enums.debtorData.AdressSOURCE;
import pl.windykacjasamochodowa.store.model._enums.debtorData.AdressTYPE;
import pl.windykacjasamochodowa.store.model._enums.debtorData.AdressVERIFIED;
import pl.windykacjasamochodowa.store.model.debt.debitors.Adress;
import pl.windykacjasamochodowa.store.model.debt.debitors.Location;
import pl.windykacjasamochodowa.store.model.debt.debitors.Subject;
import pl.windykacjasamochodowa.store.respositories.debt.debitors.AdressRepository;
import java.time.LocalDate;
import java.util.Date;
@Service
public class AdressService {
private final AdressRepository adressRepository;
private final LocationService locationService;
@Autowired
public AdressService(AdressRepository adressRepository, LocationService locationService) {
this.adressRepository = adressRepository;
this.locationService = locationService;
}
public Adress buildAdress(String adressString, AdressTYPE adressTYPE, AdressSOURCE adressSOURCE) {
return Adress.builder()
.adressFull(adressString)
.adressTYPE(adressTYPE)
.adressSOURCE(adressSOURCE).build();
}
public Adress getById(String subject) {
return adressRepository.findById(StaticFunc.intFromStringID(subject)).orElse(null);
}
public Adress getById(Integer subject) {
return adressRepository.findById(subject).orElse(null);
}
public boolean addAdressToSubject (Subject subject, Adress adress) {
Point adressGeoPoint = LocationService.getGeoPointFromAddress(adress.printFullAdress());
if (subject.getAdresses().stream()
.anyMatch(l -> l.getLocation().getId().equals(adressGeoPoint))) { //todo sprawdzić porównanie dwuch punktów
if (subject.getAdresses().stream().noneMatch(n -> n.getAdressFull().equals(adress.getAdressFull()))) {
Location adressLocation = locationService.getByPoint(adressGeoPoint);
adress.setToMap(false);
adress.setAdressVERIFIED(AdressVERIFIED.ND);
adress.setComment((new Date()).toString() + " - adres zdeaktywowany automatycznie przy dodawania z bazy -inny adres w tej samej lokalizacji");
adress.setLocation(adressLocation);
subject.getAdresses().add(adress);
adress.setSubject(subject);
return true;
} else {
return false;
}
}
Location adressLocation = locationService.addByPoint(adressGeoPoint);
adress.setLocation(adressLocation);
adress.setAdressVERIFIED(AdressVERIFIED.NIEZWERYFIKOWANY);
adress.setComment((new Date()).toString() + " - import");
adress.setToMap(true);
subject.getAdresses().add(adress);
adress.setSubject(subject);
return true;
}
}
| 3,156 | 0.717729 | 0.717729 | 76 | 40.486843 | 34.496185 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565789 | false | false | 3 |
12d60617ba124a56dbfe34b99a7dfe74cf090deb | 29,059,748,762,846 | a60c92b982df8779bf2097916d9d64010c35bedc | /LevelTwo/HomeWork5/src/Main.java | ca1632088c12244c864810fd514d6f19d54b796d | []
| no_license | ciskos/JavaProgramming | https://github.com/ciskos/JavaProgramming | fe7e8afa9cd44f2fe5d55e2313af0033ddf0bc88 | 868bf086d2b46f72a9f9a872d144ecbfe2ae6439 | refs/heads/master | 2020-06-25T20:50:49.369000 | 2018-03-03T10:27:28 | 2018-03-03T10:27:28 | 96,980,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Необходимо написать два метода, которые делают следующее:
* - Создают одномерный длинный массив, например:
* - static final int size = 10000000; static final int h = size / 2;
* float[] arr = new float[size];
* - Заполняют этот массив единицами;
* - Засекают время выполнения, используя метод System.nanoTime();
* - Проходят по всему массиву и для каждой ячейки считают новое
* значение по формуле:
* arr[i] = (float)(arr[i] * Math.sin(0.2f + i / 5)
* * Math.cos(0.2f + i / 5) * Math.cos(0.4f + i / 2));
*
* Чем отличается первый метод от второго:
* - Первый бежит по массиву и высчитывает значения.
* - Второй разбивает массив на два массива, в двух потоках высчитывает
* новые значения, и потом склеивает эти массивы обратно в один.
*
* Пример деления одного массива на два:
* System.arraycopy(arr, 0, a1, 0, h);
* System.arraycopy(arr, h, a2, 0, h);
* Пример обратной склейки:
* System.arraycopy(a1, 0, arr, 0, h);
* System.arraycopy(a2, 0, arr, h, h);
*/
public class Main {
private static int i;
private static final int SIZE = 10000000;
private static final int HALF_SIZE = SIZE / 2;
private static float[] arr = new float[SIZE];
private static float[] a1 = new float[HALF_SIZE];
private static float[] a2 = new float[HALF_SIZE];
private static float startTime;
private static float endTime;
private static float nanoSecondsToSeconds = 0.000000001f;
public static void main(String[] args) {
startTime = System.nanoTime();
fillArrayWithOnes();
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Filling array with ones - %.6f\n", endTime);
startTime = System.nanoTime();
arrayRefill(arr);
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Time of straight array refilling is - %.6f\n", endTime);
startTime = System.nanoTime();
fillArrayWithOnes();
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Filling array with ones - %.6f\n", endTime);
startTime = System.nanoTime();
threadedRefill();
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Time of two threaded array refilling is - %.6f\n", endTime);
}
private static void fillArrayWithOnes() {
int arrayLength = arr.length;
for (i = 0; i < arrayLength; i++) {
arr[i] = 1;
}
}
private static float formula(float input, int counter) {
return (float)(input
* Math.sin(0.2f + counter / 5)
* Math.cos(0.2f + counter / 5)
* Math.cos(0.4f + counter / 2));
}
private static void arrayRefill(float[] array) {
int arrayLength = array.length;
for (i = 0; i < arrayLength; i++) {
array[i] = formula(array[i], i);
}
}
private static void threadedRefill() {
System.arraycopy(arr, 0, a1, 0, HALF_SIZE);
System.arraycopy(arr, HALF_SIZE, a2, 0, HALF_SIZE);
new Thread(new Runnable() {
@Override
public void run() {
arrayRefill(a1);
}
}).start();
new Thread(()->Main.arrayRefill(a2)).start();
System.arraycopy(a1, 0, arr, 0, HALF_SIZE);
System.arraycopy(a2, 0, arr, HALF_SIZE, HALF_SIZE);
}
}
| UTF-8 | Java | 3,637 | java | Main.java | Java | []
| null | []
| /*
* Необходимо написать два метода, которые делают следующее:
* - Создают одномерный длинный массив, например:
* - static final int size = 10000000; static final int h = size / 2;
* float[] arr = new float[size];
* - Заполняют этот массив единицами;
* - Засекают время выполнения, используя метод System.nanoTime();
* - Проходят по всему массиву и для каждой ячейки считают новое
* значение по формуле:
* arr[i] = (float)(arr[i] * Math.sin(0.2f + i / 5)
* * Math.cos(0.2f + i / 5) * Math.cos(0.4f + i / 2));
*
* Чем отличается первый метод от второго:
* - Первый бежит по массиву и высчитывает значения.
* - Второй разбивает массив на два массива, в двух потоках высчитывает
* новые значения, и потом склеивает эти массивы обратно в один.
*
* Пример деления одного массива на два:
* System.arraycopy(arr, 0, a1, 0, h);
* System.arraycopy(arr, h, a2, 0, h);
* Пример обратной склейки:
* System.arraycopy(a1, 0, arr, 0, h);
* System.arraycopy(a2, 0, arr, h, h);
*/
public class Main {
private static int i;
private static final int SIZE = 10000000;
private static final int HALF_SIZE = SIZE / 2;
private static float[] arr = new float[SIZE];
private static float[] a1 = new float[HALF_SIZE];
private static float[] a2 = new float[HALF_SIZE];
private static float startTime;
private static float endTime;
private static float nanoSecondsToSeconds = 0.000000001f;
public static void main(String[] args) {
startTime = System.nanoTime();
fillArrayWithOnes();
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Filling array with ones - %.6f\n", endTime);
startTime = System.nanoTime();
arrayRefill(arr);
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Time of straight array refilling is - %.6f\n", endTime);
startTime = System.nanoTime();
fillArrayWithOnes();
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Filling array with ones - %.6f\n", endTime);
startTime = System.nanoTime();
threadedRefill();
endTime = (System.nanoTime() - startTime) * nanoSecondsToSeconds;
System.out.printf("Time of two threaded array refilling is - %.6f\n", endTime);
}
private static void fillArrayWithOnes() {
int arrayLength = arr.length;
for (i = 0; i < arrayLength; i++) {
arr[i] = 1;
}
}
private static float formula(float input, int counter) {
return (float)(input
* Math.sin(0.2f + counter / 5)
* Math.cos(0.2f + counter / 5)
* Math.cos(0.4f + counter / 2));
}
private static void arrayRefill(float[] array) {
int arrayLength = array.length;
for (i = 0; i < arrayLength; i++) {
array[i] = formula(array[i], i);
}
}
private static void threadedRefill() {
System.arraycopy(arr, 0, a1, 0, HALF_SIZE);
System.arraycopy(arr, HALF_SIZE, a2, 0, HALF_SIZE);
new Thread(new Runnable() {
@Override
public void run() {
arrayRefill(a1);
}
}).start();
new Thread(()->Main.arrayRefill(a2)).start();
System.arraycopy(a1, 0, arr, 0, HALF_SIZE);
System.arraycopy(a2, 0, arr, HALF_SIZE, HALF_SIZE);
}
}
| 3,637 | 0.66332 | 0.639159 | 99 | 31.191919 | 23.217321 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.383838 | false | false | 3 |
06ad30fc31383ca2b104f7285f64c3c2a902a5de | 23,871,428,269,030 | 5c64c1a244cb6d06ea70d4e78bb84e9f6cf4f6ff | /src/com/creaway/showicon/bean/TerminalArchives.java | f5c22d0e040f718e24efe72b1ef5615816b6a514 | []
| no_license | zhuilu/showIcon | https://github.com/zhuilu/showIcon | e3b507d0a0a0b069cd078a6009ddc91bcbeebfb1 | b456efe5c780e9ed6258fd520505d473a0d5e645 | refs/heads/master | 2019-04-26T11:36:29.693000 | 2015-05-20T01:38:20 | 2015-05-20T01:38:20 | 35,919,213 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.creaway.showicon.bean;
import org.json.JSONObject;
import android.content.ContentValues;
import android.database.Cursor;
import com.creaway.showicon.config.ICWConstants;
import com.creaway.showicon.db.CwDbHelper;
public class TerminalArchives extends CWBaseType {
/**
*
*/
private static final long serialVersionUID = 1L;
public TerminalArchives() {
}
// 故障ID
public String GZID;
// 终端局号
public String ZDJH;
// APN
public String APN;
// 终端通讯地址
public String ZDTXDZ;
// 终端通讯地址备1
public String ZDTXDZB1;
// 短信中心号码
public String ZDDXZXHM;
// CT
public String CT;
// PT
public String PT;
// 通讯端口号
public String TXDKH;
// 终端逻辑地址
public String ZDLJDZ;
// Sim卡号 public
public String SIMKH;
// 终端用途
public String ZDYT;
// 终端规约类型
public String ZDGYLX;
// 终端类型
public String ZDLX;
// 接线方式
public String JXFS;
// 接线方式中文
public String JXFSZH;
// 终端厂家
public String ZDCJ;
// 终端高级密码
public String GQXMM;
// 终端低级密码
public String DQXMM;
// 改待办任务的扩展信息是否下载
public String NeedExpand;
@Override
public String getTableName() {
return CwDbHelper.Table_Terminal_Archives;
}
public Object jsonToObj(JSONObject obj) {
if (obj != null) {
// 终端局号
ZDJH = obj.optString(Columns.ZDJH);
// APN
APN = obj.optString(Columns.APN);
// 终端通讯地址
ZDTXDZ = obj.optString(Columns.ZDTXDZ);
// 终端通讯地址备1
ZDTXDZB1 = obj.optString(Columns.ZDTXDZB1);
// 短信中心号码
ZDDXZXHM = obj.optString(Columns.ZDDXZXHM);
// CT
CT = obj.optString(Columns.CT);
// PT
PT = obj.optString(Columns.PT);
// 通讯端口号
TXDKH = obj.optString(Columns.TXDKH);
// 终端逻辑地址
ZDLJDZ = obj.optString(Columns.ZDLJDZ);
// Sim卡号 public
SIMKH = obj.optString(Columns.SIMKH);
// 终端用途
ZDYT = obj.optString(Columns.ZDYT);
// 终端规约类型
ZDGYLX = obj.optString(Columns.ZDGYLX);
// 终端类型
ZDLX = obj.optString(Columns.ZDLX);
// 接线方式
JXFS = obj.optString(Columns.JXFS);
// 接线方式中文
JXFSZH = obj.optString(Columns.JXFSZH);
// 终端厂家
ZDCJ = obj.optString(Columns.ZDCJ);
// 终端高级密码
GQXMM = obj.optString(Columns.GQXMM);
// 终端低级密码
DQXMM = obj.optString(Columns.DQXMM);
}
return this;
}
@Override
public ContentValues toContentValues() {
ContentValues values = new ContentValues();
// 故障ID
values.put(Columns.GZID, GZID);
// 终端局号
values.put(Columns.ZDJH, ZDJH);
// APN
values.put(Columns.APN, APN);
// 终端通讯地址
values.put(Columns.ZDTXDZ, ZDTXDZ);
// 终端通讯地址备1
values.put(Columns.ZDTXDZB1, ZDTXDZB1);
// 短信中心号码
values.put(Columns.ZDDXZXHM, ZDDXZXHM);
// CT
values.put(Columns.CT, CT);
// PT
values.put(Columns.PT, PT);
// 通讯端口号
values.put(Columns.TXDKH, TXDKH);
// 终端逻辑地址
values.put(Columns.ZDLJDZ, ZDLJDZ);
// Sim卡号 public
values.put(Columns.SIMKH, SIMKH);
// 终端用途
values.put(Columns.ZDYT, ZDYT);
// 终端规约类型
values.put(Columns.ZDGYLX, ZDGYLX);
// 终端类型
values.put(Columns.ZDLX, ZDLX);
// 接线方式
values.put(Columns.JXFS, JXFS);
// 接线方式中文
values.put(Columns.JXFSZH, JXFSZH);
// 终端厂家
values.put(Columns.ZDCJ, ZDCJ);
// 终端高级密码
values.put(Columns.GQXMM, GQXMM);
// 终端低级密码
values.put(Columns.DQXMM, DQXMM);
if (NeedExpand != null) {
values.put(Columns.NeedExpand, NeedExpand);
}
return values;
}
@Override
public Object CursorToObj(Cursor cursor) {
try {
_id = String.valueOf(cursor.getInt(cursor
.getColumnIndexOrThrow(ICWConstants.cursor_id)));
// 故障ID
GZID = cursor.getString(cursor.getColumnIndexOrThrow(Columns.GZID));
// 终端局号
ZDJH = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDJH));
// APN
APN = cursor.getString(cursor.getColumnIndexOrThrow(Columns.APN));
// 终端通讯地址
ZDTXDZ = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDTXDZ));
// 终端通讯地址备1
ZDTXDZB1 = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDTXDZB1));
// 短信中心号码
ZDDXZXHM = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDDXZXHM));
// CT
CT = cursor.getString(cursor.getColumnIndexOrThrow(Columns.CT));
// PT
PT = cursor.getString(cursor.getColumnIndexOrThrow(Columns.PT));
// 通讯端口号
TXDKH = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.TXDKH));
// 终端逻辑地址
ZDLJDZ = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDLJDZ));
// Sim卡号 public
SIMKH = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.SIMKH));
// 终端用途
ZDYT = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDYT));
// 终端规约类型
ZDGYLX = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDGYLX));
// 终端类型
ZDLX = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDLX));
// 接线方式
JXFS = cursor.getString(cursor.getColumnIndexOrThrow(Columns.JXFS));
// 接线方式中文
JXFSZH = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.JXFSZH));
// 终端厂家
ZDCJ = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDCJ));
// 终端高级密码
GQXMM = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.GQXMM));
// 终端低级密码
DQXMM = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.DQXMM));
NeedExpand = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.NeedExpand));
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public class Columns {
// 故障ID
public final static String GZID = "GZID";
// 终端局号
public final static String ZDJH = "ZDJH";
// APN
public final static String APN = "APN";
// 终端通讯地址ZDTXDZ
public final static String ZDTXDZ = "ZDTXDZ";
// 终端通讯地址备1
public final static String ZDTXDZB1 = "ZDTXDZB1";
// 短信中心号码
public final static String ZDDXZXHM = "ZDDXZXHM";
// CT
public final static String CT = "CT";
// PT
public final static String PT = "PT";
// 通讯端口号
public final static String TXDKH = "TXDKH";
// 终端逻辑地址
public final static String ZDLJDZ = "ZDLJDZ";
// Sim卡号 public
public final static String SIMKH = "SIMKH";
// 终端用途
public final static String ZDYT = "ZDYT";
// 终端规约类型
public final static String ZDGYLX = "ZDGYLX";
// 终端类型
public final static String ZDLX = "ZDLX";
// 接线方式
public final static String JXFS = "JXFS";
// 接线方式中文
public final static String JXFSZH = "JXFSZH";
// 终端厂家
public final static String ZDCJ = "ZDCJ";
// 终端高级密码
public final static String GQXMM = "GQXMM";
// 终端低级密码
public final static String DQXMM = "DQXMM";
public final static String NeedExpand = "NeedExpand";
public String getNeedexpand() {
return NeedExpand;
}
}
public String getGZID() {
return GZID;
}
public void setGZID(String gZID) {
GZID = gZID;
}
public String getZDJH() {
return ZDJH;
}
public void setZDJH(String zDJH) {
ZDJH = zDJH;
}
public String getAPN() {
return APN;
}
public void setAPN(String aPN) {
APN = aPN;
}
public String getZDTXDZ() {
return ZDTXDZ;
}
public void setZDTXDZ(String zDTXDZ) {
ZDTXDZ = zDTXDZ;
}
public String getZDTXDZB1() {
return ZDTXDZB1;
}
public void setZDTXDZB1(String zDTXDZB1) {
ZDTXDZB1 = zDTXDZB1;
}
public String getZDDXZXHM() {
return ZDDXZXHM;
}
public void setZDDXZXHM(String zDDXZXHM) {
ZDDXZXHM = zDDXZXHM;
}
public String getCT() {
return CT;
}
public void setCT(String cT) {
CT = cT;
}
public String getPT() {
return PT;
}
public void setPT(String pT) {
PT = pT;
}
public String getTXDKH() {
return TXDKH;
}
public void setTXDKH(String tXDKH) {
TXDKH = tXDKH;
}
public String getZDLJDZ() {
return ZDLJDZ;
}
public void setZDLJDZ(String zDLJDZ) {
ZDLJDZ = zDLJDZ;
}
public String getSIMKH() {
return SIMKH;
}
public void setSIMKH(String sIMKH) {
SIMKH = sIMKH;
}
public String getZDYT() {
return ZDYT;
}
public void setZDYT(String zDYT) {
ZDYT = zDYT;
}
public String getZDGYLX() {
return ZDGYLX;
}
public void setZDGYLX(String zDGYLX) {
ZDGYLX = zDGYLX;
}
public String getZDLX() {
return ZDLX;
}
public void setZDLX(String zDLX) {
ZDLX = zDLX;
}
public String getJXFS() {
return JXFS;
}
public void setJXFS(String jXFS) {
JXFS = jXFS;
}
public String getJXFSZH() {
return JXFSZH;
}
public void setJXFSZH(String jXFSZH) {
JXFSZH = jXFSZH;
}
public String getZDCJ() {
return ZDCJ;
}
public void setZDCJ(String zDCJ) {
ZDCJ = zDCJ;
}
public String getGQXMM() {
return GQXMM;
}
public void setGQXMM(String gQXMM) {
GQXMM = gQXMM;
}
public String getDQXMM() {
return DQXMM;
}
public void setDQXMM(String dQXMM) {
DQXMM = dQXMM;
}
public String getNeedExpand() {
return NeedExpand;
}
public void setNeedExpand(String needExpand) {
NeedExpand = needExpand;
}
}
| UTF-8 | Java | 9,452 | java | TerminalArchives.java | Java | []
| null | []
| package com.creaway.showicon.bean;
import org.json.JSONObject;
import android.content.ContentValues;
import android.database.Cursor;
import com.creaway.showicon.config.ICWConstants;
import com.creaway.showicon.db.CwDbHelper;
public class TerminalArchives extends CWBaseType {
/**
*
*/
private static final long serialVersionUID = 1L;
public TerminalArchives() {
}
// 故障ID
public String GZID;
// 终端局号
public String ZDJH;
// APN
public String APN;
// 终端通讯地址
public String ZDTXDZ;
// 终端通讯地址备1
public String ZDTXDZB1;
// 短信中心号码
public String ZDDXZXHM;
// CT
public String CT;
// PT
public String PT;
// 通讯端口号
public String TXDKH;
// 终端逻辑地址
public String ZDLJDZ;
// Sim卡号 public
public String SIMKH;
// 终端用途
public String ZDYT;
// 终端规约类型
public String ZDGYLX;
// 终端类型
public String ZDLX;
// 接线方式
public String JXFS;
// 接线方式中文
public String JXFSZH;
// 终端厂家
public String ZDCJ;
// 终端高级密码
public String GQXMM;
// 终端低级密码
public String DQXMM;
// 改待办任务的扩展信息是否下载
public String NeedExpand;
@Override
public String getTableName() {
return CwDbHelper.Table_Terminal_Archives;
}
public Object jsonToObj(JSONObject obj) {
if (obj != null) {
// 终端局号
ZDJH = obj.optString(Columns.ZDJH);
// APN
APN = obj.optString(Columns.APN);
// 终端通讯地址
ZDTXDZ = obj.optString(Columns.ZDTXDZ);
// 终端通讯地址备1
ZDTXDZB1 = obj.optString(Columns.ZDTXDZB1);
// 短信中心号码
ZDDXZXHM = obj.optString(Columns.ZDDXZXHM);
// CT
CT = obj.optString(Columns.CT);
// PT
PT = obj.optString(Columns.PT);
// 通讯端口号
TXDKH = obj.optString(Columns.TXDKH);
// 终端逻辑地址
ZDLJDZ = obj.optString(Columns.ZDLJDZ);
// Sim卡号 public
SIMKH = obj.optString(Columns.SIMKH);
// 终端用途
ZDYT = obj.optString(Columns.ZDYT);
// 终端规约类型
ZDGYLX = obj.optString(Columns.ZDGYLX);
// 终端类型
ZDLX = obj.optString(Columns.ZDLX);
// 接线方式
JXFS = obj.optString(Columns.JXFS);
// 接线方式中文
JXFSZH = obj.optString(Columns.JXFSZH);
// 终端厂家
ZDCJ = obj.optString(Columns.ZDCJ);
// 终端高级密码
GQXMM = obj.optString(Columns.GQXMM);
// 终端低级密码
DQXMM = obj.optString(Columns.DQXMM);
}
return this;
}
@Override
public ContentValues toContentValues() {
ContentValues values = new ContentValues();
// 故障ID
values.put(Columns.GZID, GZID);
// 终端局号
values.put(Columns.ZDJH, ZDJH);
// APN
values.put(Columns.APN, APN);
// 终端通讯地址
values.put(Columns.ZDTXDZ, ZDTXDZ);
// 终端通讯地址备1
values.put(Columns.ZDTXDZB1, ZDTXDZB1);
// 短信中心号码
values.put(Columns.ZDDXZXHM, ZDDXZXHM);
// CT
values.put(Columns.CT, CT);
// PT
values.put(Columns.PT, PT);
// 通讯端口号
values.put(Columns.TXDKH, TXDKH);
// 终端逻辑地址
values.put(Columns.ZDLJDZ, ZDLJDZ);
// Sim卡号 public
values.put(Columns.SIMKH, SIMKH);
// 终端用途
values.put(Columns.ZDYT, ZDYT);
// 终端规约类型
values.put(Columns.ZDGYLX, ZDGYLX);
// 终端类型
values.put(Columns.ZDLX, ZDLX);
// 接线方式
values.put(Columns.JXFS, JXFS);
// 接线方式中文
values.put(Columns.JXFSZH, JXFSZH);
// 终端厂家
values.put(Columns.ZDCJ, ZDCJ);
// 终端高级密码
values.put(Columns.GQXMM, GQXMM);
// 终端低级密码
values.put(Columns.DQXMM, DQXMM);
if (NeedExpand != null) {
values.put(Columns.NeedExpand, NeedExpand);
}
return values;
}
@Override
public Object CursorToObj(Cursor cursor) {
try {
_id = String.valueOf(cursor.getInt(cursor
.getColumnIndexOrThrow(ICWConstants.cursor_id)));
// 故障ID
GZID = cursor.getString(cursor.getColumnIndexOrThrow(Columns.GZID));
// 终端局号
ZDJH = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDJH));
// APN
APN = cursor.getString(cursor.getColumnIndexOrThrow(Columns.APN));
// 终端通讯地址
ZDTXDZ = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDTXDZ));
// 终端通讯地址备1
ZDTXDZB1 = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDTXDZB1));
// 短信中心号码
ZDDXZXHM = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDDXZXHM));
// CT
CT = cursor.getString(cursor.getColumnIndexOrThrow(Columns.CT));
// PT
PT = cursor.getString(cursor.getColumnIndexOrThrow(Columns.PT));
// 通讯端口号
TXDKH = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.TXDKH));
// 终端逻辑地址
ZDLJDZ = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDLJDZ));
// Sim卡号 public
SIMKH = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.SIMKH));
// 终端用途
ZDYT = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDYT));
// 终端规约类型
ZDGYLX = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.ZDGYLX));
// 终端类型
ZDLX = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDLX));
// 接线方式
JXFS = cursor.getString(cursor.getColumnIndexOrThrow(Columns.JXFS));
// 接线方式中文
JXFSZH = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.JXFSZH));
// 终端厂家
ZDCJ = cursor.getString(cursor.getColumnIndexOrThrow(Columns.ZDCJ));
// 终端高级密码
GQXMM = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.GQXMM));
// 终端低级密码
DQXMM = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.DQXMM));
NeedExpand = cursor.getString(cursor
.getColumnIndexOrThrow(Columns.NeedExpand));
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public class Columns {
// 故障ID
public final static String GZID = "GZID";
// 终端局号
public final static String ZDJH = "ZDJH";
// APN
public final static String APN = "APN";
// 终端通讯地址ZDTXDZ
public final static String ZDTXDZ = "ZDTXDZ";
// 终端通讯地址备1
public final static String ZDTXDZB1 = "ZDTXDZB1";
// 短信中心号码
public final static String ZDDXZXHM = "ZDDXZXHM";
// CT
public final static String CT = "CT";
// PT
public final static String PT = "PT";
// 通讯端口号
public final static String TXDKH = "TXDKH";
// 终端逻辑地址
public final static String ZDLJDZ = "ZDLJDZ";
// Sim卡号 public
public final static String SIMKH = "SIMKH";
// 终端用途
public final static String ZDYT = "ZDYT";
// 终端规约类型
public final static String ZDGYLX = "ZDGYLX";
// 终端类型
public final static String ZDLX = "ZDLX";
// 接线方式
public final static String JXFS = "JXFS";
// 接线方式中文
public final static String JXFSZH = "JXFSZH";
// 终端厂家
public final static String ZDCJ = "ZDCJ";
// 终端高级密码
public final static String GQXMM = "GQXMM";
// 终端低级密码
public final static String DQXMM = "DQXMM";
public final static String NeedExpand = "NeedExpand";
public String getNeedexpand() {
return NeedExpand;
}
}
public String getGZID() {
return GZID;
}
public void setGZID(String gZID) {
GZID = gZID;
}
public String getZDJH() {
return ZDJH;
}
public void setZDJH(String zDJH) {
ZDJH = zDJH;
}
public String getAPN() {
return APN;
}
public void setAPN(String aPN) {
APN = aPN;
}
public String getZDTXDZ() {
return ZDTXDZ;
}
public void setZDTXDZ(String zDTXDZ) {
ZDTXDZ = zDTXDZ;
}
public String getZDTXDZB1() {
return ZDTXDZB1;
}
public void setZDTXDZB1(String zDTXDZB1) {
ZDTXDZB1 = zDTXDZB1;
}
public String getZDDXZXHM() {
return ZDDXZXHM;
}
public void setZDDXZXHM(String zDDXZXHM) {
ZDDXZXHM = zDDXZXHM;
}
public String getCT() {
return CT;
}
public void setCT(String cT) {
CT = cT;
}
public String getPT() {
return PT;
}
public void setPT(String pT) {
PT = pT;
}
public String getTXDKH() {
return TXDKH;
}
public void setTXDKH(String tXDKH) {
TXDKH = tXDKH;
}
public String getZDLJDZ() {
return ZDLJDZ;
}
public void setZDLJDZ(String zDLJDZ) {
ZDLJDZ = zDLJDZ;
}
public String getSIMKH() {
return SIMKH;
}
public void setSIMKH(String sIMKH) {
SIMKH = sIMKH;
}
public String getZDYT() {
return ZDYT;
}
public void setZDYT(String zDYT) {
ZDYT = zDYT;
}
public String getZDGYLX() {
return ZDGYLX;
}
public void setZDGYLX(String zDGYLX) {
ZDGYLX = zDGYLX;
}
public String getZDLX() {
return ZDLX;
}
public void setZDLX(String zDLX) {
ZDLX = zDLX;
}
public String getJXFS() {
return JXFS;
}
public void setJXFS(String jXFS) {
JXFS = jXFS;
}
public String getJXFSZH() {
return JXFSZH;
}
public void setJXFSZH(String jXFSZH) {
JXFSZH = jXFSZH;
}
public String getZDCJ() {
return ZDCJ;
}
public void setZDCJ(String zDCJ) {
ZDCJ = zDCJ;
}
public String getGQXMM() {
return GQXMM;
}
public void setGQXMM(String gQXMM) {
GQXMM = gQXMM;
}
public String getDQXMM() {
return DQXMM;
}
public void setDQXMM(String dQXMM) {
DQXMM = dQXMM;
}
public String getNeedExpand() {
return NeedExpand;
}
public void setNeedExpand(String needExpand) {
NeedExpand = needExpand;
}
}
| 9,452 | 0.679117 | 0.676688 | 425 | 19.348236 | 17.024858 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.049412 | false | false | 3 |
c8a724d5bc530be50fc7a5c74095a6a75a2f1fa1 | 14,783,277,469,562 | e437dd0c30a78c546e7939e67c3a36c08fcee175 | /2720.java | 48cce54bf33a79686f7ee88dfe2ba29c35fb9785 | []
| no_license | engallote/BOJ | https://github.com/engallote/BOJ | 63733825a6db65a24cc0f76c934ad76a1992d3d5 | 08d5948239cbe7e04c166cd83db5d550056173b0 | refs/heads/master | 2023-03-10T14:47:13.156000 | 2023-02-17T16:40:26 | 2023-02-17T16:40:26 | 200,885,440 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int Quarter = 25, Dime = 10, Nickel = 5, Penny = 1;
for(int t = 0; t < T; t++)
{
int N = sc.nextInt();
int q = 0, d = 0, n = 0, p = 0;
while(N > 0)
{
while(N / Quarter > 0)
{
q += N / Quarter;
N %= Quarter;
}
while(N / Dime > 0)
{
d += N / Dime;
N %= Dime;
}
while(N / Nickel > 0)
{
n += N / Nickel;
N %= Nickel;
}
p += N;
break;
}
System.out.println(q + " " + d + " " + n + " " + p);
}
}
} | UTF-8 | Java | 681 | java | 2720.java | Java | [
{
"context": "Int();\r\n\t\tint Quarter = 25, Dime = 10, Nickel = 5, Penny = 1;\r\n\t\tfor(int t = 0; t < T; t++)\r\n\t\t{\r\n\t\t\tint",
"end": 198,
"score": 0.7012412548065186,
"start": 195,
"tag": "NAME",
"value": "Pen"
}
]
| null | []
| import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int Quarter = 25, Dime = 10, Nickel = 5, Penny = 1;
for(int t = 0; t < T; t++)
{
int N = sc.nextInt();
int q = 0, d = 0, n = 0, p = 0;
while(N > 0)
{
while(N / Quarter > 0)
{
q += N / Quarter;
N %= Quarter;
}
while(N / Dime > 0)
{
d += N / Dime;
N %= Dime;
}
while(N / Nickel > 0)
{
n += N / Nickel;
N %= Nickel;
}
p += N;
break;
}
System.out.println(q + " " + d + " " + n + " " + p);
}
}
} | 681 | 0.41116 | 0.389134 | 37 | 16.459459 | 14.070469 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.648649 | false | false | 3 |
b03a4194bbf81b2b065fa3d23c8bb0592d0ad571 | 24,060,406,823,900 | 4129a4118ec19b9911e9413965f274cf8a52a6ae | /src/by/bolbas/entity/CoffeeOrder.java | c3de2915beb59e81b66dc66f7e54ffd35969e85c | []
| no_license | ArtyomBolbas/CoffeeShop | https://github.com/ArtyomBolbas/CoffeeShop | eab8b4d2023d026478f1e064615fadd82988662e | af74babbd013b9811ee283bcbb4c6fb5d2516d45 | refs/heads/master | 2020-04-06T14:11:35.006000 | 2018-11-23T01:10:30 | 2018-11-23T01:10:30 | 157,531,537 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.bolbas.entity;
import java.util.Date;
/*
* Класс для хранения информации о заказе
*/
public class CoffeeOrder implements java.io.Serializable {
private static final long serialVersionUID = -1540437138823134510L;
private Integer id;
private Integer weight;
private Date orderDate;
private Date startTime;
private Date endTime;
private Integer totalCost;
private Coffee coffee;
private Delivery delivery;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getTotalCost() {
return totalCost;
}
public void setTotalCost(Integer totalCost) {
this.totalCost = totalCost;
}
public Coffee getCoffee() {
return coffee;
}
public void setCoffee(Coffee coffee) {
this.coffee = coffee;
}
public Delivery getDelivery() {
return delivery;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((coffee == null) ? 0 : coffee.hashCode());
result = prime * result + ((delivery == null) ? 0 : delivery.hashCode());
result = prime * result + ((endTime == null) ? 0 : endTime.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((orderDate == null) ? 0 : orderDate.hashCode());
result = prime * result + ((startTime == null) ? 0 : startTime.hashCode());
result = prime * result + ((totalCost == null) ? 0 : totalCost.hashCode());
result = prime * result + ((weight == null) ? 0 : weight.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CoffeeOrder other = (CoffeeOrder) obj;
if (coffee == null) {
if (other.coffee != null)
return false;
} else if (!coffee.equals(other.coffee))
return false;
if (delivery == null) {
if (other.delivery != null)
return false;
} else if (!delivery.equals(other.delivery))
return false;
if (endTime == null) {
if (other.endTime != null)
return false;
} else if (!endTime.equals(other.endTime))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (orderDate == null) {
if (other.orderDate != null)
return false;
} else if (!orderDate.equals(other.orderDate))
return false;
if (startTime == null) {
if (other.startTime != null)
return false;
} else if (!startTime.equals(other.startTime))
return false;
if (totalCost == null) {
if (other.totalCost != null)
return false;
} else if (!totalCost.equals(other.totalCost))
return false;
if (weight == null) {
if (other.weight != null)
return false;
} else if (!weight.equals(other.weight))
return false;
return true;
}
@Override
public String toString() {
return "CoffeeOrder [id=" + id + ", weight=" + weight + ", orderDate=" + orderDate + ", startTime=" + startTime
+ ", endTime=" + endTime + ", totalCost=" + totalCost + ", coffee=" + coffee + ", delivery=" + delivery
+ "]";
}
}
| UTF-8 | Java | 3,895 | java | CoffeeOrder.java | Java | []
| null | []
| package by.bolbas.entity;
import java.util.Date;
/*
* Класс для хранения информации о заказе
*/
public class CoffeeOrder implements java.io.Serializable {
private static final long serialVersionUID = -1540437138823134510L;
private Integer id;
private Integer weight;
private Date orderDate;
private Date startTime;
private Date endTime;
private Integer totalCost;
private Coffee coffee;
private Delivery delivery;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getTotalCost() {
return totalCost;
}
public void setTotalCost(Integer totalCost) {
this.totalCost = totalCost;
}
public Coffee getCoffee() {
return coffee;
}
public void setCoffee(Coffee coffee) {
this.coffee = coffee;
}
public Delivery getDelivery() {
return delivery;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((coffee == null) ? 0 : coffee.hashCode());
result = prime * result + ((delivery == null) ? 0 : delivery.hashCode());
result = prime * result + ((endTime == null) ? 0 : endTime.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((orderDate == null) ? 0 : orderDate.hashCode());
result = prime * result + ((startTime == null) ? 0 : startTime.hashCode());
result = prime * result + ((totalCost == null) ? 0 : totalCost.hashCode());
result = prime * result + ((weight == null) ? 0 : weight.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CoffeeOrder other = (CoffeeOrder) obj;
if (coffee == null) {
if (other.coffee != null)
return false;
} else if (!coffee.equals(other.coffee))
return false;
if (delivery == null) {
if (other.delivery != null)
return false;
} else if (!delivery.equals(other.delivery))
return false;
if (endTime == null) {
if (other.endTime != null)
return false;
} else if (!endTime.equals(other.endTime))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (orderDate == null) {
if (other.orderDate != null)
return false;
} else if (!orderDate.equals(other.orderDate))
return false;
if (startTime == null) {
if (other.startTime != null)
return false;
} else if (!startTime.equals(other.startTime))
return false;
if (totalCost == null) {
if (other.totalCost != null)
return false;
} else if (!totalCost.equals(other.totalCost))
return false;
if (weight == null) {
if (other.weight != null)
return false;
} else if (!weight.equals(other.weight))
return false;
return true;
}
@Override
public String toString() {
return "CoffeeOrder [id=" + id + ", weight=" + weight + ", orderDate=" + orderDate + ", startTime=" + startTime
+ ", endTime=" + endTime + ", totalCost=" + totalCost + ", coffee=" + coffee + ", delivery=" + delivery
+ "]";
}
}
| 3,895 | 0.625324 | 0.617556 | 160 | 22.137501 | 21.168516 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.95 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.