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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b33b2d60275d9c4e6e8220bb47a72f38f3f8bf54 | 30,185,030,224,601 | 762395b25c454dde40378db39c79eda0c6e80d0b | /microsec-common/src/main/java/microsec/uaa/model/v2/UserInfo.java | b23c06be0ad06d6a92adff2e2b8f7525e633a8c8 | []
| no_license | ziscloud/microservice-security | https://github.com/ziscloud/microservice-security | 014fb879f6cd26703320eb2a020ad522f27b8483 | d0707672e62b640ace6f087419bfb416884dd981 | refs/heads/master | 2021-01-23T03:53:13.595000 | 2015-10-29T01:53:07 | 2015-10-29T01:53:07 | 47,304,929 | 0 | 1 | null | true | 2015-12-03T03:28:19 | 2015-12-03T03:28:18 | 2015-12-02T21:38:41 | 2015-11-25T14:34:39 | 492 | 0 | 0 | 0 | null | null | null | package microsec.uaa.model.v2;
import lombok.Data;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@Data
@JsonNaming(LowerCaseWithUnderscoresStrategy.class)
public class UserInfo {
private String userId;
private String userName;
private String givenName;
private String familyName;
private String name;
private String email;
}
| UTF-8 | Java | 463 | java | UserInfo.java | Java | [
{
"context": "fo {\n private String userId;\n private String userName;\n private String givenName;\n private String",
"end": 346,
"score": 0.9763023853302002,
"start": 338,
"tag": "USERNAME",
"value": "userName"
}
]
| null | []
| package microsec.uaa.model.v2;
import lombok.Data;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@Data
@JsonNaming(LowerCaseWithUnderscoresStrategy.class)
public class UserInfo {
private String userId;
private String userName;
private String givenName;
private String familyName;
private String name;
private String email;
}
| 463 | 0.801296 | 0.799136 | 18 | 24.722221 | 23.867239 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 10 |
c1c178eae3eb7cdd68c6b9bec3b3390afe21b421 | 22,814,866,343,394 | 71208b6608c954bff0a26f949df10d808c9895a0 | /src/main/java/com/phonedirectory/exception/CustomizedExceptionHandling.java | fb8cb8e1fff93a82cdb571e5a6d787ddbd2474ad | []
| no_license | soorya-ns/heruko-java-api | https://github.com/soorya-ns/heruko-java-api | 914a3ce58839f85bc06f15a3c680785de53b8a8c | 27cef60fd7f6a7e01619f5977600a12953266531 | refs/heads/master | 2023-02-18T05:57:46.271000 | 2021-01-18T08:49:22 | 2021-01-18T08:49:22 | 330,603,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.phonedirectory.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class CustomizedExceptionHandling extends ResponseEntityExceptionHandler {
@ExceptionHandler(NoDataFoundException.class)
public ResponseEntity<Object> handleExceptions( NoDataFoundException exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(404, 4041, webRequest.getContextPath(), exception.getMessage());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.NOT_FOUND);
return entity;
}
@ExceptionHandler(DatabaseSQLException.class)
public ResponseEntity<Object> dbsSQLHandleExceptions( DatabaseSQLException exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(409, 4091, webRequest.getContextPath(), exception.getMessage(), exception.getDescription());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.CONFLICT);
return entity;
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<Object> badRequestHandleExceptions( BadRequestException exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(400, 4001, webRequest.getContextPath(), exception.getMessage());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
return entity;
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleExceptions( Exception exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(500, 5002, webRequest.getContextPath(), exception.getMessage(), exception.getStackTrace().toString());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.INTERNAL_SERVER_ERROR);
return entity;
}
}
| UTF-8 | Java | 2,203 | java | CustomizedExceptionHandling.java | Java | []
| null | []
| package com.phonedirectory.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class CustomizedExceptionHandling extends ResponseEntityExceptionHandler {
@ExceptionHandler(NoDataFoundException.class)
public ResponseEntity<Object> handleExceptions( NoDataFoundException exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(404, 4041, webRequest.getContextPath(), exception.getMessage());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.NOT_FOUND);
return entity;
}
@ExceptionHandler(DatabaseSQLException.class)
public ResponseEntity<Object> dbsSQLHandleExceptions( DatabaseSQLException exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(409, 4091, webRequest.getContextPath(), exception.getMessage(), exception.getDescription());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.CONFLICT);
return entity;
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<Object> badRequestHandleExceptions( BadRequestException exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(400, 4001, webRequest.getContextPath(), exception.getMessage());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
return entity;
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleExceptions( Exception exception, WebRequest webRequest) {
ApiErrorResponse response = new ApiErrorResponse(500, 5002, webRequest.getContextPath(), exception.getMessage(), exception.getStackTrace().toString());
ResponseEntity<Object> entity = new ResponseEntity<>(response,HttpStatus.INTERNAL_SERVER_ERROR);
return entity;
}
}
| 2,203 | 0.787108 | 0.774399 | 40 | 54.075001 | 45.722744 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 10 |
730322a3f95b1a33d256b026c6ecbec12f7a6d0d | 8,985,071,641,877 | 05948ca1cd3c0d2bcd65056d691c4d1b2e795318 | /classes/com/taobao/dp/http/DefaultUrlRequestService.java | 4af562b324ad66f9ced329bcefc745108fc938e0 | []
| no_license | waterwitness/xiaoenai | https://github.com/waterwitness/xiaoenai | 356a1163f422c882cabe57c0cd3427e0600ff136 | d24c4d457d6ea9281a8a789bc3a29905b06002c6 | refs/heads/master | 2021-01-10T22:14:17.059000 | 2016-10-08T08:39:11 | 2016-10-08T08:39:11 | 70,317,042 | 0 | 8 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taobao.dp.http;
import com.taobao.wireless.security.adapter.common.b;
import com.taobao.wireless.security.adapter.common.c;
public class DefaultUrlRequestService
implements IUrlRequestService
{
public void sendRequest(String paramString1, String paramString2, IResponseReceiver paramIResponseReceiver)
{
paramString1 = c.a(paramString2);
paramIResponseReceiver.onResponseReceive(paramString1.b(), paramString1.a());
}
}
/* Location: E:\apk\xiaoenai2\classes-dex2jar.jar!\com\taobao\dp\http\DefaultUrlRequestService.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 636 | java | DefaultUrlRequestService.java | Java | []
| null | []
| package com.taobao.dp.http;
import com.taobao.wireless.security.adapter.common.b;
import com.taobao.wireless.security.adapter.common.c;
public class DefaultUrlRequestService
implements IUrlRequestService
{
public void sendRequest(String paramString1, String paramString2, IResponseReceiver paramIResponseReceiver)
{
paramString1 = c.a(paramString2);
paramIResponseReceiver.onResponseReceive(paramString1.b(), paramString1.a());
}
}
/* Location: E:\apk\xiaoenai2\classes-dex2jar.jar!\com\taobao\dp\http\DefaultUrlRequestService.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 636 | 0.759434 | 0.735849 | 20 | 30.85 | 34.905979 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 10 |
08a5e3e54efabed1e34703107a917b6a303657c4 | 25,280,177,513,876 | 6b964c3dcff01a88d225835436d8289f32903000 | /mobsters-db/src/main/java/com/lvl6/mobsters/db/jooq/generated/tables/records/GoldSaleConfigRecord.java | 6a1e51d38e3068477c77737c4d1e494268fe7408 | []
| no_license | bellmit/mobsters-server | https://github.com/bellmit/mobsters-server | eeeed13092502de05f6ed8494bf4fdc6d80ad373 | eb37ed32e9183472c6e1d29f027c2d1466028b25 | refs/heads/master | 2022-02-27T18:41:03.611000 | 2016-04-02T00:46:14 | 2016-04-02T00:46:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This class is generated by jOOQ
*/
package com.lvl6.mobsters.db.jooq.generated.tables.records;
import com.lvl6.mobsters.db.jooq.generated.tables.GoldSaleConfig;
import com.lvl6.mobsters.db.jooq.generated.tables.interfaces.IGoldSaleConfig;
import java.sql.Timestamp;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record15;
import org.jooq.Row;
import org.jooq.Row15;
import org.jooq.impl.UpdatableRecordImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.6.1"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
@Entity
@Table(name = "gold_sale_config", schema = "mobsters")
public class GoldSaleConfigRecord extends UpdatableRecordImpl<GoldSaleConfigRecord> implements Record15<Integer, Timestamp, Timestamp, String, String, String, String, String, String, String, String, String, String, String, String>, IGoldSaleConfig {
private static final long serialVersionUID = -554014438;
/**
* Setter for <code>mobsters.gold_sale_config.id</code>.
*/
@Override
public GoldSaleConfigRecord setId(Integer value) {
setValue(0, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.id</code>.
*/
@Id
@Column(name = "id", unique = true, nullable = false, precision = 10)
@NotNull
@Override
public Integer getId() {
return (Integer) getValue(0);
}
/**
* Setter for <code>mobsters.gold_sale_config.start_time</code>.
*/
@Override
public GoldSaleConfigRecord setStartTime(Timestamp value) {
setValue(1, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.start_time</code>.
*/
@Column(name = "start_time")
@Override
public Timestamp getStartTime() {
return (Timestamp) getValue(1);
}
/**
* Setter for <code>mobsters.gold_sale_config.end_time</code>.
*/
@Override
public GoldSaleConfigRecord setEndTime(Timestamp value) {
setValue(2, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.end_time</code>.
*/
@Column(name = "end_time")
@Override
public Timestamp getEndTime() {
return (Timestamp) getValue(2);
}
/**
* Setter for <code>mobsters.gold_sale_config.gold_shoppe_image_name</code>.
*/
@Override
public GoldSaleConfigRecord setGoldShoppeImageName(String value) {
setValue(3, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.gold_shoppe_image_name</code>.
*/
@Column(name = "gold_shoppe_image_name", length = 50)
@Size(max = 50)
@Override
public String getGoldShoppeImageName() {
return (String) getValue(3);
}
/**
* Setter for <code>mobsters.gold_sale_config.gold_bar_image_name</code>.
*/
@Override
public GoldSaleConfigRecord setGoldBarImageName(String value) {
setValue(4, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.gold_bar_image_name</code>.
*/
@Column(name = "gold_bar_image_name", length = 50)
@Size(max = 50)
@Override
public String getGoldBarImageName() {
return (String) getValue(4);
}
/**
* Setter for <code>mobsters.gold_sale_config.package1_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage1Sale(String value) {
setValue(5, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package1_sale</code>.
*/
@Column(name = "package1_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage1Sale() {
return (String) getValue(5);
}
/**
* Setter for <code>mobsters.gold_sale_config.package2_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage2Sale(String value) {
setValue(6, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package2_sale</code>.
*/
@Column(name = "package2_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage2Sale() {
return (String) getValue(6);
}
/**
* Setter for <code>mobsters.gold_sale_config.package3_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage3Sale(String value) {
setValue(7, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package3_sale</code>.
*/
@Column(name = "package3_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage3Sale() {
return (String) getValue(7);
}
/**
* Setter for <code>mobsters.gold_sale_config.package4_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage4Sale(String value) {
setValue(8, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package4_sale</code>.
*/
@Column(name = "package4_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage4Sale() {
return (String) getValue(8);
}
/**
* Setter for <code>mobsters.gold_sale_config.package5_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage5Sale(String value) {
setValue(9, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package5_sale</code>.
*/
@Column(name = "package5_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage5Sale() {
return (String) getValue(9);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS1_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages1Sale(String value) {
setValue(10, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS1_sale</code>.
*/
@Column(name = "packageS1_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages1Sale() {
return (String) getValue(10);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS2_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages2Sale(String value) {
setValue(11, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS2_sale</code>.
*/
@Column(name = "packageS2_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages2Sale() {
return (String) getValue(11);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS3_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages3Sale(String value) {
setValue(12, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS3_sale</code>.
*/
@Column(name = "packageS3_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages3Sale() {
return (String) getValue(12);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS4_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages4Sale(String value) {
setValue(13, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS4_sale</code>.
*/
@Column(name = "packageS4_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages4Sale() {
return (String) getValue(13);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS5_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages5Sale(String value) {
setValue(14, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS5_sale</code>.
*/
@Column(name = "packageS5_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages5Sale() {
return (String) getValue(14);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record15 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row15<Integer, Timestamp, Timestamp, String, String, String, String, String, String, String, String, String, String, String, String> fieldsRow() {
return (Row15) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row15<Integer, Timestamp, Timestamp, String, String, String, String, String, String, String, String, String, String, String, String> valuesRow() {
return (Row15) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return GoldSaleConfig.GOLD_SALE_CONFIG.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field2() {
return GoldSaleConfig.GOLD_SALE_CONFIG.START_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field3() {
return GoldSaleConfig.GOLD_SALE_CONFIG.END_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return GoldSaleConfig.GOLD_SALE_CONFIG.GOLD_SHOPPE_IMAGE_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return GoldSaleConfig.GOLD_SALE_CONFIG.GOLD_BAR_IMAGE_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field6() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE1_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field7() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE2_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field8() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE3_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field9() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE4_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field10() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE5_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field11() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES1_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field12() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES2_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field13() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES3_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field14() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES4_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field15() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES5_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value2() {
return getStartTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value3() {
return getEndTime();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getGoldShoppeImageName();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getGoldBarImageName();
}
/**
* {@inheritDoc}
*/
@Override
public String value6() {
return getPackage1Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value7() {
return getPackage2Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value8() {
return getPackage3Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value9() {
return getPackage4Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value10() {
return getPackage5Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value11() {
return getPackages1Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value12() {
return getPackages2Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value13() {
return getPackages3Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value14() {
return getPackages4Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value15() {
return getPackages5Sale();
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value2(Timestamp value) {
setStartTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value3(Timestamp value) {
setEndTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value4(String value) {
setGoldShoppeImageName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value5(String value) {
setGoldBarImageName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value6(String value) {
setPackage1Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value7(String value) {
setPackage2Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value8(String value) {
setPackage3Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value9(String value) {
setPackage4Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value10(String value) {
setPackage5Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value11(String value) {
setPackages1Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value12(String value) {
setPackages2Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value13(String value) {
setPackages3Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value14(String value) {
setPackages4Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value15(String value) {
setPackages5Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord values(Integer value1, Timestamp value2, Timestamp value3, String value4, String value5, String value6, String value7, String value8, String value9, String value10, String value11, String value12, String value13, String value14, String value15) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
value11(value11);
value12(value12);
value13(value13);
value14(value14);
value15(value15);
return this;
}
// -------------------------------------------------------------------------
// FROM and INTO
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public void from(IGoldSaleConfig from) {
setId(from.getId());
setStartTime(from.getStartTime());
setEndTime(from.getEndTime());
setGoldShoppeImageName(from.getGoldShoppeImageName());
setGoldBarImageName(from.getGoldBarImageName());
setPackage1Sale(from.getPackage1Sale());
setPackage2Sale(from.getPackage2Sale());
setPackage3Sale(from.getPackage3Sale());
setPackage4Sale(from.getPackage4Sale());
setPackage5Sale(from.getPackage5Sale());
setPackages1Sale(from.getPackages1Sale());
setPackages2Sale(from.getPackages2Sale());
setPackages3Sale(from.getPackages3Sale());
setPackages4Sale(from.getPackages4Sale());
setPackages5Sale(from.getPackages5Sale());
}
/**
* {@inheritDoc}
*/
@Override
public <E extends IGoldSaleConfig> E into(E into) {
into.from(this);
return into;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached GoldSaleConfigRecord
*/
public GoldSaleConfigRecord() {
super(GoldSaleConfig.GOLD_SALE_CONFIG);
}
/**
* Create a detached, initialised GoldSaleConfigRecord
*/
public GoldSaleConfigRecord(Integer id, Timestamp startTime, Timestamp endTime, String goldShoppeImageName, String goldBarImageName, String package1Sale, String package2Sale, String package3Sale, String package4Sale, String package5Sale, String packages1Sale, String packages2Sale, String packages3Sale, String packages4Sale, String packages5Sale) {
super(GoldSaleConfig.GOLD_SALE_CONFIG);
setValue(0, id);
setValue(1, startTime);
setValue(2, endTime);
setValue(3, goldShoppeImageName);
setValue(4, goldBarImageName);
setValue(5, package1Sale);
setValue(6, package2Sale);
setValue(7, package3Sale);
setValue(8, package4Sale);
setValue(9, package5Sale);
setValue(10, packages1Sale);
setValue(11, packages2Sale);
setValue(12, packages3Sale);
setValue(13, packages4Sale);
setValue(14, packages5Sale);
}
}
| UTF-8 | Java | 16,831 | java | GoldSaleConfigRecord.java | Java | []
| null | []
| /**
* This class is generated by jOOQ
*/
package com.lvl6.mobsters.db.jooq.generated.tables.records;
import com.lvl6.mobsters.db.jooq.generated.tables.GoldSaleConfig;
import com.lvl6.mobsters.db.jooq.generated.tables.interfaces.IGoldSaleConfig;
import java.sql.Timestamp;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record15;
import org.jooq.Row;
import org.jooq.Row15;
import org.jooq.impl.UpdatableRecordImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.6.1"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
@Entity
@Table(name = "gold_sale_config", schema = "mobsters")
public class GoldSaleConfigRecord extends UpdatableRecordImpl<GoldSaleConfigRecord> implements Record15<Integer, Timestamp, Timestamp, String, String, String, String, String, String, String, String, String, String, String, String>, IGoldSaleConfig {
private static final long serialVersionUID = -554014438;
/**
* Setter for <code>mobsters.gold_sale_config.id</code>.
*/
@Override
public GoldSaleConfigRecord setId(Integer value) {
setValue(0, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.id</code>.
*/
@Id
@Column(name = "id", unique = true, nullable = false, precision = 10)
@NotNull
@Override
public Integer getId() {
return (Integer) getValue(0);
}
/**
* Setter for <code>mobsters.gold_sale_config.start_time</code>.
*/
@Override
public GoldSaleConfigRecord setStartTime(Timestamp value) {
setValue(1, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.start_time</code>.
*/
@Column(name = "start_time")
@Override
public Timestamp getStartTime() {
return (Timestamp) getValue(1);
}
/**
* Setter for <code>mobsters.gold_sale_config.end_time</code>.
*/
@Override
public GoldSaleConfigRecord setEndTime(Timestamp value) {
setValue(2, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.end_time</code>.
*/
@Column(name = "end_time")
@Override
public Timestamp getEndTime() {
return (Timestamp) getValue(2);
}
/**
* Setter for <code>mobsters.gold_sale_config.gold_shoppe_image_name</code>.
*/
@Override
public GoldSaleConfigRecord setGoldShoppeImageName(String value) {
setValue(3, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.gold_shoppe_image_name</code>.
*/
@Column(name = "gold_shoppe_image_name", length = 50)
@Size(max = 50)
@Override
public String getGoldShoppeImageName() {
return (String) getValue(3);
}
/**
* Setter for <code>mobsters.gold_sale_config.gold_bar_image_name</code>.
*/
@Override
public GoldSaleConfigRecord setGoldBarImageName(String value) {
setValue(4, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.gold_bar_image_name</code>.
*/
@Column(name = "gold_bar_image_name", length = 50)
@Size(max = 50)
@Override
public String getGoldBarImageName() {
return (String) getValue(4);
}
/**
* Setter for <code>mobsters.gold_sale_config.package1_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage1Sale(String value) {
setValue(5, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package1_sale</code>.
*/
@Column(name = "package1_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage1Sale() {
return (String) getValue(5);
}
/**
* Setter for <code>mobsters.gold_sale_config.package2_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage2Sale(String value) {
setValue(6, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package2_sale</code>.
*/
@Column(name = "package2_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage2Sale() {
return (String) getValue(6);
}
/**
* Setter for <code>mobsters.gold_sale_config.package3_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage3Sale(String value) {
setValue(7, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package3_sale</code>.
*/
@Column(name = "package3_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage3Sale() {
return (String) getValue(7);
}
/**
* Setter for <code>mobsters.gold_sale_config.package4_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage4Sale(String value) {
setValue(8, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package4_sale</code>.
*/
@Column(name = "package4_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage4Sale() {
return (String) getValue(8);
}
/**
* Setter for <code>mobsters.gold_sale_config.package5_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackage5Sale(String value) {
setValue(9, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.package5_sale</code>.
*/
@Column(name = "package5_sale", length = 50)
@Size(max = 50)
@Override
public String getPackage5Sale() {
return (String) getValue(9);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS1_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages1Sale(String value) {
setValue(10, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS1_sale</code>.
*/
@Column(name = "packageS1_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages1Sale() {
return (String) getValue(10);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS2_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages2Sale(String value) {
setValue(11, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS2_sale</code>.
*/
@Column(name = "packageS2_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages2Sale() {
return (String) getValue(11);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS3_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages3Sale(String value) {
setValue(12, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS3_sale</code>.
*/
@Column(name = "packageS3_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages3Sale() {
return (String) getValue(12);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS4_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages4Sale(String value) {
setValue(13, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS4_sale</code>.
*/
@Column(name = "packageS4_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages4Sale() {
return (String) getValue(13);
}
/**
* Setter for <code>mobsters.gold_sale_config.packageS5_sale</code>.
*/
@Override
public GoldSaleConfigRecord setPackages5Sale(String value) {
setValue(14, value);
return this;
}
/**
* Getter for <code>mobsters.gold_sale_config.packageS5_sale</code>.
*/
@Column(name = "packageS5_sale", length = 50)
@Size(max = 50)
@Override
public String getPackages5Sale() {
return (String) getValue(14);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record15 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row15<Integer, Timestamp, Timestamp, String, String, String, String, String, String, String, String, String, String, String, String> fieldsRow() {
return (Row15) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row15<Integer, Timestamp, Timestamp, String, String, String, String, String, String, String, String, String, String, String, String> valuesRow() {
return (Row15) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return GoldSaleConfig.GOLD_SALE_CONFIG.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field2() {
return GoldSaleConfig.GOLD_SALE_CONFIG.START_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field3() {
return GoldSaleConfig.GOLD_SALE_CONFIG.END_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return GoldSaleConfig.GOLD_SALE_CONFIG.GOLD_SHOPPE_IMAGE_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return GoldSaleConfig.GOLD_SALE_CONFIG.GOLD_BAR_IMAGE_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field6() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE1_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field7() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE2_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field8() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE3_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field9() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE4_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field10() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGE5_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field11() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES1_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field12() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES2_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field13() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES3_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field14() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES4_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field15() {
return GoldSaleConfig.GOLD_SALE_CONFIG.PACKAGES5_SALE;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value2() {
return getStartTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value3() {
return getEndTime();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getGoldShoppeImageName();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getGoldBarImageName();
}
/**
* {@inheritDoc}
*/
@Override
public String value6() {
return getPackage1Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value7() {
return getPackage2Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value8() {
return getPackage3Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value9() {
return getPackage4Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value10() {
return getPackage5Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value11() {
return getPackages1Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value12() {
return getPackages2Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value13() {
return getPackages3Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value14() {
return getPackages4Sale();
}
/**
* {@inheritDoc}
*/
@Override
public String value15() {
return getPackages5Sale();
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value2(Timestamp value) {
setStartTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value3(Timestamp value) {
setEndTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value4(String value) {
setGoldShoppeImageName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value5(String value) {
setGoldBarImageName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value6(String value) {
setPackage1Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value7(String value) {
setPackage2Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value8(String value) {
setPackage3Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value9(String value) {
setPackage4Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value10(String value) {
setPackage5Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value11(String value) {
setPackages1Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value12(String value) {
setPackages2Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value13(String value) {
setPackages3Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value14(String value) {
setPackages4Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord value15(String value) {
setPackages5Sale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GoldSaleConfigRecord values(Integer value1, Timestamp value2, Timestamp value3, String value4, String value5, String value6, String value7, String value8, String value9, String value10, String value11, String value12, String value13, String value14, String value15) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
value11(value11);
value12(value12);
value13(value13);
value14(value14);
value15(value15);
return this;
}
// -------------------------------------------------------------------------
// FROM and INTO
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public void from(IGoldSaleConfig from) {
setId(from.getId());
setStartTime(from.getStartTime());
setEndTime(from.getEndTime());
setGoldShoppeImageName(from.getGoldShoppeImageName());
setGoldBarImageName(from.getGoldBarImageName());
setPackage1Sale(from.getPackage1Sale());
setPackage2Sale(from.getPackage2Sale());
setPackage3Sale(from.getPackage3Sale());
setPackage4Sale(from.getPackage4Sale());
setPackage5Sale(from.getPackage5Sale());
setPackages1Sale(from.getPackages1Sale());
setPackages2Sale(from.getPackages2Sale());
setPackages3Sale(from.getPackages3Sale());
setPackages4Sale(from.getPackages4Sale());
setPackages5Sale(from.getPackages5Sale());
}
/**
* {@inheritDoc}
*/
@Override
public <E extends IGoldSaleConfig> E into(E into) {
into.from(this);
return into;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached GoldSaleConfigRecord
*/
public GoldSaleConfigRecord() {
super(GoldSaleConfig.GOLD_SALE_CONFIG);
}
/**
* Create a detached, initialised GoldSaleConfigRecord
*/
public GoldSaleConfigRecord(Integer id, Timestamp startTime, Timestamp endTime, String goldShoppeImageName, String goldBarImageName, String package1Sale, String package2Sale, String package3Sale, String package4Sale, String package5Sale, String packages1Sale, String packages2Sale, String packages3Sale, String packages4Sale, String packages5Sale) {
super(GoldSaleConfig.GOLD_SALE_CONFIG);
setValue(0, id);
setValue(1, startTime);
setValue(2, endTime);
setValue(3, goldShoppeImageName);
setValue(4, goldBarImageName);
setValue(5, package1Sale);
setValue(6, package2Sale);
setValue(7, package3Sale);
setValue(8, package4Sale);
setValue(9, package5Sale);
setValue(10, packages1Sale);
setValue(11, packages2Sale);
setValue(12, packages3Sale);
setValue(13, packages4Sale);
setValue(14, packages5Sale);
}
}
| 16,831 | 0.659973 | 0.636801 | 827 | 19.351873 | 26.612736 | 350 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.401451 | false | false | 10 |
7be70e18ef86cd97f0c25df3f0e4f44b36af3329 | 2,920,577,809,027 | d42739ed88c4ae15d173953e2982e74a4cd64249 | /java_services/src/main/java/com/example/java_services/tweet/service/PickupLinesServiceImp.java | e487d249fc7aec765d70adf5e6f11a199a84fd3f | []
| no_license | Conanxx/Polyglot-Microservices | https://github.com/Conanxx/Polyglot-Microservices | fed6c7a2288b84c003484bf38847593e7c66c259 | 2177e71b78a5d4e6bec3f1e010ba596c415f0ef4 | refs/heads/master | 2022-11-02T07:37:32.759000 | 2020-05-10T15:09:18 | 2020-05-10T15:09:18 | 262,812,537 | 0 | 0 | null | false | 2020-05-24T08:31:03 | 2020-05-10T15:05:10 | 2020-05-10T15:09:22 | 2020-05-24T08:27:17 | 58 | 0 | 0 | 1 | Java | false | false | package com.example.java_services.tweet.service;
import com.example.java_services.tweet.domain.PickupLines;
import com.example.java_services.tweet.repository.PickupLinesRepository;
import org.springframework.beans.factory.annotation.Autowired;
public class PickupLinesServiceImp implements PickupLinesService {
private PickupLinesRepository pklRepo;
private RandomService rdService;
@Autowired
public PickupLinesServiceImp(final PickupLinesRepository pklRepo, final RandomService rdService){
this.pklRepo = pklRepo;
this.rdService = rdService;
}
@Override
public PickupLines getPickupLines() {
return new PickupLines("Just kidding!");
}
}
| UTF-8 | Java | 713 | java | PickupLinesServiceImp.java | Java | []
| null | []
| package com.example.java_services.tweet.service;
import com.example.java_services.tweet.domain.PickupLines;
import com.example.java_services.tweet.repository.PickupLinesRepository;
import org.springframework.beans.factory.annotation.Autowired;
public class PickupLinesServiceImp implements PickupLinesService {
private PickupLinesRepository pklRepo;
private RandomService rdService;
@Autowired
public PickupLinesServiceImp(final PickupLinesRepository pklRepo, final RandomService rdService){
this.pklRepo = pklRepo;
this.rdService = rdService;
}
@Override
public PickupLines getPickupLines() {
return new PickupLines("Just kidding!");
}
}
| 713 | 0.757363 | 0.757363 | 23 | 30 | 28.191889 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 10 |
21152cd1bb2d2cded67c931a882d06b416b4ea6a | 1,348,619,791,796 | 522d865fecb67d891d98bbbd12b53d923d0a2f30 | /src/main/java/com/gnaf/headfirst/command/Run.java | 236aba67d7ad1c15739c806bc506eee647967c73 | []
| no_license | Derek-FFFFF/LearningDesignPattern | https://github.com/Derek-FFFFF/LearningDesignPattern | 7e214f4408a6c5345e498f6b003a0bd406c6e5c5 | 7ea8fcf2f0d9d62af5070c3424454016c596be68 | refs/heads/master | 2020-03-22T01:46:59.937000 | 2018-08-02T15:15:24 | 2018-08-02T15:15:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gnaf.headfirst.command;
/**
* @author: Derek
* @date: 2018/7/29 23:36
*/
public class Run {
public static void main(String[] args) {
RemoteControl remoteControl = new RemoteControl();
// 创建命令,并指定该命令的具体实现者
Light light = new Light();
Command lightOn = new LightOnCommand(light);
Command lightOff = new LightOffCommand(light);
remoteControl.setOnCommand(lightOn);
remoteControl.setOffCommmand(lightOff);
remoteControl.on();
remoteControl.off();
/**
* Invoker是RemoteControl,遥控器
* Receiver是Light
*
* Command实现类如MultiCommand,然后在execute中循环执行command数组的execute方法。
* 这些命令数组就是之前的套路
*/
}
}
| UTF-8 | Java | 848 | java | Run.java | Java | [
{
"context": "ckage com.gnaf.headfirst.command;\n\n/**\n * @author: Derek\n * @date: 2018/7/29 23:36\n */\npublic class Run {\n",
"end": 58,
"score": 0.9977140426635742,
"start": 53,
"tag": "NAME",
"value": "Derek"
}
]
| null | []
| package com.gnaf.headfirst.command;
/**
* @author: Derek
* @date: 2018/7/29 23:36
*/
public class Run {
public static void main(String[] args) {
RemoteControl remoteControl = new RemoteControl();
// 创建命令,并指定该命令的具体实现者
Light light = new Light();
Command lightOn = new LightOnCommand(light);
Command lightOff = new LightOffCommand(light);
remoteControl.setOnCommand(lightOn);
remoteControl.setOffCommmand(lightOff);
remoteControl.on();
remoteControl.off();
/**
* Invoker是RemoteControl,遥控器
* Receiver是Light
*
* Command实现类如MultiCommand,然后在execute中循环执行command数组的execute方法。
* 这些命令数组就是之前的套路
*/
}
}
| 848 | 0.617886 | 0.602981 | 28 | 25.357143 | 19.603598 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false | 10 |
a799ae93c2171f94f7af6a5fdecf714c5d17d5f1 | 5,815,385,779,120 | 4a62b0786794daf40a4e19838c3d66c54c825a5d | /Comlib-ADK/src/main/java/comlib/adk/agent/TacticsAgent.java | a48cb8d12322e899568dc30c81226ac7a2318565 | [
"BSD-3-Clause"
]
| permissive | AIT-Rescue/CommunicationLibrary | https://github.com/AIT-Rescue/CommunicationLibrary | 353672f2edb12bd75d6c56d4bc5104f42559b0be | 34990939b9c1f1e7a4ec10b222378e35be831f59 | refs/heads/master | 2020-05-19T23:00:53.949000 | 2014-11-21T05:20:00 | 2014-11-21T05:20:00 | 24,581,604 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package comlib.adk.agent;
import comlib.adk.team.tactics.Tactics;
import comlib.agent.CommunicationAgent;
import comlib.manager.MessageManager;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.ChangeSet;
import rescuecore2.standard.messages.AKRest;
import rescuecore2.messages.Message;
public abstract class TacticsAgent<T extends Tactics, E extends StandardEntity> extends CommunicationAgent<E> {
public Tactics tactics;
public int ignoreTime;
public TacticsAgent(T t) {
super();
this.tactics = t;
}
@Override
public void postConnect() {
super.postConnect();
this.ignoreTime = this.config.getIntValue(kernel.KernelConstants.IGNORE_AGENT_COMMANDS_KEY);
//set value
this.tactics.random = this.random;
this.tactics.model = this.model;
this.tactics.config = this.config;
this.tactics.ignoreTime = this.config.getIntValue(kernel.KernelConstants.IGNORE_AGENT_COMMANDS_KEY);
this.tactics.agentID = this.getID(); //AgentのEntityIDはかわるのか??
this.tactics.location = this.location();
this.setAgentEntity();
this.setAgentUniqueValue();
this.tactics.preparation();
}
public abstract void setAgentEntity();
public abstract void setAgentUniqueValue();
@Override
public void registerProvider(MessageManager manager) {
this.tactics.registerProvider(manager);
}
@Override
public void registerEvent(MessageManager manager) {
this.tactics.registerEvent(manager);
}
@Override
public void think(int time, ChangeSet changed) {
if(time <= this.ignoreTime) { //TODO: これでいいのか...
return;
}
Message actMessage = this.tactics.think(time, changed, this.manager);
this.send(actMessage == null ? new AKRest(this.getID(), time) : actMessage);
}
@Override
public void receiveBeforeEvent(int time, ChangeSet changed) {
//set value
this.tactics.time = time;
this.tactics.model = this.model;
this.tactics.config = this.config;
this.tactics.agentID = this.getID();
this.tactics.location = this.location();
this.setAgentEntity();
}
@Override
public void sendAfterEvent(int time, ChangeSet changed) {
}
}
| UTF-8 | Java | 2,407 | java | TacticsAgent.java | Java | []
| null | []
| package comlib.adk.agent;
import comlib.adk.team.tactics.Tactics;
import comlib.agent.CommunicationAgent;
import comlib.manager.MessageManager;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.ChangeSet;
import rescuecore2.standard.messages.AKRest;
import rescuecore2.messages.Message;
public abstract class TacticsAgent<T extends Tactics, E extends StandardEntity> extends CommunicationAgent<E> {
public Tactics tactics;
public int ignoreTime;
public TacticsAgent(T t) {
super();
this.tactics = t;
}
@Override
public void postConnect() {
super.postConnect();
this.ignoreTime = this.config.getIntValue(kernel.KernelConstants.IGNORE_AGENT_COMMANDS_KEY);
//set value
this.tactics.random = this.random;
this.tactics.model = this.model;
this.tactics.config = this.config;
this.tactics.ignoreTime = this.config.getIntValue(kernel.KernelConstants.IGNORE_AGENT_COMMANDS_KEY);
this.tactics.agentID = this.getID(); //AgentのEntityIDはかわるのか??
this.tactics.location = this.location();
this.setAgentEntity();
this.setAgentUniqueValue();
this.tactics.preparation();
}
public abstract void setAgentEntity();
public abstract void setAgentUniqueValue();
@Override
public void registerProvider(MessageManager manager) {
this.tactics.registerProvider(manager);
}
@Override
public void registerEvent(MessageManager manager) {
this.tactics.registerEvent(manager);
}
@Override
public void think(int time, ChangeSet changed) {
if(time <= this.ignoreTime) { //TODO: これでいいのか...
return;
}
Message actMessage = this.tactics.think(time, changed, this.manager);
this.send(actMessage == null ? new AKRest(this.getID(), time) : actMessage);
}
@Override
public void receiveBeforeEvent(int time, ChangeSet changed) {
//set value
this.tactics.time = time;
this.tactics.model = this.model;
this.tactics.config = this.config;
this.tactics.agentID = this.getID();
this.tactics.location = this.location();
this.setAgentEntity();
}
@Override
public void sendAfterEvent(int time, ChangeSet changed) {
}
}
| 2,407 | 0.668637 | 0.666948 | 77 | 29.766233 | 26.034889 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558442 | false | false | 10 |
c6fd7427d829c2d0380e15e1341807364ccc0dd6 | 14,396,730,430,568 | 8f9eefa53a1940656ad5469c8bd3fd72ae82a458 | /ThreadPoolAnalysis/src/main/java/com/rain/test/task/JobTask.java | 3b304a8acf290af4ed880fe3cd689969f961a3b5 | []
| no_license | jingyu323/springbootdemo | https://github.com/jingyu323/springbootdemo | a3ba2ddce999f5af0aa9b019992c3b2fd496ee7f | a0c37da566f6d412fa54fda8cd7b32f6118dda6c | refs/heads/master | 2023-08-13T20:54:23.095000 | 2023-08-10T11:35:26 | 2023-08-10T11:35:26 | 143,681,631 | 0 | 1 | null | false | 2023-01-18T13:41:56 | 2018-08-06T05:44:40 | 2022-05-07T12:25:11 | 2023-01-18T13:41:56 | 909 | 0 | 0 | 30 | Java | false | false | package com.rain.test.task;
import java.util.concurrent.Callable;
public class JobTask implements Callable {
volatile static int count =0;
@Override
public Object call() throws Exception {
Thread.sleep(2000);
System.out.println("count="+count++);
return true;
}
}
| UTF-8 | Java | 309 | java | JobTask.java | Java | []
| null | []
| package com.rain.test.task;
import java.util.concurrent.Callable;
public class JobTask implements Callable {
volatile static int count =0;
@Override
public Object call() throws Exception {
Thread.sleep(2000);
System.out.println("count="+count++);
return true;
}
}
| 309 | 0.656958 | 0.640777 | 14 | 21.071428 | 17.081587 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 10 |
6e895ae9527c40d2de0b56e706fb19da2d89bc77 | 7,988,639,209,341 | 83ff3e26600fd5192e86ec2394e6ea64129846b4 | /src/system/core/GameTable.java | ec8d764c3a4cd6dd810fdc65c63c9d4f9d11835e | [
"Apache-2.0"
]
| permissive | AtoA-ARIA/PlayingCards | https://github.com/AtoA-ARIA/PlayingCards | 21ad675a78c33599dd94dee9c92875c39c1fb1c7 | 04674374862787295af2b4be8f384a3bf79fb4ad | refs/heads/master | 2021-03-03T12:41:05.696000 | 2020-07-14T06:36:37 | 2020-07-14T06:36:37 | 245,961,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package system.core;
import system.front.ScannerForMultiThreadOnCUI;
/**
* ゲームを管理する抽象クラス。すべてのゲームはこのクラスを継承する。
* @author Takashi Sakakihara
*
*/
public abstract class GameTable extends Thread implements VisualizerOnCUI {
/**
* CUIでゲームをするときに使用する標準入力のスキャナ。
* マルチスレッド用に作ったクラス。
*/
protected ScannerForMultiThreadOnCUI scanCUI;
/**
* ゲームで使用する山札。
*/
protected CardDeck gameDeck;
/**
* ゲームの参加人数。
*/
protected int numberOfPlayers;
/**
* ゲームの最大プレイヤー人数。
*/
protected int maxPlayers;
/**
* ゲームの最小プレイヤー人数。
*/
protected int minPlayers;
/**
* CUIでゲームをするときのコンストラクタ。
* 外からScannerを共有しておく。
* @param scanCUI 標準入力のスキャナ。
*/
public GameTable(ScannerForMultiThreadOnCUI scanCUI) {
this.scanCUI = scanCUI;
}
/**
* ゲームの初期設定やプレイヤーの配置などを行う。
*/
public abstract void settingTable();
/**
* ファイルにゲームをセーブする。
*/
public abstract void saveGame();
/**
* ゲームのデータをロードする。
* @param fileName ファイル名
*/
public abstract void loadGame(String fileName);
/**
* ゲームのルールをCUIに表示する。
*/
public abstract void printRulesOnCUI();
}
| UTF-8 | Java | 1,518 | java | GameTable.java | Java | [
{
"context": "**\n * ゲームを管理する抽象クラス。すべてのゲームはこのクラスを継承する。\n * @author Takashi Sakakihara\n *\n */\npublic abstract class GameTable extends Th",
"end": 141,
"score": 0.9998441338539124,
"start": 123,
"tag": "NAME",
"value": "Takashi Sakakihara"
}
]
| null | []
| package system.core;
import system.front.ScannerForMultiThreadOnCUI;
/**
* ゲームを管理する抽象クラス。すべてのゲームはこのクラスを継承する。
* @author <NAME>
*
*/
public abstract class GameTable extends Thread implements VisualizerOnCUI {
/**
* CUIでゲームをするときに使用する標準入力のスキャナ。
* マルチスレッド用に作ったクラス。
*/
protected ScannerForMultiThreadOnCUI scanCUI;
/**
* ゲームで使用する山札。
*/
protected CardDeck gameDeck;
/**
* ゲームの参加人数。
*/
protected int numberOfPlayers;
/**
* ゲームの最大プレイヤー人数。
*/
protected int maxPlayers;
/**
* ゲームの最小プレイヤー人数。
*/
protected int minPlayers;
/**
* CUIでゲームをするときのコンストラクタ。
* 外からScannerを共有しておく。
* @param scanCUI 標準入力のスキャナ。
*/
public GameTable(ScannerForMultiThreadOnCUI scanCUI) {
this.scanCUI = scanCUI;
}
/**
* ゲームの初期設定やプレイヤーの配置などを行う。
*/
public abstract void settingTable();
/**
* ファイルにゲームをセーブする。
*/
public abstract void saveGame();
/**
* ゲームのデータをロードする。
* @param fileName ファイル名
*/
public abstract void loadGame(String fileName);
/**
* ゲームのルールをCUIに表示する。
*/
public abstract void printRulesOnCUI();
}
| 1,506 | 0.699811 | 0.699811 | 61 | 16.311476 | 16.497929 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.967213 | false | false | 10 |
7899a4bba6f1e354ee3009c8a40aa6f149c1aa8c | 23,029,614,667,474 | dd4f837764f0d69a0bee77a1bad27aa6845475a1 | /src/main/java/advisor/http/client/Request.java | 47488513dbdf1787cf749885080713e45b9cfada | []
| no_license | JurekMateusz/MusicAdvisor | https://github.com/JurekMateusz/MusicAdvisor | 7c42b83a3c6cba5c7fe9a9844d422b1a6fe97174 | 077f8f54141476672e1871de5906fd8dd45e2e74 | refs/heads/main | 2023-01-09T20:05:22.821000 | 2020-11-12T18:49:03 | 2020-11-12T18:51:10 | 300,523,278 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package advisor.http.client;
import advisor.exception.ContentNotFoundException;
import advisor.exception.InvalidAccessTokenException;
import advisor.exception.InvalidSpotifyCodeException;
import advisor.model.api.error.ErrorRoot;
import com.google.gson.Gson;
import io.vavr.control.Try;
import javax.ws.rs.core.MediaType;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Request {
private static final int HTTP_NOT_FOUND = 404;
private static final int HTTP_UNAUTHORIZED = 401;
private static final int HTTP_OK = 200;
private final HttpClient client;
public Request(HttpClient httpClient) {
this.client = httpClient;
}
public Try<HttpResponse<String>> getAccessToken(String contentToGetFirstAccessToken, String url) {
HttpRequest request =
HttpRequest.newBuilder()
.setHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED)
.uri(URI.create(url))
.POST(HttpRequest.BodyPublishers.ofString(contentToGetFirstAccessToken))
.build();
return Try.of(
() -> {
HttpResponse<String> resp = client.send(request, HttpResponse.BodyHandlers.ofString());
validateContentWithAccessToken(resp);
return resp;
});
}
private void validateContentWithAccessToken(HttpResponse<String> resp)
throws InvalidSpotifyCodeException {
if (resp.statusCode() != HTTP_OK) {
throw new InvalidSpotifyCodeException();
}
}
public Try<HttpResponse<String>> makeHttpGetRequest(String accessToken, String toUrl) {
String authHeader = createAuthHeader(accessToken);
HttpRequest httpRequest =
HttpRequest.newBuilder()
.setHeader("Content-Type", MediaType.APPLICATION_JSON)
.setHeader("Authorization", authHeader)
.uri(URI.create(toUrl))
.GET()
.build();
return Try.of(
() -> {
HttpResponse<String> resp =
client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
validateResult(resp);
return resp;
});
}
private void validateResult(HttpResponse<String> response)
throws InvalidAccessTokenException, ContentNotFoundException {
int statusCode = response.statusCode();
if (statusCode == HTTP_UNAUTHORIZED) {
throw new InvalidAccessTokenException();
}
if (statusCode == HTTP_NOT_FOUND) {
throw new ContentNotFoundException("Nothing found in: " + response.uri());
}
if (response.body().contains("error")) {
ErrorRoot errorRoot = new Gson().fromJson(response.body(), ErrorRoot.class);
throw new ContentNotFoundException(errorRoot.getError().getMessage());
}
}
private String createAuthHeader(String accessToken) {
return "Bearer " + accessToken;
}
}
| UTF-8 | Java | 2,879 | java | Request.java | Java | []
| null | []
| package advisor.http.client;
import advisor.exception.ContentNotFoundException;
import advisor.exception.InvalidAccessTokenException;
import advisor.exception.InvalidSpotifyCodeException;
import advisor.model.api.error.ErrorRoot;
import com.google.gson.Gson;
import io.vavr.control.Try;
import javax.ws.rs.core.MediaType;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Request {
private static final int HTTP_NOT_FOUND = 404;
private static final int HTTP_UNAUTHORIZED = 401;
private static final int HTTP_OK = 200;
private final HttpClient client;
public Request(HttpClient httpClient) {
this.client = httpClient;
}
public Try<HttpResponse<String>> getAccessToken(String contentToGetFirstAccessToken, String url) {
HttpRequest request =
HttpRequest.newBuilder()
.setHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED)
.uri(URI.create(url))
.POST(HttpRequest.BodyPublishers.ofString(contentToGetFirstAccessToken))
.build();
return Try.of(
() -> {
HttpResponse<String> resp = client.send(request, HttpResponse.BodyHandlers.ofString());
validateContentWithAccessToken(resp);
return resp;
});
}
private void validateContentWithAccessToken(HttpResponse<String> resp)
throws InvalidSpotifyCodeException {
if (resp.statusCode() != HTTP_OK) {
throw new InvalidSpotifyCodeException();
}
}
public Try<HttpResponse<String>> makeHttpGetRequest(String accessToken, String toUrl) {
String authHeader = createAuthHeader(accessToken);
HttpRequest httpRequest =
HttpRequest.newBuilder()
.setHeader("Content-Type", MediaType.APPLICATION_JSON)
.setHeader("Authorization", authHeader)
.uri(URI.create(toUrl))
.GET()
.build();
return Try.of(
() -> {
HttpResponse<String> resp =
client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
validateResult(resp);
return resp;
});
}
private void validateResult(HttpResponse<String> response)
throws InvalidAccessTokenException, ContentNotFoundException {
int statusCode = response.statusCode();
if (statusCode == HTTP_UNAUTHORIZED) {
throw new InvalidAccessTokenException();
}
if (statusCode == HTTP_NOT_FOUND) {
throw new ContentNotFoundException("Nothing found in: " + response.uri());
}
if (response.body().contains("error")) {
ErrorRoot errorRoot = new Gson().fromJson(response.body(), ErrorRoot.class);
throw new ContentNotFoundException(errorRoot.getError().getMessage());
}
}
private String createAuthHeader(String accessToken) {
return "Bearer " + accessToken;
}
}
| 2,879 | 0.692254 | 0.689128 | 84 | 33.273811 | 25.812212 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 10 |
a8eab598e96a4b1d92f1a59690636ec958e34229 | 30,339,649,029,964 | 25820da6b91f8b270fd9490f1de013d7207388d2 | /graph-dc/graph-dc-core/src/main/java/com/haizhi/graph/dc/core/model/vo/DcEnvFileVo.java | 42f5ffab9fec129a1f8cd87a7c72a87a507fb7fd | []
| no_license | Joegxx/graphplatform | https://github.com/Joegxx/graphplatform | d784da9d5475a84d836974474bc00263b06a4ad0 | b9341937406f5cfc946ded3ecac5126114c977c0 | refs/heads/master | 2022-04-01T14:01:43.466000 | 2019-10-15T16:27:41 | 2019-10-15T16:27:41 | 272,382,227 | 0 | 1 | null | true | 2020-06-15T08:24:19 | 2020-06-15T08:24:18 | 2019-10-16T17:08:16 | 2020-02-05T00:17:57 | 74,832 | 0 | 0 | 0 | null | false | false | package com.haizhi.graph.dc.core.model.vo;
import com.haizhi.graph.common.model.BaseVo;
import com.haizhi.graph.dc.core.model.po.DcEnvFilePo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Created by chengangxiong on 2019/03/25
*/
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "环境对象DcEnvVo", description = "环境管理")
public class DcEnvFileVo extends BaseVo {
@ApiModelProperty(value = "表名称", example = "schema_name")
private String name;
public DcEnvFileVo(DcEnvFilePo po) {
super(po);
this.name = po.getName();
}
}
| UTF-8 | Java | 740 | java | DcEnvFileVo.java | Java | [
{
"context": "shCode;\nimport lombok.ToString;\n\n/**\n * Created by chengangxiong on 2019/03/25\n */\n@Data\n@ToString(callSuper = tru",
"end": 340,
"score": 0.9991857409477234,
"start": 327,
"tag": "USERNAME",
"value": "chengangxiong"
}
]
| null | []
| package com.haizhi.graph.dc.core.model.vo;
import com.haizhi.graph.common.model.BaseVo;
import com.haizhi.graph.dc.core.model.po.DcEnvFilePo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Created by chengangxiong on 2019/03/25
*/
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "环境对象DcEnvVo", description = "环境管理")
public class DcEnvFileVo extends BaseVo {
@ApiModelProperty(value = "表名称", example = "schema_name")
private String name;
public DcEnvFileVo(DcEnvFilePo po) {
super(po);
this.name = po.getName();
}
}
| 740 | 0.736769 | 0.725627 | 27 | 25.592592 | 19.389305 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false | 10 |
7897edfffe92fd98d94b7a5941526b919f09a7fe | 18,519,898,989,449 | 528cfb3ccb5edfdf96ca22cf1c1e9939d4ed5834 | /src/main/java/br/com/pv/GitHubRepository.java | f5cc7d802f5682e11fd521a4575f3f44cfdf1a23 | []
| no_license | PauloVictorSantos/WebCrawler | https://github.com/PauloVictorSantos/WebCrawler | bf7aab9e6b5b91e0d2bc2b47b95ee9ebaf5d0749 | 1e3398e44c06617498b70d8c2691c1ab0f54b314 | refs/heads/master | 2020-03-07T20:49:40.905000 | 2018-04-05T01:47:04 | 2018-04-05T01:47:04 | 127,707,845 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.pv;
import java.io.Serializable;
public class GitHubRepository implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String title;
private String url;
private String zip;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
| UTF-8 | Java | 552 | java | GitHubRepository.java | Java | []
| null | []
| package br.com.pv;
import java.io.Serializable;
public class GitHubRepository implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String title;
private String url;
private String zip;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
| 552 | 0.679348 | 0.677536 | 39 | 13.153846 | 14.545311 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.102564 | false | false | 10 |
a5a7d050e5ca9fc20e1c9b599ff286678ebefceb | 2,860,448,271,594 | 82e1912f6fb10eb5d0433c9b01394e61c74a2ad5 | /ggp-base/src/org/ggp/base/player/gamer/statemachine/deepcardinal/heuristic/GoalProximityHeuristic.java | 2e7aa14fe744da220b31d77a80be8dada89d8872 | [
"BSD-3-Clause"
]
| permissive | adamwgoldberg/gameplaying | https://github.com/adamwgoldberg/gameplaying | d9eb69721ad600278a97c3c079591fee9a20b4e3 | d7264480e590eb5bde106a652c10bba9fded8529 | refs/heads/master | 2016-03-31T11:36:17.922000 | 2014-06-04T23:53:38 | 2014-06-04T23:53:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ggp.base.player.gamer.statemachine.deepcardinal.heuristic;
import org.ggp.base.util.statemachine.MachineState;
import org.ggp.base.util.statemachine.Role;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException;
import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException;
/**
* GoalProximityHeuristic is a heuristic that measure the goodness of a particular
* state by simply returning the goal value at that state.
*/
public class GoalProximityHeuristic implements OldHeuristic {
@Override
public int evaluate(StateMachine stateMachine, MachineState state, Role role)
throws MoveDefinitionException, GoalDefinitionException {
return stateMachine.getGoal(state, role);
}
@Override
public String name() {
return "Goal Proximity Heuristic";
}
}
| UTF-8 | Java | 885 | java | GoalProximityHeuristic.java | Java | []
| null | []
| package org.ggp.base.player.gamer.statemachine.deepcardinal.heuristic;
import org.ggp.base.util.statemachine.MachineState;
import org.ggp.base.util.statemachine.Role;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException;
import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException;
/**
* GoalProximityHeuristic is a heuristic that measure the goodness of a particular
* state by simply returning the goal value at that state.
*/
public class GoalProximityHeuristic implements OldHeuristic {
@Override
public int evaluate(StateMachine stateMachine, MachineState state, Role role)
throws MoveDefinitionException, GoalDefinitionException {
return stateMachine.getGoal(state, role);
}
@Override
public String name() {
return "Goal Proximity Heuristic";
}
}
| 885 | 0.786441 | 0.786441 | 26 | 32.03846 | 29.945438 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.961538 | false | false | 10 |
66ae390981a369ef1a0866f7def98802eff190db | 5,574,867,589,323 | 8308d6afce104bca8340ac439eef2d379e6c8398 | /CS1120GroupLA5/src/edu/wmich/cs1120/la5/Literal.java | 7737e28f97df9435b4ffe517b05c0ac5d47212de | []
| no_license | 22Titanium14/CS1120LA5 | https://github.com/22Titanium14/CS1120LA5 | 9e89fd1d8b9f2d47e81708c208060759e6887044 | 40837722a71dd7ceff61c9a2f8f6f445d0dbc9c5 | refs/heads/master | 2021-01-22T18:50:45.073000 | 2017-03-30T03:38:16 | 2017-03-30T03:38:16 | 85,122,731 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
*Assignment: CS1120 LA5_SP2017
*Authors: Adam Dubs, Devin Anderson, Dylan Lafleur
*Date: 03/20/2017
*Reference: NA
*/
package edu.wmich.cs1120.la5;
public class Literal implements IExpression {
public int value;
/**
*
* @param value
*/
Literal(int value) {
this.value = value;
}
/**
* getter method for the value field
*@return = the value field
*/
public int getValue() {
return this.value;
}
}
| UTF-8 | Java | 436 | java | Literal.java | Java | [
{
"context": "/*\n *Assignment: CS1120 LA5_SP2017\n *Authors: Adam Dubs, Devin Anderson, Dylan Lafleur\n *Date: 03/20/2017",
"end": 55,
"score": 0.9998274445533752,
"start": 46,
"tag": "NAME",
"value": "Adam Dubs"
},
{
"context": "ssignment: CS1120 LA5_SP2017\n *Authors: Adam Dubs, Devin Anderson, Dylan Lafleur\n *Date: 03/20/2017\n *Reference: NA",
"end": 71,
"score": 0.999841570854187,
"start": 57,
"tag": "NAME",
"value": "Devin Anderson"
},
{
"context": "0 LA5_SP2017\n *Authors: Adam Dubs, Devin Anderson, Dylan Lafleur\n *Date: 03/20/2017\n *Reference: NA\n */\n\npackage e",
"end": 86,
"score": 0.9998576045036316,
"start": 73,
"tag": "NAME",
"value": "Dylan Lafleur"
}
]
| null | []
| /*
*Assignment: CS1120 LA5_SP2017
*Authors: <NAME>, <NAME>, <NAME>
*Date: 03/20/2017
*Reference: NA
*/
package edu.wmich.cs1120.la5;
public class Literal implements IExpression {
public int value;
/**
*
* @param value
*/
Literal(int value) {
this.value = value;
}
/**
* getter method for the value field
*@return = the value field
*/
public int getValue() {
return this.value;
}
}
| 418 | 0.649083 | 0.598624 | 29 | 14.034483 | 14.561363 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.793103 | false | false | 10 |
d3a2fc26b98afc94f96538596ef088c0a1ea46ae | 28,999,619,197,286 | 16ecaf5a34d5f5e632ac9cdea4ac8c2be1ec24dc | /MovyparkCordoba_v5.13_apkpure.com_source_from_JADX/sources/com/google/android/gms/ads/internal/zzbm.java | 355118052fb535f08671f5513817acfae7e976f9 | []
| no_license | turbo-funicular/com.movypark.cordoba | https://github.com/turbo-funicular/com.movypark.cordoba | 3eca439eb0a14339c7f74e7ce8b3b3b50e08f7b5 | 320eee3a676969880c1a280419f2a26f87d23ce4 | refs/heads/master | 2020-08-09T23:57:23.309000 | 2019-10-10T20:06:48 | 2019-10-10T20:06:48 | 214,202,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.ads.internal;
public interface zzbm {
void zzcp();
void zzcq();
}
| UTF-8 | Java | 107 | java | zzbm.java | Java | []
| null | []
| package com.google.android.gms.ads.internal;
public interface zzbm {
void zzcp();
void zzcq();
}
| 107 | 0.672897 | 0.672897 | 7 | 14.285714 | 14.877733 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 10 |
e75ba1fd0743f8b48579c2eb50dd9dfe0dd1d489 | 18,562,848,657,545 | b8a1a3340706942927c036f6124485bc7c6a770c | /tetris/tetris-project/user/cloud/tetris-user/src/main/java/com/sumavision/tetris/user/BasicDevelopmentDAO.java | 21036083ff9b698ef881a7156adf3ec8a78352d3 | []
| no_license | lvdeyang/Caterpillar | https://github.com/lvdeyang/Caterpillar | 58ffe1320bd6c763223f1ca0277abefc6b13fd5f | 385b3dd2cf26e537ab8f22e3d5320f89152f0f7e | refs/heads/master | 2022-12-21T13:33:42.128000 | 2021-06-06T07:54:24 | 2021-06-06T07:54:24 | 55,577,236 | 5 | 2 | null | false | 2022-12-16T02:40:45 | 2016-04-06T05:05:45 | 2022-07-08T03:09:37 | 2022-12-16T02:40:42 | 365,024 | 4 | 2 | 15 | JavaScript | false | false | package com.sumavision.tetris.user;
import org.springframework.data.repository.RepositoryDefinition;
import com.sumavision.tetris.orm.dao.BaseDAO;
@RepositoryDefinition(domainClass = BasicDevelopmentPO.class, idClass = Long.class)
public interface BasicDevelopmentDAO extends BaseDAO<BasicDevelopmentPO>{
/**
* 根据appId查询用户基本配置<br/>
* <b>作者:</b>lvdeyang<br/>
* <b>版本:</b>1.0<br/>
* <b>日期:</b>2019年4月22日 下午1:50:15
* @param String appId 开发者id
* @return BasicDevelopmentPO 用户基本配置
*/
public BasicDevelopmentPO findByAppId(String appId);
/**
* 查询用户的开发者基本配置<br/>
* <b>作者:</b>lvdeyang<br/>
* <b>版本:</b>1.0<br/>
* <b>日期:</b>2019年4月22日 上午11:08:31
* @param Long userId 用户id
* @return DevelopmentPO 开发者基本配置
*/
public BasicDevelopmentPO findByUserId(Long userId);
}
| UTF-8 | Java | 953 | java | BasicDevelopmentDAO.java | Java | [
{
"context": "\r\n\r\n\t/**\r\n\t * 根据appId查询用户基本配置<br/>\r\n\t * <b>作者:</b>lvdeyang<br/>\r\n\t * <b>版本:</b>1.0<br/>\r\n\t * <b>日期:</b>2019年",
"end": 370,
"score": 0.9997601509094238,
"start": 362,
"tag": "USERNAME",
"value": "lvdeyang"
},
{
"context": ");\r\n\t\r\n\t/**\r\n\t * 查询用户的开发者基本配置<br/>\r\n\t * <b>作者:</b>lvdeyang<br/>\r\n\t * <b>版本:</b>1.0<br/>\r\n\t * <b>日期:</b>2019年",
"end": 622,
"score": 0.9997622966766357,
"start": 614,
"tag": "USERNAME",
"value": "lvdeyang"
}
]
| null | []
| package com.sumavision.tetris.user;
import org.springframework.data.repository.RepositoryDefinition;
import com.sumavision.tetris.orm.dao.BaseDAO;
@RepositoryDefinition(domainClass = BasicDevelopmentPO.class, idClass = Long.class)
public interface BasicDevelopmentDAO extends BaseDAO<BasicDevelopmentPO>{
/**
* 根据appId查询用户基本配置<br/>
* <b>作者:</b>lvdeyang<br/>
* <b>版本:</b>1.0<br/>
* <b>日期:</b>2019年4月22日 下午1:50:15
* @param String appId 开发者id
* @return BasicDevelopmentPO 用户基本配置
*/
public BasicDevelopmentPO findByAppId(String appId);
/**
* 查询用户的开发者基本配置<br/>
* <b>作者:</b>lvdeyang<br/>
* <b>版本:</b>1.0<br/>
* <b>日期:</b>2019年4月22日 上午11:08:31
* @param Long userId 用户id
* @return DevelopmentPO 开发者基本配置
*/
public BasicDevelopmentPO findByUserId(Long userId);
}
| 953 | 0.691839 | 0.656516 | 29 | 26.310345 | 22.7628 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.896552 | false | false | 10 |
5b2c973dde1d2509708c4b6f9d34573c0a2725b3 | 30,004,641,551,134 | e43b648e32c32d713a868aedba3c04f10c4cba3a | /app/src/main/java/com/tamersarioglu/sozluk/DetayActivity.java | dcdfc883868df026b659a3953e49d89ac72af5f3 | []
| no_license | TamerSarioglu/SozlukFirebase | https://github.com/TamerSarioglu/SozlukFirebase | e5e6fd5fb3e216ac43be15b1852cbac36c9e0687 | 447142686d9297cebc13b973295075dd348b9688 | refs/heads/master | 2022-11-11T14:39:37.500000 | 2020-06-23T20:16:34 | 2020-06-23T20:16:34 | 274,500,083 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tamersarioglu.sozluk;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class DetayActivity extends AppCompatActivity {
private Kelimeler kelime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detay);
TextView textViewDetayIngilizce = findViewById(R.id.textView_Detay_Ingilizce);
TextView textViewDetayTurkce = findViewById(R.id.textView_Detay_Turkce);
kelime = (Kelimeler) getIntent().getSerializableExtra("nesne");
String gelenIngilizce = kelime.getIngilizce();
String gelenTurkce = kelime.getTurkce();
textViewDetayIngilizce.setText(gelenIngilizce);
textViewDetayTurkce.setText(gelenTurkce);
}
} | UTF-8 | Java | 858 | java | DetayActivity.java | Java | []
| null | []
| package com.tamersarioglu.sozluk;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class DetayActivity extends AppCompatActivity {
private Kelimeler kelime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detay);
TextView textViewDetayIngilizce = findViewById(R.id.textView_Detay_Ingilizce);
TextView textViewDetayTurkce = findViewById(R.id.textView_Detay_Turkce);
kelime = (Kelimeler) getIntent().getSerializableExtra("nesne");
String gelenIngilizce = kelime.getIngilizce();
String gelenTurkce = kelime.getTurkce();
textViewDetayIngilizce.setText(gelenIngilizce);
textViewDetayTurkce.setText(gelenTurkce);
}
} | 858 | 0.740093 | 0.740093 | 30 | 27.633333 | 27.565054 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 10 |
c26dbd42a9db1c80058b73ff8569cc97ae27828b | 30,004,641,553,077 | b1c6b6fda9a40b9ae1d1811db13d90d6bb38bb1a | /src/com/asiainfo/cs/ed/train/dao/interfaces/IEdModelDateDAO.java | ae5ada7cef3bb951e7c9332174200eed0470f28d | []
| no_license | feiniaoying/Inet | https://github.com/feiniaoying/Inet | e7ef42ca9578f463d11e0faca2308afa0804019e | 5cb1918f7ba03024dc3b20aa32254abb2f3ec2fd | refs/heads/master | 2016-06-06T20:48:56.142000 | 2016-03-05T14:50:58 | 2016-03-05T14:50:58 | 53,204,179 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asiainfo.cs.ed.train.dao.interfaces;
import com.asiainfo.cs.ed.train.ivalues.IBOEdModelDateValue;
/**
* 计划模版天数DAO
* @author zhangcheng
*
*/
public interface IEdModelDateDAO {
/**
* 查询模版天数
* @param model_id
* @param $startrowindex
* @param $endrowindex
* @return
* @throws Exception
*/
public IBOEdModelDateValue[] queryEdModelDate(String model_id,
int $startrowindex, int $endrowindex)throws Exception;
/**
* 查询模版天数数量
* @param model_id
* @return
* @throws Exception
*/
public int queryEdModelDateCount(String model_id)throws Exception;
/**
* 根据模板编码查询模板天数
*/
public String queryEdModelDates(String modelIds,String MODEL_DATE_ID)throws Exception;
/**
* 根据模板编码查询模板天数
*/
public String queryEdModelDates()throws Exception;
/**
* 新增模版天数
*/
public void addEdTrainDate(String model_id,
IBOEdModelDateValue[] edModelDateValue)throws Exception;
/**
* 修改模版天数
*/
public void ModifyEdTrainDate(String model_id, IBOEdModelDateValue[] ivalues)throws Exception;
}
| GB18030 | Java | 1,141 | java | IEdModelDateDAO.java | Java | [
{
"context": ".IBOEdModelDateValue;\n\n/**\n * 计划模版天数DAO\n * @author zhangcheng\n *\n */\npublic interface IEdModelDateDAO {\n\n\n\t/**\n",
"end": 150,
"score": 0.9975630044937134,
"start": 140,
"tag": "USERNAME",
"value": "zhangcheng"
}
]
| null | []
| package com.asiainfo.cs.ed.train.dao.interfaces;
import com.asiainfo.cs.ed.train.ivalues.IBOEdModelDateValue;
/**
* 计划模版天数DAO
* @author zhangcheng
*
*/
public interface IEdModelDateDAO {
/**
* 查询模版天数
* @param model_id
* @param $startrowindex
* @param $endrowindex
* @return
* @throws Exception
*/
public IBOEdModelDateValue[] queryEdModelDate(String model_id,
int $startrowindex, int $endrowindex)throws Exception;
/**
* 查询模版天数数量
* @param model_id
* @return
* @throws Exception
*/
public int queryEdModelDateCount(String model_id)throws Exception;
/**
* 根据模板编码查询模板天数
*/
public String queryEdModelDates(String modelIds,String MODEL_DATE_ID)throws Exception;
/**
* 根据模板编码查询模板天数
*/
public String queryEdModelDates()throws Exception;
/**
* 新增模版天数
*/
public void addEdTrainDate(String model_id,
IBOEdModelDateValue[] edModelDateValue)throws Exception;
/**
* 修改模版天数
*/
public void ModifyEdTrainDate(String model_id, IBOEdModelDateValue[] ivalues)throws Exception;
}
| 1,141 | 0.720117 | 0.720117 | 50 | 19.58 | 24.069141 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.02 | false | false | 10 |
f0879c1f6b939f1bf41a7d0c4230cd0ed4f3370d | 12,214,887,045,862 | 0f6dab95f10a1650b12f1d9e5694144e0e307b54 | /qq-mall-common/src/main/java/com/honglinktech/zbgj/dao/TSocietyNoteDao.java | 986e7549d44d566e153225118e8bf0ca061d9d98 | []
| no_license | suevip/qq-mall | https://github.com/suevip/qq-mall | 9bb4d756bd64ec3b3cdda9b30a15d296df0cecdd | bc762ed4fc68c84db18e7b4525411eb89feb3f09 | refs/heads/master | 2017-12-31T13:59:47.108000 | 2016-09-27T07:11:31 | 2016-09-27T07:11:31 | 69,426,963 | 0 | 1 | null | true | 2016-09-28T04:54:42 | 2016-09-28T04:54:41 | 2016-09-10T13:59:15 | 2016-09-27T07:12:19 | 2,446 | 0 | 0 | 0 | null | null | null | package com.honglinktech.zbgj.dao;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.jdbc.core.RowMapper;
import com.honglinktech.zbgj.base.BaseDao;
import com.honglinktech.zbgj.entity.TSocietyNote;
/**
*帖子Dao
**/
@Component
public class TSocietyNoteDao extends BaseDao<TSocietyNote>{
public Object[] getDBMapping(String filedName){
for(TSocietyNote.DBMaping d:TSocietyNote.DBMaping.values()){
if(d.toString().equals(filedName)){
TSocietyNote.DBMaping dbMaping = TSocietyNote.DBMaping.valueOf(filedName);
Object[] values = {dbMaping.getDbName(),dbMaping.getDbType(),dbMaping.getPrimaryKey(),dbMaping.isAotuIn(),dbMaping.isAllowNull()};
return values;
}
}
return null;
}
@Resource
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
super.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate jdbcTemplate(){
return jdbcTemplate;
}
@Override
protected RowMapper<TSocietyNote> getRowMapper() {
return new TSocietyNote.TSocietyNoteRowMapper();
}
}
| UTF-8 | Java | 1,111 | java | TSocietyNoteDao.java | Java | []
| null | []
| package com.honglinktech.zbgj.dao;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.jdbc.core.RowMapper;
import com.honglinktech.zbgj.base.BaseDao;
import com.honglinktech.zbgj.entity.TSocietyNote;
/**
*帖子Dao
**/
@Component
public class TSocietyNoteDao extends BaseDao<TSocietyNote>{
public Object[] getDBMapping(String filedName){
for(TSocietyNote.DBMaping d:TSocietyNote.DBMaping.values()){
if(d.toString().equals(filedName)){
TSocietyNote.DBMaping dbMaping = TSocietyNote.DBMaping.valueOf(filedName);
Object[] values = {dbMaping.getDbName(),dbMaping.getDbType(),dbMaping.getPrimaryKey(),dbMaping.isAotuIn(),dbMaping.isAllowNull()};
return values;
}
}
return null;
}
@Resource
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
super.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate jdbcTemplate(){
return jdbcTemplate;
}
@Override
protected RowMapper<TSocietyNote> getRowMapper() {
return new TSocietyNote.TSocietyNoteRowMapper();
}
}
| 1,111 | 0.776874 | 0.776874 | 39 | 27.384615 | 28.481768 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.564103 | false | false | 10 |
943a35505882b4e368b64d6b3b3a89f3b3d5044e | 13,022,340,885,570 | c24fbeb11df8c12582ad1ecd8b040a249ab51b01 | /timeline/src/main/java/com/webapp/timeline/sns/domain/ConverterShowLevel.java | 984c341799df0b9a6dca339018420c5bd3152374 | [
"MIT"
]
| permissive | Tamrado/tamra_server | https://github.com/Tamrado/tamra_server | 1c1a9770c778b9af058ec2e4512f30f5bd8abb74 | ec7f361fdbe5f16117a264af0012e2d2eccc07ae | refs/heads/master | 2020-06-15T17:05:36.709000 | 2020-01-23T04:06:39 | 2020-01-23T04:06:39 | 195,348,768 | 6 | 1 | null | false | 2020-01-23T04:06:40 | 2019-07-05T06:09:07 | 2020-01-23T04:03:10 | 2020-01-23T04:06:39 | 6,905 | 1 | 0 | 0 | Java | false | false | package com.webapp.timeline.sns.domain;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class ConverterShowLevel implements AttributeConverter<String, Integer> {
@Override
public Integer convertToDatabaseColumn(String showLevel) {
if("public".equals(showLevel))
return 1;
else if("followers".equals(showLevel))
return 2;
else if("private".equals(showLevel))
return 3;
else
return 0;
}
@Override
public String convertToEntityAttribute(Integer code) {
if(1 == code)
return "public";
else if(2 == code)
return "followers";
else if(3 == code)
return "private";
else
return "cannot return your show level.";
}
}
| UTF-8 | Java | 882 | java | ConverterShowLevel.java | Java | []
| null | []
| package com.webapp.timeline.sns.domain;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class ConverterShowLevel implements AttributeConverter<String, Integer> {
@Override
public Integer convertToDatabaseColumn(String showLevel) {
if("public".equals(showLevel))
return 1;
else if("followers".equals(showLevel))
return 2;
else if("private".equals(showLevel))
return 3;
else
return 0;
}
@Override
public String convertToEntityAttribute(Integer code) {
if(1 == code)
return "public";
else if(2 == code)
return "followers";
else if(3 == code)
return "private";
else
return "cannot return your show level.";
}
}
| 882 | 0.582766 | 0.57483 | 32 | 25.4375 | 19.924761 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 10 |
afc0088fc81bc5d51b0077b181562a0965704e0d | 17,282,948,452,232 | 9a9291564079174d7d44a80c592a87ecf76ba6f4 | /一些测试和临时/junit/auto_aubstract/TestNLPIRFindKeyWord.java | 3d021705f1633906ada5920bf0afc669f2cb3b7b | []
| no_license | wangchunxiao/java | https://github.com/wangchunxiao/java | 72e8dd988efda21754511ecd6ea443d19db7b908 | acfd2570f26b0a261b7c6230fa00b95cb770754a | refs/heads/master | 2020-12-25T11:52:05.012000 | 2014-01-13T05:24:36 | 2014-01-13T05:24:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package auto_aubstract;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import kevin.zhang.NLPIR;
import org.junit.Test;
public class TestNLPIRFindKeyWord
{
@Test
public void test() throws IOException
{
String sInput="而“李毅吧”亦有“百度贴吧卢浮宫”之称,因为很多在网络流传甚广的内涵文都出自“李毅吧”,包括那篇红极一时的《李毅大帝本纪》。而这一次,“屌丝”爆红网络,则是又一次体现出“李毅吧”对网络文化的影响。"+
"丑穷无能但善良:“屌丝”代表了最广大年轻人的面貌";
NLPIR testNLPIR = new NLPIR();
String argu = "";
if (testNLPIR.NLPIR_Init(argu.getBytes("GB2312"), 1) == false)
{
System.out.println("Init Fail!");
return;
}
byte nativeBytes[] = testNLPIR.NLPIR_ParagraphProcess(sInput.getBytes("GB2312"), 0);
String nativeStr = new String(nativeBytes, 0, nativeBytes.length, "utf-8");
System.out.println("分词结果为: " + nativeStr);
/*
OutputStream out=new BufferedOutputStream(new FileOutputStream(new File("text.TXT")));
out.write(sInput.getBytes());
out.close();
*/
/*
Writer out=new BufferedWriter(new FileWriter(new File("text.TXT")));
out.write(sInput);
out.close();
*/
//初始化分词组件
String argu1 = "摘要test2.txt";
nativeBytes =testNLPIR.NLPIR_GetFileKeyWords(argu1.getBytes("GB2312"),10,true);
//如果是处理内存,可以调用testNLPIR.NLPIR_GetKeyWords
nativeStr = new String(nativeBytes, 0, nativeBytes.length, "utf-8");
System.out.println("关键词识别结果为: " + nativeStr);
System.out.println("--------------------------------------------------------");
Pattern pattern=Pattern.compile("([^/\\s]+)/(\\d+\\.\\d+)");
Matcher matcher=pattern.matcher(nativeStr);
while(matcher.find())
{
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println("-----");
}
/*测试空的set的size方法返回的是否为0
Set<String> set=new TreeSet<String>();
System.out.println(set.size());
*/
}
}
| GB18030 | Java | 2,332 | java | TestNLPIRFindKeyWord.java | Java | []
| null | []
| package auto_aubstract;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import kevin.zhang.NLPIR;
import org.junit.Test;
public class TestNLPIRFindKeyWord
{
@Test
public void test() throws IOException
{
String sInput="而“李毅吧”亦有“百度贴吧卢浮宫”之称,因为很多在网络流传甚广的内涵文都出自“李毅吧”,包括那篇红极一时的《李毅大帝本纪》。而这一次,“屌丝”爆红网络,则是又一次体现出“李毅吧”对网络文化的影响。"+
"丑穷无能但善良:“屌丝”代表了最广大年轻人的面貌";
NLPIR testNLPIR = new NLPIR();
String argu = "";
if (testNLPIR.NLPIR_Init(argu.getBytes("GB2312"), 1) == false)
{
System.out.println("Init Fail!");
return;
}
byte nativeBytes[] = testNLPIR.NLPIR_ParagraphProcess(sInput.getBytes("GB2312"), 0);
String nativeStr = new String(nativeBytes, 0, nativeBytes.length, "utf-8");
System.out.println("分词结果为: " + nativeStr);
/*
OutputStream out=new BufferedOutputStream(new FileOutputStream(new File("text.TXT")));
out.write(sInput.getBytes());
out.close();
*/
/*
Writer out=new BufferedWriter(new FileWriter(new File("text.TXT")));
out.write(sInput);
out.close();
*/
//初始化分词组件
String argu1 = "摘要test2.txt";
nativeBytes =testNLPIR.NLPIR_GetFileKeyWords(argu1.getBytes("GB2312"),10,true);
//如果是处理内存,可以调用testNLPIR.NLPIR_GetKeyWords
nativeStr = new String(nativeBytes, 0, nativeBytes.length, "utf-8");
System.out.println("关键词识别结果为: " + nativeStr);
System.out.println("--------------------------------------------------------");
Pattern pattern=Pattern.compile("([^/\\s]+)/(\\d+\\.\\d+)");
Matcher matcher=pattern.matcher(nativeStr);
while(matcher.find())
{
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println("-----");
}
/*测试空的set的size方法返回的是否为0
Set<String> set=new TreeSet<String>();
System.out.println(set.size());
*/
}
}
| 2,332 | 0.640201 | 0.626633 | 75 | 24.4 | 26.628807 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.053333 | false | false | 10 |
03ec9b33881544eecaa99b01497cd129a52b5186 | 4,303,557,245,407 | 0bb6653c75e3282da4f8a04b93b114c572d6184f | /src/main/java/finished/others/finished/no151/Solution.java | 8e274c37bc60247fd6bd75149e0cf6693aa865c7 | [
"Apache-2.0"
]
| permissive | fortbox/leetcode-solve | https://github.com/fortbox/leetcode-solve | 34a55a685da11ebd89dc61509f3ce4630fbaccc0 | 9a48fe48504a0250b2607432b0b84da2c528b767 | refs/heads/master | 2021-06-16T05:27:17.812000 | 2021-03-20T03:15:48 | 2021-03-20T03:15:48 | 142,773,970 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright(c) 2020-2020
* Author: xiaoweixiang
*/
package finished.others.finished.no151;
import java.util.Arrays;
class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
String s = " hello world! ";
String ans = solution.reverseWords(s);
System.out.println("ans = " + ans);
}
public String reverseWords(String s) {
s = s.trim();
// 正则表达式
String[] array = s.split("\\s+");
System.out.println("Arrays.toString(array) = " + Arrays.toString(array));
StringBuilder builder = new StringBuilder();
for (int i = array.length - 1; i >= 0; i--) {
if (array[i] != null && !"".equals(array[i])) {
builder.append(array[i]);
if (i > 0) builder.append(" ");
}
}
return builder.toString();
}
} | UTF-8 | Java | 907 | java | Solution.java | Java | [
{
"context": "/*\n * Copyright(c) 2020-2020\n * Author: xiaoweixiang\n */\n\npackage finished.others.finished.no151;\n\nimp",
"end": 52,
"score": 0.9372215270996094,
"start": 40,
"tag": "USERNAME",
"value": "xiaoweixiang"
}
]
| null | []
| /*
* Copyright(c) 2020-2020
* Author: xiaoweixiang
*/
package finished.others.finished.no151;
import java.util.Arrays;
class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
String s = " hello world! ";
String ans = solution.reverseWords(s);
System.out.println("ans = " + ans);
}
public String reverseWords(String s) {
s = s.trim();
// 正则表达式
String[] array = s.split("\\s+");
System.out.println("Arrays.toString(array) = " + Arrays.toString(array));
StringBuilder builder = new StringBuilder();
for (int i = array.length - 1; i >= 0; i--) {
if (array[i] != null && !"".equals(array[i])) {
builder.append(array[i]);
if (i > 0) builder.append(" ");
}
}
return builder.toString();
}
} | 907 | 0.537347 | 0.521739 | 32 | 27.0625 | 21.155581 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46875 | false | false | 10 |
a58d588c7899507269291c1a2cc1ab9fd328ee9f | 22,084,721,905,214 | 9b2964fcf451f16fb0c73b2855dbdc41455c235c | /src/main/java/com/scbastos/model/Valor.java | 2dd4599a8aaf2626b1b06f2facd936080dfeddeb | []
| no_license | gomesdoug/scbastosweb | https://github.com/gomesdoug/scbastosweb | a1625675aea0394e070ec684b1232ae10237a546 | cebf55c8952bb9e529fb7d3e591621e75caf8908 | refs/heads/master | 2021-03-24T11:02:07.904000 | 2017-09-17T17:46:31 | 2017-09-17T17:46:31 | 103,822,871 | 0 | 0 | null | true | 2017-09-17T11:12:52 | 2017-09-17T11:12:52 | 2017-09-17T11:12:43 | 2017-09-17T07:24:05 | 1,121 | 0 | 0 | 0 | null | null | null | package com.scbastos.model;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import com.scbastos.model.Enumerators.EnumImovelQuitado;
import com.scbastos.validation.Nome;
@Entity
public class Valor implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codigo;
@NotNull(message = "Por favor, especifique o valor do imóvel")
@DecimalMin(value="0.00", message = "O valor do imóvel deve ser positivo")
@Column(name ="valor_atual")
private BigDecimal valorAtual;
@DecimalMin(value="0.00", message = "O valor do sinal deve ser positivo")
private BigDecimal sinal;
@Min(value = 0, message="O prazo de financiamento deve ser um valor positivo")
@Column(name = "prazo_financiamento")
private int prazoFinanciamento;
@DecimalMin(value="0.00", message = "O saldo devedor deve ser positivo")
@Column(name = "saldo_devedor")
private BigDecimal saldoDevedor;
@Nome
@Column(name ="org_financeira")
private String OrgFinanceira;
@NotNull(message = "Por favor, especifique a se o imóvel está quitado ou não")
@Enumerated(EnumType.STRING)
private EnumImovelQuitado quitado;
// GETTERS AND SETTERS
public Long getIdValor() {
return codigo;
}
public void setIdValor(Long idValor) {
this.codigo = idValor;
}
public BigDecimal getValorImovel() {
return valorAtual;
}
public void setValorImovel(BigDecimal valorImovel) {
this.valorAtual = valorImovel;
}
public BigDecimal getSinal() {
return sinal;
}
public void setSinal(BigDecimal sinal) {
this.sinal = sinal;
}
public int getPrazoFinanciamento() {
return prazoFinanciamento;
}
public void setPrazoFinanciamento(int prazoFinanciamento) {
this.prazoFinanciamento = prazoFinanciamento;
}
public BigDecimal getSaldoDevedor() {
return saldoDevedor;
}
public void setSaldoDevedor(BigDecimal saldoDevedor) {
this.saldoDevedor = saldoDevedor;
//(valorImovel.subtract(sinal));
}
public String getOrgFinanceira() {
return OrgFinanceira;
}
public void setOrgFinanceira(String orgFinanceira) {
OrgFinanceira = orgFinanceira;
}
public EnumImovelQuitado getQuitado() {
return quitado;
}
public void setQuitado(EnumImovelQuitado quitado) {
this.quitado = quitado;
}
//HASHCODE AND EQUALS
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigo == null) ? 0 : codigo.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;
Valor other = (Valor) obj;
if (codigo == null) {
if (other.codigo != null)
return false;
} else if (!codigo.equals(other.codigo))
return false;
return true;
}
}
| UTF-8 | Java | 3,256 | java | Valor.java | Java | []
| null | []
| package com.scbastos.model;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import com.scbastos.model.Enumerators.EnumImovelQuitado;
import com.scbastos.validation.Nome;
@Entity
public class Valor implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codigo;
@NotNull(message = "Por favor, especifique o valor do imóvel")
@DecimalMin(value="0.00", message = "O valor do imóvel deve ser positivo")
@Column(name ="valor_atual")
private BigDecimal valorAtual;
@DecimalMin(value="0.00", message = "O valor do sinal deve ser positivo")
private BigDecimal sinal;
@Min(value = 0, message="O prazo de financiamento deve ser um valor positivo")
@Column(name = "prazo_financiamento")
private int prazoFinanciamento;
@DecimalMin(value="0.00", message = "O saldo devedor deve ser positivo")
@Column(name = "saldo_devedor")
private BigDecimal saldoDevedor;
@Nome
@Column(name ="org_financeira")
private String OrgFinanceira;
@NotNull(message = "Por favor, especifique a se o imóvel está quitado ou não")
@Enumerated(EnumType.STRING)
private EnumImovelQuitado quitado;
// GETTERS AND SETTERS
public Long getIdValor() {
return codigo;
}
public void setIdValor(Long idValor) {
this.codigo = idValor;
}
public BigDecimal getValorImovel() {
return valorAtual;
}
public void setValorImovel(BigDecimal valorImovel) {
this.valorAtual = valorImovel;
}
public BigDecimal getSinal() {
return sinal;
}
public void setSinal(BigDecimal sinal) {
this.sinal = sinal;
}
public int getPrazoFinanciamento() {
return prazoFinanciamento;
}
public void setPrazoFinanciamento(int prazoFinanciamento) {
this.prazoFinanciamento = prazoFinanciamento;
}
public BigDecimal getSaldoDevedor() {
return saldoDevedor;
}
public void setSaldoDevedor(BigDecimal saldoDevedor) {
this.saldoDevedor = saldoDevedor;
//(valorImovel.subtract(sinal));
}
public String getOrgFinanceira() {
return OrgFinanceira;
}
public void setOrgFinanceira(String orgFinanceira) {
OrgFinanceira = orgFinanceira;
}
public EnumImovelQuitado getQuitado() {
return quitado;
}
public void setQuitado(EnumImovelQuitado quitado) {
this.quitado = quitado;
}
//HASHCODE AND EQUALS
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigo == null) ? 0 : codigo.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;
Valor other = (Valor) obj;
if (codigo == null) {
if (other.codigo != null)
return false;
} else if (!codigo.equals(other.codigo))
return false;
return true;
}
}
| 3,256 | 0.734851 | 0.730237 | 148 | 20.966217 | 20.488434 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.391892 | false | false | 10 |
64d31b55eafbdf61b64551d1c6ba8ec9ce547d2b | 8,435,315,802,316 | 937ac2cf70b59da8f5eb77511224fcdcc2f01d77 | /micro-iot-gateway/src/main/java/com/solitardj9/microiot/serviceInterface/authManagerInterface/controller/AuthManagerController.java | 245f83fb14d7186c3f73ad57f43fd70ed8b125ba | [
"Apache-2.0"
]
| permissive | solitardj9/micro-iot-service | https://github.com/solitardj9/micro-iot-service | f6daa40176c01569ccdd80d1698f3c496baeb2d9 | ddf590b0efbf0c2997620c18be39f0f8921ae508 | refs/heads/master | 2023-01-08T02:33:03.270000 | 2020-10-30T02:31:50 | 2020-10-30T02:31:50 | 287,705,501 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.solitardj9.microiot.serviceInterface.authManagerInterface.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solitardj9.microiot.serviceInterface.authManagerInterface.model.request.RequestCreateCertificate;
import com.solitardj9.microiot.serviceInterface.common.model.ResponseDefualt;
@RestController
@RequestMapping(value="/gateway")
public class AuthManagerController {
private static final Logger logger = LoggerFactory.getLogger(AuthManagerController.class);
//@Autowired
//AuthManager authManager;
private ObjectMapper om = new ObjectMapper();
/**
* @param requestBody
* {
* "clientId" : "{clientId}",
* "certificateSigningRequest" : "{csr}"
* }
* @return
* {
* "certificateId" : "{certificateId}",
* "certificatePem" : "{certificatePem}"
* }
*/
@SuppressWarnings("rawtypes")
@PostMapping(value="/certificates")
public ResponseEntity createCertificate(@RequestBody(required=true) String requestBody) {
//
logger.info("[AuthManagerController].createCertificate is called.");
try {
RequestCreateCertificate request = om.readValue(requestBody, RequestCreateCertificate.class);
return new ResponseEntity<>(HttpStatus.OK);
} catch (JsonProcessingException e) {
logger.error("[ServiceManagerController].createCertificate : error = " + e);
return new ResponseEntity<>(new ResponseDefualt(HttpStatus.BAD_REQUEST.value(), e.toString()), HttpStatus.BAD_REQUEST);
}
}
// @SuppressWarnings({ "unchecked", "rawtypes" })
// @PostMapping("/certificates")
// public ResponseEntity createCertificateFromCsr (@RequestParam(value = "setAsActive", required=false) Boolean setAsActive,
// @RequestBody Map<String, String> csrMap) {
// ResponseCert deviceCertObj = null;
// String csr = csrMap.get("certificateSigningRequest");
// if (csr == null || csr.equals("")) {
// return new ResponseEntity(StatusCode.Invalid_Request , HttpStatus.BAD_REQUEST);
// }
// DeviceCertificate cert = null;
//
// try {
// cert = certManager.createDeviceCertificate(csr);
// } catch (InvalidRequestException ire) {
// return new ResponseEntity(StatusCode.Invalid_Request , HttpStatus.BAD_REQUEST);
// } catch (Exception e) {
// return new ResponseEntity(StatusCode.Invalid_Request.getMessage() , HttpStatus.INTERNAL_SERVER_ERROR);
// }
//
// if (cert == null)
// return new ResponseEntity(StatusCode.Internal_Failure.getMapMessage() , HttpStatus.INTERNAL_SERVER_ERROR);
// // 매핑
// deviceCertObj = new ResponseCert(cert.getArn(), cert.getId().toString(), cert.getPem());
//
// return new ResponseEntity(deviceCertObj , HttpStatus.OK);
// }
} | UTF-8 | Java | 3,144 | java | AuthManagerController.java | Java | []
| null | []
| package com.solitardj9.microiot.serviceInterface.authManagerInterface.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solitardj9.microiot.serviceInterface.authManagerInterface.model.request.RequestCreateCertificate;
import com.solitardj9.microiot.serviceInterface.common.model.ResponseDefualt;
@RestController
@RequestMapping(value="/gateway")
public class AuthManagerController {
private static final Logger logger = LoggerFactory.getLogger(AuthManagerController.class);
//@Autowired
//AuthManager authManager;
private ObjectMapper om = new ObjectMapper();
/**
* @param requestBody
* {
* "clientId" : "{clientId}",
* "certificateSigningRequest" : "{csr}"
* }
* @return
* {
* "certificateId" : "{certificateId}",
* "certificatePem" : "{certificatePem}"
* }
*/
@SuppressWarnings("rawtypes")
@PostMapping(value="/certificates")
public ResponseEntity createCertificate(@RequestBody(required=true) String requestBody) {
//
logger.info("[AuthManagerController].createCertificate is called.");
try {
RequestCreateCertificate request = om.readValue(requestBody, RequestCreateCertificate.class);
return new ResponseEntity<>(HttpStatus.OK);
} catch (JsonProcessingException e) {
logger.error("[ServiceManagerController].createCertificate : error = " + e);
return new ResponseEntity<>(new ResponseDefualt(HttpStatus.BAD_REQUEST.value(), e.toString()), HttpStatus.BAD_REQUEST);
}
}
// @SuppressWarnings({ "unchecked", "rawtypes" })
// @PostMapping("/certificates")
// public ResponseEntity createCertificateFromCsr (@RequestParam(value = "setAsActive", required=false) Boolean setAsActive,
// @RequestBody Map<String, String> csrMap) {
// ResponseCert deviceCertObj = null;
// String csr = csrMap.get("certificateSigningRequest");
// if (csr == null || csr.equals("")) {
// return new ResponseEntity(StatusCode.Invalid_Request , HttpStatus.BAD_REQUEST);
// }
// DeviceCertificate cert = null;
//
// try {
// cert = certManager.createDeviceCertificate(csr);
// } catch (InvalidRequestException ire) {
// return new ResponseEntity(StatusCode.Invalid_Request , HttpStatus.BAD_REQUEST);
// } catch (Exception e) {
// return new ResponseEntity(StatusCode.Invalid_Request.getMessage() , HttpStatus.INTERNAL_SERVER_ERROR);
// }
//
// if (cert == null)
// return new ResponseEntity(StatusCode.Internal_Failure.getMapMessage() , HttpStatus.INTERNAL_SERVER_ERROR);
// // 매핑
// deviceCertObj = new ResponseCert(cert.getArn(), cert.getId().toString(), cert.getPem());
//
// return new ResponseEntity(deviceCertObj , HttpStatus.OK);
// }
} | 3,144 | 0.743631 | 0.742038 | 90 | 33.900002 | 33.878231 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.988889 | false | false | 10 |
ffcc44cabceb5fe7443b9bad5d3ac6987c9a67bc | 24,498,493,498,649 | 04f503868d44a1083cda0b03c90260b2f480c65c | /app/src/main/java/bean/MeCallBean.java | 55626316649e56e61e823ce2ae0504019e1b317c | []
| no_license | Helen403/HelenTT | https://github.com/Helen403/HelenTT | af1609dcdae1c0a7d3d126f0f3946ca66cee2cbb | 7e1e457e9f9b6029698873a4177fbde3243bb6e7 | refs/heads/master | 2021-01-25T06:30:39.661000 | 2017-06-07T03:24:28 | 2017-06-07T03:24:28 | 93,588,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bean;
/**
* Created by Helen on 2017/5/23.
*/
public class MeCallBean {
}
| UTF-8 | Java | 85 | java | MeCallBean.java | Java | [
{
"context": "package bean;\n\n/**\n * Created by Helen on 2017/5/23.\n */\npublic class MeCallBean {\n}\n",
"end": 38,
"score": 0.9957213401794434,
"start": 33,
"tag": "NAME",
"value": "Helen"
}
]
| null | []
| package bean;
/**
* Created by Helen on 2017/5/23.
*/
public class MeCallBean {
}
| 85 | 0.647059 | 0.564706 | 7 | 11.142858 | 12.147058 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 10 |
b1a1e70e31f99d6444358a6926ca364b6667c3db | 31,774,168,102,383 | 7dd73504d783c7ebb0c2e51fa98dea2b25c37a11 | /eaglercraftx-1.8-main/patches/minecraft/net/minecraft/util/BlockPos.edit.java | 46a7ca84a4eaa1d820cdd67d48c1c9096d344811 | [
"LicenseRef-scancode-proprietary-license"
]
| permissive | bagel-man/bagel-man.github.io | https://github.com/bagel-man/bagel-man.github.io | 32813dd7ef0b95045f53718a74ae1319dae8c31e | eaccb6c00aa89c449c56a842052b4e24f15a8869 | refs/heads/master | 2023-04-05T10:27:26.743000 | 2023-03-16T04:24:32 | 2023-03-16T04:24:32 | 220,102,442 | 3 | 21 | MIT | false | 2022-12-14T18:44:43 | 2019-11-06T22:29:24 | 2022-12-13T16:33:24 | 2022-12-13T00:31:17 | 1,085,729 | 6 | 10 | 1 | C++ | false | false |
# Eagler Context Redacted Diff
# Copyright (c) 2022 lax1dude. All rights reserved.
# Version: 1.0
# Author: lax1dude
> DELETE 2 @ 2 : 3
> INSERT 1 : 4 @ 1
+
+ import com.google.common.collect.AbstractIterator;
+
> DELETE 1 @ 1 : 5
> INSERT 103 : 120 @ 103
+ public BlockPos offsetFaster(EnumFacing facing, MutableBlockPos ret) {
+ ret.x = this.getX() + facing.getFrontOffsetX();
+ ret.y = this.getY() + facing.getFrontOffsetY();
+ ret.z = this.getZ() + facing.getFrontOffsetZ();
+ return ret;
+ }
+
+ /**
+ * only use with a regular "net.minecraft.util.BlockPos"!
+ */
+ public BlockPos offsetEvenFaster(EnumFacing facing, MutableBlockPos ret) {
+ ret.x = this.x + facing.getFrontOffsetX();
+ ret.y = this.y + facing.getFrontOffsetY();
+ ret.z = this.z + facing.getFrontOffsetZ();
+ return ret;
+ }
+
> DELETE 108 @ 108 : 111
> CHANGE 6 : 7 @ 6 : 10
~ super(x_, y_, z_);
> EOF
| UTF-8 | Java | 939 | java | BlockPos.edit.java | Java | [
{
"context": " Eagler Context Redacted Diff\n# Copyright (c) 2022 lax1dude. All rights reserved.\n\n# Version: 1.0\n# Author: l",
"end": 61,
"score": 0.9994910359382629,
"start": 53,
"tag": "USERNAME",
"value": "lax1dude"
},
{
"context": "de. All rights reserved.\n\n# Version: 1.0\n# Author: lax1dude\n\n> DELETE 2 @ 2 : 3\n\n> INSERT 1 : 4 @ 1\n\n+ ",
"end": 118,
"score": 0.9995321035385132,
"start": 110,
"tag": "USERNAME",
"value": "lax1dude"
}
]
| null | []
|
# Eagler Context Redacted Diff
# Copyright (c) 2022 lax1dude. All rights reserved.
# Version: 1.0
# Author: lax1dude
> DELETE 2 @ 2 : 3
> INSERT 1 : 4 @ 1
+
+ import com.google.common.collect.AbstractIterator;
+
> DELETE 1 @ 1 : 5
> INSERT 103 : 120 @ 103
+ public BlockPos offsetFaster(EnumFacing facing, MutableBlockPos ret) {
+ ret.x = this.getX() + facing.getFrontOffsetX();
+ ret.y = this.getY() + facing.getFrontOffsetY();
+ ret.z = this.getZ() + facing.getFrontOffsetZ();
+ return ret;
+ }
+
+ /**
+ * only use with a regular "net.minecraft.util.BlockPos"!
+ */
+ public BlockPos offsetEvenFaster(EnumFacing facing, MutableBlockPos ret) {
+ ret.x = this.x + facing.getFrontOffsetX();
+ ret.y = this.y + facing.getFrontOffsetY();
+ ret.z = this.z + facing.getFrontOffsetZ();
+ return ret;
+ }
+
> DELETE 108 @ 108 : 111
> CHANGE 6 : 7 @ 6 : 10
~ super(x_, y_, z_);
> EOF
| 939 | 0.621938 | 0.57934 | 43 | 20.813953 | 22.457458 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.930233 | false | false | 10 |
7d17fe1bb5a137da556e65a123e3f9a4799c21f9 | 12,206,297,075,389 | 8419de079beb9e72aae6ceed9e0a2769bc682925 | /springcloud-gateway/springcloud-consumer-b-with-ribbon/src/main/java/cn/itcast/zt/web/ConsumerWithRibbonController.java | 57901493a3e2103b40a662499b16b6574cd7f799 | []
| no_license | Erik-Yim/spring_cloud_demo | https://github.com/Erik-Yim/spring_cloud_demo | b4e5e3c018735f1c4fb9ae8567705456145779f8 | 192e4a0565d770592fd18c9f48fbe776025644bf | refs/heads/master | 2021-01-19T12:33:52.887000 | 2017-05-16T09:05:14 | 2017-05-16T09:05:14 | 88,035,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.itcast.zt.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Erik_Yim on 2017/5/12.
*/
@RestController
public class ConsumerWithRibbonController {
@Autowired
private ConsumerBRibbonService consumerBRibbonService;
//zuul 可以继承Feign 和Ribbon用,因为我再zuul中写了filter需要再http中获取accessToken但是feign不好传这个参数所以就有问题,去掉filter就可以了
//但是用ribbon就可以,直接在url中后面拼接accessToken参数
@RequestMapping("/consumerb")
public String consumerb(Integer a, Integer b) {
// return "ff";
return consumerBRibbonService.consumerB(a, b);
}
}
| UTF-8 | Java | 835 | java | ConsumerWithRibbonController.java | Java | [
{
"context": "bind.annotation.RestController;\n\n/**\n * Created by Erik_Yim on 2017/5/12.\n */\n@RestController\npublic class Co",
"end": 243,
"score": 0.9085091352462769,
"start": 235,
"tag": "USERNAME",
"value": "Erik_Yim"
}
]
| null | []
| package cn.itcast.zt.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Erik_Yim on 2017/5/12.
*/
@RestController
public class ConsumerWithRibbonController {
@Autowired
private ConsumerBRibbonService consumerBRibbonService;
//zuul 可以继承Feign 和Ribbon用,因为我再zuul中写了filter需要再http中获取accessToken但是feign不好传这个参数所以就有问题,去掉filter就可以了
//但是用ribbon就可以,直接在url中后面拼接accessToken参数
@RequestMapping("/consumerb")
public String consumerb(Integer a, Integer b) {
// return "ff";
return consumerBRibbonService.consumerB(a, b);
}
}
| 835 | 0.776848 | 0.767085 | 24 | 28.875 | 27.583679 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 10 |
4348582ec3c7f3f6cabbd8afd594beb2aa1cce1e | 12,206,297,074,352 | 79348691db2ab69da1bc9e1e106534d85c86f206 | /Fragment2/src/com/example/fragment2/FragAdapter.java | ac30e6cac16babc0eec331c92d8be7dae371c506 | []
| no_license | zoeas/Tab | https://github.com/zoeas/Tab | 7069acc7623b8a1ea7e9406bb3553f0eb770fd1a | 088370b862df2e1223b95a846e62534fc0cd2b98 | refs/heads/master | 2021-01-10T20:56:59.908000 | 2013-10-18T06:45:40 | 2013-10-18T06:45:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.fragment2;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
public class FragAdapter extends FragmentPagerAdapter{
ArrayList<Fragment> fragmentList;
public FragAdapter(FragmentManager fm, ArrayList<Fragment> fragmentList) {
super(fm);
this.fragmentList = fragmentList;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
@Override
public Fragment getItem(int postion) {
return fragmentList.get(postion);
}
@Override
public int getCount() {
return fragmentList.size();
}
}
| UTF-8 | Java | 799 | java | FragAdapter.java | Java | []
| null | []
| package com.example.fragment2;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
public class FragAdapter extends FragmentPagerAdapter{
ArrayList<Fragment> fragmentList;
public FragAdapter(FragmentManager fm, ArrayList<Fragment> fragmentList) {
super(fm);
this.fragmentList = fragmentList;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
@Override
public Fragment getItem(int postion) {
return fragmentList.get(postion);
}
@Override
public int getCount() {
return fragmentList.size();
}
}
| 799 | 0.740926 | 0.73592 | 36 | 20.194445 | 22.243376 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 10 |
1cf6da5954c7c9b74dcf64291e6c2430cca4d483 | 25,984,552,157,476 | 8749990450a14c5f9c6f8bd77275509718e046b1 | /src/main/java/org/codehaus/plexus/components/io/filemappers/FileExtensionMapper.java | 14e0a4c95fa19b58a8d675607319a3e88eeaa164 | [
"Apache-2.0"
]
| permissive | codehaus-plexus/plexus-io | https://github.com/codehaus-plexus/plexus-io | 5c31b90add6789a20f6a23ca559468bfa73d7344 | f569e0aff96e038c9f54df241cb045a074831958 | refs/heads/master | 2023-08-25T15:37:09.378000 | 2023-08-03T11:37:03 | 2023-08-06T13:00:41 | 29,922,896 | 4 | 10 | null | false | 2023-08-06T13:00:42 | 2015-01-27T16:28:08 | 2023-04-01T13:33:59 | 2023-08-06T13:00:41 | 3,398 | 1 | 10 | 5 | Java | false | false | package org.codehaus.plexus.components.io.filemappers;
/*
* Copyright 2007 The Codehaus Foundation.
*
* 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.
*/
import javax.annotation.Nonnull;
import javax.inject.Named;
/**
* An implementation of {@link FileMapper}, which changes the files extension.
*/
@Named(FileExtensionMapper.ROLE_HINT)
public class FileExtensionMapper extends AbstractFileMapper {
/**
* The file extension mappers role-hint: "fileExtension".
*/
public static final String ROLE_HINT = "fileExtension";
private String targetExtension;
/**
* Sets the target files extension.
*
* @param pTargetExtension the target extensions
* @throws IllegalArgumentException
* The target extension is null or empty.
*/
public void setTargetExtension(String pTargetExtension) {
if (pTargetExtension == null) {
throw new IllegalArgumentException("The target extension is null.");
}
if (pTargetExtension.length() == 0) {
throw new IllegalArgumentException("The target extension is empty.");
}
if (pTargetExtension.charAt(0) == '.') {
targetExtension = pTargetExtension;
} else {
targetExtension = '.' + pTargetExtension;
}
}
/**
* Returns the target files extension.
* @return The target extension
*/
public String getTargetExtension() {
return targetExtension;
}
@Nonnull
public String getMappedFileName(@Nonnull String pName) {
final String ext = getTargetExtension();
if (ext == null) {
throw new IllegalStateException("The target extension has not been set.");
}
final String name = super.getMappedFileName(pName); // Check arguments
final int dirSep = Math.max(pName.lastIndexOf('/'), pName.lastIndexOf('\\'));
final int offset = pName.lastIndexOf('.');
if (offset <= dirSep) {
return name + ext;
} else {
return name.substring(0, offset) + ext;
}
}
}
| UTF-8 | Java | 2,608 | java | FileExtensionMapper.java | Java | []
| null | []
| package org.codehaus.plexus.components.io.filemappers;
/*
* Copyright 2007 The Codehaus Foundation.
*
* 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.
*/
import javax.annotation.Nonnull;
import javax.inject.Named;
/**
* An implementation of {@link FileMapper}, which changes the files extension.
*/
@Named(FileExtensionMapper.ROLE_HINT)
public class FileExtensionMapper extends AbstractFileMapper {
/**
* The file extension mappers role-hint: "fileExtension".
*/
public static final String ROLE_HINT = "fileExtension";
private String targetExtension;
/**
* Sets the target files extension.
*
* @param pTargetExtension the target extensions
* @throws IllegalArgumentException
* The target extension is null or empty.
*/
public void setTargetExtension(String pTargetExtension) {
if (pTargetExtension == null) {
throw new IllegalArgumentException("The target extension is null.");
}
if (pTargetExtension.length() == 0) {
throw new IllegalArgumentException("The target extension is empty.");
}
if (pTargetExtension.charAt(0) == '.') {
targetExtension = pTargetExtension;
} else {
targetExtension = '.' + pTargetExtension;
}
}
/**
* Returns the target files extension.
* @return The target extension
*/
public String getTargetExtension() {
return targetExtension;
}
@Nonnull
public String getMappedFileName(@Nonnull String pName) {
final String ext = getTargetExtension();
if (ext == null) {
throw new IllegalStateException("The target extension has not been set.");
}
final String name = super.getMappedFileName(pName); // Check arguments
final int dirSep = Math.max(pName.lastIndexOf('/'), pName.lastIndexOf('\\'));
final int offset = pName.lastIndexOf('.');
if (offset <= dirSep) {
return name + ext;
} else {
return name.substring(0, offset) + ext;
}
}
}
| 2,608 | 0.651457 | 0.647239 | 78 | 32.435898 | 26.798676 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.320513 | false | false | 10 |
d3fd06e202447f3cb04719aafeee997cf09f8c62 | 21,715,354,676,397 | d785cf70c80957f3bc8300a91bfa2da0876182c7 | /src/main/java/ai/aliz/gcpmeetup/insight/TableMakerServlet.java | ccb9eae764fa5fa122beae6a222b87a0e1651e96 | []
| no_license | aliz-ai/gcp-meetup-20200205 | https://github.com/aliz-ai/gcp-meetup-20200205 | e94c710cdb8d4e4e6de2fa2e599aaf315d3f42b4 | b3efba67c1cb928f14f81cbde0d5e6456ce50625 | refs/heads/master | 2023-06-23T18:35:34.696000 | 2021-04-01T07:08:46 | 2021-04-01T07:08:46 | 236,747,467 | 0 | 0 | null | false | 2023-06-14T22:29:36 | 2020-01-28T13:58:16 | 2021-04-01T07:08:49 | 2023-06-14T22:29:36 | 20 | 0 | 0 | 4 | Java | false | false | package ai.aliz.gcpmeetup.insight;
import javax.servlet.annotation.WebServlet;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.util.Utils;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryRequestInitializer;
import com.google.api.services.bigquery.BigqueryScopes;
import com.googlecode.objectify.insight.puller.InsightDataset;
import com.googlecode.objectify.insight.servlet.AbstractTableMakerServlet;
import lombok.SneakyThrows;
@WebServlet("private/tableMaker")
public class TableMakerServlet extends AbstractTableMakerServlet {
private static final long serialVersionUID = 1L;
static final InsightDataset insightDataset = new InsightDataset() {
@Override
public String projectId() {
return "gcp-meetup-20200205";
}
@Override
public String datasetId() {
return "insight";
}
};
@Override
protected InsightDataset insightDataset() {
return insightDataset;
}
@Override
protected Bigquery bigquery() {
return buildBigquery();
}
@SneakyThrows
protected static Bigquery buildBigquery() {
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = GoogleCredential.getApplicationDefault(new UrlFetchTransport(), jsonFactory);
credential = credential.createScoped(BigqueryScopes.all());
return new Bigquery.Builder(new UrlFetchTransport(), Utils.getDefaultJsonFactory(), credential)
.setApplicationName("gcp-meetup-20200205")
.setGoogleClientRequestInitializer(new BigqueryRequestInitializer()).build();
}
}
| UTF-8 | Java | 1,774 | java | TableMakerServlet.java | Java | []
| null | []
| package ai.aliz.gcpmeetup.insight;
import javax.servlet.annotation.WebServlet;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.util.Utils;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryRequestInitializer;
import com.google.api.services.bigquery.BigqueryScopes;
import com.googlecode.objectify.insight.puller.InsightDataset;
import com.googlecode.objectify.insight.servlet.AbstractTableMakerServlet;
import lombok.SneakyThrows;
@WebServlet("private/tableMaker")
public class TableMakerServlet extends AbstractTableMakerServlet {
private static final long serialVersionUID = 1L;
static final InsightDataset insightDataset = new InsightDataset() {
@Override
public String projectId() {
return "gcp-meetup-20200205";
}
@Override
public String datasetId() {
return "insight";
}
};
@Override
protected InsightDataset insightDataset() {
return insightDataset;
}
@Override
protected Bigquery bigquery() {
return buildBigquery();
}
@SneakyThrows
protected static Bigquery buildBigquery() {
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = GoogleCredential.getApplicationDefault(new UrlFetchTransport(), jsonFactory);
credential = credential.createScoped(BigqueryScopes.all());
return new Bigquery.Builder(new UrlFetchTransport(), Utils.getDefaultJsonFactory(), credential)
.setApplicationName("gcp-meetup-20200205")
.setGoogleClientRequestInitializer(new BigqueryRequestInitializer()).build();
}
}
| 1,774 | 0.803269 | 0.792559 | 55 | 31.254545 | 28.904997 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.381818 | false | false | 10 |
cd3f2a2089dd96720ff7725020db227a95360740 | 5,592,047,454,292 | 8879a3b4430a110c60ae1077ee8364ec2580f8c6 | /PrefixMe/src/main/java/net/shoal/parrot/prefixme/Command.java | 2127efc67ab4cb6188369a7a65bf5b59fbd799d9 | []
| no_license | Polar-Pumpkin/Shoal | https://github.com/Polar-Pumpkin/Shoal | d9f3439590752260d81ec77bd257cee4b393a373 | ead43b1298df7cc3fdd68a24c9ae1eb55fdbdb8a | refs/heads/master | 2021-11-19T18:32:20.842000 | 2021-08-17T15:18:10 | 2021-08-17T15:18:10 | 201,374,198 | 12 | 3 | null | false | 2021-09-20T08:53:40 | 2019-08-09T02:33:37 | 2021-08-17T15:18:16 | 2021-09-20T08:52:53 | 383 | 8 | 1 | 2 | Java | false | false | package net.shoal.parrot.prefixme;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.shoal.parrot.prefixme.subcommand.GetCommand;
import net.shoal.parrot.prefixme.subcommand.SetCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.serverct.parrot.parrotx.command.CommandHandler;
import org.serverct.parrot.parrotx.command.PCommand;
import org.serverct.parrot.parrotx.command.subcommands.DebugCommand;
import org.serverct.parrot.parrotx.command.subcommands.HelpCommand;
import org.serverct.parrot.parrotx.command.subcommands.ReloadCommand;
import org.serverct.parrot.parrotx.command.subcommands.VersionCommand;
import org.serverct.parrot.parrotx.utils.JsonChatUtil;
import org.serverct.parrot.parrotx.utils.i18n.I18n;
public class Command extends CommandHandler {
public Command() {
super(PrefixMe.getInst(), "prefixme");
register(new GetCommand());
register(new SetCommand());
register(new DebugCommand(plugin, "PrefixMe.command.debug"));
register(new ReloadCommand(plugin, "PrefixMe.command.reload"));
register(new VersionCommand(plugin));
register(new HelpCommand(plugin));
}
@Override
public boolean onCommand(@NotNull CommandSender sender, org.bukkit.command.@NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 0) {
sender.sendMessage(plugin.getLang().data.get(plugin.localeKey, "Message.Empty"));
// PCommand defCommand = commands.get((Objects.isNull(defaultCmd) ? "help" : defaultCmd));
// if (defCommand == null) {
// // plugin.lang.getHelp(plugin.localeKey).forEach(sender::sendMessage);
// formatHelp().forEach(sender::sendMessage);
// } else {
// boolean hasPerm = (defCommand.getPermission() == null || defCommand.getPermission().equals("")) || sender.hasPermission(defCommand.getPermission());
// if (hasPerm) {
// return defCommand.execute(sender, args);
// }
//
// String msg = plugin.getLang().data.warn("您没有权限这么做.");
// if (sender instanceof Player) {
// TextComponent text = JsonChatUtil.getFromLegacy(msg);
// text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(I18n.color("&7所需权限 ▶ &c" + defCommand.getPermission()))));
// ((Player) sender).spigot().sendMessage(text);
// } else sender.sendMessage(msg);
// }
return true;
}
PCommand pCommand = commands.get(args[0].toLowerCase());
if (pCommand == null) {
if (sender instanceof Player) {
if (!sender.hasPermission("PrefixMe.use")) {
sender.sendMessage(plugin.getLang().data.getInfo("Plugin.NoPerm"));
return true;
}
final StringBuilder builder = new StringBuilder();
for (String arg : args) {
builder.append(arg).append(" ");
}
final String content = builder.toString().trim();
if (content.length() <= 0) {
plugin.getLang().sender.error((Player) sender, "Message.Empty");
return true;
}
if (content.length() > Conf.limit) {
plugin.getLang().sender.error((Player) sender, "Message.Limit");
return true;
}
PrefixManager.getInst().set(((Player) sender).getUniqueId(), content);
sender.sendMessage(plugin.getLang().data.get(plugin.localeKey, "Message", "Set", content));
}
// sender.sendMessage(plugin.getLang().data.warn("未知命令, 请检查您的命令拼写是否正确."));
// plugin.getLang().log.error(I18n.EXECUTE, "子命令/" + args[0], sender.getName() + " 尝试执行未注册子命令");
return true;
}
boolean hasPerm = (pCommand.getPermission() == null || pCommand.getPermission().equals("")) || sender.hasPermission(pCommand.getPermission());
if (hasPerm) {
String[] newArg = new String[args.length - 1];
if (args.length >= 2) {
System.arraycopy(args, 1, newArg, 0, args.length - 1);
}
return pCommand.execute(sender, newArg);
}
String msg = plugin.getLang().data.warn("您没有权限这么做.");
if (sender instanceof Player) {
TextComponent text = JsonChatUtil.getFromLegacy(msg);
text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(I18n.color("&7所需权限 ▶ &c" + pCommand.getPermission()))));
((Player) sender).spigot().sendMessage(text);
} else sender.sendMessage(msg);
return true;
}
}
| UTF-8 | Java | 5,090 | java | Command.java | Java | []
| null | []
| package net.shoal.parrot.prefixme;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.shoal.parrot.prefixme.subcommand.GetCommand;
import net.shoal.parrot.prefixme.subcommand.SetCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.serverct.parrot.parrotx.command.CommandHandler;
import org.serverct.parrot.parrotx.command.PCommand;
import org.serverct.parrot.parrotx.command.subcommands.DebugCommand;
import org.serverct.parrot.parrotx.command.subcommands.HelpCommand;
import org.serverct.parrot.parrotx.command.subcommands.ReloadCommand;
import org.serverct.parrot.parrotx.command.subcommands.VersionCommand;
import org.serverct.parrot.parrotx.utils.JsonChatUtil;
import org.serverct.parrot.parrotx.utils.i18n.I18n;
public class Command extends CommandHandler {
public Command() {
super(PrefixMe.getInst(), "prefixme");
register(new GetCommand());
register(new SetCommand());
register(new DebugCommand(plugin, "PrefixMe.command.debug"));
register(new ReloadCommand(plugin, "PrefixMe.command.reload"));
register(new VersionCommand(plugin));
register(new HelpCommand(plugin));
}
@Override
public boolean onCommand(@NotNull CommandSender sender, org.bukkit.command.@NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 0) {
sender.sendMessage(plugin.getLang().data.get(plugin.localeKey, "Message.Empty"));
// PCommand defCommand = commands.get((Objects.isNull(defaultCmd) ? "help" : defaultCmd));
// if (defCommand == null) {
// // plugin.lang.getHelp(plugin.localeKey).forEach(sender::sendMessage);
// formatHelp().forEach(sender::sendMessage);
// } else {
// boolean hasPerm = (defCommand.getPermission() == null || defCommand.getPermission().equals("")) || sender.hasPermission(defCommand.getPermission());
// if (hasPerm) {
// return defCommand.execute(sender, args);
// }
//
// String msg = plugin.getLang().data.warn("您没有权限这么做.");
// if (sender instanceof Player) {
// TextComponent text = JsonChatUtil.getFromLegacy(msg);
// text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(I18n.color("&7所需权限 ▶ &c" + defCommand.getPermission()))));
// ((Player) sender).spigot().sendMessage(text);
// } else sender.sendMessage(msg);
// }
return true;
}
PCommand pCommand = commands.get(args[0].toLowerCase());
if (pCommand == null) {
if (sender instanceof Player) {
if (!sender.hasPermission("PrefixMe.use")) {
sender.sendMessage(plugin.getLang().data.getInfo("Plugin.NoPerm"));
return true;
}
final StringBuilder builder = new StringBuilder();
for (String arg : args) {
builder.append(arg).append(" ");
}
final String content = builder.toString().trim();
if (content.length() <= 0) {
plugin.getLang().sender.error((Player) sender, "Message.Empty");
return true;
}
if (content.length() > Conf.limit) {
plugin.getLang().sender.error((Player) sender, "Message.Limit");
return true;
}
PrefixManager.getInst().set(((Player) sender).getUniqueId(), content);
sender.sendMessage(plugin.getLang().data.get(plugin.localeKey, "Message", "Set", content));
}
// sender.sendMessage(plugin.getLang().data.warn("未知命令, 请检查您的命令拼写是否正确."));
// plugin.getLang().log.error(I18n.EXECUTE, "子命令/" + args[0], sender.getName() + " 尝试执行未注册子命令");
return true;
}
boolean hasPerm = (pCommand.getPermission() == null || pCommand.getPermission().equals("")) || sender.hasPermission(pCommand.getPermission());
if (hasPerm) {
String[] newArg = new String[args.length - 1];
if (args.length >= 2) {
System.arraycopy(args, 1, newArg, 0, args.length - 1);
}
return pCommand.execute(sender, newArg);
}
String msg = plugin.getLang().data.warn("您没有权限这么做.");
if (sender instanceof Player) {
TextComponent text = JsonChatUtil.getFromLegacy(msg);
text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(I18n.color("&7所需权限 ▶ &c" + pCommand.getPermission()))));
((Player) sender).spigot().sendMessage(text);
} else sender.sendMessage(msg);
return true;
}
}
| 5,090 | 0.611892 | 0.607272 | 101 | 48.287128 | 36.744053 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.910891 | false | false | 10 |
87a4a5912b9769f14f87ddf5110e99db003e957c | 23,124,103,943,217 | 3940afd2a03f29a5df4402c5031866e4a3df0431 | /app/src/main/java/so/library/draghelper/helper/view/PopupPanel.java | ddf3be6ee17eb8c41872ac6a546542d4d8b2d621 | [
"Apache-2.0"
]
| permissive | KoMinkyu/DragHelperView | https://github.com/KoMinkyu/DragHelperView | e36fd331a62a3bb8648dfd4005546189e94f5c99 | aea4c3a642f35a8ea4fdc246e8d57d343bbd3211 | refs/heads/master | 2021-01-21T19:40:23.290000 | 2015-06-17T02:15:43 | 2015-06-17T02:15:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package so.library.draghelper.helper.view;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.Log;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.graphics.drawable.GradientDrawable;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import so.library.draghelper.R;
import so.library.draghelper.helper.DragHelperViewCallback;
public class PopupPanel extends LinearLayout{
public enum State{
Closed,
Opened,
FullyOpened
}
public interface OnStateChangedListener{
void onStateChanged(State state);
}
private Context context;
OnStateChangedListener onStateChangedListener;
State state;
int contentOffsetY;
boolean isAnimating;
SmoothInterpolator smoothInterpolator = new SmoothInterpolator();
OvershootInterpolator overInterpolator = new OvershootInterpolator();
VelocityTracker velocityTracker;
GestureDetector paneGestureDetector;
State stateBeforeTracking;
boolean isTracking;
boolean preTracking;
int startY = -1;
float oldY;
int pagingTouchSlop;
int minFlingVelocity;
int maxFlingVelocity;
int idPaneHeaderView = 0;
GradientDrawable shadowDrawable;
View parentView;
private View headerView;
private View bodyView;
int deviceHeight;
int deviceWidth;
/**
* Relevant variables with ViewDragHelper
*/
private ViewDragHelper viewDragHelper;
private boolean layoutInitialized = false;
public PopupPanel(Context context){
super(context);
this.context = context;
this.initialize();
}
public PopupPanel(Context context, AttributeSet attrs){
super(context, attrs);
this.context = context;
this.initialize();
}
public PopupPanel(Context context, AttributeSet attrs, int defStyleAttr){
super(context, attrs, defStyleAttr);
this.context = context;
this.initialize();
}
public void setPaneHeaderViewId(int idPaneHeaderView){
this.idPaneHeaderView = idPaneHeaderView;
}
public void setParentView(View parentView){
this.parentView = parentView;
}
private int getPaneHeaderViewId(){
return this.idPaneHeaderView;
}
public void setChildViews(WebView headerView, View bodyView) {
this.headerView = headerView;
this.bodyView = bodyView;
}
private void initialize(){
state = State.FullyOpened;
ViewConfiguration config = ViewConfiguration.get(this.context);
this.pagingTouchSlop = config.getScaledPagingTouchSlop();
this.minFlingVelocity = config.getScaledMinimumFlingVelocity();
this.maxFlingVelocity = config.getScaledMaximumFlingVelocity();
final int baseShadowColor = 0;
int[] shadowColors = {
Color.argb(0x30, baseShadowColor, baseShadowColor, baseShadowColor),
Color.argb(0, baseShadowColor, baseShadowColor, baseShadowColor)
};
this.shadowDrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, shadowColors);
viewDragHelper = ViewDragHelper.create(this, 1.0f, new DragHelperViewCallback(this, headerView));
}
public boolean isOpened(){
return state == State.Opened || state == State.FullyOpened;
}
public boolean isFullyOpened(){
return state == State.FullyOpened;
}
public void setState(State newState, boolean animated){
Interpolator interpolator = state == State.Closed && newState == State.Opened ? overInterpolator : smoothInterpolator;
this.state = newState;
if (newState != State.Closed)
this.setVisibility(View.VISIBLE);
if (!animated){
setNewOffset(getOffsetForState(newState));
if (state == State.Closed)
this.setVisibility(View.INVISIBLE);
} else {
isAnimating = true;
int duration = Resources.getSystem().getInteger(android.R.integer.config_mediumAnimTime);
this.translationYAnimate(this, getOffsetForState(newState), duration, interpolator, new Runnable() {
@Override
public void run() {
isAnimating = false;
if (state == State.Closed)
setVisibility(View.INVISIBLE);
}
});
}
if (this.onStateChangedListener != null){
this.onStateChangedListener.onStateChanged(newState);
}
}
public void setOnStateChangedListener(OnStateChangedListener l){
this.onStateChangedListener = l;
}
private void setNewOffset(int newOffset){
if (state == State.Closed){
contentOffsetY = newOffset;
this.setTranslationY(contentOffsetY);
} else {
contentOffsetY = Math.min(Math.max( getOffsetForState(State.FullyOpened), newOffset),
getOffsetForState(State.Opened));
this.setTranslationY(contentOffsetY);
}
}
private int getOffsetForState(State state){
switch(state){
default:
case Closed:
return parentView.getBottom();
case FullyOpened:
return parentView.getBottom() - this.getHeight();
case Opened:
int idPaneHeaderView = this.getPaneHeaderViewId();
return parentView.getBottom() - findViewById(idPaneHeaderView).getHeight() - this.getPaddingTop();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e){
final int action = MotionEventCompat.getActionMasked(e);
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP){
return false;
}
boolean interceptTap = viewDragHelper.isViewUnder(headerView, (int) e.getX(), (int) e.getY());
return viewDragHelper.shouldInterceptTouchEvent(e) || interceptTap;
}
@Override
public boolean onTouchEvent(MotionEvent e){
if (paneGestureDetector == null){
DoubleTapListener l = new DoubleTapListener(new Runnable() {
@Override
public void run() {
setState(isOpened() && isFullyOpened() ? State.Opened : State.FullyOpened, true);
}
});
paneGestureDetector = new GestureDetector(this.context, l);
}
paneGestureDetector.onTouchEvent(e);
e.offsetLocation(0, this.getTranslationY());
if (e.getAction() == MotionEvent.ACTION_DOWN){
this.captureMovementCheck(e);
headerView.dispatchTouchEvent(e);
return true;
}
if (!isTracking && !captureMovementCheck(e)){
headerView.dispatchTouchEvent(e);
return true;
}
if (e.getAction() != MotionEvent.ACTION_MOVE || moveDirectionTest(e))
velocityTracker.addMovement(e);
if (e.getAction() == MotionEvent.ACTION_MOVE){
float y = e.getY();
if(state == State.Opened && y > startY || state == State.FullyOpened && y < startY)
return true;
if(state == State.Opened && y > oldY || state == State.FullyOpened && y < oldY)
velocityTracker.clear();
int traveledDistance = (int) Math.round(Math.abs(y - startY));
if (state == State.Opened)
traveledDistance = getOffsetForState(State.Opened) - traveledDistance;
setNewOffset(traveledDistance);
oldY = y;
} else if (e.getAction() == MotionEvent.ACTION_UP){
velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);
if (Math.abs(velocityTracker.getYVelocity()) > minFlingVelocity && Math.abs(velocityTracker.getYVelocity()) < maxFlingVelocity)
setState(state == State.FullyOpened ? State.Opened : State.FullyOpened, true);
else if (state == State.FullyOpened && contentOffsetY > this.getHeight() / 2)
setState(State.Opened, true);
else if (state == State.Opened && contentOffsetY < this.getHeight() / 2)
setState(State.FullyOpened, true);
else
setState(state, true);
preTracking = isTracking = false;
velocityTracker.clear();
velocityTracker.recycle();
}
return true;
}
private boolean captureMovementCheck(MotionEvent e){
if (e.getAction() == MotionEvent.ACTION_DOWN){
oldY = startY = (int)e.getY();
if(!isOpened())
return false;
velocityTracker = VelocityTracker.obtain();
velocityTracker.addMovement(e);
preTracking = true;
stateBeforeTracking = state;
return false;
}
if (e.getAction() == MotionEvent.ACTION_UP)
preTracking = isTracking = false;
if (!preTracking)
return false;
velocityTracker.addMovement(e);
if (e.getAction() == MotionEvent.ACTION_MOVE){
if(!this.moveDirectionTest(e)){
preTracking = false;
return false;
}
double distance = Math.abs(e.getY() - startY);
if (distance < pagingTouchSlop)
return false;
}
oldY = startY = (int) e.getY();
isTracking = true;
return true;
}
private boolean moveDirectionTest(MotionEvent e){
return (stateBeforeTracking == State.FullyOpened ? e.getY() >= startY : e.getY() <= startY);
}
private class SmoothInterpolator extends LinearInterpolator{
@Override
public float getInterpolation(float input){
return (float) Math.pow(input - 1, 5) + 1;
}
}
private class DoubleTapListener extends SimpleOnGestureListener{
Runnable callback;
public DoubleTapListener(Runnable callback){
this.callback = callback;
}
@Override
public boolean onDoubleTap(MotionEvent e){
callback.run();
return true;
}
}
private void translationYAnimate(View view, int translation, int duration, Interpolator interpolator, Runnable endAction){
ViewPropertyAnimatorCompat animator = ViewCompat.animate(view);
animator.setDuration(duration).translationY(translation);
if(endAction != null)
animator.withEndAction(endAction);
if(interpolator != null)
animator.setInterpolator(interpolator);
animator.start();
}
@Override
public void onWindowFocusChanged(boolean hasFocus){
if(hasFocus && !layoutInitialized){
deviceHeight = getHeight();
deviceWidth = getWidth();
layoutInitialized = true;
this.headerView.getLayoutParams().height = (int)((float)deviceWidth * 0.55f);
this.headerView.requestLayout();
}
}
}
| UTF-8 | Java | 10,696 | java | PopupPanel.java | Java | []
| null | []
| package so.library.draghelper.helper.view;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.Log;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.graphics.drawable.GradientDrawable;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import so.library.draghelper.R;
import so.library.draghelper.helper.DragHelperViewCallback;
public class PopupPanel extends LinearLayout{
public enum State{
Closed,
Opened,
FullyOpened
}
public interface OnStateChangedListener{
void onStateChanged(State state);
}
private Context context;
OnStateChangedListener onStateChangedListener;
State state;
int contentOffsetY;
boolean isAnimating;
SmoothInterpolator smoothInterpolator = new SmoothInterpolator();
OvershootInterpolator overInterpolator = new OvershootInterpolator();
VelocityTracker velocityTracker;
GestureDetector paneGestureDetector;
State stateBeforeTracking;
boolean isTracking;
boolean preTracking;
int startY = -1;
float oldY;
int pagingTouchSlop;
int minFlingVelocity;
int maxFlingVelocity;
int idPaneHeaderView = 0;
GradientDrawable shadowDrawable;
View parentView;
private View headerView;
private View bodyView;
int deviceHeight;
int deviceWidth;
/**
* Relevant variables with ViewDragHelper
*/
private ViewDragHelper viewDragHelper;
private boolean layoutInitialized = false;
public PopupPanel(Context context){
super(context);
this.context = context;
this.initialize();
}
public PopupPanel(Context context, AttributeSet attrs){
super(context, attrs);
this.context = context;
this.initialize();
}
public PopupPanel(Context context, AttributeSet attrs, int defStyleAttr){
super(context, attrs, defStyleAttr);
this.context = context;
this.initialize();
}
public void setPaneHeaderViewId(int idPaneHeaderView){
this.idPaneHeaderView = idPaneHeaderView;
}
public void setParentView(View parentView){
this.parentView = parentView;
}
private int getPaneHeaderViewId(){
return this.idPaneHeaderView;
}
public void setChildViews(WebView headerView, View bodyView) {
this.headerView = headerView;
this.bodyView = bodyView;
}
private void initialize(){
state = State.FullyOpened;
ViewConfiguration config = ViewConfiguration.get(this.context);
this.pagingTouchSlop = config.getScaledPagingTouchSlop();
this.minFlingVelocity = config.getScaledMinimumFlingVelocity();
this.maxFlingVelocity = config.getScaledMaximumFlingVelocity();
final int baseShadowColor = 0;
int[] shadowColors = {
Color.argb(0x30, baseShadowColor, baseShadowColor, baseShadowColor),
Color.argb(0, baseShadowColor, baseShadowColor, baseShadowColor)
};
this.shadowDrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, shadowColors);
viewDragHelper = ViewDragHelper.create(this, 1.0f, new DragHelperViewCallback(this, headerView));
}
public boolean isOpened(){
return state == State.Opened || state == State.FullyOpened;
}
public boolean isFullyOpened(){
return state == State.FullyOpened;
}
public void setState(State newState, boolean animated){
Interpolator interpolator = state == State.Closed && newState == State.Opened ? overInterpolator : smoothInterpolator;
this.state = newState;
if (newState != State.Closed)
this.setVisibility(View.VISIBLE);
if (!animated){
setNewOffset(getOffsetForState(newState));
if (state == State.Closed)
this.setVisibility(View.INVISIBLE);
} else {
isAnimating = true;
int duration = Resources.getSystem().getInteger(android.R.integer.config_mediumAnimTime);
this.translationYAnimate(this, getOffsetForState(newState), duration, interpolator, new Runnable() {
@Override
public void run() {
isAnimating = false;
if (state == State.Closed)
setVisibility(View.INVISIBLE);
}
});
}
if (this.onStateChangedListener != null){
this.onStateChangedListener.onStateChanged(newState);
}
}
public void setOnStateChangedListener(OnStateChangedListener l){
this.onStateChangedListener = l;
}
private void setNewOffset(int newOffset){
if (state == State.Closed){
contentOffsetY = newOffset;
this.setTranslationY(contentOffsetY);
} else {
contentOffsetY = Math.min(Math.max( getOffsetForState(State.FullyOpened), newOffset),
getOffsetForState(State.Opened));
this.setTranslationY(contentOffsetY);
}
}
private int getOffsetForState(State state){
switch(state){
default:
case Closed:
return parentView.getBottom();
case FullyOpened:
return parentView.getBottom() - this.getHeight();
case Opened:
int idPaneHeaderView = this.getPaneHeaderViewId();
return parentView.getBottom() - findViewById(idPaneHeaderView).getHeight() - this.getPaddingTop();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e){
final int action = MotionEventCompat.getActionMasked(e);
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP){
return false;
}
boolean interceptTap = viewDragHelper.isViewUnder(headerView, (int) e.getX(), (int) e.getY());
return viewDragHelper.shouldInterceptTouchEvent(e) || interceptTap;
}
@Override
public boolean onTouchEvent(MotionEvent e){
if (paneGestureDetector == null){
DoubleTapListener l = new DoubleTapListener(new Runnable() {
@Override
public void run() {
setState(isOpened() && isFullyOpened() ? State.Opened : State.FullyOpened, true);
}
});
paneGestureDetector = new GestureDetector(this.context, l);
}
paneGestureDetector.onTouchEvent(e);
e.offsetLocation(0, this.getTranslationY());
if (e.getAction() == MotionEvent.ACTION_DOWN){
this.captureMovementCheck(e);
headerView.dispatchTouchEvent(e);
return true;
}
if (!isTracking && !captureMovementCheck(e)){
headerView.dispatchTouchEvent(e);
return true;
}
if (e.getAction() != MotionEvent.ACTION_MOVE || moveDirectionTest(e))
velocityTracker.addMovement(e);
if (e.getAction() == MotionEvent.ACTION_MOVE){
float y = e.getY();
if(state == State.Opened && y > startY || state == State.FullyOpened && y < startY)
return true;
if(state == State.Opened && y > oldY || state == State.FullyOpened && y < oldY)
velocityTracker.clear();
int traveledDistance = (int) Math.round(Math.abs(y - startY));
if (state == State.Opened)
traveledDistance = getOffsetForState(State.Opened) - traveledDistance;
setNewOffset(traveledDistance);
oldY = y;
} else if (e.getAction() == MotionEvent.ACTION_UP){
velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);
if (Math.abs(velocityTracker.getYVelocity()) > minFlingVelocity && Math.abs(velocityTracker.getYVelocity()) < maxFlingVelocity)
setState(state == State.FullyOpened ? State.Opened : State.FullyOpened, true);
else if (state == State.FullyOpened && contentOffsetY > this.getHeight() / 2)
setState(State.Opened, true);
else if (state == State.Opened && contentOffsetY < this.getHeight() / 2)
setState(State.FullyOpened, true);
else
setState(state, true);
preTracking = isTracking = false;
velocityTracker.clear();
velocityTracker.recycle();
}
return true;
}
private boolean captureMovementCheck(MotionEvent e){
if (e.getAction() == MotionEvent.ACTION_DOWN){
oldY = startY = (int)e.getY();
if(!isOpened())
return false;
velocityTracker = VelocityTracker.obtain();
velocityTracker.addMovement(e);
preTracking = true;
stateBeforeTracking = state;
return false;
}
if (e.getAction() == MotionEvent.ACTION_UP)
preTracking = isTracking = false;
if (!preTracking)
return false;
velocityTracker.addMovement(e);
if (e.getAction() == MotionEvent.ACTION_MOVE){
if(!this.moveDirectionTest(e)){
preTracking = false;
return false;
}
double distance = Math.abs(e.getY() - startY);
if (distance < pagingTouchSlop)
return false;
}
oldY = startY = (int) e.getY();
isTracking = true;
return true;
}
private boolean moveDirectionTest(MotionEvent e){
return (stateBeforeTracking == State.FullyOpened ? e.getY() >= startY : e.getY() <= startY);
}
private class SmoothInterpolator extends LinearInterpolator{
@Override
public float getInterpolation(float input){
return (float) Math.pow(input - 1, 5) + 1;
}
}
private class DoubleTapListener extends SimpleOnGestureListener{
Runnable callback;
public DoubleTapListener(Runnable callback){
this.callback = callback;
}
@Override
public boolean onDoubleTap(MotionEvent e){
callback.run();
return true;
}
}
private void translationYAnimate(View view, int translation, int duration, Interpolator interpolator, Runnable endAction){
ViewPropertyAnimatorCompat animator = ViewCompat.animate(view);
animator.setDuration(duration).translationY(translation);
if(endAction != null)
animator.withEndAction(endAction);
if(interpolator != null)
animator.setInterpolator(interpolator);
animator.start();
}
@Override
public void onWindowFocusChanged(boolean hasFocus){
if(hasFocus && !layoutInitialized){
deviceHeight = getHeight();
deviceWidth = getWidth();
layoutInitialized = true;
this.headerView.getLayoutParams().height = (int)((float)deviceWidth * 0.55f);
this.headerView.requestLayout();
}
}
}
| 10,696 | 0.701851 | 0.69942 | 366 | 28.224043 | 26.358688 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.595628 | false | false | 10 |
aa1e452ffaeaae996f2c961ddbe7fb55d70814fe | 23,124,103,943,889 | 441567e28884594a3d0995e7a78f23c9c52254b6 | /webapp/src/main/java/com/connexity/demo/packUser/UserRepository.java | 063419ebdb838fc5d75d2fa1355b38f9810e63eb | []
| no_license | Edgineer/shopyourlikes | https://github.com/Edgineer/shopyourlikes | 2821969f998df20c768e96d8080237e6bbbf5936 | a4dec237ab96377b9f6178d96468d426d3398ec5 | refs/heads/master | 2020-05-19T05:13:23.833000 | 2019-06-07T09:57:52 | 2019-06-07T09:57:52 | 184,844,824 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.connexity.demo.packUser;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "user", path = "users")
interface UserRepository extends MongoRepository<User, String> {
int countByUsernameIgnoreCase(@Param("username") String username);
User findByUsernameAndHashIgnoreCase(@Param("username") String username, @Param("hash") String hash);
User findByUsernameIgnoreCase(@Param("username") String username);
}
| UTF-8 | Java | 641 | java | UserRepository.java | Java | [
{
"context": "e);\n\tUser findByUsernameAndHashIgnoreCase(@Param(\"username\") String username, @Param(\"hash\") String hash);\n\t",
"end": 522,
"score": 0.8486281633377075,
"start": 514,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package com.connexity.demo.packUser;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "user", path = "users")
interface UserRepository extends MongoRepository<User, String> {
int countByUsernameIgnoreCase(@Param("username") String username);
User findByUsernameAndHashIgnoreCase(@Param("username") String username, @Param("hash") String hash);
User findByUsernameIgnoreCase(@Param("username") String username);
}
| 641 | 0.822153 | 0.822153 | 13 | 48.307693 | 31.92873 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.076923 | false | false | 10 |
0360e9db7c633b15bebbf1908a44bd50d59b9d48 | 16,561,393,921,868 | 4080423ea259483873caf14fcccc4ee4dd5a1ac8 | /modules/core/src/main/java/be/wegenenverkeer/atomium/api/FeedPageProviderAdapters.java | cf9aecfdf6a7e77fc46d2f60d7eb197a98731928 | [
"MIT"
]
| permissive | WegenenVerkeer/atomium | https://github.com/WegenenVerkeer/atomium | 48508e450f6201b2f15c715aafc27b845654f696 | a6b8b0182dc1a5d54cc9a3f392b2bc07d955a2cf | refs/heads/develop | 2023-06-22T03:01:51.553000 | 2023-06-15T09:28:02 | 2023-06-15T09:28:02 | 19,538,897 | 6 | 12 | MIT | false | 2023-09-07T11:33:10 | 2014-05-07T15:03:14 | 2023-03-30T14:22:59 | 2023-09-07T11:33:09 | 2,084 | 4 | 11 | 13 | Java | false | false | package be.wegenenverkeer.atomium.api;
import java.util.List;
/**
* Created by Karel Maesen, Geovise BVBA on 14/12/16.
*/
public class FeedPageProviderAdapters {
public static <T> FeedPageProvider<T> adapt(EventReader<T> eventReader, FeedMetadata meta) {
return new DaoBackedFeeedPageProvider<>(eventReader, meta);
}
static class DaoBackedFeeedPageProvider<T> implements FeedPageProvider<T> {
final private EventReader<T> eventReader;
final private FeedMetadata metadata;
DaoBackedFeeedPageProvider(EventReader<T> dao, FeedMetadata meta) {
this.eventReader = dao;
this.metadata = meta;
}
private FeedPage<T> mkFeedPage(FeedPageRef requestedPage) {
long pageSize = metadata.getPageSize();
long requested = pageSize + 1;
FeedPageBuilder<T> builder = new FeedPageBuilder<>(this.metadata, requestedPage.getPageNum());
List<Event<T>> events = eventReader.getEvents(requestedPage.getPageNum() * pageSize, requested);
return builder.setEvents(events).build();
}
@Override
public FeedPage<T> getFeedPage(FeedPageRef ref) {
FeedPageRef headOfFeed = getHeadOfFeedRef();
if (ref.isStrictlyMoreRecentThan(headOfFeed)) {
throw new IndexOutOfBoundsException("Requested page currently beyond head of feed");
}
return mkFeedPage(ref);
}
/**
* Return a reference to the most recent {@code FeedPage}}
* <p>
* The head-of-feed {@code FeedPage} can be empty
*
* @return a {@code FeedPageRef} to the most recent {@code FeedPage}
*/
@Override
public FeedPageRef getHeadOfFeedRef() {
return FeedPageRef.page(eventReader.totalNumberOfEvents() / metadata.getPageSize());
}
}
}
| UTF-8 | Java | 1,916 | java | FeedPageProviderAdapters.java | Java | [
{
"context": "um.api;\n\nimport java.util.List;\n\n/**\n * Created by Karel Maesen, Geovise BVBA on 14/12/16.\n */\npublic class FeedP",
"end": 94,
"score": 0.9998742938041687,
"start": 82,
"tag": "NAME",
"value": "Karel Maesen"
},
{
"context": "t java.util.List;\n\n/**\n * Created by Karel Maesen, Geovise BVBA on 14/12/16.\n */\npublic class FeedPageProviderAda",
"end": 108,
"score": 0.9192550182342529,
"start": 96,
"tag": "NAME",
"value": "Geovise BVBA"
}
]
| null | []
| package be.wegenenverkeer.atomium.api;
import java.util.List;
/**
* Created by <NAME>, <NAME> on 14/12/16.
*/
public class FeedPageProviderAdapters {
public static <T> FeedPageProvider<T> adapt(EventReader<T> eventReader, FeedMetadata meta) {
return new DaoBackedFeeedPageProvider<>(eventReader, meta);
}
static class DaoBackedFeeedPageProvider<T> implements FeedPageProvider<T> {
final private EventReader<T> eventReader;
final private FeedMetadata metadata;
DaoBackedFeeedPageProvider(EventReader<T> dao, FeedMetadata meta) {
this.eventReader = dao;
this.metadata = meta;
}
private FeedPage<T> mkFeedPage(FeedPageRef requestedPage) {
long pageSize = metadata.getPageSize();
long requested = pageSize + 1;
FeedPageBuilder<T> builder = new FeedPageBuilder<>(this.metadata, requestedPage.getPageNum());
List<Event<T>> events = eventReader.getEvents(requestedPage.getPageNum() * pageSize, requested);
return builder.setEvents(events).build();
}
@Override
public FeedPage<T> getFeedPage(FeedPageRef ref) {
FeedPageRef headOfFeed = getHeadOfFeedRef();
if (ref.isStrictlyMoreRecentThan(headOfFeed)) {
throw new IndexOutOfBoundsException("Requested page currently beyond head of feed");
}
return mkFeedPage(ref);
}
/**
* Return a reference to the most recent {@code FeedPage}}
* <p>
* The head-of-feed {@code FeedPage} can be empty
*
* @return a {@code FeedPageRef} to the most recent {@code FeedPage}
*/
@Override
public FeedPageRef getHeadOfFeedRef() {
return FeedPageRef.page(eventReader.totalNumberOfEvents() / metadata.getPageSize());
}
}
}
| 1,904 | 0.63309 | 0.629436 | 63 | 29.396826 | 32.409847 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.349206 | false | false | 10 |
fc19a5e7c2e9046058c64ebbf49ad758850561ce | 27,255,862,498,167 | e7919dd1ed21e6e5b0bb5a0a54a1ebad3bc42d91 | /src/main/java/com/rephilo/luandun/leetcode/_021/Solution.java | 557f7713f0557dabdcc0e393dfa461f2dc07d53b | []
| no_license | Rephilo/luandun | https://github.com/Rephilo/luandun | 2b836cc5b0e9a7b9a748cb4fcda606e7f66d24c6 | c538e76863cf45ec881d4e3936e52aee09a565e9 | refs/heads/master | 2022-10-09T01:41:15.595000 | 2022-02-17T07:52:04 | 2022-02-17T07:52:04 | 140,230,563 | 1 | 0 | null | false | 2022-09-30T17:30:55 | 2018-07-09T04:18:23 | 2022-02-16T12:11:38 | 2022-09-30T17:30:54 | 517 | 1 | 0 | 3 | Java | false | false | package com.rephilo.luandun.leetcode._021;
import com.rephilo.luandun.leetcode.datastructure.ListNode;
public class Solution {
/**
* 021
*
* @param l1
* @param l2
* @return
*/
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode tempNode = null;
while (l1 != null || l2 != null) {
int currNum;
if (l1 == null) {
currNum = l2.val;
l2 = l2.next;
} else if (l2 == null) {
currNum = l1.val;
l1 = l1.next;
} else {
if (l1.val <= l2.val) {
currNum = l1.val;
l1 = l1.next;
} else {
currNum = l2.val;
l2 = l2.next;
}
}
if (head == null) {
head = new ListNode(currNum);
tempNode = head;
} else {
tempNode.next = new ListNode(currNum);
tempNode = tempNode.next;
}
}
return head;
}
}
| UTF-8 | Java | 1,155 | java | Solution.java | Java | []
| null | []
| package com.rephilo.luandun.leetcode._021;
import com.rephilo.luandun.leetcode.datastructure.ListNode;
public class Solution {
/**
* 021
*
* @param l1
* @param l2
* @return
*/
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode tempNode = null;
while (l1 != null || l2 != null) {
int currNum;
if (l1 == null) {
currNum = l2.val;
l2 = l2.next;
} else if (l2 == null) {
currNum = l1.val;
l1 = l1.next;
} else {
if (l1.val <= l2.val) {
currNum = l1.val;
l1 = l1.next;
} else {
currNum = l2.val;
l2 = l2.next;
}
}
if (head == null) {
head = new ListNode(currNum);
tempNode = head;
} else {
tempNode.next = new ListNode(currNum);
tempNode = tempNode.next;
}
}
return head;
}
}
| 1,155 | 0.409524 | 0.385281 | 46 | 24.108696 | 16.434624 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false | 10 |
e16f0a80d36742a8135a720d23b82880c29f7cf6 | 1,056,561,970,212 | 0c29020e46c1279f1c6c0c4ae0a7e156470d2958 | /QUEUE/src/Sliding_Window_Maximum.java | 19c168f503b49652e40ec787b0ec40778eebe5fa | []
| no_license | Prithwish10/Coding-Problems | https://github.com/Prithwish10/Coding-Problems | 96a53ac36536084534d1edb1ac5b3777f41e0a34 | 52df8ea80e3d822b80aeb391359d19f98b9ab76e | refs/heads/master | 2023-02-06T01:32:04.950000 | 2020-12-19T15:34:02 | 2020-12-19T15:34:02 | 270,987,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class Sliding_Window_Maximum {
public int[] maxSlidingWindow(int[] nums, int k) {
List<Integer> list = new ArrayList<>();
Deque<Integer> queue = new LinkedList<>();
int ar[] = new int[nums.length - k + 1];
int index = 0;
int end = 0, start = 0;
for(end = 0; end < k; end ++){
while(!queue.isEmpty() && nums[end] > nums[queue.peekLast()])
queue.removeLast();
queue.add(end);
}
ar[index ++] = nums[queue.peekFirst()];
for(; end < nums.length; end ++){
while(!queue.isEmpty() && queue.peekFirst() <= end - k)
queue.removeFirst();
while(!queue.isEmpty() && nums[end] > nums[queue.peekLast()])
queue.removeLast();
queue.addLast(end);
ar[index ++] = nums[queue.peekFirst()];
}
// int ar[] = new int[list.size()];
// int index = 0;
// for(int i : list)
// ar[index ++] = i;
return ar;
}
}
| UTF-8 | Java | 1,287 | java | Sliding_Window_Maximum.java | Java | []
| null | []
| import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class Sliding_Window_Maximum {
public int[] maxSlidingWindow(int[] nums, int k) {
List<Integer> list = new ArrayList<>();
Deque<Integer> queue = new LinkedList<>();
int ar[] = new int[nums.length - k + 1];
int index = 0;
int end = 0, start = 0;
for(end = 0; end < k; end ++){
while(!queue.isEmpty() && nums[end] > nums[queue.peekLast()])
queue.removeLast();
queue.add(end);
}
ar[index ++] = nums[queue.peekFirst()];
for(; end < nums.length; end ++){
while(!queue.isEmpty() && queue.peekFirst() <= end - k)
queue.removeFirst();
while(!queue.isEmpty() && nums[end] > nums[queue.peekLast()])
queue.removeLast();
queue.addLast(end);
ar[index ++] = nums[queue.peekFirst()];
}
// int ar[] = new int[list.size()];
// int index = 0;
// for(int i : list)
// ar[index ++] = i;
return ar;
}
}
| 1,287 | 0.45066 | 0.445998 | 48 | 25.8125 | 18.879725 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604167 | false | false | 10 |
c03030153a2cc0aecdaf7fa4c7f076f2b05c1ee3 | 5,935,644,850,479 | 78c005f1f7df36995c4036830087f22ef981cdb1 | /src/test/java/pl/akademiaqa/cucumber/steps/employee/DeleteEmployeeSteps.java | 450f5b45dc8460c37425c49970ba6ec12aeab231 | []
| no_license | TomaszSkrzypinski/cucumber-JSON-server | https://github.com/TomaszSkrzypinski/cucumber-JSON-server | 1c4755a2483b880ab5709fcd106e65ec14b97fc9 | 5c76f97bc24a552c65e13b05f9d01547ecbf06e8 | refs/heads/main | 2023-09-03T08:22:43.117000 | 2021-11-22T20:26:26 | 2021-11-22T20:26:26 | 423,980,320 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.akademiaqa.cucumber.steps.employee;
import io.cucumber.java.en.When;
import io.restassured.response.Response;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpStatus;
import pl.akademiaqa.api.context.Context;
import pl.akademiaqa.api.employee.DeleteEmployeeRequest;
import static org.assertj.core.api.Assertions.*;
@RequiredArgsConstructor
public class DeleteEmployeeSteps {
private final Context context;
private final DeleteEmployeeRequest deleteEmployeeRequest;
@When("I delete existing employee")
public void i_delete_existing_employee() {
int employeeId = context.getEmployeeResponse().getId();
Response response = deleteEmployeeRequest.deleteEmployee(employeeId);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
}
}
| UTF-8 | Java | 819 | java | DeleteEmployeeSteps.java | Java | []
| null | []
| package pl.akademiaqa.cucumber.steps.employee;
import io.cucumber.java.en.When;
import io.restassured.response.Response;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpStatus;
import pl.akademiaqa.api.context.Context;
import pl.akademiaqa.api.employee.DeleteEmployeeRequest;
import static org.assertj.core.api.Assertions.*;
@RequiredArgsConstructor
public class DeleteEmployeeSteps {
private final Context context;
private final DeleteEmployeeRequest deleteEmployeeRequest;
@When("I delete existing employee")
public void i_delete_existing_employee() {
int employeeId = context.getEmployeeResponse().getId();
Response response = deleteEmployeeRequest.deleteEmployee(employeeId);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
}
}
| 819 | 0.782662 | 0.782662 | 26 | 30.5 | 24.726582 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
df0df55ade4982fce17709910a6b48ae13293b2d | 18,648,748,041,691 | daa1f9040cfdb54b9cdcffb1bd30c81e48efa9d7 | /src/main/java/Util/HibernateUtil.java | 286b8ae8998bb4d1a2f1a274dd4f7ca1a34a2854 | []
| no_license | Andrey295pa/DB_3Socks | https://github.com/Andrey295pa/DB_3Socks | 9fee9d669c19f3b09aad2fcb73a489c3c15a0c62 | 2235720a3db0a438f3db3a99ec93dcb990766b48 | refs/heads/master | 2020-04-29T19:23:39.371000 | 2019-03-22T19:13:06 | 2019-03-22T19:13:06 | 176,352,617 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Util;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
public class HibernateUtil {
private static final SessionFactory sessionFuctory;
static {
try{
sessionFuctory= new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed"+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFuctory(){
return sessionFuctory;
}
}
| UTF-8 | Java | 592 | java | HibernateUtil.java | Java | []
| null | []
| package Util;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
public class HibernateUtil {
private static final SessionFactory sessionFuctory;
static {
try{
sessionFuctory= new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed"+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFuctory(){
return sessionFuctory;
}
}
| 592 | 0.646959 | 0.646959 | 21 | 27.190475 | 26.056019 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 10 |
661f0f4d0c5960845022e3d28a639315ef83997c | 20,332,375,209,764 | 4aa7ec77452c9668a187c9980805c020c454c090 | /app/src/main/java/org/seamcat/model/engines/EventProcessingPool.java | b93f5c46387542f8e1099d9f7e09613c5bed1b6f | []
| no_license | freqgis/source | https://github.com/freqgis/source | 869a3dff56b430f90f20026c9001b4d8371547c7 | 5dacd5f530751218beb4dfedde4b612053581453 | refs/heads/master | 2023-07-02T16:32:26.323000 | 2017-01-03T16:52:48 | 2017-01-03T16:52:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.seamcat.model.engines;
import org.apache.log4j.Logger;
import org.seamcat.model.simulation.SimulationResultGroup;
import org.seamcat.model.simulation.result.EventResult;
import org.seamcat.model.types.EventProcessing;
import org.seamcat.model.types.result.ResultTypes;
import org.seamcat.plugin.EventProcessingConfiguration;
import org.seamcat.simulation.Simulation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Method to capture all the results from the EPPs simulation
*/
public class EventProcessingPool {
private static final Logger LOG = Logger.getLogger(EventProcessingPool.class);
private ExecutorService pool;
private Map<EventProcessing, EventResultIterable> resultIterableMap;
private final List<SimulationResultGroup> eppResults;
private List<Future<?>> runningEpps = new ArrayList<>();
public EventProcessingPool( final Simulation simulation, final List<SimulationResultGroup> eppResults, List<EventProcessing> confs ) {
this.eppResults = eppResults;
if (confs.isEmpty() ) {
return;
} else {
pool = Executors.newFixedThreadPool(confs.size());
}
resultIterableMap = new HashMap<>();
for (final EventProcessing processing : confs) {
final EventResultIterable iterable = new EventResultIterable(simulation);
resultIterableMap.put(processing, iterable);
runningEpps.add(pool.submit(new Runnable() {
public void run() {
try {
ResultTypes result = processing.evaluate(simulation.getScenario(), iterable);
synchronized (eppResults) {
String id = ((EventProcessingConfiguration) processing).getId();
eppResults.add(new SimulationResultGroup(id, processing.toString(), result, simulation.getScenario()));
eppResults.notifyAll();
}
} catch (Exception e) {
LOG.error("Failed evaluation", e);
synchronized (eppResults) {
eppResults.add(new SimulationResultGroup(processing.toString(), e));
eppResults.notifyAll();
}
}
}
}));
}
}
public void eventResult( EventResult eventResult ) {
if ( pool == null ) return;
for (EventResultIterable eventResults : resultIterableMap.values()) {
eventResults.addResult(eventResult);
}
}
public void eventsComplete() {
if ( pool == null ) return;
for (EventResultIterable eventResults : resultIterableMap.values()) {
eventResults.lastAdded();
}
}
public void waitForTermination() throws InterruptedException {
if ( pool == null ) return;
// wait for it to complete
synchronized (eppResults) {
while (eppResults.size() != resultIterableMap.size()) {
eppResults.wait();
}
}
pool.shutdown();
}
public void cancelAll() {
for (Future<?> epp : runningEpps) {
if ( !epp.isDone() ) {
epp.cancel(true);
}
}
}
}
| UTF-8 | Java | 3,515 | java | EventProcessingPool.java | Java | []
| null | []
| package org.seamcat.model.engines;
import org.apache.log4j.Logger;
import org.seamcat.model.simulation.SimulationResultGroup;
import org.seamcat.model.simulation.result.EventResult;
import org.seamcat.model.types.EventProcessing;
import org.seamcat.model.types.result.ResultTypes;
import org.seamcat.plugin.EventProcessingConfiguration;
import org.seamcat.simulation.Simulation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Method to capture all the results from the EPPs simulation
*/
public class EventProcessingPool {
private static final Logger LOG = Logger.getLogger(EventProcessingPool.class);
private ExecutorService pool;
private Map<EventProcessing, EventResultIterable> resultIterableMap;
private final List<SimulationResultGroup> eppResults;
private List<Future<?>> runningEpps = new ArrayList<>();
public EventProcessingPool( final Simulation simulation, final List<SimulationResultGroup> eppResults, List<EventProcessing> confs ) {
this.eppResults = eppResults;
if (confs.isEmpty() ) {
return;
} else {
pool = Executors.newFixedThreadPool(confs.size());
}
resultIterableMap = new HashMap<>();
for (final EventProcessing processing : confs) {
final EventResultIterable iterable = new EventResultIterable(simulation);
resultIterableMap.put(processing, iterable);
runningEpps.add(pool.submit(new Runnable() {
public void run() {
try {
ResultTypes result = processing.evaluate(simulation.getScenario(), iterable);
synchronized (eppResults) {
String id = ((EventProcessingConfiguration) processing).getId();
eppResults.add(new SimulationResultGroup(id, processing.toString(), result, simulation.getScenario()));
eppResults.notifyAll();
}
} catch (Exception e) {
LOG.error("Failed evaluation", e);
synchronized (eppResults) {
eppResults.add(new SimulationResultGroup(processing.toString(), e));
eppResults.notifyAll();
}
}
}
}));
}
}
public void eventResult( EventResult eventResult ) {
if ( pool == null ) return;
for (EventResultIterable eventResults : resultIterableMap.values()) {
eventResults.addResult(eventResult);
}
}
public void eventsComplete() {
if ( pool == null ) return;
for (EventResultIterable eventResults : resultIterableMap.values()) {
eventResults.lastAdded();
}
}
public void waitForTermination() throws InterruptedException {
if ( pool == null ) return;
// wait for it to complete
synchronized (eppResults) {
while (eppResults.size() != resultIterableMap.size()) {
eppResults.wait();
}
}
pool.shutdown();
}
public void cancelAll() {
for (Future<?> epp : runningEpps) {
if ( !epp.isDone() ) {
epp.cancel(true);
}
}
}
}
| 3,515 | 0.606259 | 0.605974 | 99 | 34.505051 | 28.983929 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525253 | false | false | 10 |
b88c4cf3a11d7f47f6b5d73a50176ed1a03637cd | 35,940,286,367,212 | 2e90eb13f5d8938c04c4938b4b9522dc9cc1a776 | /src/main/java/au/com/ifti/controllers/PostController.java | c90062c0139d6efbd83d8c616649fdb4265de1e2 | [
"MIT"
]
| permissive | arcynum/tiramisu | https://github.com/arcynum/tiramisu | fe05e469e71f18f7e3cbeb4d77588ee451e71333 | 5fe6c54d4b1b9a8f23b40755f639a867bc478ce2 | refs/heads/master | 2020-04-06T03:53:07.903000 | 2017-01-24T05:05:24 | 2017-01-24T05:05:24 | 56,820,461 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package au.com.ifti.controllers;
import java.util.List;
import org.hibernate.Session;
import au.com.ifti.exceptions.NotFoundException;
import au.com.ifti.models.PostModel;
import au.com.ifti.utilities.TiramisuRequest;
import au.com.ifti.utilities.TiramisuResponse;
public class PostController extends Controller {
public PostController(TiramisuRequest request, TiramisuResponse response, Session session) {
super(request, response, session);
}
public TiramisuResponse index() {
System.out.println("Post Index");
List<?> posts = findAll(PostModel.class);
this.set("posts", posts);
this.getResponse().setTemplate("/posts/index.vm");
this.getResponse().setPageTitle("Posts Index");
return this.getResponse();
}
public TiramisuResponse create() throws NotFoundException {
System.out.println("Post Create");
if (this.request.getMethod().equals("POST")) {
PostModel post = new PostModel();
post.setTitle(this.getRequest().getParameter("post_title"));
post.setBody(this.getRequest().getParameter("post_body"));
this.save(post);
return this.redirect("/tiramisu/posts", 303);
}
// Render the create form.
this.getResponse().setTemplate("/posts/create.vm");
this.getResponse().setPageTitle("Create new post");
return this.getResponse();
}
public TiramisuResponse read(String id) throws NotFoundException {
System.out.println("Post Read");
PostModel post = findById(PostModel.class, Integer.parseInt(id));
if (post == null) {
throw new NotFoundException();
}
this.set("post", post);
this.getResponse().setTemplate("/posts/read.vm");
this.getResponse().setPageTitle(post.getTitle());
return this.getResponse();
}
public TiramisuResponse update(String id) throws NotFoundException {
System.out.println("Post Update");
PostModel post = findById(PostModel.class, Integer.parseInt(id));
if (post == null) {
throw new NotFoundException();
}
if (this.request.getMethod().equals("POST")) {
post.setTitle(this.getRequest().getParameter("post_title"));
post.setBody(this.getRequest().getParameter("post_body"));
this.update(post);
return this.redirect("/tiramisu/posts", 303);
}
this.set("post", post);
this.getResponse().setTemplate("/posts/update.vm");
this.getResponse().setPageTitle(post.getTitle());
// Update a post here or render form, same as create.
return this.getResponse();
}
public TiramisuResponse delete(String id) throws NotFoundException {
if (this.request.getMethod() == "DELETE") {
// Delete a post here.
}
return this.getResponse();
}
}
| UTF-8 | Java | 2,732 | java | PostController.java | Java | []
| null | []
| package au.com.ifti.controllers;
import java.util.List;
import org.hibernate.Session;
import au.com.ifti.exceptions.NotFoundException;
import au.com.ifti.models.PostModel;
import au.com.ifti.utilities.TiramisuRequest;
import au.com.ifti.utilities.TiramisuResponse;
public class PostController extends Controller {
public PostController(TiramisuRequest request, TiramisuResponse response, Session session) {
super(request, response, session);
}
public TiramisuResponse index() {
System.out.println("Post Index");
List<?> posts = findAll(PostModel.class);
this.set("posts", posts);
this.getResponse().setTemplate("/posts/index.vm");
this.getResponse().setPageTitle("Posts Index");
return this.getResponse();
}
public TiramisuResponse create() throws NotFoundException {
System.out.println("Post Create");
if (this.request.getMethod().equals("POST")) {
PostModel post = new PostModel();
post.setTitle(this.getRequest().getParameter("post_title"));
post.setBody(this.getRequest().getParameter("post_body"));
this.save(post);
return this.redirect("/tiramisu/posts", 303);
}
// Render the create form.
this.getResponse().setTemplate("/posts/create.vm");
this.getResponse().setPageTitle("Create new post");
return this.getResponse();
}
public TiramisuResponse read(String id) throws NotFoundException {
System.out.println("Post Read");
PostModel post = findById(PostModel.class, Integer.parseInt(id));
if (post == null) {
throw new NotFoundException();
}
this.set("post", post);
this.getResponse().setTemplate("/posts/read.vm");
this.getResponse().setPageTitle(post.getTitle());
return this.getResponse();
}
public TiramisuResponse update(String id) throws NotFoundException {
System.out.println("Post Update");
PostModel post = findById(PostModel.class, Integer.parseInt(id));
if (post == null) {
throw new NotFoundException();
}
if (this.request.getMethod().equals("POST")) {
post.setTitle(this.getRequest().getParameter("post_title"));
post.setBody(this.getRequest().getParameter("post_body"));
this.update(post);
return this.redirect("/tiramisu/posts", 303);
}
this.set("post", post);
this.getResponse().setTemplate("/posts/update.vm");
this.getResponse().setPageTitle(post.getTitle());
// Update a post here or render form, same as create.
return this.getResponse();
}
public TiramisuResponse delete(String id) throws NotFoundException {
if (this.request.getMethod() == "DELETE") {
// Delete a post here.
}
return this.getResponse();
}
}
| 2,732 | 0.679356 | 0.67716 | 87 | 30.402298 | 23.814156 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62069 | false | false | 10 |
c582e6d33b6b32dd99b142d288ae60c2b6d86ad7 | 34,857,954,611,509 | a8a52fe8b9f3b09fbf0d070c44a000fbb307be95 | /array/src/pers/SpiralOrder.java | 40b9a598328cd67efc213221921e03f1e9453891 | []
| no_license | luolanmeet/algorithm | https://github.com/luolanmeet/algorithm | bc9573cd929f07afabd3b5a5370cb5b65222694f | 051b25544c07e48837919c2919c7efa44eb9d76b | refs/heads/master | 2023-09-01T11:40:42.979000 | 2023-08-31T02:53:48 | 2023-08-31T02:53:48 | 169,018,777 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 54. 螺旋矩阵
* https://leetcode-cn.com/problems/spiral-matrix/
* 瑞士卷?
*/
public class SpiralOrder {
public List<Integer> spiralOrder2(int[][] matrix) {
int width = matrix.length;
if (width == 0) return Collections.emptyList();
int height = matrix[0].length;
int size = width * height;
List<Integer> res = new ArrayList<>(size);
boolean[][] bs = new boolean[width][height];
int i = 0, j = 0, di = 0, dj = 1;
while (size-- > 0) {
res.add(matrix[i][j]);
bs[i][j] = true;
// 用取模的方式判断是否需要改变方向
if ((i + di) < 0 || (j + dj) < 0 || bs[(i + di) % width][(j + dj) % height]) {
// (0,1)->(1,0)->(0,-1)->(-1,0)
int tmp = di;
di = dj;
dj = -tmp;
}
i += di;
j += dj;
}
return res;
}
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return Collections.emptyList();
}
List<Integer> res = new ArrayList<>(matrix.length * matrix[0].length);
boolean[][] travel = new boolean[matrix.length][matrix[0].length];
method(matrix, travel, res, 0, 0, 'd');
return res;
}
private void method(int[][] matrix, boolean[][] travel, List<Integer> res, int x, int y, char way) {
if (res.size() == matrix.length * matrix[0].length) {
return ;
}
switch (way) {
case 'd':
for (; y < matrix[0].length; y++) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, ++x, --y, 's');
break;
case 's':
for (; x < matrix.length; x++) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, --x, --y, 'a');
break;
case 'a':
for (; y >= 0; y--) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, --x, ++y, 'w');
break;
case 'w':
for (; x >= 0; x--) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, ++x, ++y, 'd');
break;
}
}
public static void main(String[] args) {
SpiralOrder obj = new SpiralOrder();
System.out.println(obj.spiralOrder2(new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9,10,11,12}
}));
System.out.println(obj.spiralOrder2(new int[][]{
{1, 2, 3, 4}
}));
}
}
| UTF-8 | Java | 3,614 | java | SpiralOrder.java | Java | []
| null | []
| package pers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 54. 螺旋矩阵
* https://leetcode-cn.com/problems/spiral-matrix/
* 瑞士卷?
*/
public class SpiralOrder {
public List<Integer> spiralOrder2(int[][] matrix) {
int width = matrix.length;
if (width == 0) return Collections.emptyList();
int height = matrix[0].length;
int size = width * height;
List<Integer> res = new ArrayList<>(size);
boolean[][] bs = new boolean[width][height];
int i = 0, j = 0, di = 0, dj = 1;
while (size-- > 0) {
res.add(matrix[i][j]);
bs[i][j] = true;
// 用取模的方式判断是否需要改变方向
if ((i + di) < 0 || (j + dj) < 0 || bs[(i + di) % width][(j + dj) % height]) {
// (0,1)->(1,0)->(0,-1)->(-1,0)
int tmp = di;
di = dj;
dj = -tmp;
}
i += di;
j += dj;
}
return res;
}
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return Collections.emptyList();
}
List<Integer> res = new ArrayList<>(matrix.length * matrix[0].length);
boolean[][] travel = new boolean[matrix.length][matrix[0].length];
method(matrix, travel, res, 0, 0, 'd');
return res;
}
private void method(int[][] matrix, boolean[][] travel, List<Integer> res, int x, int y, char way) {
if (res.size() == matrix.length * matrix[0].length) {
return ;
}
switch (way) {
case 'd':
for (; y < matrix[0].length; y++) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, ++x, --y, 's');
break;
case 's':
for (; x < matrix.length; x++) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, --x, --y, 'a');
break;
case 'a':
for (; y >= 0; y--) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, --x, ++y, 'w');
break;
case 'w':
for (; x >= 0; x--) {
if (travel[x][y]) {
break;
}
travel[x][y] = true;
res.add(matrix[x][y]);
}
method(matrix, travel, res, ++x, ++y, 'd');
break;
}
}
public static void main(String[] args) {
SpiralOrder obj = new SpiralOrder();
System.out.println(obj.spiralOrder2(new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9,10,11,12}
}));
System.out.println(obj.spiralOrder2(new int[][]{
{1, 2, 3, 4}
}));
}
}
| 3,614 | 0.362591 | 0.34857 | 124 | 26.758064 | 20.473181 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.895161 | false | false | 10 |
861410c0815a97451aa4cd768302e5161471b644 | 39,487,929,319,426 | e64c3bf4fe7a1396d9c6ee7332be79cebba8a574 | /src/main/java/com/kkth/web/model/param/PasswordPARM.java | 97ec3ee45d924522b1aa11d875fd2975ad535c24 | []
| no_license | iqeq00/kkth-web | https://github.com/iqeq00/kkth-web | 9cb77ac66584a0dcfd7b066855aab4f908848546 | 6f422dae5a53995747cfe5aad9bcac4f4b407589 | refs/heads/master | 2022-02-22T14:08:26.615000 | 2020-09-25T06:06:27 | 2020-09-25T06:06:27 | 220,411,978 | 1 | 0 | null | false | 2022-02-09T22:19:13 | 2019-11-08T07:34:30 | 2020-09-25T06:08:11 | 2022-02-09T22:19:12 | 29,231 | 0 | 0 | 3 | JavaScript | false | false | package com.kkth.web.model.param;
import com.kkth.framework.model.Convert;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
/**
* <p>
* 登陆参数
* </p>
*
* @author lichee
*/
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class PasswordPARM extends Convert {
@NotBlank(message = "原密码不能为空", groups = Update.class)
private String oldPassword;
@NotBlank(message = "新密码不能为空", groups = Update.class)
private String newPassword;
public interface Update {
}
}
| UTF-8 | Java | 626 | java | PasswordPARM.java | Java | [
{
"context": "otBlank;\n\n/**\n * <p>\n * 登陆参数\n * </p>\n *\n * @author lichee\n */\n@Data\n@NoArgsConstructor\n@EqualsAndHashCode(c",
"end": 257,
"score": 0.9995438456535339,
"start": 251,
"tag": "USERNAME",
"value": "lichee"
}
]
| null | []
| package com.kkth.web.model.param;
import com.kkth.framework.model.Convert;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
/**
* <p>
* 登陆参数
* </p>
*
* @author lichee
*/
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class PasswordPARM extends Convert {
@NotBlank(message = "原密码不能为空", groups = Update.class)
private String oldPassword;
@NotBlank(message = "新密码不能为空", groups = Update.class)
private String newPassword;
public interface Update {
}
}
| 626 | 0.727119 | 0.727119 | 30 | 18.666666 | 18.228792 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 10 |
f2908df4757f104a92c17ccf1b8c1cdd8bb04a70 | 39,350,490,402,877 | 10af04a7d5807b022de4a6f36d985403feb02c46 | /back/JPA/test/src/com/org/beans/manytomany/ManyToManyTest.java | cfb5e5165a267bb90051e5fe12e8b8cb76e21e6b | []
| no_license | Anymous526/javase-parent | https://github.com/Anymous526/javase-parent | 38c90902626e472f329c983cc0703ae7e1a1d59b | dd0756d1fdb077028dd32b2dd0b3ab146ef199e5 | refs/heads/master | 2019-04-09T08:07:37.368000 | 2019-03-31T03:11:38 | 2019-03-31T03:11:38 | 26,983,534 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.org.beans.manytomany;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class ManyToManyTest {
private static EntityManagerFactory factory;
private static EntityManager em;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
factory = Persistence.createEntityManagerFactory("itcast");
em = factory.createEntityManager();
}
@AfterClass
public static void globalDestroy() {
em.close();
factory.close();
}
@Before
public void init() {
em.getTransaction().begin();
}
@After
public void destroy() {
em.getTransaction().commit();
}
@Ignore
@Test
public void save() {
//Student stu = new Student("¹þ¹þ");
Teacher tea = new Teacher("ÀÏÕÅ");
//em.persist(stu);
em.persist(tea);
}
@Ignore
@Test
public void buildR(){
Student std = em.find(Student.class, 1);
std.addTeacher(em.getReference(Teacher.class, 2));
}
@Ignore
@Test
public void breakR(){
Student std = em.find(Student.class, 1);
std.removeTeacher(em.getReference(Teacher.class, 1));
}
@Ignore
@Test
public void delTeacher(){
Student std = em.find(Student.class, 1);
std.removeTeacher(em.getReference(Teacher.class, 2));
em.remove(em.getReference(Teacher.class, 2));
}
@Test
public void delStudend(){
}
}
| WINDOWS-1252 | Java | 1,512 | java | ManyToManyTest.java | Java | []
| null | []
| package com.org.beans.manytomany;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class ManyToManyTest {
private static EntityManagerFactory factory;
private static EntityManager em;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
factory = Persistence.createEntityManagerFactory("itcast");
em = factory.createEntityManager();
}
@AfterClass
public static void globalDestroy() {
em.close();
factory.close();
}
@Before
public void init() {
em.getTransaction().begin();
}
@After
public void destroy() {
em.getTransaction().commit();
}
@Ignore
@Test
public void save() {
//Student stu = new Student("¹þ¹þ");
Teacher tea = new Teacher("ÀÏÕÅ");
//em.persist(stu);
em.persist(tea);
}
@Ignore
@Test
public void buildR(){
Student std = em.find(Student.class, 1);
std.addTeacher(em.getReference(Teacher.class, 2));
}
@Ignore
@Test
public void breakR(){
Student std = em.find(Student.class, 1);
std.removeTeacher(em.getReference(Teacher.class, 1));
}
@Ignore
@Test
public void delTeacher(){
Student std = em.find(Student.class, 1);
std.removeTeacher(em.getReference(Teacher.class, 2));
em.remove(em.getReference(Teacher.class, 2));
}
@Test
public void delStudend(){
}
}
| 1,512 | 0.722074 | 0.71609 | 74 | 19.324324 | 17.503752 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.445946 | false | false | 10 |
0e4c601397437d76b4141aa5563a5987f9d8d026 | 38,792,144,626,410 | 6e6d2c0e2b2cd2fa132f28fd119ba20e2decaedf | /ms/suanfa/src/main/java/yihuo.java | 882794d246f15d8e41ebbaf113ee6c93c4a55dbf | []
| no_license | zx921006/myGitCode | https://github.com/zx921006/myGitCode | 3d679d90b23522174b7f3cdc9334bd32c1c9d5d3 | 89f2121364d3f791a00969429c02edb043266870 | refs/heads/master | 2023-04-25T15:14:12.737000 | 2021-05-11T08:50:40 | 2021-05-11T08:50:40 | 366,282,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* 数组实现队列
*/
public class yihuo {
static class MyQueue{
int[] arr;
int pushi;
int pulli;
int size;
final int limit;
MyQueue(int limit){
arr = new int[limit];
pushi=0;
pulli=0;
size=0;
this.limit=limit;
}
void push(int value){
if(size==limit){
throw new RuntimeException("队列满了,不能再加了");
}
size++;
arr[pushi]=value;
pushi=nextIndex(pushi);
}
int pop(){
if(size==0){
throw new RuntimeException("队列空了,不能再拿了");
}
size--;
int ant=arr[pulli];
pulli=nextIndex(pulli);
return ant;
}
private int nextIndex(int i) {
return i<limit-1?i+1:0;
}
}
public static void main(String[] args) {
int[] arr=new int[5];
}
}
| UTF-8 | Java | 1,020 | java | yihuo.java | Java | []
| null | []
| /**
* 数组实现队列
*/
public class yihuo {
static class MyQueue{
int[] arr;
int pushi;
int pulli;
int size;
final int limit;
MyQueue(int limit){
arr = new int[limit];
pushi=0;
pulli=0;
size=0;
this.limit=limit;
}
void push(int value){
if(size==limit){
throw new RuntimeException("队列满了,不能再加了");
}
size++;
arr[pushi]=value;
pushi=nextIndex(pushi);
}
int pop(){
if(size==0){
throw new RuntimeException("队列空了,不能再拿了");
}
size--;
int ant=arr[pulli];
pulli=nextIndex(pulli);
return ant;
}
private int nextIndex(int i) {
return i<limit-1?i+1:0;
}
}
public static void main(String[] args) {
int[] arr=new int[5];
}
}
| 1,020 | 0.423868 | 0.415638 | 47 | 19.680851 | 13.997122 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489362 | false | false | 10 |
571c2e3b5e7fbad3ca9a71b20e04e89e672e66a3 | 38,087,770,003,730 | ed5159d056e98d6715357d0d14a9b3f20b764f89 | /src/irvine/oeis/a303/A303878.java | 9f5ca1e607f7dc76c989d9ae0f2758aef0573772 | []
| no_license | flywind2/joeis | https://github.com/flywind2/joeis | c5753169cf562939b04dd246f8a2958e97f74558 | e5efd6971a0062ac99f4fae21a7c78c9f9e74fea | refs/heads/master | 2020-09-13T18:34:35.080000 | 2019-11-19T05:40:55 | 2019-11-19T05:40:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package irvine.oeis.a303;
import irvine.oeis.FiniteSequence;
/**
* A303878 Consider the representation of some integer <code>(>1)</code> as the sum of distinct unit fraction <code>(<1)</code>. The sum of these denominators is least.
* @author Georg Fischer
*/
public class A303878 extends FiniteSequence {
/** Construct the sequence. */
public A303878() {
super(2, 3, 4, 5, 6, 8, 9, 10, 15, 18, 20, 24);
}
}
| UTF-8 | Java | 430 | java | A303878.java | Java | [
{
"context": "The sum of these denominators is least.\n * @author Georg Fischer\n */\npublic class A303878 extends FiniteSequence {",
"end": 266,
"score": 0.9998558163642883,
"start": 253,
"tag": "NAME",
"value": "Georg Fischer"
}
]
| null | []
| package irvine.oeis.a303;
import irvine.oeis.FiniteSequence;
/**
* A303878 Consider the representation of some integer <code>(>1)</code> as the sum of distinct unit fraction <code>(<1)</code>. The sum of these denominators is least.
* @author <NAME>
*/
public class A303878 extends FiniteSequence {
/** Construct the sequence. */
public A303878() {
super(2, 3, 4, 5, 6, 8, 9, 10, 15, 18, 20, 24);
}
}
| 423 | 0.67907 | 0.586047 | 15 | 27.666666 | 42.606209 | 174 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.066667 | false | false | 10 |
da78aa6f7dd14fe50f7a9e4f5e01c5fc048621c9 | 39,402,029,991,030 | bbe2efeabac726b6effcda2923d0d4e9a124b6b9 | /src/Main.java | e9700b7ccf9daf6a234fdddfea4cdc2c87255ab9 | []
| no_license | SrikarCK/InheritanceChallenge | https://github.com/SrikarCK/InheritanceChallenge | 331826174650fd3ea9d2b5842f3f315b2e1fdb09 | ad3d9229f86cd9c1540f1fde2dfe587e6f294a98 | refs/heads/master | 2020-04-15T23:22:05.166000 | 2019-01-10T17:45:13 | 2019-01-10T17:45:13 | 165,103,504 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Main {
public static void main(String[] args) {
Bmw x3 = new Bmw(36);
x3.steer(45);
x3.accelerate(30);
x3.accelerate(20);
}
}
| UTF-8 | Java | 179 | java | Main.java | Java | []
| null | []
| public class Main {
public static void main(String[] args) {
Bmw x3 = new Bmw(36);
x3.steer(45);
x3.accelerate(30);
x3.accelerate(20);
}
}
| 179 | 0.530726 | 0.463687 | 8 | 21.375 | 12.756739 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
e38394df584d10b262c39de4a23f7199f0894413 | 36,953,898,646,718 | 8c604052f6f4196de5c8f6c1c54e8235c1fa61b8 | /src/main/java/com/fruitsalad/demo/sys/service/IUserInfoService.java | 8e4fd88b4c680fdd3b3a82619272cda69dbbd431 | []
| no_license | fruitsalad11/springboot-mybatisplus | https://github.com/fruitsalad11/springboot-mybatisplus | 5143aea71e948d3ef955bf024ab4baf1c77a3ca3 | fe0531d019b78bbc2cd10bae8578105f3d7dab4e | refs/heads/master | 2022-05-29T13:06:38.366000 | 2019-07-26T10:34:31 | 2019-07-26T10:34:31 | 198,998,883 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fruitsalad.demo.sys.service;
import com.fruitsalad.demo.sys.entity.UserInfo;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author wzh
* @since 2019-07-18
*/
public interface IUserInfoService extends IService<UserInfo> {
}
| UTF-8 | Java | 283 | java | IUserInfoService.java | Java | [
{
"context": "Service;\n\n/**\n * <p>\n * 服务类\n * </p>\n *\n * @author wzh\n * @since 2019-07-18\n */\npublic interface IUserIn",
"end": 185,
"score": 0.9996950626373291,
"start": 182,
"tag": "USERNAME",
"value": "wzh"
}
]
| null | []
| package com.fruitsalad.demo.sys.service;
import com.fruitsalad.demo.sys.entity.UserInfo;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author wzh
* @since 2019-07-18
*/
public interface IUserInfoService extends IService<UserInfo> {
}
| 283 | 0.714801 | 0.685921 | 16 | 16.3125 | 20.232149 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 10 |
15a14b35143b8e807035f24e32525c4c4dcb660f | 36,953,898,642,876 | abf2e2b6b5dab85431008f95b1784e3d43a60526 | /src/algorithm/Tree/Traversal/InOrder.java | 09410310b10946e6d35f4fc519847838f1aed2f2 | []
| no_license | mu-ni/data-structure-and-algorithm | https://github.com/mu-ni/data-structure-and-algorithm | 0b116b7d4a345d215040101d159840ba2562b6ae | 2f60dd28b51bf2d70f607bbb99fe7aeace502337 | refs/heads/master | 2023-03-09T23:04:23.252000 | 2021-02-23T09:21:21 | 2021-02-23T09:21:21 | 112,596,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package algorithm.Tree.Traversal;
import algorithm.Tree.Dao.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class InOrder {
public static void main(String[] args) {
System.out.println(new InOrder().inOrder(TreeNode.genTree()));
System.out.println(new InOrder().inOrder2(TreeNode.genTree()));
}
public List<Integer> inOrder(TreeNode root) {
List<Integer> rst = new ArrayList<>();
if (root == null) return rst;
inOrder(rst, root);
return rst;
}
public void inOrder(List<Integer> rst, TreeNode node) {
if (node == null) return;
inOrder(rst, node.left);
rst.add(node.val);
inOrder(rst, node.right);
}
public List<Integer> inOrder2(TreeNode root) {
List<Integer> rst = new ArrayList<>();
if (root == null) return rst;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
rst.add(cur.val);
cur = cur.right;
}
return rst;
}
}
| UTF-8 | Java | 1,254 | java | InOrder.java | Java | []
| null | []
| package algorithm.Tree.Traversal;
import algorithm.Tree.Dao.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class InOrder {
public static void main(String[] args) {
System.out.println(new InOrder().inOrder(TreeNode.genTree()));
System.out.println(new InOrder().inOrder2(TreeNode.genTree()));
}
public List<Integer> inOrder(TreeNode root) {
List<Integer> rst = new ArrayList<>();
if (root == null) return rst;
inOrder(rst, root);
return rst;
}
public void inOrder(List<Integer> rst, TreeNode node) {
if (node == null) return;
inOrder(rst, node.left);
rst.add(node.val);
inOrder(rst, node.right);
}
public List<Integer> inOrder2(TreeNode root) {
List<Integer> rst = new ArrayList<>();
if (root == null) return rst;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
rst.add(cur.val);
cur = cur.right;
}
return rst;
}
}
| 1,254 | 0.559011 | 0.557416 | 45 | 26.866667 | 18.777765 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.688889 | false | false | 10 |
491a2a298297569f68fb9ccdd5d3966cdbe5f37a | 33,603,824,144,725 | 38d36d542a1640bf28d3e3f263873a8b522b5bb0 | /src/me/mcuper/compass/commendy/Hunter.java | c793037ace8622caa302456472040df9afbc5df7 | []
| no_license | SweeftyZz/ManhuntCompass | https://github.com/SweeftyZz/ManhuntCompass | a59a0bc4b9578ac4bc6c54237a46235d09cf32f5 | 425a5fc36c3663c3eabc5bc15c5112f2afaa6b9d | refs/heads/master | 2023-04-27T12:17:35.486000 | 2021-05-08T14:33:02 | 2021-05-08T14:33:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.mcuper.compass.commendy;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.mcuper.compass.Main;
import java.util.UUID;
public class Hunter implements CommandExecutor {
// constructor
private final Main plugin = Main.getPlugin( Main.class );
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args ) {
/*
/hunter - add a player executing that command to hunters
/hunter add <player> - add a <player> to hunters
/hunter remove <player> - remove a <player> from hunters
/hunter clear - remove all players from hunters
/hunter list - returns nicks of hunters
*/
if( cmd.getName().equalsIgnoreCase("hunter") ) {
if( !(sender instanceof Player) && args.length == 0 ) {
plugin.loger.info("Only player can use this command without arguments!");
return true;
}
Player p = (Player) sender;
UUID id = p.getUniqueId();
if( args.length == 0 ) {
if( !plugin.runners.isEmpty() && plugin.runners.contains(id) ) plugin.runners.remove(id);
plugin.hunters.add(id);
p.sendMessage(ChatColor.AQUA+"You have been succesfully added to HUNTERS");
} else if( args[0].equalsIgnoreCase("add") ) {
if( args.length < 2 ) {
p.sendMessage(ChatColor.RED+"You must specify a player nickname!");
return true;
}
UUID newHunter = plugin.getServer().getPlayer(args[1]).getUniqueId();
if( !plugin.runners.isEmpty() && plugin.runners.contains(newHunter) ) plugin.runners.remove(newHunter);
if( newHunter!=null) plugin.hunters.add(newHunter);
p.sendMessage(ChatColor.AQUA+"Succesfully added "+args[1]+" to HUNTERS.");
} else if( args[0].equalsIgnoreCase("remove") ) {
if( args.length < 2 ) {
p.sendMessage(ChatColor.RED+"You must specify a player nickname!");
return true;
}
UUID newHunter = plugin.getServer().getPlayer(args[1]).getUniqueId();
plugin.hunters.remove(newHunter);
p.sendMessage(ChatColor.AQUA+"Succesfully removed "+args[1]+" from HUNTERS.");
} else if( args[0].equalsIgnoreCase("clear") ) {
plugin.hunters.clear();
p.sendMessage(ChatColor.RED+"All hunters have been removed!");
} else if( args[0].equalsIgnoreCase("list")) {
String text = "";
if( !plugin.hunters.isEmpty() ) {
for (UUID ids : plugin.hunters) {
text += plugin.getServer().getPlayer(ids).getName() + ",";
}
}
text = text.substring(0, text.length() - 1);
p.sendMessage(ChatColor.AQUA + "HUNTERS: "+ChatColor.GREEN+ text);
}
}
return true;
}
}
| UTF-8 | Java | 3,225 | java | Hunter.java | Java | []
| null | []
| package me.mcuper.compass.commendy;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.mcuper.compass.Main;
import java.util.UUID;
public class Hunter implements CommandExecutor {
// constructor
private final Main plugin = Main.getPlugin( Main.class );
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args ) {
/*
/hunter - add a player executing that command to hunters
/hunter add <player> - add a <player> to hunters
/hunter remove <player> - remove a <player> from hunters
/hunter clear - remove all players from hunters
/hunter list - returns nicks of hunters
*/
if( cmd.getName().equalsIgnoreCase("hunter") ) {
if( !(sender instanceof Player) && args.length == 0 ) {
plugin.loger.info("Only player can use this command without arguments!");
return true;
}
Player p = (Player) sender;
UUID id = p.getUniqueId();
if( args.length == 0 ) {
if( !plugin.runners.isEmpty() && plugin.runners.contains(id) ) plugin.runners.remove(id);
plugin.hunters.add(id);
p.sendMessage(ChatColor.AQUA+"You have been succesfully added to HUNTERS");
} else if( args[0].equalsIgnoreCase("add") ) {
if( args.length < 2 ) {
p.sendMessage(ChatColor.RED+"You must specify a player nickname!");
return true;
}
UUID newHunter = plugin.getServer().getPlayer(args[1]).getUniqueId();
if( !plugin.runners.isEmpty() && plugin.runners.contains(newHunter) ) plugin.runners.remove(newHunter);
if( newHunter!=null) plugin.hunters.add(newHunter);
p.sendMessage(ChatColor.AQUA+"Succesfully added "+args[1]+" to HUNTERS.");
} else if( args[0].equalsIgnoreCase("remove") ) {
if( args.length < 2 ) {
p.sendMessage(ChatColor.RED+"You must specify a player nickname!");
return true;
}
UUID newHunter = plugin.getServer().getPlayer(args[1]).getUniqueId();
plugin.hunters.remove(newHunter);
p.sendMessage(ChatColor.AQUA+"Succesfully removed "+args[1]+" from HUNTERS.");
} else if( args[0].equalsIgnoreCase("clear") ) {
plugin.hunters.clear();
p.sendMessage(ChatColor.RED+"All hunters have been removed!");
} else if( args[0].equalsIgnoreCase("list")) {
String text = "";
if( !plugin.hunters.isEmpty() ) {
for (UUID ids : plugin.hunters) {
text += plugin.getServer().getPlayer(ids).getName() + ",";
}
}
text = text.substring(0, text.length() - 1);
p.sendMessage(ChatColor.AQUA + "HUNTERS: "+ChatColor.GREEN+ text);
}
}
return true;
}
}
| 3,225 | 0.564031 | 0.55969 | 71 | 44.422535 | 29.918982 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.549296 | false | false | 10 |
d3185622d886abb4c03fea9a5bcf1cc9737a4081 | 9,637,906,644,977 | 8162f1876540a149e3dc573e0887253eda92039c | /spider/src/main/java/com/hmmzhtx/spider/sipo/SIPOSpiderOne.java | 0ca9aab1c344082f1c235c5c6a95de6468d8b61f | []
| no_license | hmmzhtx/zhirong | https://github.com/hmmzhtx/zhirong | 9e35d76bff5951197bab85cd60828d8d5afc8270 | f651b661c27a74c0fce10f159b5763fab6b29697 | refs/heads/master | 2020-04-02T01:41:06.426000 | 2019-02-14T13:16:57 | 2019-02-14T13:16:57 | 153,869,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hmmzhtx.spider.sipo;
import com.hmmzhtx.zr_web.common.Sensitiveword.SensitivewordFilter;
import com.hmmzhtx.spider.common.RegExHtml;
import com.hmmzhtx.spider.common.UserAgentUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;
import java.util.List;
import java.util.Set;
/**
* @author huangmingming
*/
public class SIPOSpiderOne implements PageProcessor {
public static Logger logger = LoggerFactory.getLogger(SIPOSpiderOne.class);
private static final String URL_LIST = "http://www.sipo.gov.cn/zscqgz/index.htm";
public static final String HOST = "http://www.sipo.gov.cn/zscqgz/";
private Site site = Site.me()
.setCycleRetryTimes(3)
.setTimeOut(3 * 60 * 1000)
.setRetryTimes(3)
.setSleepTime(2000)
.setCharset("utf-8")
.setUserAgent(UserAgentUtils.radomUserAgent());;
@Override
public Site getSite() {
return site;
}
@Override
public void process(Page page) {
if(page.getStatusCode() == 200){
if (page.getUrl().regex(URL_LIST).match()) {
logger.info("提取List:{}",page.getUrl());
Selectable sipoParent = page.getHtml().xpath("/html/body/div/div/div/div[4]/div/div[2]/ul//li/a/text()");
List<String> title_all = sipoParent.all();
SensitivewordFilter filter = new SensitivewordFilter();
for(int i = 0;i< title_all.size();i++){
String title = title_all.get(i);
Set<String> set = filter.getSensitiveWord(title, 2);
if(set.size() > 0 ){
int n = i+1;
Selectable sipoParentHref = page.getHtml().xpath("/html/body/div/div/div/div[4]/div/div[2]/ul/li["+n+"]/a");
List<String> href_all = sipoParentHref.links().all();
System.out.println(title + "------" + href_all.get(0));
if(href_all.size() > 0){
page.addTargetRequests(href_all);
}
}
}
}else{
logger.info("提取One");
page.putField("title", page.getHtml().xpath("/html/body/div/div/div/div[3]/div[2]/div[2]/text()"));
page.putField("date", page.getHtml().xpath("/html/body/div/div/div/div[3]/div[2]/span[1]/text()"));
String html_str = String.valueOf(page.getHtml().xpath("//*[@id=\"printContent\"]/table/tbody"));
String con = RegExHtml.delHTMLTag(html_str);
page.putField("content", con);
}
}
}
/*处理文章链接*/
public static String HrefUtil(String hrefUrl){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(HOST);
stringBuffer.append(hrefUrl);
return stringBuffer.toString();
}
public static void main(String[] args) {
Spider.create(new SIPOSpiderOne())
.addUrl("http://www.sipo.gov.cn/zscqgz/1134549.htm")
.addPipeline(new SIPOPipeline())
.thread(5)
.run();
}
}
| UTF-8 | Java | 3,442 | java | SIPOSpiderOne.java | Java | [
{
"context": "a.util.List;\nimport java.util.Set;\n\n/**\n * @author huangmingming\n */\n\npublic class SIPOSpiderOne implements PagePr",
"end": 538,
"score": 0.9988332390785217,
"start": 525,
"tag": "USERNAME",
"value": "huangmingming"
}
]
| null | []
| package com.hmmzhtx.spider.sipo;
import com.hmmzhtx.zr_web.common.Sensitiveword.SensitivewordFilter;
import com.hmmzhtx.spider.common.RegExHtml;
import com.hmmzhtx.spider.common.UserAgentUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;
import java.util.List;
import java.util.Set;
/**
* @author huangmingming
*/
public class SIPOSpiderOne implements PageProcessor {
public static Logger logger = LoggerFactory.getLogger(SIPOSpiderOne.class);
private static final String URL_LIST = "http://www.sipo.gov.cn/zscqgz/index.htm";
public static final String HOST = "http://www.sipo.gov.cn/zscqgz/";
private Site site = Site.me()
.setCycleRetryTimes(3)
.setTimeOut(3 * 60 * 1000)
.setRetryTimes(3)
.setSleepTime(2000)
.setCharset("utf-8")
.setUserAgent(UserAgentUtils.radomUserAgent());;
@Override
public Site getSite() {
return site;
}
@Override
public void process(Page page) {
if(page.getStatusCode() == 200){
if (page.getUrl().regex(URL_LIST).match()) {
logger.info("提取List:{}",page.getUrl());
Selectable sipoParent = page.getHtml().xpath("/html/body/div/div/div/div[4]/div/div[2]/ul//li/a/text()");
List<String> title_all = sipoParent.all();
SensitivewordFilter filter = new SensitivewordFilter();
for(int i = 0;i< title_all.size();i++){
String title = title_all.get(i);
Set<String> set = filter.getSensitiveWord(title, 2);
if(set.size() > 0 ){
int n = i+1;
Selectable sipoParentHref = page.getHtml().xpath("/html/body/div/div/div/div[4]/div/div[2]/ul/li["+n+"]/a");
List<String> href_all = sipoParentHref.links().all();
System.out.println(title + "------" + href_all.get(0));
if(href_all.size() > 0){
page.addTargetRequests(href_all);
}
}
}
}else{
logger.info("提取One");
page.putField("title", page.getHtml().xpath("/html/body/div/div/div/div[3]/div[2]/div[2]/text()"));
page.putField("date", page.getHtml().xpath("/html/body/div/div/div/div[3]/div[2]/span[1]/text()"));
String html_str = String.valueOf(page.getHtml().xpath("//*[@id=\"printContent\"]/table/tbody"));
String con = RegExHtml.delHTMLTag(html_str);
page.putField("content", con);
}
}
}
/*处理文章链接*/
public static String HrefUtil(String hrefUrl){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(HOST);
stringBuffer.append(hrefUrl);
return stringBuffer.toString();
}
public static void main(String[] args) {
Spider.create(new SIPOSpiderOne())
.addUrl("http://www.sipo.gov.cn/zscqgz/1134549.htm")
.addPipeline(new SIPOPipeline())
.thread(5)
.run();
}
}
| 3,442 | 0.571345 | 0.558772 | 97 | 34.257732 | 30.836542 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.494845 | false | false | 10 |
a6d071a6aa4cc0dfb4bbf898bdf0f38631ae7842 | 11,398,843,235,148 | 839f7f2157c02fdf5638d1b8fa9f05a8565a9da7 | /src/ISOTOPEDISTRIBUTION/MS1/CalculateDegradedPeptideIsotopePattern.java | bfd8f58ed9357275cd3a7632bd6d145218813c6b | []
| no_license | gatechatl/MaSpecTOR | https://github.com/gatechatl/MaSpecTOR | 61c7007d1365b38c7394dbfb3ac97a944b797a6b | ef0a2a776ee19c6efd60c90df5c2cad4ee310f13 | refs/heads/master | 2020-04-14T22:12:13.775000 | 2016-09-13T16:30:22 | 2016-09-13T16:30:22 | 68,126,098 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ISOTOPEDISTRIBUTION.MS1;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import org.openscience.cdk.formula.IsotopeContainer;
import org.openscience.cdk.formula.IsotopePattern;
import org.openscience.cdk.formula.IsotopePatternManipulator;
import ISOTOPEDISTRIBUTION.IsotopeCalculator;
import MISC.ToolBox;
/**
* calculates the isotope pattern
* @author tshaw
*
*/
public class CalculateDegradedPeptideIsotopePattern {
/*public static double A = -1;
public static double A_freq = -1;
public static double B = -1;
public static double B_freq = -1;
public static double C = -1;
public static double C_freq = -1;
public static int C_num = 0;
public static int H_num = 0;
public static int N_num = 0;
public static int S_num = 0;
public static int O_num = 0;
public static int P_num = 0;
*/
public static double C12 = 0.9893;
public static double N14 = 0.99632;
public static double H1 = 0.999885;
public static Random rand = new Random();
public static void execute(String[] args) {
try {
//String outputFile = "C:\\Users\\tshaw\\Desktop\\PROTEOMICS\\PeptideSimulation\\simulation.txt";
int i = 0;
String inputFile = args[0];
String outputFile = args[1];
String type = args[2];
FileWriter fwriter = new FileWriter(outputFile);
BufferedWriter out = new BufferedWriter(fwriter);
LinkedList list = readPeptideList(inputFile);
Iterator itr = list.iterator();
while (itr.hasNext()) {
//String peptideFormula = generateRandPeptide(i);
String peptideFormula = (String)itr.next();
i++;
String chemFormula = peptide2formula(peptideFormula);
int number_of_carbons = ToolBox.retrieve_num_element(chemFormula, "C");
int number_of_oxygen = ToolBox.retrieve_num_element(chemFormula, "O");
int number_of_nitrogen = ToolBox.retrieve_num_element(chemFormula, "N");
//System.out.println(peptideFormula + "\t" + chemFormula);
if (type.equals("TMT")) {
chemFormula += "C8H20Ci4N1Nm1O2";
}
IsotopePattern pattern = IsotopeCalculator.calculate_pattern(chemFormula, 50, C12, H1, N14, 1);
double highestMass = getMassOfHighestPeak(pattern);
double firstMass = getFirstMass(pattern);
double highestIntensity = getIntensityOfHighestPeak(pattern);
double firstIntensity = getFirstIntensity(pattern);
/*for (int k = 0; k < pattern.getNumberOfIsotopes(); k++) {
IsotopeContainer container = pattern.getIsotope(k);
out2.write(container.getMass() + "\t" + container.getIntensity() + "\t" + new Double(highestMass - firstMass).intValue() + "\n");
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}*/
String stuff = i + "\t" + firstIntensity + "\t" + highestIntensity + "\t" + (highestIntensity / firstIntensity)
+ "\t" + firstMass + "\t" + highestMass + "\t" + new Double(highestMass - firstMass).intValue() + "\t" + peptideFormula + "\t"
+ chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
+ "\t" + number_of_nitrogen + "\t" + (number_of_carbons + number_of_oxygen) + "\t"
+ (number_of_carbons + number_of_nitrogen) + "\t" + (number_of_carbons + number_of_oxygen + number_of_nitrogen) + "\t" + getStrIsotope(pattern);
//System.out.println(firstMass + "\t" + highestMass + "\t" + (highestMass - firstMass) + "\t" + peptideFormula + "\t"
// + chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
// + "\t" + number_of_nitrogen + "\t" + getStrIsotope(pattern));
out.write(stuff + "\n");
if (i % 1000 == 0) {
out.flush();
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//String outputFile = "C:\\Users\\tshaw\\Desktop\\PROTEOMICS\\PeptideSimulation\\simulation.txt";
int i = 0;
String inputFile = args[0];
String outputFile = args[1];
FileWriter fwriter = new FileWriter(outputFile);
BufferedWriter out = new BufferedWriter(fwriter);
LinkedList list = readPeptideList(inputFile);
Iterator itr = list.iterator();
while (itr.hasNext()) {
//String peptideFormula = generateRandPeptide(i);
String peptideFormula = (String)itr.next();
i++;
String chemFormula = peptide2formula(peptideFormula);
int number_of_carbons = ToolBox.retrieve_num_element(chemFormula, "C");
int number_of_oxygen = ToolBox.retrieve_num_element(chemFormula, "O");
int number_of_nitrogen = ToolBox.retrieve_num_element(chemFormula, "N");
//System.out.println(peptideFormula + "\t" + chemFormula);
IsotopePattern pattern = IsotopeCalculator.calculate_pattern(chemFormula, 50, C12, H1, N14, 1);
double highestMass = getMassOfHighestPeak(pattern);
double firstMass = getFirstMass(pattern);
double highestIntensity = getIntensityOfHighestPeak(pattern);
double firstIntensity = getFirstIntensity(pattern);
/*for (int k = 0; k < pattern.getNumberOfIsotopes(); k++) {
IsotopeContainer container = pattern.getIsotope(k);
out2.write(container.getMass() + "\t" + container.getIntensity() + "\t" + new Double(highestMass - firstMass).intValue() + "\n");
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}*/
String stuff = i + "\t" + firstIntensity + "\t" + highestIntensity + "\t" + (highestIntensity / firstIntensity)
+ "\t" + firstMass + "\t" + highestMass + "\t" + new Double(highestMass - firstMass).intValue() + "\t" + peptideFormula + "\t"
+ chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
+ "\t" + number_of_nitrogen + "\t" + (number_of_carbons + number_of_oxygen) + "\t"
+ (number_of_carbons + number_of_nitrogen) + "\t" + (number_of_carbons + number_of_oxygen + number_of_nitrogen) + "\t" + getStrIsotope(pattern);
//System.out.println(firstMass + "\t" + highestMass + "\t" + (highestMass - firstMass) + "\t" + peptideFormula + "\t"
// + chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
// + "\t" + number_of_nitrogen + "\t" + getStrIsotope(pattern));
out.write(stuff + "\n");
if (i % 1000 == 0) {
out.flush();
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static LinkedList readPeptideList(String fileName) {
LinkedList list = new LinkedList();
try {
String seq = "";
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream din = new DataInputStream(fstream);
BufferedReader in = new BufferedReader(new InputStreamReader(din));
while (in.ready()) {
String str = in.readLine();
list.add(str);
}
in.close();
list.add(seq);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static double getFirstMass(IsotopePattern pattern) {
IsotopeContainer container = pattern.getIsotope(0);
return container.getMass();
}
public static double getMassOfHighestPeak(IsotopePattern pattern) {
String returnStr = pattern.getNumberOfIsotopes() + "";
double max_intensity = -1;
double max_mass = -1;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (max_intensity < container.getIntensity()) {
max_intensity = container.getIntensity();
max_mass = container.getMass();
}
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}
return max_mass;
}
public static double getFirstIntensity(IsotopePattern pattern) {
IsotopeContainer container = pattern.getIsotope(0);
return container.getIntensity();
}
public static double getIntensityOfHighestPeak(IsotopePattern pattern) {
String returnStr = pattern.getNumberOfIsotopes() + "";
double max_intensity = -1;
double max_mass = -1;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (max_intensity < container.getIntensity()) {
max_intensity = container.getIntensity();
max_mass = container.getMass();
}
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}
return max_intensity;
}
public static String getStrIsotope(IsotopePattern pattern) {
int countNumIsotopes = 0;
double cutoff = 0.00001;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (container.getIntensity() > cutoff) {
countNumIsotopes++;
}
}
String returnStr = countNumIsotopes + "";
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (container.getIntensity() > cutoff) {
if (returnStr.equals("")) {
returnStr += container.getMass() + ":" + container.getIntensity();
} else {
returnStr += "," + container.getMass() + ":" + container.getIntensity();
}
}
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}
return returnStr;
}
public static String peptide2formula(String str) {
str = str.replaceAll("FORMULA", "").trim();
str = str.replaceAll("=", "").trim();
MOLECULE mol = new MOLECULE();
// Grab Alanine A
int num = ToolBox.retrieve_num_element(str, "A");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("A"));
}
// Grab Arginine R
num = ToolBox.retrieve_num_element(str, "R");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("R"));
}
// Grab Asaparagine N
num = ToolBox.retrieve_num_element(str, "N");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("N"));
}
// Grab Aspartic acid D
num = ToolBox.retrieve_num_element(str, "D");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("D"));
}
// Grab Cysteine C
num = ToolBox.retrieve_num_element(str, "C");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("C"));
}
// Grab Glutamine Q
num = ToolBox.retrieve_num_element(str, "Q");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("Q"));
}
// Grab Glutamic acid E
num = ToolBox.retrieve_num_element(str, "E");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("E"));
}
// Grab Glycine G
num = ToolBox.retrieve_num_element(str, "G");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("G"));
}
// Grab Histidine H
num = ToolBox.retrieve_num_element(str, "H");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("H"));
}
// Grab Isoleucine I
num = ToolBox.retrieve_num_element(str, "I");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("I"));
}
// Grab Leucine L
num = ToolBox.retrieve_num_element(str, "L");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("L"));
}
// Grab Lysine K
num = ToolBox.retrieve_num_element(str, "K");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("K"));
}
// Grab Methionine M
num = ToolBox.retrieve_num_element(str, "M");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("M"));
}
// Grab Phenylalanine F
num = ToolBox.retrieve_num_element(str, "F");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("F"));
}
// Grab Proline P
num = ToolBox.retrieve_num_element(str, "P");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("P"));
}
// Grab Serine S
num = ToolBox.retrieve_num_element(str, "S");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("S"));
}
// Grab Threonine T
num = ToolBox.retrieve_num_element(str, "T");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("T"));
}
// Grab Tryptophan W
num = ToolBox.retrieve_num_element(str, "W");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("W"));
}
// Grab Tyrosine Y
num = ToolBox.retrieve_num_element(str, "Y");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("Y"));
}
// Grab Valine V
num = ToolBox.retrieve_num_element(str, "V");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("V"));
}
// add an additional of OH group to the concatenated residues.
mol.O++;
mol.H++;
String finalStr = "";
if (mol.C > 0) {
finalStr += "C" + mol.C;
}
if (mol.H > 0) {
finalStr += "H" + (new Integer(mol.H) + 1);
}
if (mol.N > 0) {
finalStr += "N" + mol.N;
}
if (mol.O > 0) {
finalStr += "O" + mol.O;
}
if (mol.S > 0) {
finalStr += "S" + mol.S;
}
return finalStr;
/*C_num = mol.C;
H_num = mol.H;
N_num = mol.N;
O_num = mol.O;
S_num = mol.S;*/
}
public static MOLECULE concatenate_molecule(MOLECULE mol1, MOLECULE mol2) {
MOLECULE final_mol = new MOLECULE();
final_mol.C = mol1.C + mol2.C;
final_mol.H = mol1.H + mol2.H;
final_mol.N = mol1.N + mol2.N;
final_mol.S = mol1.S + mol2.S;
final_mol.O = mol1.O + mol2.O;
return final_mol;
}
/**
* data class for molecule/peptide
*/
static class MOLECULE {
public int C = 0;
public int H = 0;
public int N = 0;
public int S = 0;
public int O = 0;
public String getFormula() {
String formula = "";
if (C > 0) {
formula += "C" + C;
}
if (H > 0) {
formula += "H" + H;
}
if (N > 0) {
formula += "N" + N;
}
if (S > 0) {
formula += "S" + S;
}
if (O > 0) {
formula += "O" + O;
}
return formula;
}
}
/**
* Formula conversion based on
* http://www.imgt.org/IMGTeducation/Aide-memoire/_UK/aminoacids/formuleAA/
* @param aa
* @return
*/
public static MOLECULE ConvertAAtoFormula(String aa) {
MOLECULE mol = new MOLECULE();
if (aa.equals("A")) {
//C3H7NO2
mol.C += 3;
mol.H += 5;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("R")) {
//C6H14N4O2
mol.C += 6;
mol.H += 12;
mol.N += 4;
mol.O += 1;
}
if (aa.equals("N")) {
//C4H8N2O3
mol.C += 4;
mol.H += 6;
mol.N += 2;
mol.O += 2;
}
if (aa.equals("D")) {
//C4H7NO4
mol.C += 4;
mol.H += 5;
mol.N += 1;
mol.O += 3;
}
if (aa.equals("C")) {
//C3H7NO2S
mol.C += 3;
mol.H += 5;
mol.N += 1;
mol.O += 1;
mol.S += 1;
}
if (aa.equals("Q")) {
//C5H10N2O3
mol.C += 5;
mol.H += 8;
mol.N += 2;
mol.O += 2;
}
if (aa.equals("E")) {
//C5H9NO4
mol.C += 5;
mol.H += 7;
mol.N += 1;
mol.O += 3;
}
if (aa.equals("G")) {
//C2H5NO2
mol.C += 2;
mol.H += 3;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("H")) {
//C6H9N3O2
mol.C += 6;
mol.H += 7;
mol.N += 3;
mol.O += 1;
}
if (aa.equals("I") || aa.equals("L")) {
//C6H13NO2
mol.C += 6;
mol.H += 11;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("K")) {
//C6H14N2O2
mol.C += 6;
mol.H += 12;
mol.N += 2;
mol.O += 1;
}
if (aa.equals("M")) {
//C5H11NO2S
mol.C += 5;
mol.H += 9;
mol.N += 1;
mol.O += 1;
mol.S += 1;
}
if (aa.equals("F")) {
//C9H11NO2
mol.C += 9;
mol.H += 9;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("P")) {
//C5H9NO2
mol.C += 5;
mol.H += 7;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("S")) {
//C3H7NO3
mol.C += 3;
mol.H += 5;
mol.N += 1;
mol.O += 2;
}
if (aa.equals("T")) {
//C4H9NO3
mol.C += 4;
mol.H += 7;
mol.N += 1;
mol.O += 2;
}
if (aa.equals("W")) {
//C11H12N2O2
mol.C += 11;
mol.H += 10;
mol.N += 2;
mol.O += 1;
}
if (aa.equals("Y")) {
//C9H11NO3
mol.C += 9;
mol.H += 9;
mol.N += 1;
mol.O += 2;
}
if (aa.equals("V")) {
//C5H11NO2
mol.C += 5;
mol.H += 9;
mol.N += 1;
mol.O += 1;
}
return mol;
}
public static String generateRandPeptide(int size) {
String result = "";
HashMap map = new HashMap();
for (int i = 0; i < size; i++) {
int n = rand.nextInt(20);
//System.out.println(n);
String aa = convertInt2AA(n);
if (map.containsKey(aa)) {
int num = (Integer)map.get(aa);
num++;
map.put(aa, num);
} else {
map.put(aa, 1);
}
}
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String key = (String)itr.next();
int num = (Integer)map.get(key);
result += key + num;
}
return result;
}
public static String convertInt2AA(int num) {
String result = "";
switch (num) {
case 0:
result = "R";
break;
case 1:
result = "H";
break;
case 2:
result = "K";
break;
case 3:
result = "D";
break;
case 4:
result = "E";
break;
case 5:
result = "S";
break;
case 6:
result = "T";
break;
case 7:
result = "N";
break;
case 8:
result = "Q";
break;
case 9:
result = "C";
break;
case 10:
result = "G";
break;
case 11:
result = "P";
break;
case 12:
result = "A";
break;
case 13:
result = "V";
break;
case 14:
result = "I";
break;
case 15:
result = "L";
break;
case 16:
result = "M";
break;
case 17:
result = "F";
break;
case 18:
result = "Y";
break;
case 19:
result = "W";
break;
case 20:
result = "U";
break;
}
return result;
}
public static BIGNUM cutoff = new BIGNUM(1, -50);
/**
* Calculate the pattern for a formula
* @param C12
* @param N14
* @param H1
* @return
*/
/*public static IsotopePattern calculate_pattern(String formula, int charge) {
C_num = retrieve_num_element(formula, "C");
H_num = retrieve_num_element(formula, "H");
N_num = retrieve_num_element(formula, "N");
O_num = retrieve_num_element(formula, "O");
S_num = retrieve_num_element(formula, "S");
P_num = retrieve_num_element(formula, "P");
double C12 = 0.9893;
double N14 = 0.99632;
double H1 = 0.999885;
LinkedList ini_list = create_ini_list(C12, N14, H1);
LinkedList listC = preload_ini_file(ini_list, "C");
LinkedList listH = preload_ini_file(ini_list, "H");
LinkedList listN = preload_ini_file(ini_list, "N");
LinkedList listS = preload_ini_file(ini_list, "S");
LinkedList listO = preload_ini_file(ini_list, "O");
LinkedList listP = preload_ini_file(ini_list, "P");
// possibly the following line might be causing trouble
boolean tolerance_type = true;
double ppm_val = 50;
listC = merge_mass_tolerance(listC, tolerance_type, ppm_val);
listH = merge_mass_tolerance(listH, tolerance_type, ppm_val);
listN = merge_mass_tolerance(listN, tolerance_type, ppm_val);
listS = merge_mass_tolerance(listS, tolerance_type, ppm_val);
listO = merge_mass_tolerance(listO, tolerance_type, ppm_val);
listP = merge_mass_tolerance(listP, tolerance_type, ppm_val);
boolean ppm = true;
//System.out.println(C_num + "\t" + H_num + "\t" + N_num + "\t" + O_num + "\t" + S_num + "\t" + P_num);
//write_example(list, path, 1);
LinkedList newList = new LinkedList();
for (int i = 0; i < C_num; i++) {
if (newList.size() == 0) {
newList = listC;
} else {
newList = MergeList(newList, listC);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < H_num; i++) {
if (newList.size() == 0) {
newList = listH;
} else {
newList = MergeList(newList, listH);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < N_num; i++) {
if (newList.size() == 0) {
newList = listN;
} else {
newList = MergeList(newList, listN);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < S_num; i++) {
if (newList.size() == 0) {
newList = listS;
} else {
newList = MergeList(newList, listS);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < O_num; i++) {
if (newList.size() == 0) {
newList = listO;
} else {
newList = MergeList(newList, listO);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < P_num; i++) {
if (newList.size() == 0) {
newList = listP;
} else {
newList = MergeList(newList, listP);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
//print_list(newList);
IsotopePattern query_pattern = convert_Compounds2IsotopePattern(newList, -1, charge);
return query_pattern;
}*/
/*public static LinkedList create_ini_list(double C12, double N14, double H1) {
LinkedList list = new LinkedList();
list.add("C: 12," + C12);
list.add("C: 13.0033548378," + (1 - C12));
list.add("H: 1.0078250321," + H1);
list.add("H: 2.0141017780," + (1 - H1));
list.add("N: 14.0030740052," + N14);
list.add("N: 15.0001088984," + (1 - N14));
list.add("O: 15.9949146221,0.99757");
list.add("O: 16.99913150,0.00038");
list.add("O: 17.9991604,0.00205");
list.add("S: 31.97207069,0.9493");
list.add("S: 32.97145850,0.0076");
list.add("S: 33.96786683,0.0429");
list.add("P: 30.97376151,1.0");
return list;
}*/
/**
* Subtract two bignum
* subtract bn2 from bn1
*/
public static BIGNUM subtract(BIGNUM bn1, BIGNUM bn2) {
BIGNUM newbn = new BIGNUM(-bn2.NUM, bn2.E);
return add(bn1, newbn);
}
/**
* ADD two big num
* If the factor between the two number is greater than 52 then just return the larger number
* @param bn1
* @param bn2
* @return
*/
public static BIGNUM add(BIGNUM bn1, BIGNUM bn2) {
int diff = 0;
double COMB = 0;
double newE = 0;
if (bn1.E > bn2.E) {
double factor = bn1.E - bn2.E;
if (factor > 52 ) {
return bn1;
}
COMB = bn1.NUM + bn2.NUM / Math.pow(10, factor);
newE = bn1.E;
} else {
double factor = bn2.E - bn1.E;
if (factor > 52 ) {
return bn2;
}
COMB = bn2.NUM + bn1.NUM / Math.pow(10, factor);
newE = bn2.E;
}
BIGNUM result = new BIGNUM(COMB, newE);
return result;
}
/**
* Merge Resolution
* @param mass1 other mass
* @param mass2 theoretical mass
* @param ppm_cutoff
* @return
*/
public static boolean within_distance(BIGNUM mass1, BIGNUM mass2, BIGNUM ppm_cutoff) {
BIGNUM million = new BIGNUM(1e6);
BIGNUM difference;
if (isGreater(mass1, mass2)) {
difference = subtract(mass1, mass2);
} else {
difference = subtract(mass2, mass1);
}
//System.out.println(mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString());
if (isGreater(ppm_cutoff, difference)) {
//System.out.println("Is greater: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return true;
}
//System.out.println("Is smaller: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return false;
}
public static BIGNUM total_val(int N, int M) {
BIGNUM val = new BIGNUM(0.0);
for (int i = 0; i <= M; i++) {
val = add(val, calc_N_choose_M(N, i));
}
return val;
}
public static BIGNUM calc_N_choose_M(int N, int M) {
BIGNUM top = new BIGNUM(new Double(N));
BIGNUM bottom = new BIGNUM(1.0);
if (M == 0) {
return new BIGNUM(1.0);
}
for (int j = 1; j <= M; j++) {
bottom = multiply(bottom, new BIGNUM(new Double(j)));
}
for (int j = 1; j < M; j++) {
top = multiply(top, new BIGNUM(new Double(N - j)));
}
return divide(top, bottom);
}
/**
* Dividing two big num
* @param bn1
* @param bn2
* @return
*/
public static BIGNUM divide(BIGNUM bn1, BIGNUM bn2) {
double divide = bn1.NUM / bn2.NUM;
double newE = bn1.E - bn2.E;
//System.out.println("divide function: " + multiply + "\t" + newE);
BIGNUM result = new BIGNUM(divide, newE);
return result;
}
/**
* Multiplying two big num
* @param bn1
* @param bn2
* @return
*/
public static BIGNUM multiply(BIGNUM bn1, BIGNUM bn2) {
double multiply = bn1.NUM * bn2.NUM;
double newE = bn1.E + bn2.E;
//System.out.println("multiply function: " + multiply + "\t" + newE);
BIGNUM result = new BIGNUM(multiply, newE);
return result;
}
/**
* Test if first number is larger than second number
* @param num
* @param num2
* @return
*/
public static boolean isGreater(BIGNUM num, BIGNUM num2) {
if (num.E > num2.E) {
return true;
} else if (num.E == num2.E) {
if (num.NUM > num2.NUM) {
return true;
}
}
return false;
}
/**
* PPM = 1E6 * (Mass1 - Mass2) / Mass2
* @param mass1 other mass
* @param mass2 theoretical mass
* @param ppm_cutoff
* @return
*/
public static boolean check_within_ppm(BIGNUM mass1, BIGNUM mass2, BIGNUM ppm_cutoff) {
BIGNUM million = new BIGNUM(1e6);
BIGNUM difference;
if (isGreater(mass1, mass2)) {
difference = subtract(mass1, mass2);
} else {
difference = subtract(mass2, mass1);
}
BIGNUM ppm = divide(multiply(million, difference), divide(add(mass2, mass1), new BIGNUM(2)));
//System.out.println(mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString());
if (isGreater(ppm_cutoff, ppm)) {
//System.out.println("Is greater: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return true;
}
//System.out.println("Is smaller: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return false;
}
/*public static COMPOUND merge_compound(COMPOUND compound_A, COMPOUND compound_B) {
COMPOUND new_compound = new COMPOUND();
//System.out.println(compound_A.TYPE + "\t" + compound_B.TYPE);
if (compound_A.TYPE.equals(compound_B.TYPE)) {
new_compound.PROB = multiply(compound_A.PROB, compound_B.PROB);
new_compound.SIZE = compound_A.SIZE + compound_B.SIZE;
//new_compound.NUM_ISOTOPE = compound_A.NUM_ISOTOPE + compound_B.NUM_ISOTOPE;
new_compound.TYPE1 = compound_A.TYPE1 + compound_B.TYPE1;
new_compound.TYPE2 = compound_A.TYPE2 + compound_B.TYPE2;
new_compound.TYPE3 = compound_A.TYPE3 + compound_B.TYPE3;
new_compound.FREQ = multiply(compound_A.FREQ, compound_B.FREQ); //calc_N_choose_M(new_compound.SIZE, new_compound.NUM_ISOTOPE);
new_compound.TYPE = compound_A.TYPE;
new_compound.MASS = add(compound_A.MASS, compound_B.MASS);
//new_compound.TOTALPROB = multiply(new_compound.FREQ, new_compound.PROB);
new_compound.TOTALPROB = multiply(compound_A.TOTALPROB, compound_B.TOTALPROB);
}
return new_compound;
}*/
public static COMPOUND merge_compound(COMPOUND compound_A, COMPOUND compound_B) {
COMPOUND new_compound = new COMPOUND();
new_compound.NUM_ISOTOPE = compound_A.NUM_ISOTOPE + compound_B.NUM_ISOTOPE;
new_compound.SIZE = compound_A.SIZE + compound_B.SIZE;
new_compound.MASS = add(compound_A.MASS, compound_B.MASS);
new_compound.TOTALPROB = multiply(compound_A.TOTALPROB, compound_B.TOTALPROB);
return new_compound;
}
/**
* Merging two different elements and return a merged list
* @param element_A
* @param element_B
* @return
*/
public static LinkedList MergeList(LinkedList element_A, LinkedList element_B) {
LinkedList merged = new LinkedList();
if (element_B.size() == 0) {
return element_A;
}
if (element_A.size() == 0) {
return element_B;
}
Iterator itr = element_A.iterator();
while (itr.hasNext()) {
COMPOUND compound_A = (COMPOUND)itr.next();
Iterator itr2 = element_B.iterator();
while (itr2.hasNext()) {
COMPOUND compound_B = (COMPOUND)itr2.next();
COMPOUND new_compound = merge_compound(compound_A, compound_B);
// add whether to save this value
if (isGreater(new_compound.TOTALPROB, cutoff)) {
merged.add(new_compound);
}
}
}
return merged;
}
/**
* Merge the compound based on the mass tolerance
* @param list
* @param ppm_cutoff
* @return
*/
public static LinkedList merge_mass_tolerance(LinkedList list, boolean ppm, double ppm_val) {
HashMap final_map = new HashMap();
LinkedList mass_list = new LinkedList();
LinkedList final_list = new LinkedList();
Iterator itr = list.iterator();
while (itr.hasNext()) {
COMPOUND compound1 = (COMPOUND)itr.next();
double mass = compound1.MASS.NUM * Math.pow(10, compound1.MASS.E);
if (final_map.containsKey(mass)) {
COMPOUND old = (COMPOUND)final_map.get(mass);
//System.out.println("Merge1: " + compound1.TOTALPROB + "\t" + old.TOTALPROB);
compound1.TOTALPROB = add(compound1.TOTALPROB, old.TOTALPROB);
final_map.put(mass, compound1);
} else {
final_map.put(mass, compound1);
mass_list.add(mass);
}
}
double[] double_list = new double[mass_list.size()];
int i = 0;
itr = mass_list.iterator();
while (itr.hasNext()) {
double mass = (Double)itr.next();
double_list[i] = mass;
i++;
}
Arrays.sort(double_list);
//System.out.println(double_list.length);
//final_map.clear();
double mass1 = double_list[0];;
for (i = 1 ;i < double_list.length; i++) {
double mass2 = double_list[i];
COMPOUND compound1 = (COMPOUND)final_map.get(mass1);
COMPOUND compound2 = (COMPOUND)final_map.get(mass2);
boolean update = false;
if (ppm) {
//System.out.println(mass1 + "\t" + mass2);
//if (check_within_ppm(compound1.MASS, compound2.MASS, new BIGNUM(10))) {
if (check_within_ppm(compound1.MASS, compound2.MASS, new BIGNUM(ppm_val))) {
update = true;
if (isGreater(compound1.TOTALPROB, compound2.TOTALPROB)) {
//System.out.println("Merge2: " + compound1.TOTALPROB.getString() + "\t" + compound2.TOTALPROB.getString());
compound1.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass2);
final_map.put(mass1, compound1);
mass1 = mass1;
} else {
compound2.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass1);
final_map.put(mass2, compound2);
mass1 = mass2;
}
} else {
//System.out.println(mass1 + "\t" + mass2);
}
} else {
//if (within_distance(compound1.MASS, compound2.MASS, new BIGNUM(0.1))) {
if (within_distance(compound1.MASS, compound2.MASS, new BIGNUM(ppm_val))) {
update = true;
if (isGreater(compound1.TOTALPROB, compound2.TOTALPROB)) {
//System.out.println("Merge2: " + compound1.TOTALPROB.getString() + "\t" + compound2.TOTALPROB.getString());
compound1.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass2);
final_map.put(mass1, compound1);
mass1 = mass1;
} else {
compound2.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass1);
final_map.put(mass2, compound2);
mass1 = mass2;
}
//System.out.println("Merge2: " + compound1.TOTALPROB.getString() + "\t" + compound2.TOTALPROB.getString());
} else {
//System.out.println(mass1 + "\t" + mass2);
}
}
if (!update) {
mass1 = mass2;
}
}
//System.out.println(final_map.size());
i = 0;
double_list = new double[final_map.size()];
itr = final_map.keySet().iterator();
while (itr.hasNext()) {
double mass = (Double)itr.next();
double_list[i] = mass;
i++;
}
Arrays.sort(double_list);
for (double mass: double_list) {
final_list.add(final_map.get(mass));
}
return final_list;
}
/**
*
* @param fileName
* @param chem
* @return
*/
public static LinkedList preload_ini_file(LinkedList list, String chem) {
LinkedList isotope_list = new LinkedList();
try {
int C_ID = 0;
int H_ID = 0;
int N_ID = 0;
int S_ID = 0;
int O_ID = 0;
int P_ID = 0;
Iterator itr = list.iterator();
while (itr.hasNext()) {
String str = (String)itr.next();
if (str.startsWith("C:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("C:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "C";
compound.SETTYPE(C_ID);
//compound.TYPE2 = C_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
C_ID++;
isotope_list.add(compound);
}
if (str.startsWith("H:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("H:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "H";
compound.SETTYPE(H_ID);
//compound.TYPE2 = H_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
H_ID++;
isotope_list.add(compound);
}
if (str.startsWith("N:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("N:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "N";
compound.SETTYPE(N_ID);
//compound.TYPE2 = N_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
N_ID++;
isotope_list.add(compound);
}
if (str.startsWith("O:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("O:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "O";
compound.SETTYPE(O_ID);
//compound.TYPE2 = O_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
O_ID++;
isotope_list.add(compound);
}
if (str.startsWith("S:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("S:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "S";
compound.SETTYPE(S_ID);
//compound.TYPE2 = S_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
S_ID++;
isotope_list.add(compound);
}
if (str.startsWith("P:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("P:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "P";
compound.SETTYPE(S_ID);
//compound.TYPE2 = S_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
P_ID++;
isotope_list.add(compound);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return isotope_list;
}
/**
* Convert a linkedlist of compound and output Isotopic Pattern
* @param list
*/
public static IsotopePattern convert_Compounds2IsotopePattern(LinkedList list, int top, int charge) {
if (top <= 0) {
top = list.size();
}
int count = 0;
double[] intensities = new double[list.size()];
Iterator itr = list.iterator();
while (itr.hasNext()) {
COMPOUND compound = (COMPOUND)itr.next();
double mass = compound.MASS.toDouble();
double intensity = compound.TOTALPROB.toDouble();
intensities[count] = intensity;
//System.out.println(mass + "\t" + intensity);
count++;
}
/*
Arrays.sort(intensities);
for (double intensity: intensities) {
System.out.println(intensity);
}
*/
count = 0;
IsotopePattern pattern = new IsotopePattern();
itr = list.iterator();
while (itr.hasNext()) {
COMPOUND compound = (COMPOUND)itr.next();
if (count < top) {
double mass = compound.MASS.toDouble();
double intensity = compound.TOTALPROB.toDouble();
//mass = (mass / charge + charge * 1.007825);
mass = (mass / charge + 1.007825);
pattern.addIsotope(new IsotopeContainer(mass, intensity));
//System.out.println(mass + "\t" + intensity);
}
count++;
}
return pattern;
}
/**
* A Class for storing compound information
* @author tshaw
*
*/
static class COMPOUND {
public String TYPE = "";
public int TYPE1 = 0; // isotope cumulative types
public int TYPE2 = 0; // isotope cumulative types
public int TYPE3 = 0; // isotope cumulative types
public int TYPE4 = 0; // isotope cumulative types
public int TYPE5 = 0; // isotope cumulative types
public BIGNUM MASS = new BIGNUM(0.0);
public BIGNUM PROB = new BIGNUM(0.0);
public BIGNUM FREQ = new BIGNUM(0.0);
public BIGNUM TOTALPROB = new BIGNUM(0.0);
public int NUM_ISOTOPE = 0; // the number of isotopes
public int SIZE = 0;
public void SETTYPE(int ID) {
if (ID == 0) {
TYPE1 = 1;
}
if (ID == 1) {
TYPE2 = 1;
}
if (ID == 2) {
TYPE3 = 1;
}
if (ID == 3) {
TYPE4 = 1;
}
if (ID == 4) {
TYPE5 = 1;
}
}
}
/**
* Parsing the string and retrieve the number of elements
* @param str
* @param query_element
* @return
*/
/*public static int retrieve_num_element(String str, String query_element) {
int total = 0;
int str_index = str.indexOf(query_element);
for (int i = 0; i < str.length(); i++) {
if (str.substring(i, i + 1).equals(query_element)) {
int value = 0;
String num_str = "";
for (int j = i + 1; j < str.length(); j++) {
if (str.substring(j, j + 1).matches("[0-9]")) {
num_str += str.substring(j, j + 1);
value = new Integer(num_str);
} else {
if (value == 0) {
value = 1;
}
break;
}
}
if (i == str.length() - 1) {
value = 1;
}
total += value;
}
}
return total;
}*/
/**
* A Class for storing large numbers;
* @author tshaw
*
*/
static class BIGNUM {
public double NUM = 0;
public double E = 0;
public String getString() {
return (new Double(NUM).toString() + "E" + new Integer((int)E).toString());
}
public double toDouble() {
return new Double(this.getString());
}
public BIGNUM(double newNUM, double newE) {
NUM = newNUM;
E = newE;
double value = newNUM;
if (value >= 1) {
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
}
public BIGNUM(String value2) {
//System.out.println(value);
if (value2.contains("E")) {
String[] split = value2.split("E");
NUM = new Double(split[0]);
E = new Double(split[1]);
double value = new Double(split[0]);
if (value >= 1) {
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
} else {
double value = new Double(value2);
NUM = new Double(value);
if (value >= 1) {
E = 0;
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
}
}
public BIGNUM(double value) {
//System.out.println(value);
NUM = value;
if (value >= 1) {
E = 0;
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
}
}
}
| UTF-8 | Java | 41,462 | java | CalculateDegradedPeptideIsotopePattern.java | Java | [
{
"context": "\n\n/**\n * calculates the isotope pattern\n * @author tshaw\n *\n */\npublic class CalculateDegradedPeptideIsoto",
"end": 727,
"score": 0.9995821118354797,
"start": 722,
"tag": "USERNAME",
"value": "tshaw"
},
{
"context": "y {\n\t\t\t\n\n\t\t\t\n\t\t\t//String outputFile = \"C:\\\\Users\\\\tshaw\\\\Desktop\\\\PROTEOMICS\\\\PeptideSimulation\\\\simulati",
"end": 1436,
"score": 0.9896368384361267,
"start": 1431,
"tag": "USERNAME",
"value": "tshaw"
},
{
"context": "\n\t\ttry {\n\t\t\t\n\t\t\t//String outputFile = \"C:\\\\Users\\\\tshaw\\\\Desktop\\\\PROTEOMICS\\\\PeptideSimulation\\\\simulati",
"end": 4168,
"score": 0.9902482032775879,
"start": 4163,
"tag": "USERNAME",
"value": "tshaw"
},
{
"context": "Class for storing compound information\n\t * @author tshaw\n\t * \n\t */\n\tstatic class COMPOUND {\n\t\tpublic Strin",
"end": 37428,
"score": 0.9995779395103455,
"start": 37423,
"tag": "USERNAME",
"value": "tshaw"
},
{
"context": "\t * A Class for storing large numbers;\n\t * @author tshaw\n\t *\n\t */\n\tstatic class BIGNUM {\n\t\t\n\t\tpublic doubl",
"end": 39089,
"score": 0.999579906463623,
"start": 39084,
"tag": "USERNAME",
"value": "tshaw"
}
]
| null | []
| package ISOTOPEDISTRIBUTION.MS1;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import org.openscience.cdk.formula.IsotopeContainer;
import org.openscience.cdk.formula.IsotopePattern;
import org.openscience.cdk.formula.IsotopePatternManipulator;
import ISOTOPEDISTRIBUTION.IsotopeCalculator;
import MISC.ToolBox;
/**
* calculates the isotope pattern
* @author tshaw
*
*/
public class CalculateDegradedPeptideIsotopePattern {
/*public static double A = -1;
public static double A_freq = -1;
public static double B = -1;
public static double B_freq = -1;
public static double C = -1;
public static double C_freq = -1;
public static int C_num = 0;
public static int H_num = 0;
public static int N_num = 0;
public static int S_num = 0;
public static int O_num = 0;
public static int P_num = 0;
*/
public static double C12 = 0.9893;
public static double N14 = 0.99632;
public static double H1 = 0.999885;
public static Random rand = new Random();
public static void execute(String[] args) {
try {
//String outputFile = "C:\\Users\\tshaw\\Desktop\\PROTEOMICS\\PeptideSimulation\\simulation.txt";
int i = 0;
String inputFile = args[0];
String outputFile = args[1];
String type = args[2];
FileWriter fwriter = new FileWriter(outputFile);
BufferedWriter out = new BufferedWriter(fwriter);
LinkedList list = readPeptideList(inputFile);
Iterator itr = list.iterator();
while (itr.hasNext()) {
//String peptideFormula = generateRandPeptide(i);
String peptideFormula = (String)itr.next();
i++;
String chemFormula = peptide2formula(peptideFormula);
int number_of_carbons = ToolBox.retrieve_num_element(chemFormula, "C");
int number_of_oxygen = ToolBox.retrieve_num_element(chemFormula, "O");
int number_of_nitrogen = ToolBox.retrieve_num_element(chemFormula, "N");
//System.out.println(peptideFormula + "\t" + chemFormula);
if (type.equals("TMT")) {
chemFormula += "C8H20Ci4N1Nm1O2";
}
IsotopePattern pattern = IsotopeCalculator.calculate_pattern(chemFormula, 50, C12, H1, N14, 1);
double highestMass = getMassOfHighestPeak(pattern);
double firstMass = getFirstMass(pattern);
double highestIntensity = getIntensityOfHighestPeak(pattern);
double firstIntensity = getFirstIntensity(pattern);
/*for (int k = 0; k < pattern.getNumberOfIsotopes(); k++) {
IsotopeContainer container = pattern.getIsotope(k);
out2.write(container.getMass() + "\t" + container.getIntensity() + "\t" + new Double(highestMass - firstMass).intValue() + "\n");
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}*/
String stuff = i + "\t" + firstIntensity + "\t" + highestIntensity + "\t" + (highestIntensity / firstIntensity)
+ "\t" + firstMass + "\t" + highestMass + "\t" + new Double(highestMass - firstMass).intValue() + "\t" + peptideFormula + "\t"
+ chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
+ "\t" + number_of_nitrogen + "\t" + (number_of_carbons + number_of_oxygen) + "\t"
+ (number_of_carbons + number_of_nitrogen) + "\t" + (number_of_carbons + number_of_oxygen + number_of_nitrogen) + "\t" + getStrIsotope(pattern);
//System.out.println(firstMass + "\t" + highestMass + "\t" + (highestMass - firstMass) + "\t" + peptideFormula + "\t"
// + chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
// + "\t" + number_of_nitrogen + "\t" + getStrIsotope(pattern));
out.write(stuff + "\n");
if (i % 1000 == 0) {
out.flush();
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//String outputFile = "C:\\Users\\tshaw\\Desktop\\PROTEOMICS\\PeptideSimulation\\simulation.txt";
int i = 0;
String inputFile = args[0];
String outputFile = args[1];
FileWriter fwriter = new FileWriter(outputFile);
BufferedWriter out = new BufferedWriter(fwriter);
LinkedList list = readPeptideList(inputFile);
Iterator itr = list.iterator();
while (itr.hasNext()) {
//String peptideFormula = generateRandPeptide(i);
String peptideFormula = (String)itr.next();
i++;
String chemFormula = peptide2formula(peptideFormula);
int number_of_carbons = ToolBox.retrieve_num_element(chemFormula, "C");
int number_of_oxygen = ToolBox.retrieve_num_element(chemFormula, "O");
int number_of_nitrogen = ToolBox.retrieve_num_element(chemFormula, "N");
//System.out.println(peptideFormula + "\t" + chemFormula);
IsotopePattern pattern = IsotopeCalculator.calculate_pattern(chemFormula, 50, C12, H1, N14, 1);
double highestMass = getMassOfHighestPeak(pattern);
double firstMass = getFirstMass(pattern);
double highestIntensity = getIntensityOfHighestPeak(pattern);
double firstIntensity = getFirstIntensity(pattern);
/*for (int k = 0; k < pattern.getNumberOfIsotopes(); k++) {
IsotopeContainer container = pattern.getIsotope(k);
out2.write(container.getMass() + "\t" + container.getIntensity() + "\t" + new Double(highestMass - firstMass).intValue() + "\n");
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}*/
String stuff = i + "\t" + firstIntensity + "\t" + highestIntensity + "\t" + (highestIntensity / firstIntensity)
+ "\t" + firstMass + "\t" + highestMass + "\t" + new Double(highestMass - firstMass).intValue() + "\t" + peptideFormula + "\t"
+ chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
+ "\t" + number_of_nitrogen + "\t" + (number_of_carbons + number_of_oxygen) + "\t"
+ (number_of_carbons + number_of_nitrogen) + "\t" + (number_of_carbons + number_of_oxygen + number_of_nitrogen) + "\t" + getStrIsotope(pattern);
//System.out.println(firstMass + "\t" + highestMass + "\t" + (highestMass - firstMass) + "\t" + peptideFormula + "\t"
// + chemFormula + "\t" + number_of_carbons + "\t" + number_of_oxygen
// + "\t" + number_of_nitrogen + "\t" + getStrIsotope(pattern));
out.write(stuff + "\n");
if (i % 1000 == 0) {
out.flush();
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static LinkedList readPeptideList(String fileName) {
LinkedList list = new LinkedList();
try {
String seq = "";
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream din = new DataInputStream(fstream);
BufferedReader in = new BufferedReader(new InputStreamReader(din));
while (in.ready()) {
String str = in.readLine();
list.add(str);
}
in.close();
list.add(seq);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static double getFirstMass(IsotopePattern pattern) {
IsotopeContainer container = pattern.getIsotope(0);
return container.getMass();
}
public static double getMassOfHighestPeak(IsotopePattern pattern) {
String returnStr = pattern.getNumberOfIsotopes() + "";
double max_intensity = -1;
double max_mass = -1;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (max_intensity < container.getIntensity()) {
max_intensity = container.getIntensity();
max_mass = container.getMass();
}
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}
return max_mass;
}
public static double getFirstIntensity(IsotopePattern pattern) {
IsotopeContainer container = pattern.getIsotope(0);
return container.getIntensity();
}
public static double getIntensityOfHighestPeak(IsotopePattern pattern) {
String returnStr = pattern.getNumberOfIsotopes() + "";
double max_intensity = -1;
double max_mass = -1;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (max_intensity < container.getIntensity()) {
max_intensity = container.getIntensity();
max_mass = container.getMass();
}
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}
return max_intensity;
}
public static String getStrIsotope(IsotopePattern pattern) {
int countNumIsotopes = 0;
double cutoff = 0.00001;
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (container.getIntensity() > cutoff) {
countNumIsotopes++;
}
}
String returnStr = countNumIsotopes + "";
for (int i = 0; i < pattern.getNumberOfIsotopes(); i++) {
IsotopeContainer container = pattern.getIsotope(i);
if (container.getIntensity() > cutoff) {
if (returnStr.equals("")) {
returnStr += container.getMass() + ":" + container.getIntensity();
} else {
returnStr += "," + container.getMass() + ":" + container.getIntensity();
}
}
//System.out.println(container.getMass() + "\t" + container.getIntensity());
}
return returnStr;
}
public static String peptide2formula(String str) {
str = str.replaceAll("FORMULA", "").trim();
str = str.replaceAll("=", "").trim();
MOLECULE mol = new MOLECULE();
// Grab Alanine A
int num = ToolBox.retrieve_num_element(str, "A");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("A"));
}
// Grab Arginine R
num = ToolBox.retrieve_num_element(str, "R");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("R"));
}
// Grab Asaparagine N
num = ToolBox.retrieve_num_element(str, "N");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("N"));
}
// Grab Aspartic acid D
num = ToolBox.retrieve_num_element(str, "D");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("D"));
}
// Grab Cysteine C
num = ToolBox.retrieve_num_element(str, "C");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("C"));
}
// Grab Glutamine Q
num = ToolBox.retrieve_num_element(str, "Q");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("Q"));
}
// Grab Glutamic acid E
num = ToolBox.retrieve_num_element(str, "E");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("E"));
}
// Grab Glycine G
num = ToolBox.retrieve_num_element(str, "G");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("G"));
}
// Grab Histidine H
num = ToolBox.retrieve_num_element(str, "H");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("H"));
}
// Grab Isoleucine I
num = ToolBox.retrieve_num_element(str, "I");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("I"));
}
// Grab Leucine L
num = ToolBox.retrieve_num_element(str, "L");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("L"));
}
// Grab Lysine K
num = ToolBox.retrieve_num_element(str, "K");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("K"));
}
// Grab Methionine M
num = ToolBox.retrieve_num_element(str, "M");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("M"));
}
// Grab Phenylalanine F
num = ToolBox.retrieve_num_element(str, "F");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("F"));
}
// Grab Proline P
num = ToolBox.retrieve_num_element(str, "P");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("P"));
}
// Grab Serine S
num = ToolBox.retrieve_num_element(str, "S");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("S"));
}
// Grab Threonine T
num = ToolBox.retrieve_num_element(str, "T");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("T"));
}
// Grab Tryptophan W
num = ToolBox.retrieve_num_element(str, "W");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("W"));
}
// Grab Tyrosine Y
num = ToolBox.retrieve_num_element(str, "Y");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("Y"));
}
// Grab Valine V
num = ToolBox.retrieve_num_element(str, "V");
for (int i = 0; i < num; i++) {
mol = concatenate_molecule(mol, ConvertAAtoFormula("V"));
}
// add an additional of OH group to the concatenated residues.
mol.O++;
mol.H++;
String finalStr = "";
if (mol.C > 0) {
finalStr += "C" + mol.C;
}
if (mol.H > 0) {
finalStr += "H" + (new Integer(mol.H) + 1);
}
if (mol.N > 0) {
finalStr += "N" + mol.N;
}
if (mol.O > 0) {
finalStr += "O" + mol.O;
}
if (mol.S > 0) {
finalStr += "S" + mol.S;
}
return finalStr;
/*C_num = mol.C;
H_num = mol.H;
N_num = mol.N;
O_num = mol.O;
S_num = mol.S;*/
}
public static MOLECULE concatenate_molecule(MOLECULE mol1, MOLECULE mol2) {
MOLECULE final_mol = new MOLECULE();
final_mol.C = mol1.C + mol2.C;
final_mol.H = mol1.H + mol2.H;
final_mol.N = mol1.N + mol2.N;
final_mol.S = mol1.S + mol2.S;
final_mol.O = mol1.O + mol2.O;
return final_mol;
}
/**
* data class for molecule/peptide
*/
static class MOLECULE {
public int C = 0;
public int H = 0;
public int N = 0;
public int S = 0;
public int O = 0;
public String getFormula() {
String formula = "";
if (C > 0) {
formula += "C" + C;
}
if (H > 0) {
formula += "H" + H;
}
if (N > 0) {
formula += "N" + N;
}
if (S > 0) {
formula += "S" + S;
}
if (O > 0) {
formula += "O" + O;
}
return formula;
}
}
/**
* Formula conversion based on
* http://www.imgt.org/IMGTeducation/Aide-memoire/_UK/aminoacids/formuleAA/
* @param aa
* @return
*/
public static MOLECULE ConvertAAtoFormula(String aa) {
MOLECULE mol = new MOLECULE();
if (aa.equals("A")) {
//C3H7NO2
mol.C += 3;
mol.H += 5;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("R")) {
//C6H14N4O2
mol.C += 6;
mol.H += 12;
mol.N += 4;
mol.O += 1;
}
if (aa.equals("N")) {
//C4H8N2O3
mol.C += 4;
mol.H += 6;
mol.N += 2;
mol.O += 2;
}
if (aa.equals("D")) {
//C4H7NO4
mol.C += 4;
mol.H += 5;
mol.N += 1;
mol.O += 3;
}
if (aa.equals("C")) {
//C3H7NO2S
mol.C += 3;
mol.H += 5;
mol.N += 1;
mol.O += 1;
mol.S += 1;
}
if (aa.equals("Q")) {
//C5H10N2O3
mol.C += 5;
mol.H += 8;
mol.N += 2;
mol.O += 2;
}
if (aa.equals("E")) {
//C5H9NO4
mol.C += 5;
mol.H += 7;
mol.N += 1;
mol.O += 3;
}
if (aa.equals("G")) {
//C2H5NO2
mol.C += 2;
mol.H += 3;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("H")) {
//C6H9N3O2
mol.C += 6;
mol.H += 7;
mol.N += 3;
mol.O += 1;
}
if (aa.equals("I") || aa.equals("L")) {
//C6H13NO2
mol.C += 6;
mol.H += 11;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("K")) {
//C6H14N2O2
mol.C += 6;
mol.H += 12;
mol.N += 2;
mol.O += 1;
}
if (aa.equals("M")) {
//C5H11NO2S
mol.C += 5;
mol.H += 9;
mol.N += 1;
mol.O += 1;
mol.S += 1;
}
if (aa.equals("F")) {
//C9H11NO2
mol.C += 9;
mol.H += 9;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("P")) {
//C5H9NO2
mol.C += 5;
mol.H += 7;
mol.N += 1;
mol.O += 1;
}
if (aa.equals("S")) {
//C3H7NO3
mol.C += 3;
mol.H += 5;
mol.N += 1;
mol.O += 2;
}
if (aa.equals("T")) {
//C4H9NO3
mol.C += 4;
mol.H += 7;
mol.N += 1;
mol.O += 2;
}
if (aa.equals("W")) {
//C11H12N2O2
mol.C += 11;
mol.H += 10;
mol.N += 2;
mol.O += 1;
}
if (aa.equals("Y")) {
//C9H11NO3
mol.C += 9;
mol.H += 9;
mol.N += 1;
mol.O += 2;
}
if (aa.equals("V")) {
//C5H11NO2
mol.C += 5;
mol.H += 9;
mol.N += 1;
mol.O += 1;
}
return mol;
}
public static String generateRandPeptide(int size) {
String result = "";
HashMap map = new HashMap();
for (int i = 0; i < size; i++) {
int n = rand.nextInt(20);
//System.out.println(n);
String aa = convertInt2AA(n);
if (map.containsKey(aa)) {
int num = (Integer)map.get(aa);
num++;
map.put(aa, num);
} else {
map.put(aa, 1);
}
}
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String key = (String)itr.next();
int num = (Integer)map.get(key);
result += key + num;
}
return result;
}
public static String convertInt2AA(int num) {
String result = "";
switch (num) {
case 0:
result = "R";
break;
case 1:
result = "H";
break;
case 2:
result = "K";
break;
case 3:
result = "D";
break;
case 4:
result = "E";
break;
case 5:
result = "S";
break;
case 6:
result = "T";
break;
case 7:
result = "N";
break;
case 8:
result = "Q";
break;
case 9:
result = "C";
break;
case 10:
result = "G";
break;
case 11:
result = "P";
break;
case 12:
result = "A";
break;
case 13:
result = "V";
break;
case 14:
result = "I";
break;
case 15:
result = "L";
break;
case 16:
result = "M";
break;
case 17:
result = "F";
break;
case 18:
result = "Y";
break;
case 19:
result = "W";
break;
case 20:
result = "U";
break;
}
return result;
}
public static BIGNUM cutoff = new BIGNUM(1, -50);
/**
* Calculate the pattern for a formula
* @param C12
* @param N14
* @param H1
* @return
*/
/*public static IsotopePattern calculate_pattern(String formula, int charge) {
C_num = retrieve_num_element(formula, "C");
H_num = retrieve_num_element(formula, "H");
N_num = retrieve_num_element(formula, "N");
O_num = retrieve_num_element(formula, "O");
S_num = retrieve_num_element(formula, "S");
P_num = retrieve_num_element(formula, "P");
double C12 = 0.9893;
double N14 = 0.99632;
double H1 = 0.999885;
LinkedList ini_list = create_ini_list(C12, N14, H1);
LinkedList listC = preload_ini_file(ini_list, "C");
LinkedList listH = preload_ini_file(ini_list, "H");
LinkedList listN = preload_ini_file(ini_list, "N");
LinkedList listS = preload_ini_file(ini_list, "S");
LinkedList listO = preload_ini_file(ini_list, "O");
LinkedList listP = preload_ini_file(ini_list, "P");
// possibly the following line might be causing trouble
boolean tolerance_type = true;
double ppm_val = 50;
listC = merge_mass_tolerance(listC, tolerance_type, ppm_val);
listH = merge_mass_tolerance(listH, tolerance_type, ppm_val);
listN = merge_mass_tolerance(listN, tolerance_type, ppm_val);
listS = merge_mass_tolerance(listS, tolerance_type, ppm_val);
listO = merge_mass_tolerance(listO, tolerance_type, ppm_val);
listP = merge_mass_tolerance(listP, tolerance_type, ppm_val);
boolean ppm = true;
//System.out.println(C_num + "\t" + H_num + "\t" + N_num + "\t" + O_num + "\t" + S_num + "\t" + P_num);
//write_example(list, path, 1);
LinkedList newList = new LinkedList();
for (int i = 0; i < C_num; i++) {
if (newList.size() == 0) {
newList = listC;
} else {
newList = MergeList(newList, listC);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < H_num; i++) {
if (newList.size() == 0) {
newList = listH;
} else {
newList = MergeList(newList, listH);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < N_num; i++) {
if (newList.size() == 0) {
newList = listN;
} else {
newList = MergeList(newList, listN);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < S_num; i++) {
if (newList.size() == 0) {
newList = listS;
} else {
newList = MergeList(newList, listS);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < O_num; i++) {
if (newList.size() == 0) {
newList = listO;
} else {
newList = MergeList(newList, listO);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
for (int i = 0; i < P_num; i++) {
if (newList.size() == 0) {
newList = listP;
} else {
newList = MergeList(newList, listP);
newList = merge_mass_tolerance(newList, ppm, ppm_val);
}
}
//print_list(newList);
IsotopePattern query_pattern = convert_Compounds2IsotopePattern(newList, -1, charge);
return query_pattern;
}*/
/*public static LinkedList create_ini_list(double C12, double N14, double H1) {
LinkedList list = new LinkedList();
list.add("C: 12," + C12);
list.add("C: 13.0033548378," + (1 - C12));
list.add("H: 1.0078250321," + H1);
list.add("H: 2.0141017780," + (1 - H1));
list.add("N: 14.0030740052," + N14);
list.add("N: 15.0001088984," + (1 - N14));
list.add("O: 15.9949146221,0.99757");
list.add("O: 16.99913150,0.00038");
list.add("O: 17.9991604,0.00205");
list.add("S: 31.97207069,0.9493");
list.add("S: 32.97145850,0.0076");
list.add("S: 33.96786683,0.0429");
list.add("P: 30.97376151,1.0");
return list;
}*/
/**
* Subtract two bignum
* subtract bn2 from bn1
*/
public static BIGNUM subtract(BIGNUM bn1, BIGNUM bn2) {
BIGNUM newbn = new BIGNUM(-bn2.NUM, bn2.E);
return add(bn1, newbn);
}
/**
* ADD two big num
* If the factor between the two number is greater than 52 then just return the larger number
* @param bn1
* @param bn2
* @return
*/
public static BIGNUM add(BIGNUM bn1, BIGNUM bn2) {
int diff = 0;
double COMB = 0;
double newE = 0;
if (bn1.E > bn2.E) {
double factor = bn1.E - bn2.E;
if (factor > 52 ) {
return bn1;
}
COMB = bn1.NUM + bn2.NUM / Math.pow(10, factor);
newE = bn1.E;
} else {
double factor = bn2.E - bn1.E;
if (factor > 52 ) {
return bn2;
}
COMB = bn2.NUM + bn1.NUM / Math.pow(10, factor);
newE = bn2.E;
}
BIGNUM result = new BIGNUM(COMB, newE);
return result;
}
/**
* Merge Resolution
* @param mass1 other mass
* @param mass2 theoretical mass
* @param ppm_cutoff
* @return
*/
public static boolean within_distance(BIGNUM mass1, BIGNUM mass2, BIGNUM ppm_cutoff) {
BIGNUM million = new BIGNUM(1e6);
BIGNUM difference;
if (isGreater(mass1, mass2)) {
difference = subtract(mass1, mass2);
} else {
difference = subtract(mass2, mass1);
}
//System.out.println(mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString());
if (isGreater(ppm_cutoff, difference)) {
//System.out.println("Is greater: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return true;
}
//System.out.println("Is smaller: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return false;
}
public static BIGNUM total_val(int N, int M) {
BIGNUM val = new BIGNUM(0.0);
for (int i = 0; i <= M; i++) {
val = add(val, calc_N_choose_M(N, i));
}
return val;
}
public static BIGNUM calc_N_choose_M(int N, int M) {
BIGNUM top = new BIGNUM(new Double(N));
BIGNUM bottom = new BIGNUM(1.0);
if (M == 0) {
return new BIGNUM(1.0);
}
for (int j = 1; j <= M; j++) {
bottom = multiply(bottom, new BIGNUM(new Double(j)));
}
for (int j = 1; j < M; j++) {
top = multiply(top, new BIGNUM(new Double(N - j)));
}
return divide(top, bottom);
}
/**
* Dividing two big num
* @param bn1
* @param bn2
* @return
*/
public static BIGNUM divide(BIGNUM bn1, BIGNUM bn2) {
double divide = bn1.NUM / bn2.NUM;
double newE = bn1.E - bn2.E;
//System.out.println("divide function: " + multiply + "\t" + newE);
BIGNUM result = new BIGNUM(divide, newE);
return result;
}
/**
* Multiplying two big num
* @param bn1
* @param bn2
* @return
*/
public static BIGNUM multiply(BIGNUM bn1, BIGNUM bn2) {
double multiply = bn1.NUM * bn2.NUM;
double newE = bn1.E + bn2.E;
//System.out.println("multiply function: " + multiply + "\t" + newE);
BIGNUM result = new BIGNUM(multiply, newE);
return result;
}
/**
* Test if first number is larger than second number
* @param num
* @param num2
* @return
*/
public static boolean isGreater(BIGNUM num, BIGNUM num2) {
if (num.E > num2.E) {
return true;
} else if (num.E == num2.E) {
if (num.NUM > num2.NUM) {
return true;
}
}
return false;
}
/**
* PPM = 1E6 * (Mass1 - Mass2) / Mass2
* @param mass1 other mass
* @param mass2 theoretical mass
* @param ppm_cutoff
* @return
*/
public static boolean check_within_ppm(BIGNUM mass1, BIGNUM mass2, BIGNUM ppm_cutoff) {
BIGNUM million = new BIGNUM(1e6);
BIGNUM difference;
if (isGreater(mass1, mass2)) {
difference = subtract(mass1, mass2);
} else {
difference = subtract(mass2, mass1);
}
BIGNUM ppm = divide(multiply(million, difference), divide(add(mass2, mass1), new BIGNUM(2)));
//System.out.println(mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString());
if (isGreater(ppm_cutoff, ppm)) {
//System.out.println("Is greater: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return true;
}
//System.out.println("Is smaller: " + mass1.getString() + "\t" + mass2.getString() + "\t" + ppm.getString() + "\t" + ppm_cutoff.getString());
return false;
}
/*public static COMPOUND merge_compound(COMPOUND compound_A, COMPOUND compound_B) {
COMPOUND new_compound = new COMPOUND();
//System.out.println(compound_A.TYPE + "\t" + compound_B.TYPE);
if (compound_A.TYPE.equals(compound_B.TYPE)) {
new_compound.PROB = multiply(compound_A.PROB, compound_B.PROB);
new_compound.SIZE = compound_A.SIZE + compound_B.SIZE;
//new_compound.NUM_ISOTOPE = compound_A.NUM_ISOTOPE + compound_B.NUM_ISOTOPE;
new_compound.TYPE1 = compound_A.TYPE1 + compound_B.TYPE1;
new_compound.TYPE2 = compound_A.TYPE2 + compound_B.TYPE2;
new_compound.TYPE3 = compound_A.TYPE3 + compound_B.TYPE3;
new_compound.FREQ = multiply(compound_A.FREQ, compound_B.FREQ); //calc_N_choose_M(new_compound.SIZE, new_compound.NUM_ISOTOPE);
new_compound.TYPE = compound_A.TYPE;
new_compound.MASS = add(compound_A.MASS, compound_B.MASS);
//new_compound.TOTALPROB = multiply(new_compound.FREQ, new_compound.PROB);
new_compound.TOTALPROB = multiply(compound_A.TOTALPROB, compound_B.TOTALPROB);
}
return new_compound;
}*/
public static COMPOUND merge_compound(COMPOUND compound_A, COMPOUND compound_B) {
COMPOUND new_compound = new COMPOUND();
new_compound.NUM_ISOTOPE = compound_A.NUM_ISOTOPE + compound_B.NUM_ISOTOPE;
new_compound.SIZE = compound_A.SIZE + compound_B.SIZE;
new_compound.MASS = add(compound_A.MASS, compound_B.MASS);
new_compound.TOTALPROB = multiply(compound_A.TOTALPROB, compound_B.TOTALPROB);
return new_compound;
}
/**
* Merging two different elements and return a merged list
* @param element_A
* @param element_B
* @return
*/
public static LinkedList MergeList(LinkedList element_A, LinkedList element_B) {
LinkedList merged = new LinkedList();
if (element_B.size() == 0) {
return element_A;
}
if (element_A.size() == 0) {
return element_B;
}
Iterator itr = element_A.iterator();
while (itr.hasNext()) {
COMPOUND compound_A = (COMPOUND)itr.next();
Iterator itr2 = element_B.iterator();
while (itr2.hasNext()) {
COMPOUND compound_B = (COMPOUND)itr2.next();
COMPOUND new_compound = merge_compound(compound_A, compound_B);
// add whether to save this value
if (isGreater(new_compound.TOTALPROB, cutoff)) {
merged.add(new_compound);
}
}
}
return merged;
}
/**
* Merge the compound based on the mass tolerance
* @param list
* @param ppm_cutoff
* @return
*/
public static LinkedList merge_mass_tolerance(LinkedList list, boolean ppm, double ppm_val) {
HashMap final_map = new HashMap();
LinkedList mass_list = new LinkedList();
LinkedList final_list = new LinkedList();
Iterator itr = list.iterator();
while (itr.hasNext()) {
COMPOUND compound1 = (COMPOUND)itr.next();
double mass = compound1.MASS.NUM * Math.pow(10, compound1.MASS.E);
if (final_map.containsKey(mass)) {
COMPOUND old = (COMPOUND)final_map.get(mass);
//System.out.println("Merge1: " + compound1.TOTALPROB + "\t" + old.TOTALPROB);
compound1.TOTALPROB = add(compound1.TOTALPROB, old.TOTALPROB);
final_map.put(mass, compound1);
} else {
final_map.put(mass, compound1);
mass_list.add(mass);
}
}
double[] double_list = new double[mass_list.size()];
int i = 0;
itr = mass_list.iterator();
while (itr.hasNext()) {
double mass = (Double)itr.next();
double_list[i] = mass;
i++;
}
Arrays.sort(double_list);
//System.out.println(double_list.length);
//final_map.clear();
double mass1 = double_list[0];;
for (i = 1 ;i < double_list.length; i++) {
double mass2 = double_list[i];
COMPOUND compound1 = (COMPOUND)final_map.get(mass1);
COMPOUND compound2 = (COMPOUND)final_map.get(mass2);
boolean update = false;
if (ppm) {
//System.out.println(mass1 + "\t" + mass2);
//if (check_within_ppm(compound1.MASS, compound2.MASS, new BIGNUM(10))) {
if (check_within_ppm(compound1.MASS, compound2.MASS, new BIGNUM(ppm_val))) {
update = true;
if (isGreater(compound1.TOTALPROB, compound2.TOTALPROB)) {
//System.out.println("Merge2: " + compound1.TOTALPROB.getString() + "\t" + compound2.TOTALPROB.getString());
compound1.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass2);
final_map.put(mass1, compound1);
mass1 = mass1;
} else {
compound2.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass1);
final_map.put(mass2, compound2);
mass1 = mass2;
}
} else {
//System.out.println(mass1 + "\t" + mass2);
}
} else {
//if (within_distance(compound1.MASS, compound2.MASS, new BIGNUM(0.1))) {
if (within_distance(compound1.MASS, compound2.MASS, new BIGNUM(ppm_val))) {
update = true;
if (isGreater(compound1.TOTALPROB, compound2.TOTALPROB)) {
//System.out.println("Merge2: " + compound1.TOTALPROB.getString() + "\t" + compound2.TOTALPROB.getString());
compound1.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass2);
final_map.put(mass1, compound1);
mass1 = mass1;
} else {
compound2.TOTALPROB = add(compound1.TOTALPROB, compound2.TOTALPROB);
final_map.remove(mass1);
final_map.put(mass2, compound2);
mass1 = mass2;
}
//System.out.println("Merge2: " + compound1.TOTALPROB.getString() + "\t" + compound2.TOTALPROB.getString());
} else {
//System.out.println(mass1 + "\t" + mass2);
}
}
if (!update) {
mass1 = mass2;
}
}
//System.out.println(final_map.size());
i = 0;
double_list = new double[final_map.size()];
itr = final_map.keySet().iterator();
while (itr.hasNext()) {
double mass = (Double)itr.next();
double_list[i] = mass;
i++;
}
Arrays.sort(double_list);
for (double mass: double_list) {
final_list.add(final_map.get(mass));
}
return final_list;
}
/**
*
* @param fileName
* @param chem
* @return
*/
public static LinkedList preload_ini_file(LinkedList list, String chem) {
LinkedList isotope_list = new LinkedList();
try {
int C_ID = 0;
int H_ID = 0;
int N_ID = 0;
int S_ID = 0;
int O_ID = 0;
int P_ID = 0;
Iterator itr = list.iterator();
while (itr.hasNext()) {
String str = (String)itr.next();
if (str.startsWith("C:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("C:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "C";
compound.SETTYPE(C_ID);
//compound.TYPE2 = C_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
C_ID++;
isotope_list.add(compound);
}
if (str.startsWith("H:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("H:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "H";
compound.SETTYPE(H_ID);
//compound.TYPE2 = H_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
H_ID++;
isotope_list.add(compound);
}
if (str.startsWith("N:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("N:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "N";
compound.SETTYPE(N_ID);
//compound.TYPE2 = N_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
N_ID++;
isotope_list.add(compound);
}
if (str.startsWith("O:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("O:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "O";
compound.SETTYPE(O_ID);
//compound.TYPE2 = O_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
O_ID++;
isotope_list.add(compound);
}
if (str.startsWith("S:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("S:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "S";
compound.SETTYPE(S_ID);
//compound.TYPE2 = S_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
S_ID++;
isotope_list.add(compound);
}
if (str.startsWith("P:") && str.split(":")[0].equals(chem)) {
str = str.replaceAll("P:", "").trim();
String[] split = str.split(",");
double mass = new Double(split[0]);
double prob = new Double(split[1]);
COMPOUND compound = new COMPOUND();
compound.TYPE = "P";
compound.SETTYPE(S_ID);
//compound.TYPE2 = S_ID;
compound.MASS = new BIGNUM(mass);
compound.SIZE = 1;
compound.PROB = new BIGNUM(prob);
compound.FREQ = new BIGNUM(1.0);
compound.TOTALPROB = new BIGNUM(prob);
P_ID++;
isotope_list.add(compound);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return isotope_list;
}
/**
* Convert a linkedlist of compound and output Isotopic Pattern
* @param list
*/
public static IsotopePattern convert_Compounds2IsotopePattern(LinkedList list, int top, int charge) {
if (top <= 0) {
top = list.size();
}
int count = 0;
double[] intensities = new double[list.size()];
Iterator itr = list.iterator();
while (itr.hasNext()) {
COMPOUND compound = (COMPOUND)itr.next();
double mass = compound.MASS.toDouble();
double intensity = compound.TOTALPROB.toDouble();
intensities[count] = intensity;
//System.out.println(mass + "\t" + intensity);
count++;
}
/*
Arrays.sort(intensities);
for (double intensity: intensities) {
System.out.println(intensity);
}
*/
count = 0;
IsotopePattern pattern = new IsotopePattern();
itr = list.iterator();
while (itr.hasNext()) {
COMPOUND compound = (COMPOUND)itr.next();
if (count < top) {
double mass = compound.MASS.toDouble();
double intensity = compound.TOTALPROB.toDouble();
//mass = (mass / charge + charge * 1.007825);
mass = (mass / charge + 1.007825);
pattern.addIsotope(new IsotopeContainer(mass, intensity));
//System.out.println(mass + "\t" + intensity);
}
count++;
}
return pattern;
}
/**
* A Class for storing compound information
* @author tshaw
*
*/
static class COMPOUND {
public String TYPE = "";
public int TYPE1 = 0; // isotope cumulative types
public int TYPE2 = 0; // isotope cumulative types
public int TYPE3 = 0; // isotope cumulative types
public int TYPE4 = 0; // isotope cumulative types
public int TYPE5 = 0; // isotope cumulative types
public BIGNUM MASS = new BIGNUM(0.0);
public BIGNUM PROB = new BIGNUM(0.0);
public BIGNUM FREQ = new BIGNUM(0.0);
public BIGNUM TOTALPROB = new BIGNUM(0.0);
public int NUM_ISOTOPE = 0; // the number of isotopes
public int SIZE = 0;
public void SETTYPE(int ID) {
if (ID == 0) {
TYPE1 = 1;
}
if (ID == 1) {
TYPE2 = 1;
}
if (ID == 2) {
TYPE3 = 1;
}
if (ID == 3) {
TYPE4 = 1;
}
if (ID == 4) {
TYPE5 = 1;
}
}
}
/**
* Parsing the string and retrieve the number of elements
* @param str
* @param query_element
* @return
*/
/*public static int retrieve_num_element(String str, String query_element) {
int total = 0;
int str_index = str.indexOf(query_element);
for (int i = 0; i < str.length(); i++) {
if (str.substring(i, i + 1).equals(query_element)) {
int value = 0;
String num_str = "";
for (int j = i + 1; j < str.length(); j++) {
if (str.substring(j, j + 1).matches("[0-9]")) {
num_str += str.substring(j, j + 1);
value = new Integer(num_str);
} else {
if (value == 0) {
value = 1;
}
break;
}
}
if (i == str.length() - 1) {
value = 1;
}
total += value;
}
}
return total;
}*/
/**
* A Class for storing large numbers;
* @author tshaw
*
*/
static class BIGNUM {
public double NUM = 0;
public double E = 0;
public String getString() {
return (new Double(NUM).toString() + "E" + new Integer((int)E).toString());
}
public double toDouble() {
return new Double(this.getString());
}
public BIGNUM(double newNUM, double newE) {
NUM = newNUM;
E = newE;
double value = newNUM;
if (value >= 1) {
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
}
public BIGNUM(String value2) {
//System.out.println(value);
if (value2.contains("E")) {
String[] split = value2.split("E");
NUM = new Double(split[0]);
E = new Double(split[1]);
double value = new Double(split[0]);
if (value >= 1) {
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
} else {
double value = new Double(value2);
NUM = new Double(value);
if (value >= 1) {
E = 0;
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
}
}
public BIGNUM(double value) {
//System.out.println(value);
NUM = value;
if (value >= 1) {
E = 0;
for (double i = 10; i < 1e50; i = i * 10) {
if (value / i < 1 || value == 0) {
break;
} else {
NUM = value / i;
E++;
}
}
} else {
for (double i = 10; i < 1e50; i = i * 10) {
if (value * i > 10 || value == 0) {
break;
} else {
NUM = value * i;
E--;
}
}
}
}
}
}
| 41,462 | 0.59452 | 0.570474 | 1,499 | 26.659773 | 23.898754 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.637091 | false | false | 10 |
394a59d91c965cca6ac6bb41c1b252226f56c13d | 16,346,645,568,329 | 8c3d027f5a39efdee533e94042297ae110895cdb | /BASICS/vlojeni/src/passwortgen.java | cd53c85c66f515044c89a66df2d937ef4c1793a7 | []
| no_license | epitsov/Random-Java | https://github.com/epitsov/Random-Java | d9db389480033bbce495d273b321167affc6b9c4 | 68de48dad55d9f918cbc143c84bafd6f13692a2e | refs/heads/main | 2023-02-27T22:34:50.011000 | 2021-02-06T10:14:07 | 2021-02-06T10:14:07 | 336,508,187 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class passwortgen {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int l = Integer.parseInt(scanner.nextLine());
String stringatL = l + "";
char u = stringatL.charAt(0);
for (int i = 1; i < n; i++) {
for (int b = 1; b < n; b++) {
for (char a = 97; a < 97 + l; a++) {
for (char c = 97; c < 97 + l; c++) {
if (i > b) {
for (int p = 1 + i; p <= n; p++) {
System.out.print(i + "" + b + "" + a + "" + c + "" + p + " ");
}
} else {
for (int q = 1 + b; q <= n; q++) {
System.out.print(i + "" + b + "" + a + "" + c + "" + q + " ");
}
}
}
}
}
}
}
}
| UTF-8 | Java | 1,065 | java | passwortgen.java | Java | []
| null | []
| import java.util.Scanner;
public class passwortgen {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int l = Integer.parseInt(scanner.nextLine());
String stringatL = l + "";
char u = stringatL.charAt(0);
for (int i = 1; i < n; i++) {
for (int b = 1; b < n; b++) {
for (char a = 97; a < 97 + l; a++) {
for (char c = 97; c < 97 + l; c++) {
if (i > b) {
for (int p = 1 + i; p <= n; p++) {
System.out.print(i + "" + b + "" + a + "" + c + "" + p + " ");
}
} else {
for (int q = 1 + b; q <= n; q++) {
System.out.print(i + "" + b + "" + a + "" + c + "" + q + " ");
}
}
}
}
}
}
}
}
| 1,065 | 0.311737 | 0.299531 | 29 | 35.724136 | 23.963905 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false | 10 |
f5add7395a2d867d73d7d3c12f2f45c067d71017 | 6,734,508,742,011 | f2c8f819ee993909bbf0c0858df8dda70c2d9425 | /VTMBAAndroid/src/edu/vt/mba/alumni/controllers/jobboard/JobResultsListFragment.java | 6a0fe5125c94d489effbc791a4ee5576c9d886f4 | []
| no_license | hickeyadamc/VTMBAAndroid | https://github.com/hickeyadamc/VTMBAAndroid | 472f53330c90b2cadc6ee24a3337ec5ddad04dcf | 15c0ca8e7f9b0ea10e256313971cd75d4bb6e415 | refs/heads/master | 2016-09-06T06:15:27.509000 | 2013-11-27T20:19:21 | 2013-11-27T20:19:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.vt.mba.alumni.controllers.jobboard;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragment;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
import edu.vt.mba.alumni.controllers.slidingmenu.MainActivity;
import edu.vt.mba.alumni.database.Database;
import edu.vt.mba.alumni.database.Database.SearchJobsTaskCallback;
import edu.vt.mba.alumni.utils.Utils;
import edu.vt.mba.alumni.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class JobResultsListFragment
extends SherlockFragment
{
public static final String EXTRA_SEARCH_ARRAY = "search array";
private ArrayList<Job> mJobs;
private ArrayList<String> mPreviousSearch;
private ListView mJobsListView;
private View mRootView;
private MainActivity mMainActivity;
private static final String TAG = JobResultsListFragment.class.getName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mMainActivity = (MainActivity) getActivity();
mRootView = inflater.inflate(R.layout.fragment_generic_results,container,false);
mJobsListView = (ListView) mRootView.findViewById(R.id.listViewItems);
mJobsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = mJobsListView.getItemAtPosition(position);
Job fullObject = (Job)o;
openJobPage(fullObject);
}
});
setupActionBar();
//Compare previous search criteria with current search criteria
//If they're equal, use the old job list and do no searching
//if they're not equal, search the database
ArrayList<String> currentSearchCriteria = getArguments().getStringArrayList(EXTRA_SEARCH_ARRAY);
if(Utils.listsAreEqualAndNotNull(mPreviousSearch,currentSearchCriteria)) {
updateJobsAndLoadUi(mJobs);
} else {
mPreviousSearch = currentSearchCriteria;
searchForJobs(currentSearchCriteria);
}
return mRootView;
}
private void searchForJobs(List<String> searchList) {
Database db = new Database();
SearchJobsTaskCallback callback = new SearchJobsTaskCallback() {
@Override
public void onSearchFinished(ArrayList<Job> jobs) {
updateJobsAndLoadUi(jobs);
}
};
db.searchJobs(searchList.get(0), searchList.get(1), searchList.get(2), searchList.get(3), callback);
}
private void setupActionBar() {
LayoutInflater inflator = (LayoutInflater) mMainActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.actionbar_main, null);
mMainActivity.getSupportActionBar().setCustomView(v);
ImageButton leftBarButton = (ImageButton) mMainActivity.getSupportActionBar().getCustomView().findViewById(R.id.leftBarButton);
leftBarButton.setBackgroundResource(R.drawable.ic_bar_item_back);
leftBarButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMainActivity.switchContent(MainActivity.FRAGMENT_JOB_SEARCH);
}
});
//setup text view
TextView barTitle = (TextView) v.findViewById(R.id.barTitle);
barTitle.setText(MainActivity.FRAGMENT_JOB_RESULTS);
}
protected void updateJobsAndLoadUi(ArrayList<Job> jobs) {
mJobs = jobs;
if(jobs.size() < 1)
{
Toast.makeText(mMainActivity, "No Results Were Found" ,Toast.LENGTH_LONG).show();
}
else
{
if(mJobsListView == null) {
Log.d(TAG ,"list view was null");
} else {
mJobsListView.setAdapter(new JobResultsAdapter(mMainActivity, jobs));
}
}
}
/**
* View info for selected job
* @param job
*/
private void openJobPage(Job job)
{
mMainActivity.switchContent(MainActivity.FRAGMENT_JOB_DETAILS, job.getBundle());
}
}
| UTF-8 | Java | 4,814 | java | JobResultsListFragment.java | Java | []
| null | []
| package edu.vt.mba.alumni.controllers.jobboard;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragment;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
import edu.vt.mba.alumni.controllers.slidingmenu.MainActivity;
import edu.vt.mba.alumni.database.Database;
import edu.vt.mba.alumni.database.Database.SearchJobsTaskCallback;
import edu.vt.mba.alumni.utils.Utils;
import edu.vt.mba.alumni.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class JobResultsListFragment
extends SherlockFragment
{
public static final String EXTRA_SEARCH_ARRAY = "search array";
private ArrayList<Job> mJobs;
private ArrayList<String> mPreviousSearch;
private ListView mJobsListView;
private View mRootView;
private MainActivity mMainActivity;
private static final String TAG = JobResultsListFragment.class.getName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mMainActivity = (MainActivity) getActivity();
mRootView = inflater.inflate(R.layout.fragment_generic_results,container,false);
mJobsListView = (ListView) mRootView.findViewById(R.id.listViewItems);
mJobsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = mJobsListView.getItemAtPosition(position);
Job fullObject = (Job)o;
openJobPage(fullObject);
}
});
setupActionBar();
//Compare previous search criteria with current search criteria
//If they're equal, use the old job list and do no searching
//if they're not equal, search the database
ArrayList<String> currentSearchCriteria = getArguments().getStringArrayList(EXTRA_SEARCH_ARRAY);
if(Utils.listsAreEqualAndNotNull(mPreviousSearch,currentSearchCriteria)) {
updateJobsAndLoadUi(mJobs);
} else {
mPreviousSearch = currentSearchCriteria;
searchForJobs(currentSearchCriteria);
}
return mRootView;
}
private void searchForJobs(List<String> searchList) {
Database db = new Database();
SearchJobsTaskCallback callback = new SearchJobsTaskCallback() {
@Override
public void onSearchFinished(ArrayList<Job> jobs) {
updateJobsAndLoadUi(jobs);
}
};
db.searchJobs(searchList.get(0), searchList.get(1), searchList.get(2), searchList.get(3), callback);
}
private void setupActionBar() {
LayoutInflater inflator = (LayoutInflater) mMainActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.actionbar_main, null);
mMainActivity.getSupportActionBar().setCustomView(v);
ImageButton leftBarButton = (ImageButton) mMainActivity.getSupportActionBar().getCustomView().findViewById(R.id.leftBarButton);
leftBarButton.setBackgroundResource(R.drawable.ic_bar_item_back);
leftBarButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMainActivity.switchContent(MainActivity.FRAGMENT_JOB_SEARCH);
}
});
//setup text view
TextView barTitle = (TextView) v.findViewById(R.id.barTitle);
barTitle.setText(MainActivity.FRAGMENT_JOB_RESULTS);
}
protected void updateJobsAndLoadUi(ArrayList<Job> jobs) {
mJobs = jobs;
if(jobs.size() < 1)
{
Toast.makeText(mMainActivity, "No Results Were Found" ,Toast.LENGTH_LONG).show();
}
else
{
if(mJobsListView == null) {
Log.d(TAG ,"list view was null");
} else {
mJobsListView.setAdapter(new JobResultsAdapter(mMainActivity, jobs));
}
}
}
/**
* View info for selected job
* @param job
*/
private void openJobPage(Job job)
{
mMainActivity.switchContent(MainActivity.FRAGMENT_JOB_DETAILS, job.getBundle());
}
}
| 4,814 | 0.714998 | 0.713752 | 157 | 29.66242 | 27.382769 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.197452 | false | false | 10 |
0b84d98b0d24151cee9bbb93ac80404dbd39af05 | 14,336,600,902,085 | 4457ef1125262f0638d39cb789ab51078403aaf9 | /src/main/java/com/common/util/PrintUtil.java | c5d6ef9afea5ae21bbae3bdf96de627dd54cc1e5 | []
| no_license | duan-duan/core-common | https://github.com/duan-duan/core-common | 76bd13f89ef0bc046f2379ed7299abceb4f40cf8 | b2c55c963296b130ca7b2bdaf76197d053317ef5 | refs/heads/master | 2020-12-05T15:35:55.633000 | 2016-08-28T02:55:37 | 2016-08-28T02:55:37 | 66,746,537 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @Title: PrintUtil.java
* @Package com.gome.common.util
* @Description: TODO
* @author lianzhiqiang
* @date 2015年1月13日 上午10:48:45
* @version V1.0
*/
package com.common.util;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
/**
* @ClassName: PrintUtil
* @Description: 打印工具类
* @author lianzhiqiang
* @date 2015年1月13日 上午10:48:45
*
*/
public class PrintUtil {
/**
* @Title: print
* @Description: 打印PDF到页面,调用的时候需要window.open打开新的页面
* @param reportName 报表名称,需要对应报表模板的名称
* @param parameters 报表模板对应的参数,对应模板上$P{}
* @param dataSource 报表模板对应的列表,对应模板上$F{}
* @param request
* @param response
* @throws JRException
* @throws IOException
* @return void
*/
public static void print(String reportName, Map<String, Object> parameters, Collection dataSource, HttpServletRequest request, HttpServletResponse response) throws JRException, IOException{
File jasperFile=null;
byte[] bytes = null;
String path = request.getSession().getServletContext()
.getRealPath("/") + "/resource/labeltemplate/gome/" + reportName + ".jasper";
jasperFile = new File(path);
bytes = JasperRunManager.runReportToPdf(jasperFile.getPath(), parameters,
new JRBeanCollectionDataSource(dataSource));
if (bytes != null && bytes.length > 0) {
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();
}
}
}
| UTF-8 | Java | 2,206 | java | PrintUtil.java | Java | [
{
"context": "e.common.util \r\n * @Description: TODO \r\n * @author lianzhiqiang\r\n * @date 2015年1月13日 上午10:48:45 \r\n * @version V1.",
"end": 118,
"score": 0.9879153966903687,
"start": 106,
"tag": "USERNAME",
"value": "lianzhiqiang"
},
{
"context": "me: PrintUtil \r\n * @Description: 打印工具类\r\n * @author lianzhiqiang\r\n * @date 2015年1月13日 上午10:48:45 \r\n * \r\n */\r\npubl",
"end": 707,
"score": 0.9872350692749023,
"start": 695,
"tag": "USERNAME",
"value": "lianzhiqiang"
}
]
| null | []
| /**
* @Title: PrintUtil.java
* @Package com.gome.common.util
* @Description: TODO
* @author lianzhiqiang
* @date 2015年1月13日 上午10:48:45
* @version V1.0
*/
package com.common.util;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
/**
* @ClassName: PrintUtil
* @Description: 打印工具类
* @author lianzhiqiang
* @date 2015年1月13日 上午10:48:45
*
*/
public class PrintUtil {
/**
* @Title: print
* @Description: 打印PDF到页面,调用的时候需要window.open打开新的页面
* @param reportName 报表名称,需要对应报表模板的名称
* @param parameters 报表模板对应的参数,对应模板上$P{}
* @param dataSource 报表模板对应的列表,对应模板上$F{}
* @param request
* @param response
* @throws JRException
* @throws IOException
* @return void
*/
public static void print(String reportName, Map<String, Object> parameters, Collection dataSource, HttpServletRequest request, HttpServletResponse response) throws JRException, IOException{
File jasperFile=null;
byte[] bytes = null;
String path = request.getSession().getServletContext()
.getRealPath("/") + "/resource/labeltemplate/gome/" + reportName + ".jasper";
jasperFile = new File(path);
bytes = JasperRunManager.runReportToPdf(jasperFile.getPath(), parameters,
new JRBeanCollectionDataSource(dataSource));
if (bytes != null && bytes.length > 0) {
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();
}
}
}
| 2,206 | 0.684262 | 0.669599 | 65 | 29.476923 | 28.94244 | 190 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.046154 | false | false | 10 |
3bf41111c9798632e088f40df02fa12d7af42324 | 10,273,561,805,268 | 2ea5b22e460c93495fcf428cbcba9e34f21d93eb | /src/main/java/pages/actions/CarsSearchPageActions.java | 3cfb63d7e1094d31d8a400f1794439e0c421a019 | []
| no_license | siddhardha49/CarsguideCucumber | https://github.com/siddhardha49/CarsguideCucumber | 983958d558e284443d4885608f11c592511aecc0 | 6b0244ca5e79113ccf690ab7ec7acd186b6716ae | refs/heads/master | 2023-06-19T10:13:30.642000 | 2021-07-05T01:45:19 | 2021-07-05T01:45:19 | 382,974,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pages.actions;
import org.openqa.selenium.By;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import pages.locators.CarSearchPageLocators;
import utils.SeleniumDriver;
public class CarsSearchPageActions {
CarSearchPageLocators carSearchPageLocators = null;
public CarsSearchPageActions() {
this.carSearchPageLocators = new CarSearchPageLocators();
PageFactory.initElements(SeleniumDriver.getDriver(), carSearchPageLocators);
}
public void selectCarMake(String carBrand) throws InterruptedException {
//carSearchPageLocators.allnewusedcarlink.click();
//driver.findElement(By.xpath("//*[@id=\"block-system-main\"]/div/div/div/div/div/form/div[1]/label[1]")).click();
Select selectCarMaker = new Select(carSearchPageLocators.anyMake);
selectCarMaker.selectByVisibleText(carBrand);
Thread.sleep(3000);
}
public void selectCarModel(String carModel) {
Select selectCarModels = new Select(carSearchPageLocators.anyModel);
selectCarModels.selectByVisibleText(carModel);
}
public void selectCarLocation(String carLocation) {
Select selectCarLocations = new Select(carSearchPageLocators.anyLocation);
selectCarLocations.selectByVisibleText(carLocation);
}
public void selectCarPrice(String carPrice) {
Select selectCarPricer = new Select(carSearchPageLocators.price);
selectCarPricer.selectByVisibleText(carPrice);
}
public void findMyNextCarButton() {
carSearchPageLocators.findMyNextCar.click();
}
}
| UTF-8 | Java | 1,518 | java | CarsSearchPageActions.java | Java | []
| null | []
| package pages.actions;
import org.openqa.selenium.By;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import pages.locators.CarSearchPageLocators;
import utils.SeleniumDriver;
public class CarsSearchPageActions {
CarSearchPageLocators carSearchPageLocators = null;
public CarsSearchPageActions() {
this.carSearchPageLocators = new CarSearchPageLocators();
PageFactory.initElements(SeleniumDriver.getDriver(), carSearchPageLocators);
}
public void selectCarMake(String carBrand) throws InterruptedException {
//carSearchPageLocators.allnewusedcarlink.click();
//driver.findElement(By.xpath("//*[@id=\"block-system-main\"]/div/div/div/div/div/form/div[1]/label[1]")).click();
Select selectCarMaker = new Select(carSearchPageLocators.anyMake);
selectCarMaker.selectByVisibleText(carBrand);
Thread.sleep(3000);
}
public void selectCarModel(String carModel) {
Select selectCarModels = new Select(carSearchPageLocators.anyModel);
selectCarModels.selectByVisibleText(carModel);
}
public void selectCarLocation(String carLocation) {
Select selectCarLocations = new Select(carSearchPageLocators.anyLocation);
selectCarLocations.selectByVisibleText(carLocation);
}
public void selectCarPrice(String carPrice) {
Select selectCarPricer = new Select(carSearchPageLocators.price);
selectCarPricer.selectByVisibleText(carPrice);
}
public void findMyNextCarButton() {
carSearchPageLocators.findMyNextCar.click();
}
}
| 1,518 | 0.79249 | 0.788538 | 59 | 24.728813 | 28.743654 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.169492 | false | false | 10 |
2d18d05f04e0f6c11f2fc1dac10629b2418b84ee | 23,691,039,609,092 | d0088d7be7aedd7846894372b22c783e9a08e207 | /src/CCI/C8_Power.java | 75b7366a56eacde21f306590be0906d1b4ab44c1 | []
| no_license | srishti77/Algorithm | https://github.com/srishti77/Algorithm | 4b21c21f6cf307e3d3cb98242d0802d112977dd7 | 0cde94becc1623c6859b89c62abf15a48ddd356a | refs/heads/master | 2021-10-25T20:54:10.660000 | 2019-04-07T13:58:06 | 2019-04-07T13:58:06 | 106,170,144 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CCI;
public class C8_Power {
float value=1;
public static void main(String s[]) {
C8_Power power= new C8_Power();
System.out.println(power.getXPowerY(5,-3));
}
public float getXPowerY(int x, int y) {
System.out.println(x+" "+y);
if(y==0) return 1;
else if(y==1) return x;
else if(y>1){
value= value*x*getXPowerY(x, y-1);
return value;
}
else {
value= value/x*getXPowerY(x, y+1);
return value;
}
}
}
| UTF-8 | Java | 466 | java | C8_Power.java | Java | []
| null | []
| package CCI;
public class C8_Power {
float value=1;
public static void main(String s[]) {
C8_Power power= new C8_Power();
System.out.println(power.getXPowerY(5,-3));
}
public float getXPowerY(int x, int y) {
System.out.println(x+" "+y);
if(y==0) return 1;
else if(y==1) return x;
else if(y>1){
value= value*x*getXPowerY(x, y-1);
return value;
}
else {
value= value/x*getXPowerY(x, y+1);
return value;
}
}
}
| 466 | 0.592275 | 0.566524 | 31 | 14.032258 | 14.36502 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.032258 | false | false | 10 |
8a5f62a7ded065ae2d01c8cd683bd6ab6f9f888c | 8,340,826,525,010 | 5b2c309c903625b14991568c442eb3a889762c71 | /classes/b/a/a/a.java | f67e33481860f344adb71a09518e2d735776a33a | []
| no_license | iidioter/xueqiu | https://github.com/iidioter/xueqiu | c71eb4bcc53480770b9abe20c180da693b2d7946 | a7d8d7dfbaf9e603f72890cf861ed494099f5a80 | refs/heads/master | 2020-12-14T23:55:07.246000 | 2016-10-08T08:56:27 | 2016-10-08T08:56:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package b.a.a;
final class a
implements Runnable
{
final i a;
private final c b;
a(c paramc)
{
this.b = paramc;
this.a = new i();
}
public final void run()
{
h localh = this.a.a();
if (localh == null) {
throw new IllegalStateException("No pending post available");
}
this.b.a(localh);
}
}
/* Location: E:\apk\xueqiu2\classes-dex2jar.jar!\b\a\a\a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 492 | java | a.java | Java | []
| null | []
| package b.a.a;
final class a
implements Runnable
{
final i a;
private final c b;
a(c paramc)
{
this.b = paramc;
this.a = new i();
}
public final void run()
{
h localh = this.a.a();
if (localh == null) {
throw new IllegalStateException("No pending post available");
}
this.b.a(localh);
}
}
/* Location: E:\apk\xueqiu2\classes-dex2jar.jar!\b\a\a\a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 492 | 0.565041 | 0.546748 | 29 | 16 | 18.207615 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275862 | false | false | 10 |
efb0c09115abdcd31863e98a2d47fc5decc0aae6 | 26,336,739,483,009 | d37db1e0d77106292010d84821a8e62c88715fd5 | /src/main/java/com/hp/hpl/json/JsonUtils.java | 13b644e7940a1efa0ddbf89ce473acb3a26bf59d | [
"Apache-2.0"
]
| permissive | duantonghai1984/Research | https://github.com/duantonghai1984/Research | 35caced4f5cdf954a22ce3a6ef6ddc2b8cc8cdab | 67ac958087125a77149f4ae7d35859f2d8d62a51 | refs/heads/master | 2021-01-19T09:35:00.829000 | 2017-07-12T02:54:37 | 2017-07-12T02:54:37 | 87,766,316 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hp.hpl.json;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JsonUtils {
final static Log log = LogFactory.getLog(JsonUtils.class);
/**
* 将数据集转化为json对象
{
"total":2,
"rows":[
{"code":"001","name":"Name 1","addr":"Address 11","col4":"col4 data"},
{"code":"010","name":"Name 10","addr":"Address 78","col4":"col4 data"}
]
}
* @param totalCount
* @param obj
* @return
*/
public static JSONObject toGridJson(int totalCount,Object obj){
//如果数据集对象为null做个特殊处理
if(null==obj){
JSONObject jsonResult = new JSONObject();
jsonResult.put("total", totalCount);
jsonResult.put("rows", new JSONArray());
return jsonResult;
}
if(!Collection.class.isAssignableFrom(obj.getClass())){
JSONObject jsonResult = new JSONObject();
jsonResult.put("total", totalCount);
jsonResult.put("rows", new JSONArray());
return jsonResult;
}
JSONArray jsonArray = JSONArray.fromObject(obj);
JSONObject jsonResult = new JSONObject();
jsonResult.put("total", totalCount);
jsonResult.put("rows", jsonArray);
return jsonResult;
}
public static boolean isBaseType(Object obj){
boolean result1=Number.class.isInstance(obj);
result1=result1 ||String.class.isInstance(obj);
result1=result1 ||Character.class.isInstance(obj);
result1=result1 ||Byte.class.isInstance(obj);
result1=result1 ||Boolean.class.isInstance(obj);
result1=result1 ||Void.class.isInstance(obj);
result1=result1 || obj==null;
result1=result1 ||Date.class.isInstance(obj);
return result1;
}
public static String getJsonArrayStrFromObject(Collection obj){
JSONArray jsonArray=new JSONArray();
Iterator it=obj.iterator();
while(it.hasNext()){
Object objT=it.next();
if(isBaseType(objT)){
jsonArray.add(objT);
}else{
jsonArray.add(getJsonFromObject(objT));
}
}
return jsonArray.toString();
}
public static JSONArray getJsonArrayFromObject(Collection obj){
JSONArray jsonArray=new JSONArray();
Iterator it=obj.iterator();
while(it.hasNext()){
Object objT=it.next();
if(isBaseType(objT)){
jsonArray.add(objT);
}else{
jsonArray.add(getJsonFromObject(objT));
}
}
return jsonArray;
}
private static JSONObject transMapToJson(Map<Object,Object> obj) {
if (Map.class.isInstance(obj)) {
JSONObject json = new JSONObject();
Iterator<Map.Entry<Object,Object>> it = ((Map<Object,Object>) obj).entrySet().iterator();
Map.Entry entry = null;
while (it.hasNext()) {
entry = it.next();
if (isBaseType(entry.getValue())) {
json.put(entry.getKey(), entry.getValue());
} else {
json.put(entry.getKey(), getJsonFromObject(entry.getValue()));
}
}
return json;
}else{
throw new RuntimeException("input is not map");
}
}
public static JSONObject getJsonFromObject(Object obj){
if(Collection.class.isInstance(obj)){
throw new RuntimeException("arg is a collection");
}
if(Map.class.isInstance(obj)){
return transMapToJson((Map)obj);
}
JSONObject json=new JSONObject();
Method[] methods=obj.getClass().getMethods();
Object temp=null;
String tempMname="";
String jsonKey="";
for(Method method:methods){
temp=null;
tempMname=method.getName();
if(tempMname.startsWith("get") && tempMname.indexOf("Class")==-1
&& (method.getParameterTypes()==null ||method.getParameterTypes().length==0)){
try {
temp=method.invoke(obj);
jsonKey=method.getName().substring(3);
jsonKey=jsonKey.substring(0, 1).toLowerCase()+jsonKey.substring(1);
if(temp!=null){
//process map
if(Map.class.isInstance(temp)){
json.put(jsonKey, transMapToJson((Map)temp));
}else if(Collection.class.isInstance(temp)){ //process collection
String jsonArray=getJsonArrayStrFromObject((Collection)temp);
json.put(jsonKey, new String(jsonArray.trim()));
}else{ //other type object
json.put(jsonKey, temp.toString().trim());
}
}else{
json.put(jsonKey, "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return json;
}
public static Object getObjectFromJson(Class cls,JSONObject json,Map<String,Class> subElementClses){
try {
Object t=cls.newInstance();
Method[] methods=cls.getDeclaredMethods();
String methodName="";
for(Method method:methods){
methodName=method.getName();
if (methodName.startsWith("get")
&& methodName.indexOf("Class") == -1
&& (method.getParameterTypes() == null
|| method.getParameterTypes().length == 0)) {
executeSetMethod(t,method,json,subElementClses);
}
}
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
private static void executeSetMethod(Object instance,Method method,JSONObject json,Map<String,Class> subElementClses) throws Exception{
String methodName=method.getName();
String jsonKey=methodName.substring(3);
jsonKey=jsonKey.substring(0, 1).toLowerCase()+jsonKey.substring(1);
if (!json.containsKey(jsonKey)) {
return;
}
Class paraCls=method.getReturnType();
Object jsValue=null;
if(paraCls.isPrimitive()){
if(paraCls.isAssignableFrom(int.class)){
jsValue=json.getInt(jsonKey);
}else if(paraCls.isAssignableFrom(double.class)){
jsValue=json.getDouble(jsonKey);
}else if(paraCls.isAssignableFrom(float.class)){
jsValue=new Float(json.getString(jsonKey));
}else if(paraCls.isAssignableFrom(boolean.class)){
jsValue=json.getBoolean(jsonKey);
}else if(paraCls.isAssignableFrom(short.class)){
jsValue=new Short(json.getString(jsonKey));
}else if(paraCls.isAssignableFrom(long.class)){
jsValue=json.getLong(jsonKey);
}else if(paraCls.isAssignableFrom(char.class)){
jsValue=new Character(json.getString(jsonKey).charAt(0));
}
}else if(Number.class.isAssignableFrom(paraCls) || String.class.isAssignableFrom(paraCls)
|| Boolean.class.isAssignableFrom(paraCls)){
if(json.getString(jsonKey)!=null){
jsValue=paraCls.getConstructor(String.class).newInstance(json.getString(jsonKey));
}
}else if(Collection.class.isAssignableFrom(paraCls)) {
if(subElementClses==null ||subElementClses.isEmpty()){
return;
}
Collection collection=null;
if(!paraCls.isInterface()){
collection=(Collection) paraCls.newInstance();
}else{
collection=(Collection) ArrayList.class.newInstance();
}
Class subCls=subElementClses.get(jsonKey);
if(subCls!=null){
JSONArray jsonArray = json.getJSONArray(jsonKey);
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonObj=jsonArray.getJSONObject(i);
collection.add(JsonUtils.getObjectFromJson(subCls,jsonObj,null));
}
jsValue=collection;
}
}
Method setMethod = instance.getClass().getMethod(methodName.replace("get", "set"),paraCls);
if (setMethod != null && jsValue!=null && setMethod.getParameterTypes().length==1) {
setMethod.invoke(instance, jsValue);
}else{
log.debug("not execute "+methodName.replace("get", "set")+" paraType:"+paraCls+" arg:"+jsValue);
//System.out.println("can not find method:"+methodName.replace("get", "set"));
}
}
public static void main(String[] args){
List o=new ArrayList();
for(int i=0;i<10;i++){
o.add("duant"+i);
}
// System.out.println(JsonUtils.mapToJsonArray(o));
String method="getNameAccount";
String jsonKey=method.substring(3);
jsonKey=jsonKey.substring(0, 1).toLowerCase()+jsonKey.substring(1);
System.out.println(jsonKey);
}
}
| UTF-8 | Java | 8,186 | java | JsonUtils.java | Java | []
| null | []
| package com.hp.hpl.json;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JsonUtils {
final static Log log = LogFactory.getLog(JsonUtils.class);
/**
* 将数据集转化为json对象
{
"total":2,
"rows":[
{"code":"001","name":"Name 1","addr":"Address 11","col4":"col4 data"},
{"code":"010","name":"Name 10","addr":"Address 78","col4":"col4 data"}
]
}
* @param totalCount
* @param obj
* @return
*/
public static JSONObject toGridJson(int totalCount,Object obj){
//如果数据集对象为null做个特殊处理
if(null==obj){
JSONObject jsonResult = new JSONObject();
jsonResult.put("total", totalCount);
jsonResult.put("rows", new JSONArray());
return jsonResult;
}
if(!Collection.class.isAssignableFrom(obj.getClass())){
JSONObject jsonResult = new JSONObject();
jsonResult.put("total", totalCount);
jsonResult.put("rows", new JSONArray());
return jsonResult;
}
JSONArray jsonArray = JSONArray.fromObject(obj);
JSONObject jsonResult = new JSONObject();
jsonResult.put("total", totalCount);
jsonResult.put("rows", jsonArray);
return jsonResult;
}
public static boolean isBaseType(Object obj){
boolean result1=Number.class.isInstance(obj);
result1=result1 ||String.class.isInstance(obj);
result1=result1 ||Character.class.isInstance(obj);
result1=result1 ||Byte.class.isInstance(obj);
result1=result1 ||Boolean.class.isInstance(obj);
result1=result1 ||Void.class.isInstance(obj);
result1=result1 || obj==null;
result1=result1 ||Date.class.isInstance(obj);
return result1;
}
public static String getJsonArrayStrFromObject(Collection obj){
JSONArray jsonArray=new JSONArray();
Iterator it=obj.iterator();
while(it.hasNext()){
Object objT=it.next();
if(isBaseType(objT)){
jsonArray.add(objT);
}else{
jsonArray.add(getJsonFromObject(objT));
}
}
return jsonArray.toString();
}
public static JSONArray getJsonArrayFromObject(Collection obj){
JSONArray jsonArray=new JSONArray();
Iterator it=obj.iterator();
while(it.hasNext()){
Object objT=it.next();
if(isBaseType(objT)){
jsonArray.add(objT);
}else{
jsonArray.add(getJsonFromObject(objT));
}
}
return jsonArray;
}
private static JSONObject transMapToJson(Map<Object,Object> obj) {
if (Map.class.isInstance(obj)) {
JSONObject json = new JSONObject();
Iterator<Map.Entry<Object,Object>> it = ((Map<Object,Object>) obj).entrySet().iterator();
Map.Entry entry = null;
while (it.hasNext()) {
entry = it.next();
if (isBaseType(entry.getValue())) {
json.put(entry.getKey(), entry.getValue());
} else {
json.put(entry.getKey(), getJsonFromObject(entry.getValue()));
}
}
return json;
}else{
throw new RuntimeException("input is not map");
}
}
public static JSONObject getJsonFromObject(Object obj){
if(Collection.class.isInstance(obj)){
throw new RuntimeException("arg is a collection");
}
if(Map.class.isInstance(obj)){
return transMapToJson((Map)obj);
}
JSONObject json=new JSONObject();
Method[] methods=obj.getClass().getMethods();
Object temp=null;
String tempMname="";
String jsonKey="";
for(Method method:methods){
temp=null;
tempMname=method.getName();
if(tempMname.startsWith("get") && tempMname.indexOf("Class")==-1
&& (method.getParameterTypes()==null ||method.getParameterTypes().length==0)){
try {
temp=method.invoke(obj);
jsonKey=method.getName().substring(3);
jsonKey=jsonKey.substring(0, 1).toLowerCase()+jsonKey.substring(1);
if(temp!=null){
//process map
if(Map.class.isInstance(temp)){
json.put(jsonKey, transMapToJson((Map)temp));
}else if(Collection.class.isInstance(temp)){ //process collection
String jsonArray=getJsonArrayStrFromObject((Collection)temp);
json.put(jsonKey, new String(jsonArray.trim()));
}else{ //other type object
json.put(jsonKey, temp.toString().trim());
}
}else{
json.put(jsonKey, "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return json;
}
public static Object getObjectFromJson(Class cls,JSONObject json,Map<String,Class> subElementClses){
try {
Object t=cls.newInstance();
Method[] methods=cls.getDeclaredMethods();
String methodName="";
for(Method method:methods){
methodName=method.getName();
if (methodName.startsWith("get")
&& methodName.indexOf("Class") == -1
&& (method.getParameterTypes() == null
|| method.getParameterTypes().length == 0)) {
executeSetMethod(t,method,json,subElementClses);
}
}
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
private static void executeSetMethod(Object instance,Method method,JSONObject json,Map<String,Class> subElementClses) throws Exception{
String methodName=method.getName();
String jsonKey=methodName.substring(3);
jsonKey=jsonKey.substring(0, 1).toLowerCase()+jsonKey.substring(1);
if (!json.containsKey(jsonKey)) {
return;
}
Class paraCls=method.getReturnType();
Object jsValue=null;
if(paraCls.isPrimitive()){
if(paraCls.isAssignableFrom(int.class)){
jsValue=json.getInt(jsonKey);
}else if(paraCls.isAssignableFrom(double.class)){
jsValue=json.getDouble(jsonKey);
}else if(paraCls.isAssignableFrom(float.class)){
jsValue=new Float(json.getString(jsonKey));
}else if(paraCls.isAssignableFrom(boolean.class)){
jsValue=json.getBoolean(jsonKey);
}else if(paraCls.isAssignableFrom(short.class)){
jsValue=new Short(json.getString(jsonKey));
}else if(paraCls.isAssignableFrom(long.class)){
jsValue=json.getLong(jsonKey);
}else if(paraCls.isAssignableFrom(char.class)){
jsValue=new Character(json.getString(jsonKey).charAt(0));
}
}else if(Number.class.isAssignableFrom(paraCls) || String.class.isAssignableFrom(paraCls)
|| Boolean.class.isAssignableFrom(paraCls)){
if(json.getString(jsonKey)!=null){
jsValue=paraCls.getConstructor(String.class).newInstance(json.getString(jsonKey));
}
}else if(Collection.class.isAssignableFrom(paraCls)) {
if(subElementClses==null ||subElementClses.isEmpty()){
return;
}
Collection collection=null;
if(!paraCls.isInterface()){
collection=(Collection) paraCls.newInstance();
}else{
collection=(Collection) ArrayList.class.newInstance();
}
Class subCls=subElementClses.get(jsonKey);
if(subCls!=null){
JSONArray jsonArray = json.getJSONArray(jsonKey);
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonObj=jsonArray.getJSONObject(i);
collection.add(JsonUtils.getObjectFromJson(subCls,jsonObj,null));
}
jsValue=collection;
}
}
Method setMethod = instance.getClass().getMethod(methodName.replace("get", "set"),paraCls);
if (setMethod != null && jsValue!=null && setMethod.getParameterTypes().length==1) {
setMethod.invoke(instance, jsValue);
}else{
log.debug("not execute "+methodName.replace("get", "set")+" paraType:"+paraCls+" arg:"+jsValue);
//System.out.println("can not find method:"+methodName.replace("get", "set"));
}
}
public static void main(String[] args){
List o=new ArrayList();
for(int i=0;i<10;i++){
o.add("duant"+i);
}
// System.out.println(JsonUtils.mapToJsonArray(o));
String method="getNameAccount";
String jsonKey=method.substring(3);
jsonKey=jsonKey.substring(0, 1).toLowerCase()+jsonKey.substring(1);
System.out.println(jsonKey);
}
}
| 8,186 | 0.664128 | 0.657248 | 262 | 30.068703 | 24.441608 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.198473 | false | false | 10 |
91b7c5ad56b3c4c6a8dec090f0bff67b73fc7aa9 | 12,678,743,507,880 | abe49d8d8a0fc950e4d99022adeb701a103aa1af | /unified-report/validation-proxy/src/main/java/validator/Validation.java | 78c4fc78c709b3d210803da14022e99843b3fc43 | []
| no_license | usnistgov/unified-report | https://github.com/usnistgov/unified-report | 5ddd052f4bef91847b07d7df496d55a7df13cc3a | 74110e12f242f6e5d1bb00caeabbaa7e87feabc8 | refs/heads/master | 2023-06-25T13:47:18.341000 | 2022-09-19T13:29:21 | 2022-09-19T13:29:21 | 42,546,262 | 0 | 0 | null | false | 2023-04-14T17:12:27 | 2015-09-15T21:00:14 | 2022-09-19T13:29:37 | 2023-04-14T17:12:27 | 158 | 0 | 1 | 1 | Java | false | false | package validator;
import java.io.InputStream;
import java.io.Reader;
import java.util.Arrays;
import java.util.List;
import javax.xml.validation.Schema;
import gov.nist.validation.report.Report;
import hl7.v2.profile.Profile;
import hl7.v2.profile.XMLDeserializer;
import hl7.v2.validation.SyncHL7Validator;
import hl7.v2.validation.content.ConformanceContext;
import hl7.v2.validation.content.DefaultConformanceContext;
import hl7.v2.validation.vs.ValueSetLibrary;
import hl7.v2.validation.vs.ValueSetLibraryImpl;
public class Validation {
public static Report validate(String profile,String constraint,String vs,String message,String id) throws Exception{
// InputStream is_pro = Validation.class.getResourceAsStream(profile);
// InputStream is_cons = Validation.class.getResourceAsStream(constraint);
// InputStream is_vs = Validation.class.getResourceAsStream(vs);
Profile is_pro = getProfile(profile);
ConformanceContext is_cons = getConformanceContext(constraint);
ValueSetLibrary is_vs = getValueSetLibrary(vs);
// ConformanceContext c = DefaultConformanceContext.apply(is_cons).get();
// Map<String, Function3<Plugin, Element, Separators, EvalResult>> pluginMap = Map$.MODULE$.empty();
// ValueSetLibrary valueSetLibrary = ValueSetLibrary.apply(is_vs).get();
return new SyncHL7Validator(is_pro, is_vs, is_cons).check(message, id);
}
public static Report validate(Profile profile,ConformanceContext constraint,ValueSetLibrary vs,String message,String id,Reader configuration) throws Exception{
return new SyncHL7Validator(profile, vs, constraint).checkUsingConfiguration(message, id,configuration);
}
public static Report validate(Profile profile,ConformanceContext constraint,ValueSetLibrary vs,String message,String id) throws Exception{
return new SyncHL7Validator(profile, vs, constraint).check(message, id);
}
public static Report validate(String xmlFile, List<Schema> schemas, List<String> schematrons, String phase){
return gov.nist.hit.xml.Validator.validate(xmlFile,schemas,schematrons,phase);
}
public static Report validate(String wctpFile){
return gov.nist.hit.wctp.WCTPValidation.generic(wctpFile);
}
// public static Report validate(){
// try {
//
// SyncHL7Validator validator = createValidator("/izp/Profile.xml", "/izp/Constraints.xml", "/izp/ValueSets_Validation.xml");
// // The message instance (ER7)
// String message = Util.streamAsString("/izp/message.er7");
//
// // The check method will throw an exception if something goes wrong
// Report report = validator.check(message, "bfb1c703-c96e-4f2b-8950-3f5b1c9cd2d8");
//
// // Print the report
// //report.prettyPrint();
//
// return report;
//
//
//
// } catch(Exception e) {
// e.printStackTrace();
// return null;
// }
// }
// private static SyncHL7Validator createValidator(
// String profileFileName,
// String constraintsFileName,
// String valueSetLibFileName) throws Exception {
//
// // The profile in XML
// InputStream profileXML = Validation.class.getResourceAsStream(profileFileName);
//
// // ### [Update]
// // The conformance context file XML
// InputStream confContext = Validation.class.getResourceAsStream(constraintsFileName);
//
// // The get() at the end will throw an exception if something goes wrong
// Profile profile = XMLDeserializer.deserialize(profileXML).get();
//
// // ### [Update]
// // The get() at the end will throw an exception if something goes wrong
// ConformanceContext c = DefaultConformanceContext.apply(confContext).get();
//
// // The plugin map. This should be empty if no plugin is used
// Map<String, Function3<Plugin, Element, Separators, EvalResult>> pluginMap = Map$.MODULE$.empty();
//
//
// InputStream vsLibXML = Validation.class.getResourceAsStream(valueSetLibFileName);
// ValueSetLibrary valueSetLibrary = ValueSetLibrary.apply(vsLibXML).get();
//
// // A java friendly version of an HL7 validator
// // This should be a singleton for a specific tool. We create it once and reuse it across validations
// return new SyncHL7Validator(profile, valueSetLibrary, c);
// }
static Profile getProfile(String name) {
// The profile in XML
InputStream profileXML = Util.class.getResourceAsStream(name);
// The get() at the end will throw an exception if something goes wrong
Profile profile = XMLDeserializer.deserialize(profileXML).get();
return profile;
}
/**
* @return An instance of the conformance context
*/
static ConformanceContext getConformanceContext(String name) {
// The first conformance context XML file
InputStream contextXML1 = Util.class.getResourceAsStream(name);
// The second conformance context XML file
//InputStream contextXML2 = ValidationApp.class.getResourceAsStream("/Predicates.xml");
List<InputStream> confContexts = Arrays.asList( contextXML1 );
// The get() at the end will throw an exception if something goes wrong
ConformanceContext c = DefaultConformanceContext.apply(confContexts).get();
return c;
}
/**
* @return An instance of the value set library
*/
static ValueSetLibrary getValueSetLibrary(String name) {
InputStream vsLibXML = Util.class.getResourceAsStream(name);
ValueSetLibrary valueSetLibrary = ValueSetLibraryImpl.apply(vsLibXML).get();
return valueSetLibrary;
}
}
| UTF-8 | Java | 5,337 | java | Validation.java | Java | []
| null | []
| package validator;
import java.io.InputStream;
import java.io.Reader;
import java.util.Arrays;
import java.util.List;
import javax.xml.validation.Schema;
import gov.nist.validation.report.Report;
import hl7.v2.profile.Profile;
import hl7.v2.profile.XMLDeserializer;
import hl7.v2.validation.SyncHL7Validator;
import hl7.v2.validation.content.ConformanceContext;
import hl7.v2.validation.content.DefaultConformanceContext;
import hl7.v2.validation.vs.ValueSetLibrary;
import hl7.v2.validation.vs.ValueSetLibraryImpl;
public class Validation {
public static Report validate(String profile,String constraint,String vs,String message,String id) throws Exception{
// InputStream is_pro = Validation.class.getResourceAsStream(profile);
// InputStream is_cons = Validation.class.getResourceAsStream(constraint);
// InputStream is_vs = Validation.class.getResourceAsStream(vs);
Profile is_pro = getProfile(profile);
ConformanceContext is_cons = getConformanceContext(constraint);
ValueSetLibrary is_vs = getValueSetLibrary(vs);
// ConformanceContext c = DefaultConformanceContext.apply(is_cons).get();
// Map<String, Function3<Plugin, Element, Separators, EvalResult>> pluginMap = Map$.MODULE$.empty();
// ValueSetLibrary valueSetLibrary = ValueSetLibrary.apply(is_vs).get();
return new SyncHL7Validator(is_pro, is_vs, is_cons).check(message, id);
}
public static Report validate(Profile profile,ConformanceContext constraint,ValueSetLibrary vs,String message,String id,Reader configuration) throws Exception{
return new SyncHL7Validator(profile, vs, constraint).checkUsingConfiguration(message, id,configuration);
}
public static Report validate(Profile profile,ConformanceContext constraint,ValueSetLibrary vs,String message,String id) throws Exception{
return new SyncHL7Validator(profile, vs, constraint).check(message, id);
}
public static Report validate(String xmlFile, List<Schema> schemas, List<String> schematrons, String phase){
return gov.nist.hit.xml.Validator.validate(xmlFile,schemas,schematrons,phase);
}
public static Report validate(String wctpFile){
return gov.nist.hit.wctp.WCTPValidation.generic(wctpFile);
}
// public static Report validate(){
// try {
//
// SyncHL7Validator validator = createValidator("/izp/Profile.xml", "/izp/Constraints.xml", "/izp/ValueSets_Validation.xml");
// // The message instance (ER7)
// String message = Util.streamAsString("/izp/message.er7");
//
// // The check method will throw an exception if something goes wrong
// Report report = validator.check(message, "bfb1c703-c96e-4f2b-8950-3f5b1c9cd2d8");
//
// // Print the report
// //report.prettyPrint();
//
// return report;
//
//
//
// } catch(Exception e) {
// e.printStackTrace();
// return null;
// }
// }
// private static SyncHL7Validator createValidator(
// String profileFileName,
// String constraintsFileName,
// String valueSetLibFileName) throws Exception {
//
// // The profile in XML
// InputStream profileXML = Validation.class.getResourceAsStream(profileFileName);
//
// // ### [Update]
// // The conformance context file XML
// InputStream confContext = Validation.class.getResourceAsStream(constraintsFileName);
//
// // The get() at the end will throw an exception if something goes wrong
// Profile profile = XMLDeserializer.deserialize(profileXML).get();
//
// // ### [Update]
// // The get() at the end will throw an exception if something goes wrong
// ConformanceContext c = DefaultConformanceContext.apply(confContext).get();
//
// // The plugin map. This should be empty if no plugin is used
// Map<String, Function3<Plugin, Element, Separators, EvalResult>> pluginMap = Map$.MODULE$.empty();
//
//
// InputStream vsLibXML = Validation.class.getResourceAsStream(valueSetLibFileName);
// ValueSetLibrary valueSetLibrary = ValueSetLibrary.apply(vsLibXML).get();
//
// // A java friendly version of an HL7 validator
// // This should be a singleton for a specific tool. We create it once and reuse it across validations
// return new SyncHL7Validator(profile, valueSetLibrary, c);
// }
static Profile getProfile(String name) {
// The profile in XML
InputStream profileXML = Util.class.getResourceAsStream(name);
// The get() at the end will throw an exception if something goes wrong
Profile profile = XMLDeserializer.deserialize(profileXML).get();
return profile;
}
/**
* @return An instance of the conformance context
*/
static ConformanceContext getConformanceContext(String name) {
// The first conformance context XML file
InputStream contextXML1 = Util.class.getResourceAsStream(name);
// The second conformance context XML file
//InputStream contextXML2 = ValidationApp.class.getResourceAsStream("/Predicates.xml");
List<InputStream> confContexts = Arrays.asList( contextXML1 );
// The get() at the end will throw an exception if something goes wrong
ConformanceContext c = DefaultConformanceContext.apply(confContexts).get();
return c;
}
/**
* @return An instance of the value set library
*/
static ValueSetLibrary getValueSetLibrary(String name) {
InputStream vsLibXML = Util.class.getResourceAsStream(name);
ValueSetLibrary valueSetLibrary = ValueSetLibraryImpl.apply(vsLibXML).get();
return valueSetLibrary;
}
}
| 5,337 | 0.750609 | 0.741803 | 144 | 36.0625 | 35.675274 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.125 | false | false | 10 |
6c103c13c72790ac927733e3a23d59cd0e51b0fc | 35,338,990,958,077 | 54a186406765dd7e25917d4256003b73212f934b | /Assignment 2/src/Database.java | f25a0e412ad52cab536ed887b82104e8f8fa9219 | []
| no_license | mazatsushi/CSC-102-Assignments | https://github.com/mazatsushi/CSC-102-Assignments | 340ba9fec0ec1f38f0151f3bb2e6beea55e3a7df | f59054dd0470bac411bb9eba1f3ae8f90d08c1d0 | refs/heads/master | 2021-01-10T19:20:25.206000 | 2012-05-28T12:14:30 | 2012-05-28T12:14:51 | 3,623,912 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @Student Name: Desmond Poh Lik Meng
* @Lab Group: BCG1
*/
// Import classes not included in the default Java environment
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
/*
* @Exception handling for this class is handled by itself
* @This is to provide more granular control over the type of error messages displayed
*/
public class Database {
/*
* @Private attributes for the class
*/
private Abbreviation [] abbreviations;
private BufferedReader br;
private StreamTokenizer input;
/*
* @Default constructor
* @Accepts the name of the file containing the entire list of abbreviations
* @List of abbreviations is reconstructed, saved and stored on RAM while the main program runs
* @Does not create new abbreviations, and thus no need to save the list of abbreviations upon exiting
*/
public Database(String filename) throws IOException, NullPointerException {
try {
/*
* @Create a new data input stream using a buffered reader
* @This buffered reader wraps around the resource-intensive file reader class
* @The file reader in turn wraps around a file class that represents the abbreviations database
* @The buffered reader is then wrapped with a stream tokenizer to read input as various tokens
* @Since the buffered reader is initialized separately, it can be closed once not needed
*/
br = new BufferedReader(new FileReader(new File(filename)));
input = new StreamTokenizer(br);
// Set boolean flags for special delimiters
input.eolIsSignificant(true);
input.ordinaryChar('"');
// Declared here are local scope variables and flags to be used
ArrayList<Abbreviation> al = new ArrayList<Abbreviation>();
String abbr = null;
StringBuffer abbrName = new StringBuffer();
boolean isNewLine = true, isAfterHyphen = false;
/*
* @Loop through the entire input file just once, reading one token at a time
* @The tokens are used to internally create a new abbreviation object once there is sufficient information
* @The entire database of abbreviations is temporarily stored in an array list while being reconstructed
* @After reconstruction, the array list is converted into an abbreviation object array and saved
*/
while (input.nextToken() != StreamTokenizer.TT_EOF) {
// Action to take if token is a string
if (input.ttype == StreamTokenizer.TT_WORD) {
// If the string is after a new line, then it is an abbreviation
if (isNewLine) {
abbr = new String(input.sval);
isNewLine = false;
}
else {
// If the string is after a '-', then it is the start of the abbreviation's name
if (isAfterHyphen) {
abbrName.append(input.sval);
isAfterHyphen = false;
}
else {
abbrName.append(" ");
abbrName.append(input.sval);
}
}
}
// Action to take if token is a '-'
else if (input.ttype == KeyEvent.VK_MINUS) {
isAfterHyphen = true;
}
// Action to take if token is a ','
else if (input.ttype == KeyEvent.VK_COMMA) {
abbrName.append(",");
}
// Action to take if token is a '
else if (input.ttype == KeyEvent.VK_RIGHT) {
abbrName.append("'");
abbrName.append(input.sval);
}
// Action to take if token is a new line
else if (input.ttype == StreamTokenizer.TT_EOL) {
add(al, abbr, abbrName);
abbr = null;
abbrName = new StringBuffer();
isNewLine = true;
isAfterHyphen = false;
}
}
/*
* @As the loop exits upon hitting the end of file token, the last token is always not added
* @Fortunately the information needed to the last abbreviation object is already saved to the control variables
* @This line of code adds that last object to the array list
*/
add(al, abbr, abbrName);
/*
* @Convert and store the array list of abbreviations into the attribute
* @The entire list is sorted as a prerequisite for the search algorithm implemented
*/
abbreviations = new Abbreviation[al.size()];
al.toArray(abbreviations);
sort(abbreviations, 0, abbreviations.length - 1);
}
// This exception is thrown when the abbreviation list file cannot be found
catch (FileNotFoundException e) {
System.out.print("\nCannot find \"abbreviations.txt\"!");
System.out.print("\nPlease ensure that \"abbreviations.txt\" is in the same directory as the program before trying again.");
System.out.print("\nThe program will now terminate.\n");
System.exit(1);
}
// This exception is thrown when some error occurs while reading in from the abbreviation list
catch (IOException e) {
System.out.print("\nAn error occured while performing a file read from \"abbreviations.txt\".");
System.out.print("\nPossilities for this error is due to the following: ");
System.out.print("\n 1) Failure or interrupted read operation while reading from " + filename);
System.out.print("\nPlease contact your system administrator for further assistance.");
}
finally {
/*
* @Unlike most other variables, the buffered reader continues to hog system resources regardless of the success of the IO operation
* @It is therefore closed here explicitly to free system resources
*/
if (br != null) {
br.close();
}
}
}
/*
* @Method that adds a new abbreviation object to the array list during reconstruction
* @First checks if the object to be added actually exists within the list
* @If exists, simply add a new name to the existing object
* @If does not exist, create and add to a new object to the list
*/
private void add(ArrayList<Abbreviation> al, String abbr, StringBuffer abbrName) {
// Check for an empty array list, valid only for the first object added
if (al.isEmpty()) {
al.add(new Abbreviation(abbr, abbrName.toString()));
}
else {
// Check to see if any previous abbreviation is the same
int index = exists(al, abbr);
if (index != -1) {
Abbreviation temp = al.get(index);
temp.addFullName(abbrName.toString());
}
else {
al.add(new Abbreviation(abbr, abbrName.toString()));
}
}
}
/*
* @Method that searches for an existing abbreviation during attribute reconstruction
* @Unfortunately as the array list is not yet sorted at this point of time the search has to done sequentially
* @This on top of being called once for every new abbreviation object added to the array list
* @Efforts will be made to implement the insertion sort algorithm in future to try reduce this overhead
*/
private int exists(ArrayList<Abbreviation> al, String abbr) {
int index = -1;
for (int i = 0; i < al.size(); ++i) {
if (abbr.compareToIgnoreCase(al.get(i).getAbbrName()) == 0) {
index = i;
break;
}
}
return index;
}
/*
* @Method that returns the total number of abbreviations
*/
public int getNumAbbreviations() {
return (abbreviations.length);
}
/*
* @Method that returns an Abbreviation object from a valid index
*/
public Abbreviation getAbbreviationByIndex(int index) {
Abbreviation a = null;
if ((getNumAbbreviations() > 0) && (index > -1) && (index < abbreviations.length)) {
a = new Abbreviation(abbreviations[index]);
}
return a;
}
/*
* @Method that prints all abbreviations in the array
*/
public void printAllAbbreviations() {
if (getNumAbbreviations() < 1) {
System.out.println("\nThere are no abbreviations to print!");
}
else {
System.out.print("\nAll available abbreviations (in alphabetical order): ");
for (int i = 0; i < getNumAbbreviations(); ++i) {
System.out.print("\n" + abbreviations[i].getAbbrName());
}
System.out.print("\n");
}
}
/*
* @Recursive method that sorts the elements in the attribute after initialization
* @Calls another method that implements the actual sorting algorithm
*/
private void sort(Abbreviation [] a, int start, int end) {
int index = quickSort(a, start, end);
if (index - 1 > start) {
sort(a, start, index - 1);
}
if (index < end) {
sort(a, index, end);
}
}
/*
* @Method that sorts the elements in the attribute using quick sort
*/
private int quickSort(Abbreviation [] a, int start, int end) {
int left = start;
int right = end;
Abbreviation ab = abbreviations[(start + end) / 2];
while (left <= right) {
// Keep advancing so long as current string is smaller than pivot string
while ((abbreviations[left].getAbbrName().compareToIgnoreCase(ab.getAbbrName())) < 0) {
++left;
}
// Keep retreating so long as current string is larger than pivot string
while ((abbreviations[right].getAbbrName().compareToIgnoreCase(ab.getAbbrName())) > 0){
--right;
}
/*
* @At this point, left string is larger in value than pivot string
* @At this point, right string is also larger in value than pivot string
* @Check that left the left string position is smaller than right string position
* @All three conditions fulfilled means that both strings should be swapped
*/
if (left <= right) {
Abbreviation temp = abbreviations[right];
abbreviations[right] = abbreviations[left];
abbreviations[left] = temp;
++left;
--right;
}
}
return left;
}
/*
* @Method that searches for an exact match of the specified abbreviation
* @Calls another method that implements the actual search algorithm
* @The abbreviations attribute will already have been sorted beforehand
*/
public Abbreviation queryByAbbrName(String target) {
// Placeholder for the pivot element as it is referenced more than once
return BinarySearch(abbreviations, target, 0, (getNumAbbreviations() - 1));
}
/*
* @Recursive method that searches for exact abbreviation match using binary search
* @Initial UML design hints at using sequential search which has O(n) performance
* @This method can do the same in O(log n) performance
*/
private Abbreviation BinarySearch(Abbreviation [] abbr, String target, int start, int end) {
// Code block for possibility of not finding anything, starting from next line
if (start > end) {
return null;
}
// Code block for possibility of finding target value
int pivot = (start + end) / 2;
/*
* @Placeholder for whether target value is the same, larger, smaller than compared value
* @Declared and used as the variable is reference more than once
*/
int comparator = target.compareToIgnoreCase(abbreviations[pivot].getAbbrName());
// Exact match found
if (comparator == 0) {
return (new Abbreviation(abbreviations[pivot]));
}
// Target value is to the right of the pivot
else if (comparator > 0) {
return BinarySearch(abbr, target, (pivot + 1), end);
}
// Target value is to the left of the pivot
else {
return BinarySearch(abbr, target, start, (pivot - 1));
}
}
/*
* @Method that returns all abbreviations whose prefix matches the argument
* @Array is searched through sequentially as there can be more than one result
* @To reduce overhead, in future maybe this portion can use multi-threaded access
*/
public Abbreviation [] queryByAbbrPrefix(String abbrPrefix) {
// Code block to identify the first and last elements of the matching prefixes
int end = -2, start = -1;
for (int i = 0; i < getNumAbbreviations(); ++i) {
if (abbreviations[i].matchByAbbrPrefix(abbrPrefix)) {
// Start element has not yet been identified
if (start < 0) {
start = end = i;
}
// Start element has already been identified
else {
end = i;
}
}
}
if (!(start > end)) {
return Arrays.copyOfRange(abbreviations, start, end + 1);
}
return null;
}
} | UTF-8 | Java | 11,885 | java | Database.java | Java | [
{
"context": "/**\n * @Student Name: Desmond Poh Lik Meng\n * @Lab Group: BCG1\n */\n\n// Import classes not in",
"end": 42,
"score": 0.9998679161071777,
"start": 22,
"tag": "NAME",
"value": "Desmond Poh Lik Meng"
}
]
| null | []
| /**
* @Student Name: <NAME>
* @Lab Group: BCG1
*/
// Import classes not included in the default Java environment
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
/*
* @Exception handling for this class is handled by itself
* @This is to provide more granular control over the type of error messages displayed
*/
public class Database {
/*
* @Private attributes for the class
*/
private Abbreviation [] abbreviations;
private BufferedReader br;
private StreamTokenizer input;
/*
* @Default constructor
* @Accepts the name of the file containing the entire list of abbreviations
* @List of abbreviations is reconstructed, saved and stored on RAM while the main program runs
* @Does not create new abbreviations, and thus no need to save the list of abbreviations upon exiting
*/
public Database(String filename) throws IOException, NullPointerException {
try {
/*
* @Create a new data input stream using a buffered reader
* @This buffered reader wraps around the resource-intensive file reader class
* @The file reader in turn wraps around a file class that represents the abbreviations database
* @The buffered reader is then wrapped with a stream tokenizer to read input as various tokens
* @Since the buffered reader is initialized separately, it can be closed once not needed
*/
br = new BufferedReader(new FileReader(new File(filename)));
input = new StreamTokenizer(br);
// Set boolean flags for special delimiters
input.eolIsSignificant(true);
input.ordinaryChar('"');
// Declared here are local scope variables and flags to be used
ArrayList<Abbreviation> al = new ArrayList<Abbreviation>();
String abbr = null;
StringBuffer abbrName = new StringBuffer();
boolean isNewLine = true, isAfterHyphen = false;
/*
* @Loop through the entire input file just once, reading one token at a time
* @The tokens are used to internally create a new abbreviation object once there is sufficient information
* @The entire database of abbreviations is temporarily stored in an array list while being reconstructed
* @After reconstruction, the array list is converted into an abbreviation object array and saved
*/
while (input.nextToken() != StreamTokenizer.TT_EOF) {
// Action to take if token is a string
if (input.ttype == StreamTokenizer.TT_WORD) {
// If the string is after a new line, then it is an abbreviation
if (isNewLine) {
abbr = new String(input.sval);
isNewLine = false;
}
else {
// If the string is after a '-', then it is the start of the abbreviation's name
if (isAfterHyphen) {
abbrName.append(input.sval);
isAfterHyphen = false;
}
else {
abbrName.append(" ");
abbrName.append(input.sval);
}
}
}
// Action to take if token is a '-'
else if (input.ttype == KeyEvent.VK_MINUS) {
isAfterHyphen = true;
}
// Action to take if token is a ','
else if (input.ttype == KeyEvent.VK_COMMA) {
abbrName.append(",");
}
// Action to take if token is a '
else if (input.ttype == KeyEvent.VK_RIGHT) {
abbrName.append("'");
abbrName.append(input.sval);
}
// Action to take if token is a new line
else if (input.ttype == StreamTokenizer.TT_EOL) {
add(al, abbr, abbrName);
abbr = null;
abbrName = new StringBuffer();
isNewLine = true;
isAfterHyphen = false;
}
}
/*
* @As the loop exits upon hitting the end of file token, the last token is always not added
* @Fortunately the information needed to the last abbreviation object is already saved to the control variables
* @This line of code adds that last object to the array list
*/
add(al, abbr, abbrName);
/*
* @Convert and store the array list of abbreviations into the attribute
* @The entire list is sorted as a prerequisite for the search algorithm implemented
*/
abbreviations = new Abbreviation[al.size()];
al.toArray(abbreviations);
sort(abbreviations, 0, abbreviations.length - 1);
}
// This exception is thrown when the abbreviation list file cannot be found
catch (FileNotFoundException e) {
System.out.print("\nCannot find \"abbreviations.txt\"!");
System.out.print("\nPlease ensure that \"abbreviations.txt\" is in the same directory as the program before trying again.");
System.out.print("\nThe program will now terminate.\n");
System.exit(1);
}
// This exception is thrown when some error occurs while reading in from the abbreviation list
catch (IOException e) {
System.out.print("\nAn error occured while performing a file read from \"abbreviations.txt\".");
System.out.print("\nPossilities for this error is due to the following: ");
System.out.print("\n 1) Failure or interrupted read operation while reading from " + filename);
System.out.print("\nPlease contact your system administrator for further assistance.");
}
finally {
/*
* @Unlike most other variables, the buffered reader continues to hog system resources regardless of the success of the IO operation
* @It is therefore closed here explicitly to free system resources
*/
if (br != null) {
br.close();
}
}
}
/*
* @Method that adds a new abbreviation object to the array list during reconstruction
* @First checks if the object to be added actually exists within the list
* @If exists, simply add a new name to the existing object
* @If does not exist, create and add to a new object to the list
*/
private void add(ArrayList<Abbreviation> al, String abbr, StringBuffer abbrName) {
// Check for an empty array list, valid only for the first object added
if (al.isEmpty()) {
al.add(new Abbreviation(abbr, abbrName.toString()));
}
else {
// Check to see if any previous abbreviation is the same
int index = exists(al, abbr);
if (index != -1) {
Abbreviation temp = al.get(index);
temp.addFullName(abbrName.toString());
}
else {
al.add(new Abbreviation(abbr, abbrName.toString()));
}
}
}
/*
* @Method that searches for an existing abbreviation during attribute reconstruction
* @Unfortunately as the array list is not yet sorted at this point of time the search has to done sequentially
* @This on top of being called once for every new abbreviation object added to the array list
* @Efforts will be made to implement the insertion sort algorithm in future to try reduce this overhead
*/
private int exists(ArrayList<Abbreviation> al, String abbr) {
int index = -1;
for (int i = 0; i < al.size(); ++i) {
if (abbr.compareToIgnoreCase(al.get(i).getAbbrName()) == 0) {
index = i;
break;
}
}
return index;
}
/*
* @Method that returns the total number of abbreviations
*/
public int getNumAbbreviations() {
return (abbreviations.length);
}
/*
* @Method that returns an Abbreviation object from a valid index
*/
public Abbreviation getAbbreviationByIndex(int index) {
Abbreviation a = null;
if ((getNumAbbreviations() > 0) && (index > -1) && (index < abbreviations.length)) {
a = new Abbreviation(abbreviations[index]);
}
return a;
}
/*
* @Method that prints all abbreviations in the array
*/
public void printAllAbbreviations() {
if (getNumAbbreviations() < 1) {
System.out.println("\nThere are no abbreviations to print!");
}
else {
System.out.print("\nAll available abbreviations (in alphabetical order): ");
for (int i = 0; i < getNumAbbreviations(); ++i) {
System.out.print("\n" + abbreviations[i].getAbbrName());
}
System.out.print("\n");
}
}
/*
* @Recursive method that sorts the elements in the attribute after initialization
* @Calls another method that implements the actual sorting algorithm
*/
private void sort(Abbreviation [] a, int start, int end) {
int index = quickSort(a, start, end);
if (index - 1 > start) {
sort(a, start, index - 1);
}
if (index < end) {
sort(a, index, end);
}
}
/*
* @Method that sorts the elements in the attribute using quick sort
*/
private int quickSort(Abbreviation [] a, int start, int end) {
int left = start;
int right = end;
Abbreviation ab = abbreviations[(start + end) / 2];
while (left <= right) {
// Keep advancing so long as current string is smaller than pivot string
while ((abbreviations[left].getAbbrName().compareToIgnoreCase(ab.getAbbrName())) < 0) {
++left;
}
// Keep retreating so long as current string is larger than pivot string
while ((abbreviations[right].getAbbrName().compareToIgnoreCase(ab.getAbbrName())) > 0){
--right;
}
/*
* @At this point, left string is larger in value than pivot string
* @At this point, right string is also larger in value than pivot string
* @Check that left the left string position is smaller than right string position
* @All three conditions fulfilled means that both strings should be swapped
*/
if (left <= right) {
Abbreviation temp = abbreviations[right];
abbreviations[right] = abbreviations[left];
abbreviations[left] = temp;
++left;
--right;
}
}
return left;
}
/*
* @Method that searches for an exact match of the specified abbreviation
* @Calls another method that implements the actual search algorithm
* @The abbreviations attribute will already have been sorted beforehand
*/
public Abbreviation queryByAbbrName(String target) {
// Placeholder for the pivot element as it is referenced more than once
return BinarySearch(abbreviations, target, 0, (getNumAbbreviations() - 1));
}
/*
* @Recursive method that searches for exact abbreviation match using binary search
* @Initial UML design hints at using sequential search which has O(n) performance
* @This method can do the same in O(log n) performance
*/
private Abbreviation BinarySearch(Abbreviation [] abbr, String target, int start, int end) {
// Code block for possibility of not finding anything, starting from next line
if (start > end) {
return null;
}
// Code block for possibility of finding target value
int pivot = (start + end) / 2;
/*
* @Placeholder for whether target value is the same, larger, smaller than compared value
* @Declared and used as the variable is reference more than once
*/
int comparator = target.compareToIgnoreCase(abbreviations[pivot].getAbbrName());
// Exact match found
if (comparator == 0) {
return (new Abbreviation(abbreviations[pivot]));
}
// Target value is to the right of the pivot
else if (comparator > 0) {
return BinarySearch(abbr, target, (pivot + 1), end);
}
// Target value is to the left of the pivot
else {
return BinarySearch(abbr, target, start, (pivot - 1));
}
}
/*
* @Method that returns all abbreviations whose prefix matches the argument
* @Array is searched through sequentially as there can be more than one result
* @To reduce overhead, in future maybe this portion can use multi-threaded access
*/
public Abbreviation [] queryByAbbrPrefix(String abbrPrefix) {
// Code block to identify the first and last elements of the matching prefixes
int end = -2, start = -1;
for (int i = 0; i < getNumAbbreviations(); ++i) {
if (abbreviations[i].matchByAbbrPrefix(abbrPrefix)) {
// Start element has not yet been identified
if (start < 0) {
start = end = i;
}
// Start element has already been identified
else {
end = i;
}
}
}
if (!(start > end)) {
return Arrays.copyOfRange(abbreviations, start, end + 1);
}
return null;
}
} | 11,871 | 0.688515 | 0.685991 | 358 | 32.201118 | 32.036446 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.648045 | false | false | 10 |
e2aeda8286c5c6f15b2c4d18360184ed1a41d753 | 39,616,778,340,065 | b264b30b1ab4b03b231c8ddb82b882b29a88fc81 | /src/main/java/fof/action/SelectVietnamAction.java | 7ed6a3f3506b326bc1393142b47e294acf0c4cb1 | []
| no_license | ajmitc/fof | https://github.com/ajmitc/fof | ef85f75be5f3af60cda37c62bd607314f4aa6d87 | a88b66995add8d8fb9d5af9f3b8ac8b3254f0101 | refs/heads/master | 2020-06-04T03:15:30.177000 | 2019-06-21T02:22:15 | 2019-06-21T02:22:15 | 191,851,089 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fof.action;
import fof.game.Model;
import fof.game.war.War;
import fof.scene.MissionSelectionScene;
import fof.scene.SceneStackManager;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
public class SelectVietnamAction implements EventHandler<ActionEvent> {
public SelectVietnamAction() {
}
@Override
public void handle(ActionEvent event) {
Model.getInstance().setWar(War.Vietnam);
SceneStackManager.getInstance().push(new MissionSelectionScene());
}
}
| UTF-8 | Java | 518 | java | SelectVietnamAction.java | Java | []
| null | []
| package fof.action;
import fof.game.Model;
import fof.game.war.War;
import fof.scene.MissionSelectionScene;
import fof.scene.SceneStackManager;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
public class SelectVietnamAction implements EventHandler<ActionEvent> {
public SelectVietnamAction() {
}
@Override
public void handle(ActionEvent event) {
Model.getInstance().setWar(War.Vietnam);
SceneStackManager.getInstance().push(new MissionSelectionScene());
}
}
| 518 | 0.756757 | 0.756757 | 20 | 24.9 | 22.277567 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 10 |
0e5234323c9f081f084f602413b8ee4108ac32c3 | 33,809,982,614,299 | ca0e9689023cc9998c7f24b9e0532261fd976e0e | /src/com/tencent/mm/ui/chatting/ChatFooterCustom$1.java | 8b46e2a5abcd5a69214e9d70000666d76a92765f | []
| no_license | honeyflyfish/com.tencent.mm | https://github.com/honeyflyfish/com.tencent.mm | c7e992f51070f6ac5e9c05e9a2babd7b712cf713 | ce6e605ff98164359a7073ab9a62a3f3101b8c34 | refs/heads/master | 2020-03-28T15:42:52.284000 | 2016-07-19T16:33:30 | 2016-07-19T16:33:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.mm.ui.chatting;
import com.tencent.mm.ui.base.g.c;
final class ChatFooterCustom$1
implements g.c
{
ChatFooterCustom$1(ChatFooterCustom paramChatFooterCustom) {}
public final void fg(int paramInt)
{
switch (paramInt)
{
default:
return;
case 0:
ChatFooterCustom.a(lrR);
return;
}
ChatFooterCustom.b(lrR);
}
}
/* Location:
* Qualified Name: com.tencent.mm.ui.chatting.ChatFooterCustom.1
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 533 | java | ChatFooterCustom$1.java | Java | []
| null | []
| package com.tencent.mm.ui.chatting;
import com.tencent.mm.ui.base.g.c;
final class ChatFooterCustom$1
implements g.c
{
ChatFooterCustom$1(ChatFooterCustom paramChatFooterCustom) {}
public final void fg(int paramInt)
{
switch (paramInt)
{
default:
return;
case 0:
ChatFooterCustom.a(lrR);
return;
}
ChatFooterCustom.b(lrR);
}
}
/* Location:
* Qualified Name: com.tencent.mm.ui.chatting.ChatFooterCustom.1
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 533 | 0.65666 | 0.636023 | 28 | 18.071428 | 17.958143 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 10 |
61b0c2d8ba147c76c3d9060fe24c73b5d76dd96f | 38,534,446,601,116 | 84c8b6454a3f7ee2b380dd0ee95a30ea0c2d4bd1 | /src/com/lpc/model/stok_assy_model.java | 62045d89edf2f5003b2d22d3631f02e6295525b8 | []
| no_license | rootdavinalfa/project_lpc | https://github.com/rootdavinalfa/project_lpc | 92f9597e470e6de4138af87cf1b920a359bb9f07 | f26941270cd067e7e0ab9639b5fd8d8195e502b9 | refs/heads/master | 2021-04-30T10:31:02.071000 | 2018-04-11T01:40:34 | 2018-04-11T01:40:34 | 121,334,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lpc.model;
import javafx.beans.property.SimpleStringProperty;
public class stok_assy_model {
private final SimpleStringProperty namapart;
private final SimpleStringProperty jumlah;
private final SimpleStringProperty ng;
private final SimpleStringProperty total;
public stok_assy_model(String np ,String jmlh,String n,String tot){
this.namapart = new SimpleStringProperty(np);
this.jumlah = new SimpleStringProperty(jmlh);
this.ng = new SimpleStringProperty(n);
this.total = new SimpleStringProperty(tot);
}
public SimpleStringProperty namapartProperty() {
return namapart;
}
public SimpleStringProperty totalProperty() {
return total;
}
public SimpleStringProperty ngProperty() {
return ng;
}
public SimpleStringProperty jumlahProperty() {
return jumlah;
}
}
| UTF-8 | Java | 898 | java | stok_assy_model.java | Java | []
| null | []
| package com.lpc.model;
import javafx.beans.property.SimpleStringProperty;
public class stok_assy_model {
private final SimpleStringProperty namapart;
private final SimpleStringProperty jumlah;
private final SimpleStringProperty ng;
private final SimpleStringProperty total;
public stok_assy_model(String np ,String jmlh,String n,String tot){
this.namapart = new SimpleStringProperty(np);
this.jumlah = new SimpleStringProperty(jmlh);
this.ng = new SimpleStringProperty(n);
this.total = new SimpleStringProperty(tot);
}
public SimpleStringProperty namapartProperty() {
return namapart;
}
public SimpleStringProperty totalProperty() {
return total;
}
public SimpleStringProperty ngProperty() {
return ng;
}
public SimpleStringProperty jumlahProperty() {
return jumlah;
}
}
| 898 | 0.701559 | 0.701559 | 33 | 26.212122 | 22.338657 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 10 |
50a4110325782e1dad3105e397f84a9f7e3c3897 | 38,534,446,600,810 | 53f74a27004a4b04dbfa5bac17e419facdb129fa | /app/src/main/java/com/person/newscopy/user/net/bean/PrivateTalkOutBeansBean.java | 2318d361ffbfe2e2bc241d0a9f3cb3668679e819 | [
"Apache-2.0"
]
| permissive | lichukuan/NewsCopy | https://github.com/lichukuan/NewsCopy | 90ceb9f2809339bfbf37b81d6a3df997f2cdfdaf | dd24d9147d3d972ad534b88f7f5b81c209c42342 | refs/heads/master | 2021-07-25T06:11:07.481000 | 2020-07-13T01:51:55 | 2020-07-13T01:51:55 | 198,649,378 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.person.newscopy.user.net.bean;
public class PrivateTalkOutBeansBean {
/**
* name : 用户3
* icon :
* lastMessage : 😊
* id : c3b822cf755446358f23dc8123e88911
*/
private String name;
private String icon;
private String lastMessage;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getLastMessage() {
return lastMessage;
}
public void setLastMessage(String lastMessage) {
this.lastMessage = lastMessage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| UTF-8 | Java | 864 | java | PrivateTalkOutBeansBean.java | Java | [
{
"context": "ss PrivateTalkOutBeansBean {\n /**\n * name : 用户3\n * icon :\n * lastMessage : 😊\n * id : ",
"end": 108,
"score": 0.8022512793540955,
"start": 105,
"tag": "USERNAME",
"value": "用户3"
}
]
| null | []
| package com.person.newscopy.user.net.bean;
public class PrivateTalkOutBeansBean {
/**
* name : 用户3
* icon :
* lastMessage : 😊
* id : c3b822cf755446358f23dc8123e88911
*/
private String name;
private String icon;
private String lastMessage;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getLastMessage() {
return lastMessage;
}
public void setLastMessage(String lastMessage) {
this.lastMessage = lastMessage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| 864 | 0.583431 | 0.554259 | 47 | 17.234043 | 14.97688 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276596 | false | false | 10 |
f3ea3249f36dffa73ee90c1396ba0ae00597650c | 9,199,819,975,460 | c13b76945f51dba58f3c9096b110e9714a33d47f | /src/main/java/cn/ibdsr/web/modular/business/controller/CompanyController.java | 550dd49419d2c0357404422631aac5356ff91f24 | []
| no_license | wangdeming/srsczx-admin | https://github.com/wangdeming/srsczx-admin | 6ee56a4c319fe5bb29f40d74ec58e3ed15e3de41 | 46072bb10f86252da80fb37ed4bcba11723311bd | refs/heads/master | 2023-05-11T01:51:38.921000 | 2020-06-08T02:21:10 | 2020-06-08T02:21:10 | 270,498,015 | 1 | 0 | null | false | 2021-06-04T02:41:27 | 2020-06-08T02:20:10 | 2020-06-08T03:46:30 | 2021-06-04T02:41:25 | 15,794 | 1 | 0 | 1 | JavaScript | false | false | package cn.ibdsr.web.modular.business.controller;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.ibdsr.core.base.controller.BaseController;
import cn.ibdsr.core.base.tips.SuccessDataTip;
import cn.ibdsr.core.base.tips.SuccessTip;
import cn.ibdsr.core.util.DateUtil;
import cn.ibdsr.web.common.constant.factory.PageFactory;
import cn.ibdsr.web.common.constant.state.ReadStatus;
import cn.ibdsr.web.common.exception.BizExceptionEnum;
import cn.ibdsr.web.common.exception.BussinessException;
import cn.ibdsr.web.common.persistence.model.Company;
import cn.ibdsr.web.core.util.ExcelPoiUtil;
import cn.ibdsr.web.modular.business.service.ICompanyService;
import cn.ibdsr.web.modular.business.transfer.CompanyPoiVo;
import cn.ibdsr.web.modular.business.warpper.CompanyWarpper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* @Description 招商管理控制器
* @Version V1.0
* @CreateDate 2019/8/29 9:32
*
* Date Author Description
* ------------------------------------------------------
* 2019/8/29 lvyou 招商管理控制器
*/
@Controller
@RequestMapping("/company")
public class CompanyController extends BaseController {
private String PREFIX = "/business/company/";
@Resource
private ICompanyService companyService;
/**
* 跳转到招商管理首页
*/
@RequestMapping("")
public String index() {
return PREFIX + "company.html";
}
/**
* 获取企业列表
*/
@GetMapping(value = "/list")
@ResponseBody
public Object list(@RequestParam(value = "isRead", required = false) Integer isRead) {
if (isRead != null && StringUtils.isEmpty(ReadStatus.valueOf(isRead))) {
throw new BussinessException(BizExceptionEnum.REQUEST_INVALIDATE);
}
Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
List<Map<String, Object>> records = companyService.list(page, isRead);
page.setRecords((List<Map<String, Object>>) new CompanyWarpper(records).warp());
return super.packForBT(page);
}
/**
* 标记入孵记录为已读
*/
@PostMapping(value = "/read")
@ResponseBody
public Object read(@RequestParam(value = "companyIds") Long... companyIds) {
if (companyIds == null || companyIds.length <= 0) {
throw new BussinessException(BizExceptionEnum.REQUEST_INVALIDATE);
}
companyService.readCompany(companyIds);
return new SuccessTip();
}
/**
* 跳转到留言管理首页
*/
@GetMapping(value = "/company_detail/{id}")
public String companyDetail(@PathVariable("id") Long id, Model model) {
model.addAttribute("id", id);
return PREFIX + "company_detail.html";
}
/**
* 查看入孵记录详情
*/
@PostMapping(value = "/detail")
@ResponseBody
public Object detail(@RequestParam(value = "id") Long id) {
Company company = companyService.checkMessageId(id);
String setTime = DateUtil.format(company.getSetTime(), "yyyy-MM-dd");
JSONObject companyJson = JSONObject.parseObject(JSONObject.toJSONString(company));
companyService.readCompany(company.getId());
companyJson.put("setTime", setTime);
return new SuccessDataTip(companyJson);
}
/**
* 导出留言详情
*/
@GetMapping(value = "/export")
public void export(HttpServletResponse response, @RequestParam(value = "companyIds") Long... companyIds) {
if (companyIds == null || companyIds.length <= 0) {
throw new BussinessException(BizExceptionEnum.REQUEST_INVALIDATE);
}
//构建excel导出数据 start
List<CompanyPoiVo> records = companyService.getExportList(companyIds);
Workbook workbook = ExcelPoiUtil.defaultExport(records, CompanyPoiVo.class, new ExportParams("入孵记录", "入孵记录表", ExcelType.XSSF));
ExcelPoiUtil.downLoadExcel("入孵记录表.xlsx", response, workbook);
}
}
| UTF-8 | Java | 4,823 | java | CompanyController.java | Java | [
{
"context": "--------------------------------\n * 2019/8/29 lvyou 招商管理控制器\n */\n@Controller\n@RequestMa",
"end": 1813,
"score": 0.9996702671051025,
"start": 1808,
"tag": "USERNAME",
"value": "lvyou"
}
]
| null | []
| package cn.ibdsr.web.modular.business.controller;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.ibdsr.core.base.controller.BaseController;
import cn.ibdsr.core.base.tips.SuccessDataTip;
import cn.ibdsr.core.base.tips.SuccessTip;
import cn.ibdsr.core.util.DateUtil;
import cn.ibdsr.web.common.constant.factory.PageFactory;
import cn.ibdsr.web.common.constant.state.ReadStatus;
import cn.ibdsr.web.common.exception.BizExceptionEnum;
import cn.ibdsr.web.common.exception.BussinessException;
import cn.ibdsr.web.common.persistence.model.Company;
import cn.ibdsr.web.core.util.ExcelPoiUtil;
import cn.ibdsr.web.modular.business.service.ICompanyService;
import cn.ibdsr.web.modular.business.transfer.CompanyPoiVo;
import cn.ibdsr.web.modular.business.warpper.CompanyWarpper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* @Description 招商管理控制器
* @Version V1.0
* @CreateDate 2019/8/29 9:32
*
* Date Author Description
* ------------------------------------------------------
* 2019/8/29 lvyou 招商管理控制器
*/
@Controller
@RequestMapping("/company")
public class CompanyController extends BaseController {
private String PREFIX = "/business/company/";
@Resource
private ICompanyService companyService;
/**
* 跳转到招商管理首页
*/
@RequestMapping("")
public String index() {
return PREFIX + "company.html";
}
/**
* 获取企业列表
*/
@GetMapping(value = "/list")
@ResponseBody
public Object list(@RequestParam(value = "isRead", required = false) Integer isRead) {
if (isRead != null && StringUtils.isEmpty(ReadStatus.valueOf(isRead))) {
throw new BussinessException(BizExceptionEnum.REQUEST_INVALIDATE);
}
Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
List<Map<String, Object>> records = companyService.list(page, isRead);
page.setRecords((List<Map<String, Object>>) new CompanyWarpper(records).warp());
return super.packForBT(page);
}
/**
* 标记入孵记录为已读
*/
@PostMapping(value = "/read")
@ResponseBody
public Object read(@RequestParam(value = "companyIds") Long... companyIds) {
if (companyIds == null || companyIds.length <= 0) {
throw new BussinessException(BizExceptionEnum.REQUEST_INVALIDATE);
}
companyService.readCompany(companyIds);
return new SuccessTip();
}
/**
* 跳转到留言管理首页
*/
@GetMapping(value = "/company_detail/{id}")
public String companyDetail(@PathVariable("id") Long id, Model model) {
model.addAttribute("id", id);
return PREFIX + "company_detail.html";
}
/**
* 查看入孵记录详情
*/
@PostMapping(value = "/detail")
@ResponseBody
public Object detail(@RequestParam(value = "id") Long id) {
Company company = companyService.checkMessageId(id);
String setTime = DateUtil.format(company.getSetTime(), "yyyy-MM-dd");
JSONObject companyJson = JSONObject.parseObject(JSONObject.toJSONString(company));
companyService.readCompany(company.getId());
companyJson.put("setTime", setTime);
return new SuccessDataTip(companyJson);
}
/**
* 导出留言详情
*/
@GetMapping(value = "/export")
public void export(HttpServletResponse response, @RequestParam(value = "companyIds") Long... companyIds) {
if (companyIds == null || companyIds.length <= 0) {
throw new BussinessException(BizExceptionEnum.REQUEST_INVALIDATE);
}
//构建excel导出数据 start
List<CompanyPoiVo> records = companyService.getExportList(companyIds);
Workbook workbook = ExcelPoiUtil.defaultExport(records, CompanyPoiVo.class, new ExportParams("入孵记录", "入孵记录表", ExcelType.XSSF));
ExcelPoiUtil.downLoadExcel("入孵记录表.xlsx", response, workbook);
}
}
| 4,823 | 0.697704 | 0.692984 | 126 | 35.992062 | 28.262796 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603175 | false | false | 10 |
06ccf0af3e901da1bb00b4986384a80bb9a0b570 | 26,268,020,026,941 | 510063c1890d9310874bf1144c5e7aa636e2d73b | /web/src/main/java/com/ralf/cardmanager/interceptor/SiteSwitchInterceptorConfig.java | d708668bed9d051567effb5bcd96e45532bc4038 | []
| no_license | ralfbawg/cardmanager | https://github.com/ralfbawg/cardmanager | 616269839a6be963eaeb5f19daca2fcfc1cfc89a | 3ea9d80cf19491e1dcde3c185c49681067309e97 | refs/heads/master | 2023-05-13T18:36:10.024000 | 2021-06-01T12:54:57 | 2021-06-01T12:54:57 | 199,315,359 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.ralf.cardmanager.interceptor;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.sys.interceptor.LogInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
*
*/
@Configuration
@EnableWebMvc
public class SiteSwitchInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration registration = registry.addInterceptor(new SiteSwitchInterceptor());
}
} | UTF-8 | Java | 992 | java | SiteSwitchInterceptorConfig.java | Java | []
| null | []
| /**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.ralf.cardmanager.interceptor;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.sys.interceptor.LogInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
*
*/
@Configuration
@EnableWebMvc
public class SiteSwitchInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration registration = registry.addInterceptor(new SiteSwitchInterceptor());
}
} | 992 | 0.837702 | 0.833669 | 28 | 34.464287 | 32.654556 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 10 |
fe91aacf3fdf32125eb28d19d88cea9c67784b4b | 35,699,768,169,643 | cbb042edc985720f2f5498e81038eb4a7d16db42 | /jilinwula-ioc/src/main/java/com/jilinwula/ioc/bean/TwoPlugin.java | fbe1a67f0057492340a66fdd8863ac7025010ebe | []
| no_license | jilinwula/jilinwulas | https://github.com/jilinwula/jilinwulas | b02e80c0f9262d5ba9947f4782c9b9c6a4bf7f11 | 8dda69e36179e140fc9a18064e0afcaaba1144e6 | refs/heads/master | 2021-01-10T22:43:41.097000 | 2016-10-14T09:40:31 | 2016-10-14T09:40:31 | 70,382,798 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jilinwula.ioc.bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author jilinwula@foxmail.com
* @datetime 16/9/15 下午2:55
*/
public class TwoPlugin implements Plugin {
public void test() {
System.out.println("towPlugin");
}
}
| UTF-8 | Java | 334 | java | TwoPlugin.java | Java | [
{
"context": "ingframework.stereotype.Component;\n\n/**\n * @author jilinwula@foxmail.com\n * @datetime 16/9/15 下午2:55\n */\npublic class TwoP",
"end": 180,
"score": 0.9999228715896606,
"start": 159,
"tag": "EMAIL",
"value": "jilinwula@foxmail.com"
}
]
| null | []
| package com.jilinwula.ioc.bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author <EMAIL>
* @datetime 16/9/15 下午2:55
*/
public class TwoPlugin implements Plugin {
public void test() {
System.out.println("towPlugin");
}
}
| 320 | 0.730303 | 0.706061 | 14 | 22.571428 | 19.765461 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 10 |
db94b1ab3ed152d4ced95e04924a19f518144ea9 | 29,935,922,107,839 | 12b08117920175091df935b6ceb41ab6689573b3 | /Contacts/src/PhoneBook.java | d6e342facb6740742b671c1245207b52952f4fde | []
| no_license | samattolebay/Java-projects | https://github.com/samattolebay/Java-projects | 98def4427d95de059f5a57df11adc9fc9dba914d | 2c7425d6867f520f163e1e706c33c3ae5b939941 | refs/heads/master | 2023-02-09T05:09:09.746000 | 2020-12-23T08:53:54 | 2020-12-23T08:53:54 | 268,070,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PhoneBook implements Serializable {
private final List<Contact> phoneBook;
public PhoneBook() { phoneBook = new ArrayList<>(); }
public int getNumberOfContacts() { return phoneBook.size(); }
public void addContact(Contact contact) { phoneBook.add(contact); }
public Contact getContact(int index) { return phoneBook.get(index); }
public boolean isEmpty() { return phoneBook.isEmpty(); }
public ArrayList<Integer> searchQuery(String query) {
Pattern pattern = Pattern.compile("(?i).*" + query + ".*");
ArrayList<Integer> foundContacts = new ArrayList<>();
for (int i = 0; i < phoneBook.size(); i++) {
Contact contact = phoneBook.get(i);
Matcher matcher = pattern.matcher(contact.getFullName());
Matcher matcher1 = pattern.matcher(contact.getNumber());
if (matcher.find() || matcher1.find()) {
foundContacts.add(i);
}
}
return foundContacts;
}
public void removeContact(int index) { phoneBook.remove(index); }
}
| UTF-8 | Java | 1,226 | java | PhoneBook.java | Java | []
| null | []
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PhoneBook implements Serializable {
private final List<Contact> phoneBook;
public PhoneBook() { phoneBook = new ArrayList<>(); }
public int getNumberOfContacts() { return phoneBook.size(); }
public void addContact(Contact contact) { phoneBook.add(contact); }
public Contact getContact(int index) { return phoneBook.get(index); }
public boolean isEmpty() { return phoneBook.isEmpty(); }
public ArrayList<Integer> searchQuery(String query) {
Pattern pattern = Pattern.compile("(?i).*" + query + ".*");
ArrayList<Integer> foundContacts = new ArrayList<>();
for (int i = 0; i < phoneBook.size(); i++) {
Contact contact = phoneBook.get(i);
Matcher matcher = pattern.matcher(contact.getFullName());
Matcher matcher1 = pattern.matcher(contact.getNumber());
if (matcher.find() || matcher1.find()) {
foundContacts.add(i);
}
}
return foundContacts;
}
public void removeContact(int index) { phoneBook.remove(index); }
}
| 1,226 | 0.64845 | 0.646003 | 35 | 34.028572 | 26.517365 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 10 |
c130bb9d63db00abfb91be80303717976a99ff73 | 22,565,758,229,799 | d7451c9f2c73dd4af07b7b6f46847421c4c20d5a | /spring-boot-soap-service/src/main/java/com/example/howtodoinjava/springbootsoapservice/TestSoap.java | ac87768d6121ed1b16b80c66efa3bd4d89af37fa | []
| no_license | kevinZhangSFI/soap-iot | https://github.com/kevinZhangSFI/soap-iot | 1d9816f14520c5512ecf7b80e1872549bb28aaa3 | 3639e61490ffdb0ac62ee95d0db11b883550873a | refs/heads/master | 2022-11-19T08:27:53.738000 | 2020-07-07T19:32:12 | 2020-07-07T19:32:12 | 277,881,545 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.howtodoinjava.springbootsoapservice;
import com.howtodoinjava.xml.school.StudentDetailsResponse;
public class TestSoap {
public static void main(String[] args) {
// TODO Auto-generated method stub
SoapClient soapClient = new SoapClient();
StudentDetailsResponse studentResp = soapClient.getStudent("Luke");
System.out.println(studentResp.toString());
}
}
| UTF-8 | Java | 404 | java | TestSoap.java | Java | [
{
"context": "ailsResponse studentResp = soapClient.getStudent(\"Luke\");\n System.out.println(studentResp.toString",
"end": 343,
"score": 0.9984418153762817,
"start": 339,
"tag": "NAME",
"value": "Luke"
}
]
| null | []
| package com.example.howtodoinjava.springbootsoapservice;
import com.howtodoinjava.xml.school.StudentDetailsResponse;
public class TestSoap {
public static void main(String[] args) {
// TODO Auto-generated method stub
SoapClient soapClient = new SoapClient();
StudentDetailsResponse studentResp = soapClient.getStudent("Luke");
System.out.println(studentResp.toString());
}
}
| 404 | 0.754951 | 0.754951 | 14 | 27.857143 | 26.109268 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 10 |
151662965b5fd4c25409c51776160a60dc60c00b | 24,687,472,045,241 | 5063f2d58df710a60ce3855fe1ffd82d462e16e1 | /gpsearch/src/main/java/com/btb/search/core/conf/server/QueryMethod.java | 9db63d05020eee83524f1c360ece6def521d22b9 | []
| no_license | luobintianya/gpsearch | https://github.com/luobintianya/gpsearch | 401aff7ea2b0529bdd709fb93d1b868478c50dac | 365256a616129ae714adc64fe016b7cfa1bec552 | refs/heads/master | 2020-03-26T16:56:46.450000 | 2018-08-17T15:05:05 | 2018-08-17T15:05:05 | 145,133,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.btb.search.core.conf.server;
public enum QueryMethod {
GET,
POST
}
| UTF-8 | Java | 92 | java | QueryMethod.java | Java | []
| null | []
| package com.btb.search.core.conf.server;
public enum QueryMethod {
GET,
POST
}
| 92 | 0.663043 | 0.663043 | 8 | 9.5 | 13.93736 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
f25da7570deba003a1ef959ca422b28587e7d309 | 6,700,149,019,067 | 5b19939828b989358f5db74d3bc75aa1344b4897 | /com.fundingo/src/main/java/com/fundingo/service/funding/FundingDao.java | 28f094e458164ae870187ce2ed8b6d47d34e4d76 | []
| no_license | JaeHyeon-Kim94/fundingo | https://github.com/JaeHyeon-Kim94/fundingo | 72bd41d419bc8cb3aa16cfd4a250f89ad89b89e3 | fbddfc2b0edc8f0f153c7fdb0281708cd37a1b59 | refs/heads/master | 2023-07-14T09:26:36.358000 | 2021-08-26T08:07:43 | 2021-08-26T08:07:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fundingo.service.funding;
import java.util.List;
import java.util.Map;
import com.fundingo.common.Search;
import com.fundingo.service.domain.FundedProduct;
import com.fundingo.service.domain.Funding;
import com.fundingo.service.domain.User;
public interface FundingDao {
//FundingTable & FundedTable
//펀딩
public void addFund(Funding fund) throws Exception;
//펀딩한 상품
public void addFundedProduct(FundedProduct fundedProduct) throws Exception;
//펀딩취소
public void cancelFund(int fundNo) throws Exception;
//펀딩한 내역 목록 조회
public List<Funding> getFundList(Map<String, Object> map) throws Exception;
//펀딩한 상품 상세 조회
public Funding getFund(int fundNo) throws Exception;
//펀딩한 상품 리스트 조회
public List<FundedProduct> getFpList(int fundNo) throws Exception;
//펀딩한 상품 배송정보변경
public void updateFund(Funding fund) throws Exception;
//UserTable---------------------------------------
//간편결제등록
public void addEasyPay(User user) throws Exception;
//간편결제삭제
public void deleteEasyPay(User user) throws Exception;
//배송정보 등록
public void updateAddr(User user) throws Exception;
//배송정보 삭제
public void deleteAddr(User user) throws Exception;
//Page 처리를 위한 전체Row(totalCount) return
public int getTotalCount(Map<String, Object> map) throws Exception;
public int getFundCountByUserNoAndPjtNo(int pjtNo, int userNo);
//누적 펀딩액수 페이지
//public int gettotalCount(Search search) throws Exception;
}
| UTF-8 | Java | 1,621 | java | FundingDao.java | Java | []
| null | []
| package com.fundingo.service.funding;
import java.util.List;
import java.util.Map;
import com.fundingo.common.Search;
import com.fundingo.service.domain.FundedProduct;
import com.fundingo.service.domain.Funding;
import com.fundingo.service.domain.User;
public interface FundingDao {
//FundingTable & FundedTable
//펀딩
public void addFund(Funding fund) throws Exception;
//펀딩한 상품
public void addFundedProduct(FundedProduct fundedProduct) throws Exception;
//펀딩취소
public void cancelFund(int fundNo) throws Exception;
//펀딩한 내역 목록 조회
public List<Funding> getFundList(Map<String, Object> map) throws Exception;
//펀딩한 상품 상세 조회
public Funding getFund(int fundNo) throws Exception;
//펀딩한 상품 리스트 조회
public List<FundedProduct> getFpList(int fundNo) throws Exception;
//펀딩한 상품 배송정보변경
public void updateFund(Funding fund) throws Exception;
//UserTable---------------------------------------
//간편결제등록
public void addEasyPay(User user) throws Exception;
//간편결제삭제
public void deleteEasyPay(User user) throws Exception;
//배송정보 등록
public void updateAddr(User user) throws Exception;
//배송정보 삭제
public void deleteAddr(User user) throws Exception;
//Page 처리를 위한 전체Row(totalCount) return
public int getTotalCount(Map<String, Object> map) throws Exception;
public int getFundCountByUserNoAndPjtNo(int pjtNo, int userNo);
//누적 펀딩액수 페이지
//public int gettotalCount(Search search) throws Exception;
}
| 1,621 | 0.745316 | 0.745316 | 58 | 23.844828 | 24.536251 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.224138 | false | false | 10 |
b2425a474c83273f32caec6da5fd3fd4f21c27f4 | 35,442,070,136,429 | ec7e48fe57aeb515af0fc47cf6ead476143caca6 | /src/coreJava/MergeStringArray.java | 287ffd20c1a1dcd84ff74e0637fe4c6226cff008 | []
| no_license | malaypatel/Practice | https://github.com/malaypatel/Practice | 3336904ee8acf2234a2ac976d0ecc2d1ea265e9c | e3c711d2b0f1c1f9598d4150a6c75ac693540664 | refs/heads/master | 2020-03-05T23:55:49.488000 | 2018-02-26T22:21:13 | 2018-02-26T22:21:13 | 93,715,289 | 0 | 2 | null | false | 2017-08-15T07:50:19 | 2017-06-08T06:33:10 | 2017-06-08T06:37:10 | 2017-08-15T07:50:18 | 1,596 | 0 | 1 | 0 | Java | null | null | /**
*
*/
package coreJava;
/**
* @author malay
*
*/
public class MergeStringArray {
public static void main(String[] args) {
String[] a = {"Dog", "Cat"};
String[] b = {"Mal", "Nala"};
String sA = "";
String sB = "";
for(String s: a) {
sA+=s;
}
for(String s: b) {
sB+=s;
}
MergeStringArray me = new MergeStringArray();
System.out.println(me.merge(sA, sB));
}
public String merge(String leftStr, String rightStr) {
char[]left = leftStr.toCharArray();
char[]right = rightStr.toCharArray();
int nL = left.length;
int nR= right.length;
char[] mergeArr= new char[nL+nR];
int i=0,j=0,k=0;
int temp =0;
while(i<nL && j<nR){
if (temp==0){
mergeArr[k]=left[i];
i++;
temp =1;
}else{
mergeArr[k]=right[j];
j++;
temp=0;
}
k++;
}
while(i<nL){
mergeArr[k]=left[i]; k++; i++;
}
while(j<nR){
mergeArr[k]=right[j]; k++; j++;
}
return new String(mergeArr);
}
}
| UTF-8 | Java | 1,193 | java | MergeStringArray.java | Java | [
{
"context": "/**\n * \n */\npackage coreJava;\n\n/**\n * @author malay\n *\n */\npublic class MergeStringArray {\n\t\n\tpublic ",
"end": 51,
"score": 0.9788151979446411,
"start": 46,
"tag": "USERNAME",
"value": "malay"
}
]
| null | []
| /**
*
*/
package coreJava;
/**
* @author malay
*
*/
public class MergeStringArray {
public static void main(String[] args) {
String[] a = {"Dog", "Cat"};
String[] b = {"Mal", "Nala"};
String sA = "";
String sB = "";
for(String s: a) {
sA+=s;
}
for(String s: b) {
sB+=s;
}
MergeStringArray me = new MergeStringArray();
System.out.println(me.merge(sA, sB));
}
public String merge(String leftStr, String rightStr) {
char[]left = leftStr.toCharArray();
char[]right = rightStr.toCharArray();
int nL = left.length;
int nR= right.length;
char[] mergeArr= new char[nL+nR];
int i=0,j=0,k=0;
int temp =0;
while(i<nL && j<nR){
if (temp==0){
mergeArr[k]=left[i];
i++;
temp =1;
}else{
mergeArr[k]=right[j];
j++;
temp=0;
}
k++;
}
while(i<nL){
mergeArr[k]=left[i]; k++; i++;
}
while(j<nR){
mergeArr[k]=right[j]; k++; j++;
}
return new String(mergeArr);
}
}
| 1,193 | 0.438391 | 0.432523 | 64 | 17.640625 | 15.40025 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.109375 | false | false | 10 |
bcc2300c73bdbbc2b667cfde5033b3c52ec60b29 | 35,442,070,136,616 | f384079db11f90d523a171c2be5e637bb3c51a71 | /proba/probamodul/src/main/java/gui/guidance/probamodul.java | 401c86890f04bf8f42e62065a59f663f3cf0b723 | []
| no_license | poliphonalj/magnolia | https://github.com/poliphonalj/magnolia | 392d699ce619fe941ef12c7f766d31b60aa07e23 | f897f5763a0e1bcc80a59e48f86681fea72b34f0 | refs/heads/master | 2023-07-04T00:17:11.788000 | 2021-08-04T12:47:03 | 2021-08-04T12:47:03 | 385,380,921 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gui.guidance;
/**
* This class is optional and represents the configuration for the probamodul
* module. By exposing simple getter/setter/adder methods, this bean can be
* configured via content2bean using the properties and node from
* <tt>config:/modules/probamodul</tt>. If you don't need this, simply remove
* the reference to this class in the module descriptor xml. See
* https://documentation.magnolia-cms.com/display/DOCS/Module+configuration for
* information about module configuration.
*/
public class probamodul {
/* you can optionally implement info.magnolia.module.ModuleLifecycle */
}
| UTF-8 | Java | 620 | java | probamodul.java | Java | []
| null | []
| package gui.guidance;
/**
* This class is optional and represents the configuration for the probamodul
* module. By exposing simple getter/setter/adder methods, this bean can be
* configured via content2bean using the properties and node from
* <tt>config:/modules/probamodul</tt>. If you don't need this, simply remove
* the reference to this class in the module descriptor xml. See
* https://documentation.magnolia-cms.com/display/DOCS/Module+configuration for
* information about module configuration.
*/
public class probamodul {
/* you can optionally implement info.magnolia.module.ModuleLifecycle */
}
| 620 | 0.774194 | 0.772581 | 16 | 37.75 | 32.8605 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 10 |
2eb824415d1e2566588a067da1a5f7773ef34f57 | 27,668,179,331,604 | a0b098f0041b1a4604247f87e32943fbbfb081f8 | /src/synchronization_java/MySynchronization.java | 4f34ed86d1eb12f83dbcfa08554887ab1fd5280c | []
| no_license | ashish-cs-er/java_basics | https://github.com/ashish-cs-er/java_basics | 1aea7648e63866f69e69ba7c98dcc62fd925c3bd | 826a26b143338fd6cf8992607301344411008b09 | refs/heads/master | 2023-01-07T10:18:49.412000 | 2020-11-14T11:17:31 | 2020-11-14T11:17:31 | 311,400,237 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package synchronization_java;
class Sender {
public void send(String msg) {
System.out.println("Sending\t" + msg );
try{
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
class ThreadedSend extends Thread{
String msg="";
Sender sender;
ThreadedSend(String msg, Sender obj){
this.msg = msg;
sender = obj;
}
public void run() {
synchronized(sender) {
sender.send(msg);
}
}
}
public class MySynchronization {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Synchronization in java is to control access of multiple threads to any shared resource");
System.out.println("There are two types of thread synchronization: 1. Mutual Exclusive 2.Cooperation");
System.out.println("Mutual Exclusive: synchronized method,synchronized block,static synchronization");
System.out.println("Lets check this in action");
Sender obj = new Sender();
ThreadedSend ts1 = new ThreadedSend("Hello", obj);
ThreadedSend ts2 = new ThreadedSend("Bye", obj);
ts1.start();
ts2.start();
}
}
| UTF-8 | Java | 1,230 | java | MySynchronization.java | Java | []
| null | []
| package synchronization_java;
class Sender {
public void send(String msg) {
System.out.println("Sending\t" + msg );
try{
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
class ThreadedSend extends Thread{
String msg="";
Sender sender;
ThreadedSend(String msg, Sender obj){
this.msg = msg;
sender = obj;
}
public void run() {
synchronized(sender) {
sender.send(msg);
}
}
}
public class MySynchronization {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Synchronization in java is to control access of multiple threads to any shared resource");
System.out.println("There are two types of thread synchronization: 1. Mutual Exclusive 2.Cooperation");
System.out.println("Mutual Exclusive: synchronized method,synchronized block,static synchronization");
System.out.println("Lets check this in action");
Sender obj = new Sender();
ThreadedSend ts1 = new ThreadedSend("Hello", obj);
ThreadedSend ts2 = new ThreadedSend("Bye", obj);
ts1.start();
ts2.start();
}
}
| 1,230 | 0.65935 | 0.651219 | 45 | 26.333334 | 27.320322 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 10 |
19e0c5a1b33dae1893224cfe634f006ace713f9f | 8,229,157,381,036 | 45ef928cff23b4bb95f739caad3341515b1e1f55 | /app/src/main/java/com/ryanharter/gesturesample/MainActivity.java | 7470094048df6b96b572f5e4b58a29b8fcb994b0 | [
"MIT"
]
| permissive | rizwan-dev/android-gesture-sample | https://github.com/rizwan-dev/android-gesture-sample | e2fe68a0571d5568b4ab91299ec00cc137f66960 | 6f94a4b5109fb6eaa70a283df0cbb6c68cfeefb1 | refs/heads/master | 2021-05-04T12:17:50.132000 | 2014-10-06T19:49:48 | 2014-10-06T19:49:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ryanharter.gesturesample;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by rharter on 9/27/14.
*/
public class MainActivity extends Activity {
TouchImageView mImageView;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (TouchImageView) findViewById(R.id.image_view);
mImageView.setImageResource(R.drawable.ic_launcher);
}
}
| UTF-8 | Java | 513 | java | MainActivity.java | Java | [
{
"context": "vity;\nimport android.os.Bundle;\n\n/**\n * Created by rharter on 9/27/14.\n */\npublic class MainActivity extends",
"end": 120,
"score": 0.999614417552948,
"start": 113,
"tag": "USERNAME",
"value": "rharter"
}
]
| null | []
| package com.ryanharter.gesturesample;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by rharter on 9/27/14.
*/
public class MainActivity extends Activity {
TouchImageView mImageView;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (TouchImageView) findViewById(R.id.image_view);
mImageView.setImageResource(R.drawable.ic_launcher);
}
}
| 513 | 0.727096 | 0.717349 | 20 | 24.65 | 23.698681 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 10 |
2e5f1d8813fbfcb9b348932d6fda6dd9dcb8f684 | 19,009,525,287,206 | 1cc6ecbe3bb0957f25fe167d3db50a5b8aa59c45 | /CGOnlineShopSpringRESTJPAData/src/com/cg/onlineshop/services/OnlineShopServices.java | 6e88ce9b2b452b021450cb63f739429092be62cf | []
| no_license | TRIGGEREDcoder/Spring | https://github.com/TRIGGEREDcoder/Spring | 8a2d31559a709b8346d66e685513c0ff18250ea5 | e7a50b0476ab75d061095314110d890fb75a6876 | refs/heads/master | 2020-04-05T21:09:21.752000 | 2018-11-21T09:39:16 | 2018-11-21T09:39:16 | 157,209,869 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cg.onlineshop.services;
import com.cg.onlineshop.beans.Product;
import com.cg.onlineshop.exceptions.ProductDetailsNotFoundException;
import java.util.List;
public interface OnlineShopServices {
public Product acceptProductDetails(Product product);
public List<Product> getAllProductDetails();
public Product getProductDetails(int productId) throws ProductDetailsNotFoundException;
public void removeProductDetails(int productId);
}
| UTF-8 | Java | 458 | java | OnlineShopServices.java | Java | []
| null | []
| package com.cg.onlineshop.services;
import com.cg.onlineshop.beans.Product;
import com.cg.onlineshop.exceptions.ProductDetailsNotFoundException;
import java.util.List;
public interface OnlineShopServices {
public Product acceptProductDetails(Product product);
public List<Product> getAllProductDetails();
public Product getProductDetails(int productId) throws ProductDetailsNotFoundException;
public void removeProductDetails(int productId);
}
| 458 | 0.831878 | 0.831878 | 12 | 36.166668 | 26.053898 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 10 |
1ddad60760ceb65816d5a69e679423b28787e266 | 19,619,410,608,669 | 443d2ee1457899558bc42082d7479314ac5a9eec | /classes-dex2jar.jar.src/PQ.java | 345cf05d63019e24a67af4245d0b1aaf7c14c852 | []
| no_license | MAVProxyUser/FaceApp | https://github.com/MAVProxyUser/FaceApp | 5130518bb15c6f48f1cb28b26d01088aa9c6d242 | 774f786d809a45f2cfc65a0770679d51bbd7a4be | refs/heads/master | 2020-06-22T01:39:02.978000 | 2019-07-18T14:12:46 | 2019-07-18T14:12:46 | 197,599,148 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import com.google.android.gms.common.api.f;
final class pq
extends sq
{
pq(oq paramoq, f paramf)
{
super(paramf);
}
}
/* Location: /Applications/dex2jar/classes-dex2jar.jar!/pq.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 281 | java | PQ.java | Java | []
| null | []
| import com.google.android.gms.common.api.f;
final class pq
extends sq
{
pq(oq paramoq, f paramf)
{
super(paramf);
}
}
/* Location: /Applications/dex2jar/classes-dex2jar.jar!/pq.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 281 | 0.622776 | 0.590747 | 16 | 16.625 | 20.678719 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 10 |
66bb1a3f95dcbea1168a9af56018f5c782edae4f | 32,727,650,810,749 | 2390f43a7045b40682aad64aeb5f29d2a3338904 | /calculadora/src/Calculadora.java | 04b676151b27d5fcdffdd1215672b66b261068c9 | []
| no_license | Lovattows/faculdade-java | https://github.com/Lovattows/faculdade-java | 5c52cbaa590cf738ada29f906f821422811c7c0d | 8f90c79005ddab6352544af123f2052086f788cf | refs/heads/master | 2021-07-11T02:52:56.575000 | 2020-10-31T05:40:58 | 2020-10-31T05:40:58 | 210,435,859 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Calculadora {
public double calcular(double v1, double v2, String op) {
double res = 0;
switch (op) {
case "[+]": {
res = v1 + v2;
break;
}
case "[-]": {
res = v1 - v2;
break;
}
case "[*]": {
res = v1 * v2;
break;
}
case "[/]": {
res = v1 / v2;
break;
}
}
return res;
}
}
| UTF-8 | Java | 551 | java | Calculadora.java | Java | []
| null | []
| public class Calculadora {
public double calcular(double v1, double v2, String op) {
double res = 0;
switch (op) {
case "[+]": {
res = v1 + v2;
break;
}
case "[-]": {
res = v1 - v2;
break;
}
case "[*]": {
res = v1 * v2;
break;
}
case "[/]": {
res = v1 / v2;
break;
}
}
return res;
}
}
| 551 | 0.284936 | 0.264973 | 26 | 20.192308 | 12.319526 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 10 |
5ff323333cb4f64b45869675ae339b86802cb022 | 10,625,749,143,476 | f4a87e04992e37a165c86a015cadad364a24d404 | /src/main/java/servicedeskuat/RemoveAttachmentResponse.java | 97df72a918cfbc14ff79602c51fb66510cf511bb | []
| no_license | malika15/servicedeskintegration | https://github.com/malika15/servicedeskintegration | 3097eaee1801f224b11173dd3e7ec42239fe2c85 | 2facd13f91e5a871463a5cd26e7374d0b1235a8a | refs/heads/master | 2018-01-10T04:41:11.206000 | 2015-12-17T03:32:47 | 2015-12-17T03:32:47 | 48,137,082 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package servicedeskuat;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="removeAttachmentReturn" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"removeAttachmentReturn"
})
@XmlRootElement(name = "removeAttachmentResponse")
public class RemoveAttachmentResponse {
protected int removeAttachmentReturn;
/**
* Gets the value of the removeAttachmentReturn property.
*
*/
public int getRemoveAttachmentReturn() {
return removeAttachmentReturn;
}
/**
* Sets the value of the removeAttachmentReturn property.
*
*/
public void setRemoveAttachmentReturn(int value) {
this.removeAttachmentReturn = value;
}
}
| UTF-8 | Java | 1,349 | java | RemoveAttachmentResponse.java | Java | []
| null | []
|
package servicedeskuat;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="removeAttachmentReturn" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"removeAttachmentReturn"
})
@XmlRootElement(name = "removeAttachmentResponse")
public class RemoveAttachmentResponse {
protected int removeAttachmentReturn;
/**
* Gets the value of the removeAttachmentReturn property.
*
*/
public int getRemoveAttachmentReturn() {
return removeAttachmentReturn;
}
/**
* Sets the value of the removeAttachmentReturn property.
*
*/
public void setRemoveAttachmentReturn(int value) {
this.removeAttachmentReturn = value;
}
}
| 1,349 | 0.683469 | 0.676056 | 53 | 24.433962 | 24.62742 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.339623 | false | false | 10 |
d3844a28b295d5008ab0d04766e4a14995d9abd2 | 7,146,825,609,457 | 8709c25317f622f6c13a7e7aa47ebdd66a15b0c8 | /src/DomeinController/Test.java | 6c2963540000993f6eba0b1d7bae9bd03a09f4bc | []
| no_license | herv250/testD1 | https://github.com/herv250/testD1 | 3c25bf9c7c2c21faacfdae18dc92e81fc1502070 | eb44fc38d703f14a29ac8b685465c80521f0577d | refs/heads/master | 2016-08-11T00:20:14.753000 | 2016-02-11T09:27:10 | 2016-02-11T09:27:10 | 51,503,445 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DomeinController;
/**
*
* @author Mat
*/
public class Test {
String temp = "shutup";
String answer = "go work";
}
| UTF-8 | Java | 324 | java | Test.java | Java | [
{
"context": ".\n */\npackage DomeinController;\n\n/**\n *\n * @author Mat\n */\npublic class Test {\n String temp = \"shutup",
"end": 233,
"score": 0.9560797214508057,
"start": 230,
"tag": "NAME",
"value": "Mat"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DomeinController;
/**
*
* @author Mat
*/
public class Test {
String temp = "shutup";
String answer = "go work";
}
| 324 | 0.67284 | 0.67284 | 16 | 19.25 | 22.283682 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 10 |
f57e64103c890d4926e225b2989ed10f76f48dee | 8,942,121,939,177 | 5ba06335d9c749b5846bcdbf5ada3b78dc6c0762 | /src/main/java/com/eza/jerseydemo/Client.java | 74aa200f2d999469cfa111dc124b5f8d608a4438 | []
| no_license | esayasGebre/jerseydemo | https://github.com/esayasGebre/jerseydemo | 466ddb53585a616ad166ab0cd34955d01886feda | 695092e0eabd175b9090f62702351cd7f768c753 | refs/heads/master | 2022-07-06T11:33:32.901000 | 2017-08-24T17:22:28 | 2017-08-24T17:22:28 | 101,004,371 | 0 | 0 | null | false | 2022-06-20T23:49:39 | 2017-08-22T00:43:48 | 2017-08-22T00:45:02 | 2022-06-20T23:49:37 | 8 | 0 | 0 | 1 | Java | false | false | package com.eza.jerseydemo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Client {
private int id;
private String name;
/* private double amount;
private String street;*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}*/
public Client(int id, String name/*, double amount, String street*/) {
super();
this.id = id;
this.name = name;
/* this.amount = amount;
this.street = street;*/
}
public Client() {}
@Override
public String toString() {
return "Client [id=" + id + ", name=" + name + "]";
}
}
| UTF-8 | Java | 934 | java | Client.java | Java | []
| null | []
| package com.eza.jerseydemo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Client {
private int id;
private String name;
/* private double amount;
private String street;*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}*/
public Client(int id, String name/*, double amount, String street*/) {
super();
this.id = id;
this.name = name;
/* this.amount = amount;
this.street = street;*/
}
public Client() {}
@Override
public String toString() {
return "Client [id=" + id + ", name=" + name + "]";
}
}
| 934 | 0.656317 | 0.656317 | 52 | 16.961538 | 15.23276 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.557692 | false | false | 10 |
58b2973fa282d038ae077c28e131956414813e8d | 644,245,110,556 | 53d677a55e4ece8883526738f1c9d00fa6560ff7 | /com/tencent/mm/ui/tools/ZoneSelectOtherCountryPreference$1.java | 1a97afb2952239b2915a8d318783b970395d70fc | []
| no_license | 0jinxing/wechat-apk-source | https://github.com/0jinxing/wechat-apk-source | 544c2d79bfc10261eb36389c1edfdf553d8f312a | f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d | refs/heads/master | 2020-06-07T20:06:03.580000 | 2019-06-21T09:17:26 | 2019-06-21T09:17:26 | 193,069,132 | 9 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.mm.ui.tools;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.matrix.trace.core.AppMethodBeat;
final class ZoneSelectOtherCountryPreference$1
implements View.OnClickListener
{
ZoneSelectOtherCountryPreference$1(ZoneSelectOtherCountryPreference paramZoneSelectOtherCountryPreference)
{
}
public final void onClick(View paramView)
{
AppMethodBeat.i(35019);
if (ZoneSelectOtherCountryPreference.a(this.zIr) != null)
ZoneSelectOtherCountryPreference.a(this.zIr).onClick();
AppMethodBeat.o(35019);
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes5-dex2jar.jar
* Qualified Name: com.tencent.mm.ui.tools.ZoneSelectOtherCountryPreference.1
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 843 | java | ZoneSelectOtherCountryPreference$1.java | Java | []
| null | []
| package com.tencent.mm.ui.tools;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.matrix.trace.core.AppMethodBeat;
final class ZoneSelectOtherCountryPreference$1
implements View.OnClickListener
{
ZoneSelectOtherCountryPreference$1(ZoneSelectOtherCountryPreference paramZoneSelectOtherCountryPreference)
{
}
public final void onClick(View paramView)
{
AppMethodBeat.i(35019);
if (ZoneSelectOtherCountryPreference.a(this.zIr) != null)
ZoneSelectOtherCountryPreference.a(this.zIr).onClick();
AppMethodBeat.o(35019);
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes5-dex2jar.jar
* Qualified Name: com.tencent.mm.ui.tools.ZoneSelectOtherCountryPreference.1
* JD-Core Version: 0.6.2
*/ | 843 | 0.744958 | 0.718861 | 26 | 30.5 | 32.402813 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false | 10 |
31adf9912b686fa963c72546d14424ed01d5b5fb | 6,803,228,216,811 | f8ea31a6ac72a692d0461cec1fe80bee17115e89 | /src/main/java/org/latlab/core/model/BayesNet.java | fdc8ca2a4dc8f4775024a7afd79aac03b3585660 | [
"Apache-2.0"
]
| permissive | ferjorosa/parkinson-multidimensional-clustering | https://github.com/ferjorosa/parkinson-multidimensional-clustering | 6af6d48469ae2abc8208973840cf54bc87f308f0 | e40fe476430b74c0098c806502e91acb164036d7 | refs/heads/main | 2023-04-19T10:41:58.600000 | 2021-12-09T13:02:30 | 2021-12-09T13:02:30 | 362,428,417 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* BayesNet.java Copyright (C) 2006 Tao Chen, Kin Man Poon, Yi Wang, and Nevin
* L. Zhang
*/
package org.latlab.core.model;
import org.latlab.core.graph.AbstractNode;
import org.latlab.core.graph.DirectedAcyclicGraph;
import org.latlab.core.graph.DirectedNode;
import org.latlab.core.graph.Edge;
import org.latlab.core.util.*;
import java.io.*;
import java.util.*;
/**
* This class provides an implementation for Bayes nets (BNs).
*
* @author Yi Wang
*
*/
public class BayesNet extends DirectedAcyclicGraph {
/**
* the prefix of default names of BNs.
*/
private final static String NAME_PREFIX = "BayesNet";
/**
* the number of created BNs.
*/
private static int _count = 0;
/**
* Creates a BN that is defined by the specified file.
*
* @param file
* file that defines a BN.
* @return the BN defined by the specified file.
* @throws IOException
* if an I/O error occurs.
*/
public final static BayesNet createBayesNet(String file) throws IOException {
BayesNet bayesNet = new BayesNet(createDefaultName());
// only supports BIF format by now
bayesNet.loadBif(file);
return bayesNet;
}
/**
* Returns the default name for the next BN.
*
* @return the default name for the next BN.
*/
public final static String createDefaultName() {
return NAME_PREFIX + _count;
}
/**
* the name of this BN.
*/
protected String _name;
protected MixedVariableMap<BeliefNode, ContinuousBeliefNode, DiscreteBeliefNode> _variables;
/**
* the map from data sets to loglikelihoods of this BN on them.
* loglikelihoods will expire once the structure or the parameters of this
* BN change.
*/
protected HashMap<DataSet, Double> _loglikelihoods;
/**
* Constructs an empty BN.
*
*/
public BayesNet() {
this(createDefaultName());
}
/**
* Constructs an empty BN with the specified name.
*
* @param name
* name of this BN.
*/
public BayesNet(String name) {
super();
name = name.trim();
// name cannot be blank
assert name.length() > 0;
_name = name;
_variables =
new MixedVariableMap<BeliefNode, ContinuousBeliefNode, DiscreteBeliefNode>();
_loglikelihoods = new HashMap<DataSet, Double>();
_count++;
}
protected BayesNet(BayesNet other) {
this();
// copies nodes
for (AbstractNode node : other._nodes) {
addNode(((BeliefNode) node).getVariable());
}
// copies edges
for (Edge edge : other._edges) {
try {
addEdge(getNode(edge.getHead().getName()),
getNode(edge.getTail().getName()));
} catch (RuntimeException e) {
throw e;
}
}
// copies CPTs
for (AbstractNode node : _nodes) {
BeliefNode beliefNode = (BeliefNode) node;
BeliefNode otherNode = other.getNode(beliefNode.getVariable());
beliefNode.setPotential(otherNode.potential().clone());
}
// copies loglikelihoods
_loglikelihoods = new HashMap<DataSet, Double>(other._loglikelihoods);
}
/**
* Adds an edge that connects the two specified nodes to this BN and returns
* the edge. This implementation extends
* <code>AbstractGraph.addEdge(AbstractNode, AbstractNode)</code> such that
* all loglikelihoods will be expired.
*
* The resulting edge is {@code head <- tail}.
*
* @param head
* head of the edge.
* @param tail
* tail of the edge.
* @return the edge that was added to this BN.
*/
public final Edge addEdge(AbstractNode head, AbstractNode tail) {
Edge edge = super.addEdge(head, tail);
// loglikelihoods expire
expireLoglikelihoods();
return edge;
}
/**
* This implementation is no long supported in <code>BayesNet</code>. Use
* <code>addNode(Variable)</code> instead.
*
* @see addNode(Variable)
*/
public final DiscreteBeliefNode addNode(String name)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public BeliefNode addNode(Variable variable) {
return variable.accept(new Variable.Visitor<BeliefNode>() {
@Override
public BeliefNode visit(DiscreteVariable variable) {
return addNode(variable);
}
@Override
public BeliefNode visit(JointContinuousVariable variable) {
return addNode(variable);
}
@Override
public BeliefNode visit(SingularContinuousVariable variable) {
return addNode(variable);
}
});
}
/**
* Adds a node with the specified variable attached to this BN and returns
* the node.
*
* @param variable
* variable to be attached to the node.
* @return the node that was added to this BN.
*/
public final DiscreteBeliefNode addNode(DiscreteVariable variable) {
DiscreteBeliefNode node = new DiscreteBeliefNode(this, variable);
addNode(node);
_variables.put(variable, node);
return node;
}
public ContinuousBeliefNode addNode(SingularContinuousVariable variable) {
return addContinuousNode(new ContinuousBeliefNode(this, variable));
}
public ContinuousBeliefNode addNode(JointContinuousVariable variable) {
return addContinuousNode(new ContinuousBeliefNode(this, variable));
}
private ContinuousBeliefNode addContinuousNode(ContinuousBeliefNode node) {
addNode(node);
_variables.put(node.getVariable(), node);
return node;
}
public ContinuousBeliefNode combine(boolean connectNewNode,
ContinuousBeliefNode node1, ContinuousBeliefNode node2) {
return combine(connectNewNode, Arrays.asList(node1, node2));
}
/**
* Combines the given collection of nodes into a new node. It removes those
* given nodes from the network and adds the merge node into the network.
* <p>
* It connects the new node to the original neighbors
*
* @param connectNewNode
* @param nodes
* @return
*/
public ContinuousBeliefNode combine(boolean connectNewNode,
List<ContinuousBeliefNode> nodes) {
if (nodes.size() < 2)
return nodes.get(0);
Set<DirectedNode> parents = Collections.emptySet();
Set<DirectedNode> children = Collections.emptySet();
TreeSet<SingularContinuousVariable> variables =
new TreeSet<SingularContinuousVariable>();
// it removes all the other nodes first so that they will not appear in
// the parents and children list
for (int i = 1; i < nodes.size(); i++) {
ContinuousBeliefNode node = nodes.get(i);
variables.addAll(node.getVariable().variables());
removeNode(node);
}
// need to make copies because removing the base node will change these
if (connectNewNode) {
parents = new HashSet<DirectedNode>(nodes.get(0).getParents());
children = new HashSet<DirectedNode>(nodes.get(0).getChildren());
}
variables.addAll(nodes.get(0).getVariable().variables());
removeNode(nodes.get(0));
ContinuousBeliefNode newNode =
addNode(JointContinuousVariable.attach(variables));
if (connectNewNode) {
for (DirectedNode child : children) {
addEdge(child, newNode);
}
for (DirectedNode parent : parents) {
addEdge(newNode, parent);
}
}
// the likelihoods are expired by the previous functions so it needs
// not be called again.
return newNode;
}
//
// /**
// * Creates a new node by combining the {@code base} node to the {@code
// * other} node. The new node will have the same neighbors as the {@code
// * base} node.
// *
// * @param base
// * @param other
// * @return the combined new node
// */
// public ContinuousBeliefNode combine(
// ContinuousBeliefNode base, ContinuousBeliefNode other) {
// // need to make copies because removing the base node will change these
// Set<DirectedNode> children =
// new HashSet<DirectedNode>(base.getChildren());
// Set<DirectedNode> parents =
// new HashSet<DirectedNode>(base.getParents());
//
// removeNode(base);
// removeNode(other);
//
// ContinuousBeliefNode newNode =
// addNode(new JointContinuousVariable(base.getVariable(), other
// .getVariable()));
//
// for (DirectedNode child : children) {
// addEdge(child, newNode);
// }
//
// for (DirectedNode parent : parents) {
// addEdge(newNode, parent);
// }
//
// // the likelihoods are expired by the previous functions so it needs
// // not be called again.
//
// _variables.put(newNode.getVariable(), newNode);
// return newNode;
// }
/**
* Separates the given variables from the base node. The base node is
* deleted, and two new nodes with the partitioned variables are added.
* Returns the the separated nodes in a pair, in which the first node holds
* the reduced set of variables, and the second node the separated set of
* variables.
* <p>
* It connects the two new nodes to the same neighbors of the old node if
* requested.
*
* @param connectNewNodes
* @param base
* @param variables
* @return
*/
public Pair<ContinuousBeliefNode, ContinuousBeliefNode> separate(
boolean connectNewNodes, JointContinuousVariable base,
Collection<SingularContinuousVariable> variables) {
Set<DirectedNode> parents = Collections.emptySet();
Set<DirectedNode> children = Collections.emptySet();
ContinuousBeliefNode baseNode = getNode(base);
if (connectNewNodes) {
parents = new HashSet<DirectedNode>(baseNode.getParents());
children = new HashSet<DirectedNode>(baseNode.getChildren());
}
// form the reduced set of variables
Collection<SingularContinuousVariable> baseVariables =
new HashSet<SingularContinuousVariable>(base.variables());
baseVariables.removeAll(variables);
removeNode(baseNode);
ContinuousBeliefNode newReducedNode =
addNode(new JointContinuousVariable(baseVariables));
ContinuousBeliefNode newSeparatedNode =
addNode(new JointContinuousVariable(variables));
if (connectNewNodes) {
for (DirectedNode parent : parents) {
addEdge(newReducedNode, parent);
addEdge(newSeparatedNode, parent);
}
for (DirectedNode child : children) {
addEdge(child, newReducedNode);
addEdge(child, newSeparatedNode);
}
}
// the likelihoods are expired by the previous functions so it needs
// not be called again.
return new Pair<ContinuousBeliefNode, ContinuousBeliefNode>(
newReducedNode, newSeparatedNode);
}
private void addNode(BeliefNode node) {
if (containsNode(node.getName())) {
System.out.println("node contained.");
}
// name must be unique in this BN. note that the name is unique implies
// that the variable is unique, too. note also that the name of a
// variable has already been trimmed.
assert !containsNode(node.getName());
// adds node to the list of nodes in this BN
_nodes.add(node);
// maps name to node
putNode(node.getName(), node);
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Creates and returns a deep copy of this BN. This implementation copies
* everything in this BN but the name and variables. The default name will
* be used for the copy instead of the original one. The variables will be
* reused other than deeply copied. This will facilitate learning process.
* However, one cannot change node names after clone. TODO avoid redundant
* operations on CPTs.
* <p>
* Also note that cpts are also cloned.
* </p>
*
* @return a deep copy of this BN.
*/
public BayesNet clone() {
return new BayesNet(this);
}
/**
* Returns the standard dimension, namely, the number of free parameters in
* the CPTs, of this BN.
*
* @return the standard dimension of this BN.
*/
public final int computeDimension() {
// sums up dimension for each node
int dimension = 0;
for (AbstractNode node : _nodes) {
dimension += ((BeliefNode) node).computeDimension();
}
return dimension;
}
/**
* <p>
* Makes loglikelihoods evaluated for this BN expired.
* </p>
*
* <p>
* <b>Note: Besides methods in this class, only
* <code>BeliefNode.setCpt(Function)</code> is supposed to call this method.
* </p>
*
* @see DiscreteBeliefNode#setCpt(Function)
*/
protected final void expireLoglikelihoods() {
if (!_loglikelihoods.isEmpty()) {
_loglikelihoods.clear();
}
}
/**
* Get AICc Score of this BayesNet w.r.t data. Note that the loglikelihood
* of the model has already been computed and been stored in this model. (We
* should improve this point later.)
*
* @author wangyi
* @param data
* @return AICc Score computed.
*/
public final double getAICcScore(DataSet data) {
// TODO We will deal with the expiring case later.
double logL = this.getLoglikelihood(data);
assert logL != Double.NaN;
// c.f. http://en.wikipedia.org/wiki/Akaike_information_criterion
int k = computeDimension();
return logL - k - k * (k + 1) / (data.getTotalWeight() - k - 1);
}
/**
* Get AIC Score of this BayesNet w.r.t data. Note that the loglikelihood of
* the model has already been computed and been stored in this model. (We
* should improve this point later.)
*
* @author wangyi
* @param data
* @return AIC Score computed.
*/
public final double getAICScore(DataSet data) {
// TODO We will deal with the expiring case later.
double logL = this.getLoglikelihood(data);
assert logL != Double.NaN;
return logL - this.computeDimension();
}
/**
* Get BIC Score of this BayesNet w.r.t data. Note that the loglikelihood of
* the model has already been computed and been stored in this model.(We
* should improve this point later.)
*
* @author csct Added by Chen Tao
* @param data
* @return BIC Score computed.
*/
public final double getBICScore(DataSet data) {
// TODO We will deal with the expiring case later.
double logL = this.getLoglikelihood(data);
assert logL != Double.NaN;
return logL - this.computeDimension() * Math.log(data.getTotalWeight())
/ 2.0;
}
/**
* Returns the set of internal variables.
*
* @return The set of internal variables.
*/
public final Set<DiscreteVariable> getInternalVars() {
Set<DiscreteVariable> vars = new HashSet<DiscreteVariable>();
for (DiscreteVariable var : getDiscreteVariables()) {
if (!getNode(var).isLeaf())
vars.add(var);
}
return vars;
}
/**
* Returns the set of leaf variables.
*
* @return The set of leaf variables.
*/
public final Set<DiscreteVariable> getLeafVars() {
Set<DiscreteVariable> vars = new HashSet<DiscreteVariable>();
for (DiscreteVariable var : getDiscreteVariables()) {
if (getNode(var).isLeaf())
vars.add(var);
}
return vars;
}
/**
* Return the loglikelihood of this BN with respect to the specified data
* set.
*
* @param dataSet
* data set at request.
* @return the loglikelihood of this BN with respect to the specified data
* set; return <code>Double.NaN</code> if the loglikelihood has not
* been evaluated yet.
*/
public final double getLoglikelihood(DataSet dataSet) {
Double loglikelihood = _loglikelihoods.get(dataSet);
return loglikelihood == null ? Double.NaN : loglikelihood;
}
/**
* Returns the name of this BN.
*
* @return the name of this BN.
*/
public final String getName() {
return _name;
}
/**
* Gets a belief node from this network by name.
*
* @param name
* name of the target node
* @return node with the specified name, or null if not found
*/
public BeliefNode getNode(String name) {
return (BeliefNode) super.getNode(name);
}
/**
* Returns a continuous belief node of the specified name. It throws an
* exception if the node of the given name is not a continuous node.
*
* @param name
* name of the continuous node
* @return a continuous belief node of the specified name
*/
public ContinuousBeliefNode getContinuousNode(String name) {
return (ContinuousBeliefNode) super.getNode(name);
}
/**
* Returns a discrete belief node of the specified name. It throws an
* exception if the node of the given name is not a discrete node.
*
* @param name
* name of the discrete node
* @return a discrete belief node of the specified name
*/
public DiscreteBeliefNode getDiscreteNode(String name) {
return (DiscreteBeliefNode) super.getNode(name);
}
/**
* Returns the node to which the specified variable is attached in this BN.
*
* @param variable
* variable attached to the node.
* @return the node to which the specified variable is attached; returns
* <code>null</code> if none uses this variable.
*/
public final DiscreteBeliefNode getNode(DiscreteVariable variable) {
return _variables.get(variable);
}
/**
* Returns the continuous belief node containing the given variable.
*
* @param variable
* variable of the node
* @return node containing the given variable, or {@code null} if it is not
* found
*/
public ContinuousBeliefNode getNode(ContinuousVariable variable) {
return _variables.get(variable);
}
/**
* Returns the belief node containing the given variable.
*
* @param variable
* variable of the node
* @return node containing the given variable, or {@code null} if it is not
* found
*/
public BeliefNode getNode(Variable variable) {
return _variables.get(variable);
}
/**
* Returns the list of variables in this BN. For the sake of efficiency,
* this implementation returns the reference to the private field. Make sure
* you understand this before using this method.
*
* @return the list of variables in this BN.
*/
public final Set<DiscreteVariable> getDiscreteVariables() {
Set<DiscreteVariable> vars = new HashSet<DiscreteVariable>();
for (DiscreteVariable var : _variables.discreteMap().keySet()) {
vars.add(var);
}
return vars;
// return _variables.keySet();
}
/**
* Returns the set of all singular continuous variables.
*
* @return set of all singular continuous variables
*/
public Set<SingularContinuousVariable> getSingularContinuousVariables() {
return Collections.unmodifiableSet(_variables.continuousMap().keySet());
}
public Set<Variable> getVariables() {
return _variables.keySet();
}
/**
* Whether a variable has a cardinality that allows a regular model. Calling
* it with continuous variable argument returns {@code true}.
*
* @param variable
* variable under check
* @return whether the variable has a regular cardinality
*/
public boolean hasRegularCardinality(Variable variable) {
return variable.accept(new Variable.Visitor<Boolean>() {
@Override
public Boolean visit(DiscreteVariable variable) {
DiscreteBeliefNode node = getNode(variable);
if (node.isLeaf())
return true;
return variable.getCardinality() <= node.computeMaxPossibleCardInHLCM();
}
// since continuous node must be leaf node, it returns true
@Override
public Boolean visit(JointContinuousVariable variable) {
return true;
}
@Override
public Boolean visit(SingularContinuousVariable variable) {
return true;
}
});
}
/**
* Loads the specified BIF file.
*
* @param file
* BIF file that defines a BN.
*/
private final void loadBif(String file) throws IOException {
StreamTokenizer tokenizer = new StreamTokenizer(new FileReader(file));
tokenizer.resetSyntax();
// characters that will be ignored
tokenizer.whitespaceChars('=', '=');
tokenizer.whitespaceChars(' ', ' ');
tokenizer.whitespaceChars('"', '"');
tokenizer.whitespaceChars('\t', '\t');
// word characters
tokenizer.wordChars('A', 'z');
// we will parse numbers
tokenizer.parseNumbers();
// special characters considered in the gramma
tokenizer.ordinaryChar(';');
tokenizer.ordinaryChar('(');
tokenizer.ordinaryChar(')');
tokenizer.ordinaryChar('{');
tokenizer.ordinaryChar('}');
tokenizer.ordinaryChar('[');
tokenizer.ordinaryChar(']');
// does NOT treat eol as a token
tokenizer.eolIsSignificant(false);
// ignores c++ comments
tokenizer.slashSlashComments(true);
// starts parsing
int value;
// reads until the end of the stream (file)
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_WORD) {
// start of a new block here
String word = tokenizer.sval;
if (word.equals("network")) {
// parses network properties. next string must be the name
// of this BN
tokenizer.nextToken();
setName(tokenizer.sval);
} else if (word.equals("variable")) {
// parses variable. get name of variable first
tokenizer.nextToken();
String name = tokenizer.sval;
// looks for '['
do {
value = tokenizer.nextToken();
} while (value != '[');
// gets integer as cardinality
tokenizer.nextToken();
int cardinality = (int) tokenizer.nval;
// looks for '{'
do {
value = tokenizer.nextToken();
} while (value != '{');
// state list
ArrayList<String> states = new ArrayList<String>();
// gets states
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_WORD) {
states.add(tokenizer.sval);
}
} while (value != '}');
// tests consistency
assert states.size() == cardinality;
// creates node
addNode(new DiscreteVariable(name, states));
} else if (word.equals("probability")) {
// parses CPT. skips next '('
tokenizer.nextToken();
// variables in this family
ArrayList<DiscreteVariable> family =
new ArrayList<DiscreteVariable>();
// gets variable name and node
tokenizer.nextToken();
DiscreteBeliefNode node =
(DiscreteBeliefNode) getNode(tokenizer.sval);
family.add(node.getVariable());
// gets parents and adds edges
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_WORD) {
DiscreteBeliefNode parent =
(DiscreteBeliefNode) getNode(tokenizer.sval);
family.add(parent.getVariable());
// adds edge from parent to node
addEdge(node, parent);
}
} while (value != ')');
// creates CPT
Function cpt = Function.createFunction(family);
// looks for '(' or words
do {
value = tokenizer.nextToken();
} while (value != '(' && value != StreamTokenizer.TT_WORD);
// checks next token: there are two formats, one with
// "table" and the other fills in cells one by one.
if (value == StreamTokenizer.TT_WORD) {
// we only accept "table" but not "default"
assert tokenizer.sval.equals("table");
// probability values
ArrayList<Double> values = new ArrayList<Double>();
// gets numerical tokens
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_NUMBER) {
values.add(tokenizer.nval);
}
} while (value != ';');
// consistency between family and values will be tested
cpt.setCells(family, values);
} else {
// states array
ArrayList<Integer> states = new ArrayList<Integer>();
states.add(0);
int cardinality = node.getVariable().getCardinality();
// parses row by row
while (value != '}') {
// gets parent states
for (int i = 1; i < family.size(); i++) {
do {
value = tokenizer.nextToken();
} while (value != StreamTokenizer.TT_WORD);
states.add(family.get(i).indexOf(tokenizer.sval));
}
// fills in data
for (int i = 0; i < cardinality; i++) {
states.set(0, i);
do {
value = tokenizer.nextToken();
} while (value != StreamTokenizer.TT_NUMBER);
cpt.setCell(family, states, tokenizer.nval);
}
// looks for next '(' or '}'
while (value != '(' && value != '}') {
value = tokenizer.nextToken();
}
}
}
// normalizes the CPT with respect to the attached variable
cpt.normalize(node.getVariable());
// sets the CPT
node.setCpt(cpt);
}
}
} while (value != StreamTokenizer.TT_EOF);
}
/**
* Randomly sets the parameters of this BN. TODO avoid redundant operations
* on CPTs.
*/
public final void randomlyParameterize() {
for (AbstractNode node : _nodes) {
((DiscreteBeliefNode) node).randomlyParameterize();
}
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Randomly sets the parameters of the specified list of nodes in this BN.
* TODO avoid redundant operations on CPTs.
*
* @param mutableNodes
* list of nodes whose parameters are to be randomized.
*/
public final void randomlyParameterize(
Collection<DiscreteBeliefNode> mutableNodes) {
// mutable nodes must be in this BN
assert _nodes.containsAll(mutableNodes);
for (DiscreteBeliefNode node : mutableNodes) {
node.randomlyParameterize();
}
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Removes the specified edge from this BN. This implementation extends
* <code>AbstractGraph.removeEdge(Edge)</code> such that all loglikelihoods
* will be expired.
*
* @param edge
* edge to be removed from this BN.
*/
@Override
public final void removeEdge(Edge edge) {
super.removeEdge(edge);
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Removes the specified node from this BN. This implementation extends
* <code>AbstractGraph.removeNode(AbstractNode)</code> such that map from
* variables to nodes will be updated and all loglikelihoods will be
* expired.
*
* @param node
* node to be removed from this BN.
*/
public final void removeNode(AbstractNode node) {
super.removeNode(node);
_variables.remove(((BeliefNode) node).getVariable());
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Generates a batch of samples from this BN.
*
* @param sampleSize
* number of samples to be generated.
* @return a batch of samples from this BN.
*/
public DataSet sample(int sampleSize) {
// initialize data set
int nNodes = getNumberOfNodes();
DataSet samples =
new DataSet(getDiscreteVariables().toArray(
new DiscreteVariable[nNodes]));
// since variables are sorted in data set, find mapping from belief
// nodes to variables
DiscreteVariable[] vars = samples.getVariables();
HashMap<AbstractNode, Integer> map =
new HashMap<AbstractNode, Integer>();
for (AbstractNode node : getNodes()) {
DiscreteVariable var = ((DiscreteBeliefNode) node).getVariable();
int pos = Arrays.binarySearch(vars, var);
map.put(node, pos);
}
// topological sort
AbstractNode[] order = topologicalSort();
for (int i = 0; i < sampleSize; i++) {
int[] states = new int[nNodes];
// forward sampling
for (AbstractNode node : order) {
DiscreteBeliefNode bNode = (DiscreteBeliefNode) node;
// find parents and their states
ArrayList<DiscreteVariable> parents =
new ArrayList<DiscreteVariable>();
ArrayList<Integer> parentStates = new ArrayList<Integer>();
for (DirectedNode parent : bNode.getParents()) {
DiscreteVariable var =
((DiscreteBeliefNode) parent).getVariable();
parents.add(var);
int pos = map.get(parent);
parentStates.add(states[pos]);
}
// instantiate parents
Function cond =
bNode.potential().project(parents, parentStates);
// sample according to the conditional distribution
states[map.get(node)] = cond.sample();
}
// add to samples
samples.addDataCase(states, 1.0);
}
return samples;
}
/**
* Outputs this BN to the specified file in BIF format. See
* http://www.cs.cmu
* .edu/~fgcozman/Research/InterchangeFormat/Old/xmlbif02.html for the
* grammar of BIF format.
*
* @param file
* output of this BN.
* @throws FileNotFoundException
* if the file exists but is a directory rather than a regular
* file, does not exist but cannot be created, or cannot be
* opened for any other reason.
*/
public final void saveAsBif(String file) throws FileNotFoundException {
PrintWriter out = new PrintWriter(file);
// outputs header
out.println("// " + file);
out.println("// Produced by org.latlab at "
+ (new Date(System.currentTimeMillis())));
// outputs name
out.println("network \"" + _name + "\" {");
out.println("}");
out.println();
// outputs nodes
for (AbstractNode node : _nodes) {
DiscreteVariable variable =
((DiscreteBeliefNode) node).getVariable();
// name of variable
out.println("variable \"" + variable.getName() + "\" {");
// states of variable
out.print("\ttype discrete[" + variable.getCardinality() + "] { ");
Iterator<String> iter = variable.getStates().iterator();
while (iter.hasNext()) {
out.print("\"" + iter.next() + "\"");
if (iter.hasNext()) {
out.print(" ");
}
}
out.println(" };");
out.println("}");
out.println();
}
// Output CPTs
for (AbstractNode node : _nodes) {
DiscreteBeliefNode bNode = (DiscreteBeliefNode) node;
// variables in this family. note that the variables in the
// probability block are arranged from the most significant place to
// the least significant place.
ArrayList<DiscreteVariable> vars =
new ArrayList<DiscreteVariable>();
vars.add(bNode.getVariable());
// name of node
out.print("probability ( \"" + bNode.getName() + "\" ");
// names of parents
if (!bNode.isRoot()) {
out.print("| ");
}
Iterator<DirectedNode> iter = bNode.getParents().iterator();
while (iter.hasNext()) {
DiscreteBeliefNode parent = (DiscreteBeliefNode) iter.next();
out.print("\"" + parent.getName() + "\"");
if (iter.hasNext()) {
out.print(", ");
}
vars.add(parent.getVariable());
}
out.println(" ) {");
// cells in CPT
out.print("\ttable");
for (double cell : bNode.potential().getCells(vars)) {
out.print(" " + cell);
}
out.println(";");
out.println("}");
}
out.close();
}
/**
* Replaces the loglikelihood of this BN with respect to the specified data
* set.
*
* @param dataSet
* data set at request.
* @param loglikelihood
* new loglikelihood of this BN.
*/
public final void setLoglikelihood(DataSet dataSet, double loglikelihood) {
// loglikelihood must be non-positive
assert loglikelihood <= 0.0;
_loglikelihoods.put(dataSet, loglikelihood);
}
/**
* Replaces the name of this BN.
*
* @param name
* new name of this BN.
*/
public final void setName(String name) {
name = name.trim();
// name cannot be blank
assert name.length() > 0;
_name = name;
}
/**
* Returns a string representation of this BN. The string representation
* will be indented by the specified amount.
*
* @param amount
* amount by which the string representation is to be indented.
* @return a string representation of this BN.
*/
public String toString(int amount) {
// amount must be non-negative
assert amount >= 0;
// prepares white space for indent
StringBuffer whiteSpace = new StringBuffer();
for (int i = 0; i < amount; i++) {
whiteSpace.append('\t');
}
// builds string representation
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(whiteSpace);
stringBuffer.append(getName() + " {\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tnumber of nodes = " + getNumberOfNodes() + ";\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tnodes = {\n");
for (AbstractNode node : _nodes) {
stringBuffer.append(node.toString(amount + 2));
}
stringBuffer.append(whiteSpace);
stringBuffer.append("\t};\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tnumber of edges = " + getNumberOfEdges() + ";\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tedges = {\n");
for (Edge edge : _edges) {
stringBuffer.append(edge.toString(amount + 2));
}
stringBuffer.append(whiteSpace);
stringBuffer.append("\t};\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("};\n");
return stringBuffer.toString();
}
/**
* Finds a variable by name. It supports only singular variable (continuous
* or discrete).
*
* @param name
* name of the variable
* @return variable with the given name, or {@code null} if not found
*/
public Variable findVariableByName(String name) {
return _variables.findVariableByName(name);
}
/**
* Finds a joint continuous variable by the name of one of its singular
* variable.
*
* @param singularVariableName
* name of the singular continuous variable
* @return joint variable containing the given singular variable
*/
public JointContinuousVariable findJointVariableByName(
String singularVariableName) {
SingularContinuousVariable variable =
(SingularContinuousVariable) _variables.findVariableByName(singularVariableName);
ContinuousBeliefNode node = getNode(variable);
return node != null ? node.getVariable() : null;
}
}
| UTF-8 | Java | 32,951 | java | BayesNet.java | Java | [
{
"context": "/**\n * BayesNet.java Copyright (C) 2006 Tao Chen, Kin Man Poon, Yi Wang, and Nevin\n * L. Zhang\n */",
"end": 48,
"score": 0.9996988773345947,
"start": 40,
"tag": "NAME",
"value": "Tao Chen"
},
{
"context": "/**\n * BayesNet.java Copyright (C) 2006 Tao Chen, Kin Man Poon, Yi Wang, and Nevin\n * L. Zhang\n */\npackage org.l",
"end": 62,
"score": 0.9997403025627136,
"start": 50,
"tag": "NAME",
"value": "Kin Man Poon"
},
{
"context": "et.java Copyright (C) 2006 Tao Chen, Kin Man Poon, Yi Wang, and Nevin\n * L. Zhang\n */\npackage org.latlab.cor",
"end": 71,
"score": 0.9996657371520996,
"start": 64,
"tag": "NAME",
"value": "Yi Wang"
},
{
"context": "ight (C) 2006 Tao Chen, Kin Man Poon, Yi Wang, and Nevin\n * L. Zhang\n */\npackage org.latlab.core.model;\n\ni",
"end": 82,
"score": 0.9996392130851746,
"start": 77,
"tag": "NAME",
"value": "Nevin"
},
{
"context": "2006 Tao Chen, Kin Man Poon, Yi Wang, and Nevin\n * L. Zhang\n */\npackage org.latlab.core.model;\n\nimport org.la",
"end": 94,
"score": 0.9985923767089844,
"start": 86,
"tag": "NAME",
"value": "L. Zhang"
},
{
"context": "mplementation for Bayes nets (BNs).\n * \n * @author Yi Wang\n * \n */\npublic class BayesNet extends DirectedAcy",
"end": 463,
"score": 0.9997946619987488,
"start": 456,
"tag": "NAME",
"value": "Yi Wang"
},
{
"context": "should improve this point later.)\n\t * \n\t * @author wangyi\n\t * @param data\n\t * @return AICc Score computed.\n",
"end": 12200,
"score": 0.9992244839668274,
"start": 12194,
"tag": "USERNAME",
"value": "wangyi"
},
{
"context": "should improve this point later.)\n\t * \n\t * @author wangyi\n\t * @param data\n\t * @return AIC Score computed.\n\t",
"end": 12822,
"score": 0.9995982646942139,
"start": 12816,
"tag": "USERNAME",
"value": "wangyi"
},
{
"context": "should improve this point later.)\n\t * \n\t * @author csct Added by Chen Tao\n\t * @param data\n\t * @return BIC",
"end": 13315,
"score": 0.9994817972183228,
"start": 13311,
"tag": "USERNAME",
"value": "csct"
},
{
"context": " this point later.)\n\t * \n\t * @author csct Added by Chen Tao\n\t * @param data\n\t * @return BIC Score computed.\n\t",
"end": 13333,
"score": 0.9998524785041809,
"start": 13325,
"tag": "NAME",
"value": "Chen Tao"
},
{
"context": "n BIF format. See\n\t * http://www.cs.cmu\n\t * .edu/~fgcozman/Research/InterchangeFormat/Old/xmlbif02.html for ",
"end": 27503,
"score": 0.9060006737709045,
"start": 27495,
"tag": "USERNAME",
"value": "fgcozman"
}
]
| null | []
| /**
* BayesNet.java Copyright (C) 2006 <NAME>, <NAME>, <NAME>, and Nevin
* <NAME>
*/
package org.latlab.core.model;
import org.latlab.core.graph.AbstractNode;
import org.latlab.core.graph.DirectedAcyclicGraph;
import org.latlab.core.graph.DirectedNode;
import org.latlab.core.graph.Edge;
import org.latlab.core.util.*;
import java.io.*;
import java.util.*;
/**
* This class provides an implementation for Bayes nets (BNs).
*
* @author <NAME>
*
*/
public class BayesNet extends DirectedAcyclicGraph {
/**
* the prefix of default names of BNs.
*/
private final static String NAME_PREFIX = "BayesNet";
/**
* the number of created BNs.
*/
private static int _count = 0;
/**
* Creates a BN that is defined by the specified file.
*
* @param file
* file that defines a BN.
* @return the BN defined by the specified file.
* @throws IOException
* if an I/O error occurs.
*/
public final static BayesNet createBayesNet(String file) throws IOException {
BayesNet bayesNet = new BayesNet(createDefaultName());
// only supports BIF format by now
bayesNet.loadBif(file);
return bayesNet;
}
/**
* Returns the default name for the next BN.
*
* @return the default name for the next BN.
*/
public final static String createDefaultName() {
return NAME_PREFIX + _count;
}
/**
* the name of this BN.
*/
protected String _name;
protected MixedVariableMap<BeliefNode, ContinuousBeliefNode, DiscreteBeliefNode> _variables;
/**
* the map from data sets to loglikelihoods of this BN on them.
* loglikelihoods will expire once the structure or the parameters of this
* BN change.
*/
protected HashMap<DataSet, Double> _loglikelihoods;
/**
* Constructs an empty BN.
*
*/
public BayesNet() {
this(createDefaultName());
}
/**
* Constructs an empty BN with the specified name.
*
* @param name
* name of this BN.
*/
public BayesNet(String name) {
super();
name = name.trim();
// name cannot be blank
assert name.length() > 0;
_name = name;
_variables =
new MixedVariableMap<BeliefNode, ContinuousBeliefNode, DiscreteBeliefNode>();
_loglikelihoods = new HashMap<DataSet, Double>();
_count++;
}
protected BayesNet(BayesNet other) {
this();
// copies nodes
for (AbstractNode node : other._nodes) {
addNode(((BeliefNode) node).getVariable());
}
// copies edges
for (Edge edge : other._edges) {
try {
addEdge(getNode(edge.getHead().getName()),
getNode(edge.getTail().getName()));
} catch (RuntimeException e) {
throw e;
}
}
// copies CPTs
for (AbstractNode node : _nodes) {
BeliefNode beliefNode = (BeliefNode) node;
BeliefNode otherNode = other.getNode(beliefNode.getVariable());
beliefNode.setPotential(otherNode.potential().clone());
}
// copies loglikelihoods
_loglikelihoods = new HashMap<DataSet, Double>(other._loglikelihoods);
}
/**
* Adds an edge that connects the two specified nodes to this BN and returns
* the edge. This implementation extends
* <code>AbstractGraph.addEdge(AbstractNode, AbstractNode)</code> such that
* all loglikelihoods will be expired.
*
* The resulting edge is {@code head <- tail}.
*
* @param head
* head of the edge.
* @param tail
* tail of the edge.
* @return the edge that was added to this BN.
*/
public final Edge addEdge(AbstractNode head, AbstractNode tail) {
Edge edge = super.addEdge(head, tail);
// loglikelihoods expire
expireLoglikelihoods();
return edge;
}
/**
* This implementation is no long supported in <code>BayesNet</code>. Use
* <code>addNode(Variable)</code> instead.
*
* @see addNode(Variable)
*/
public final DiscreteBeliefNode addNode(String name)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public BeliefNode addNode(Variable variable) {
return variable.accept(new Variable.Visitor<BeliefNode>() {
@Override
public BeliefNode visit(DiscreteVariable variable) {
return addNode(variable);
}
@Override
public BeliefNode visit(JointContinuousVariable variable) {
return addNode(variable);
}
@Override
public BeliefNode visit(SingularContinuousVariable variable) {
return addNode(variable);
}
});
}
/**
* Adds a node with the specified variable attached to this BN and returns
* the node.
*
* @param variable
* variable to be attached to the node.
* @return the node that was added to this BN.
*/
public final DiscreteBeliefNode addNode(DiscreteVariable variable) {
DiscreteBeliefNode node = new DiscreteBeliefNode(this, variable);
addNode(node);
_variables.put(variable, node);
return node;
}
public ContinuousBeliefNode addNode(SingularContinuousVariable variable) {
return addContinuousNode(new ContinuousBeliefNode(this, variable));
}
public ContinuousBeliefNode addNode(JointContinuousVariable variable) {
return addContinuousNode(new ContinuousBeliefNode(this, variable));
}
private ContinuousBeliefNode addContinuousNode(ContinuousBeliefNode node) {
addNode(node);
_variables.put(node.getVariable(), node);
return node;
}
public ContinuousBeliefNode combine(boolean connectNewNode,
ContinuousBeliefNode node1, ContinuousBeliefNode node2) {
return combine(connectNewNode, Arrays.asList(node1, node2));
}
/**
* Combines the given collection of nodes into a new node. It removes those
* given nodes from the network and adds the merge node into the network.
* <p>
* It connects the new node to the original neighbors
*
* @param connectNewNode
* @param nodes
* @return
*/
public ContinuousBeliefNode combine(boolean connectNewNode,
List<ContinuousBeliefNode> nodes) {
if (nodes.size() < 2)
return nodes.get(0);
Set<DirectedNode> parents = Collections.emptySet();
Set<DirectedNode> children = Collections.emptySet();
TreeSet<SingularContinuousVariable> variables =
new TreeSet<SingularContinuousVariable>();
// it removes all the other nodes first so that they will not appear in
// the parents and children list
for (int i = 1; i < nodes.size(); i++) {
ContinuousBeliefNode node = nodes.get(i);
variables.addAll(node.getVariable().variables());
removeNode(node);
}
// need to make copies because removing the base node will change these
if (connectNewNode) {
parents = new HashSet<DirectedNode>(nodes.get(0).getParents());
children = new HashSet<DirectedNode>(nodes.get(0).getChildren());
}
variables.addAll(nodes.get(0).getVariable().variables());
removeNode(nodes.get(0));
ContinuousBeliefNode newNode =
addNode(JointContinuousVariable.attach(variables));
if (connectNewNode) {
for (DirectedNode child : children) {
addEdge(child, newNode);
}
for (DirectedNode parent : parents) {
addEdge(newNode, parent);
}
}
// the likelihoods are expired by the previous functions so it needs
// not be called again.
return newNode;
}
//
// /**
// * Creates a new node by combining the {@code base} node to the {@code
// * other} node. The new node will have the same neighbors as the {@code
// * base} node.
// *
// * @param base
// * @param other
// * @return the combined new node
// */
// public ContinuousBeliefNode combine(
// ContinuousBeliefNode base, ContinuousBeliefNode other) {
// // need to make copies because removing the base node will change these
// Set<DirectedNode> children =
// new HashSet<DirectedNode>(base.getChildren());
// Set<DirectedNode> parents =
// new HashSet<DirectedNode>(base.getParents());
//
// removeNode(base);
// removeNode(other);
//
// ContinuousBeliefNode newNode =
// addNode(new JointContinuousVariable(base.getVariable(), other
// .getVariable()));
//
// for (DirectedNode child : children) {
// addEdge(child, newNode);
// }
//
// for (DirectedNode parent : parents) {
// addEdge(newNode, parent);
// }
//
// // the likelihoods are expired by the previous functions so it needs
// // not be called again.
//
// _variables.put(newNode.getVariable(), newNode);
// return newNode;
// }
/**
* Separates the given variables from the base node. The base node is
* deleted, and two new nodes with the partitioned variables are added.
* Returns the the separated nodes in a pair, in which the first node holds
* the reduced set of variables, and the second node the separated set of
* variables.
* <p>
* It connects the two new nodes to the same neighbors of the old node if
* requested.
*
* @param connectNewNodes
* @param base
* @param variables
* @return
*/
public Pair<ContinuousBeliefNode, ContinuousBeliefNode> separate(
boolean connectNewNodes, JointContinuousVariable base,
Collection<SingularContinuousVariable> variables) {
Set<DirectedNode> parents = Collections.emptySet();
Set<DirectedNode> children = Collections.emptySet();
ContinuousBeliefNode baseNode = getNode(base);
if (connectNewNodes) {
parents = new HashSet<DirectedNode>(baseNode.getParents());
children = new HashSet<DirectedNode>(baseNode.getChildren());
}
// form the reduced set of variables
Collection<SingularContinuousVariable> baseVariables =
new HashSet<SingularContinuousVariable>(base.variables());
baseVariables.removeAll(variables);
removeNode(baseNode);
ContinuousBeliefNode newReducedNode =
addNode(new JointContinuousVariable(baseVariables));
ContinuousBeliefNode newSeparatedNode =
addNode(new JointContinuousVariable(variables));
if (connectNewNodes) {
for (DirectedNode parent : parents) {
addEdge(newReducedNode, parent);
addEdge(newSeparatedNode, parent);
}
for (DirectedNode child : children) {
addEdge(child, newReducedNode);
addEdge(child, newSeparatedNode);
}
}
// the likelihoods are expired by the previous functions so it needs
// not be called again.
return new Pair<ContinuousBeliefNode, ContinuousBeliefNode>(
newReducedNode, newSeparatedNode);
}
private void addNode(BeliefNode node) {
if (containsNode(node.getName())) {
System.out.println("node contained.");
}
// name must be unique in this BN. note that the name is unique implies
// that the variable is unique, too. note also that the name of a
// variable has already been trimmed.
assert !containsNode(node.getName());
// adds node to the list of nodes in this BN
_nodes.add(node);
// maps name to node
putNode(node.getName(), node);
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Creates and returns a deep copy of this BN. This implementation copies
* everything in this BN but the name and variables. The default name will
* be used for the copy instead of the original one. The variables will be
* reused other than deeply copied. This will facilitate learning process.
* However, one cannot change node names after clone. TODO avoid redundant
* operations on CPTs.
* <p>
* Also note that cpts are also cloned.
* </p>
*
* @return a deep copy of this BN.
*/
public BayesNet clone() {
return new BayesNet(this);
}
/**
* Returns the standard dimension, namely, the number of free parameters in
* the CPTs, of this BN.
*
* @return the standard dimension of this BN.
*/
public final int computeDimension() {
// sums up dimension for each node
int dimension = 0;
for (AbstractNode node : _nodes) {
dimension += ((BeliefNode) node).computeDimension();
}
return dimension;
}
/**
* <p>
* Makes loglikelihoods evaluated for this BN expired.
* </p>
*
* <p>
* <b>Note: Besides methods in this class, only
* <code>BeliefNode.setCpt(Function)</code> is supposed to call this method.
* </p>
*
* @see DiscreteBeliefNode#setCpt(Function)
*/
protected final void expireLoglikelihoods() {
if (!_loglikelihoods.isEmpty()) {
_loglikelihoods.clear();
}
}
/**
* Get AICc Score of this BayesNet w.r.t data. Note that the loglikelihood
* of the model has already been computed and been stored in this model. (We
* should improve this point later.)
*
* @author wangyi
* @param data
* @return AICc Score computed.
*/
public final double getAICcScore(DataSet data) {
// TODO We will deal with the expiring case later.
double logL = this.getLoglikelihood(data);
assert logL != Double.NaN;
// c.f. http://en.wikipedia.org/wiki/Akaike_information_criterion
int k = computeDimension();
return logL - k - k * (k + 1) / (data.getTotalWeight() - k - 1);
}
/**
* Get AIC Score of this BayesNet w.r.t data. Note that the loglikelihood of
* the model has already been computed and been stored in this model. (We
* should improve this point later.)
*
* @author wangyi
* @param data
* @return AIC Score computed.
*/
public final double getAICScore(DataSet data) {
// TODO We will deal with the expiring case later.
double logL = this.getLoglikelihood(data);
assert logL != Double.NaN;
return logL - this.computeDimension();
}
/**
* Get BIC Score of this BayesNet w.r.t data. Note that the loglikelihood of
* the model has already been computed and been stored in this model.(We
* should improve this point later.)
*
* @author csct Added by <NAME>
* @param data
* @return BIC Score computed.
*/
public final double getBICScore(DataSet data) {
// TODO We will deal with the expiring case later.
double logL = this.getLoglikelihood(data);
assert logL != Double.NaN;
return logL - this.computeDimension() * Math.log(data.getTotalWeight())
/ 2.0;
}
/**
* Returns the set of internal variables.
*
* @return The set of internal variables.
*/
public final Set<DiscreteVariable> getInternalVars() {
Set<DiscreteVariable> vars = new HashSet<DiscreteVariable>();
for (DiscreteVariable var : getDiscreteVariables()) {
if (!getNode(var).isLeaf())
vars.add(var);
}
return vars;
}
/**
* Returns the set of leaf variables.
*
* @return The set of leaf variables.
*/
public final Set<DiscreteVariable> getLeafVars() {
Set<DiscreteVariable> vars = new HashSet<DiscreteVariable>();
for (DiscreteVariable var : getDiscreteVariables()) {
if (getNode(var).isLeaf())
vars.add(var);
}
return vars;
}
/**
* Return the loglikelihood of this BN with respect to the specified data
* set.
*
* @param dataSet
* data set at request.
* @return the loglikelihood of this BN with respect to the specified data
* set; return <code>Double.NaN</code> if the loglikelihood has not
* been evaluated yet.
*/
public final double getLoglikelihood(DataSet dataSet) {
Double loglikelihood = _loglikelihoods.get(dataSet);
return loglikelihood == null ? Double.NaN : loglikelihood;
}
/**
* Returns the name of this BN.
*
* @return the name of this BN.
*/
public final String getName() {
return _name;
}
/**
* Gets a belief node from this network by name.
*
* @param name
* name of the target node
* @return node with the specified name, or null if not found
*/
public BeliefNode getNode(String name) {
return (BeliefNode) super.getNode(name);
}
/**
* Returns a continuous belief node of the specified name. It throws an
* exception if the node of the given name is not a continuous node.
*
* @param name
* name of the continuous node
* @return a continuous belief node of the specified name
*/
public ContinuousBeliefNode getContinuousNode(String name) {
return (ContinuousBeliefNode) super.getNode(name);
}
/**
* Returns a discrete belief node of the specified name. It throws an
* exception if the node of the given name is not a discrete node.
*
* @param name
* name of the discrete node
* @return a discrete belief node of the specified name
*/
public DiscreteBeliefNode getDiscreteNode(String name) {
return (DiscreteBeliefNode) super.getNode(name);
}
/**
* Returns the node to which the specified variable is attached in this BN.
*
* @param variable
* variable attached to the node.
* @return the node to which the specified variable is attached; returns
* <code>null</code> if none uses this variable.
*/
public final DiscreteBeliefNode getNode(DiscreteVariable variable) {
return _variables.get(variable);
}
/**
* Returns the continuous belief node containing the given variable.
*
* @param variable
* variable of the node
* @return node containing the given variable, or {@code null} if it is not
* found
*/
public ContinuousBeliefNode getNode(ContinuousVariable variable) {
return _variables.get(variable);
}
/**
* Returns the belief node containing the given variable.
*
* @param variable
* variable of the node
* @return node containing the given variable, or {@code null} if it is not
* found
*/
public BeliefNode getNode(Variable variable) {
return _variables.get(variable);
}
/**
* Returns the list of variables in this BN. For the sake of efficiency,
* this implementation returns the reference to the private field. Make sure
* you understand this before using this method.
*
* @return the list of variables in this BN.
*/
public final Set<DiscreteVariable> getDiscreteVariables() {
Set<DiscreteVariable> vars = new HashSet<DiscreteVariable>();
for (DiscreteVariable var : _variables.discreteMap().keySet()) {
vars.add(var);
}
return vars;
// return _variables.keySet();
}
/**
* Returns the set of all singular continuous variables.
*
* @return set of all singular continuous variables
*/
public Set<SingularContinuousVariable> getSingularContinuousVariables() {
return Collections.unmodifiableSet(_variables.continuousMap().keySet());
}
public Set<Variable> getVariables() {
return _variables.keySet();
}
/**
* Whether a variable has a cardinality that allows a regular model. Calling
* it with continuous variable argument returns {@code true}.
*
* @param variable
* variable under check
* @return whether the variable has a regular cardinality
*/
public boolean hasRegularCardinality(Variable variable) {
return variable.accept(new Variable.Visitor<Boolean>() {
@Override
public Boolean visit(DiscreteVariable variable) {
DiscreteBeliefNode node = getNode(variable);
if (node.isLeaf())
return true;
return variable.getCardinality() <= node.computeMaxPossibleCardInHLCM();
}
// since continuous node must be leaf node, it returns true
@Override
public Boolean visit(JointContinuousVariable variable) {
return true;
}
@Override
public Boolean visit(SingularContinuousVariable variable) {
return true;
}
});
}
/**
* Loads the specified BIF file.
*
* @param file
* BIF file that defines a BN.
*/
private final void loadBif(String file) throws IOException {
StreamTokenizer tokenizer = new StreamTokenizer(new FileReader(file));
tokenizer.resetSyntax();
// characters that will be ignored
tokenizer.whitespaceChars('=', '=');
tokenizer.whitespaceChars(' ', ' ');
tokenizer.whitespaceChars('"', '"');
tokenizer.whitespaceChars('\t', '\t');
// word characters
tokenizer.wordChars('A', 'z');
// we will parse numbers
tokenizer.parseNumbers();
// special characters considered in the gramma
tokenizer.ordinaryChar(';');
tokenizer.ordinaryChar('(');
tokenizer.ordinaryChar(')');
tokenizer.ordinaryChar('{');
tokenizer.ordinaryChar('}');
tokenizer.ordinaryChar('[');
tokenizer.ordinaryChar(']');
// does NOT treat eol as a token
tokenizer.eolIsSignificant(false);
// ignores c++ comments
tokenizer.slashSlashComments(true);
// starts parsing
int value;
// reads until the end of the stream (file)
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_WORD) {
// start of a new block here
String word = tokenizer.sval;
if (word.equals("network")) {
// parses network properties. next string must be the name
// of this BN
tokenizer.nextToken();
setName(tokenizer.sval);
} else if (word.equals("variable")) {
// parses variable. get name of variable first
tokenizer.nextToken();
String name = tokenizer.sval;
// looks for '['
do {
value = tokenizer.nextToken();
} while (value != '[');
// gets integer as cardinality
tokenizer.nextToken();
int cardinality = (int) tokenizer.nval;
// looks for '{'
do {
value = tokenizer.nextToken();
} while (value != '{');
// state list
ArrayList<String> states = new ArrayList<String>();
// gets states
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_WORD) {
states.add(tokenizer.sval);
}
} while (value != '}');
// tests consistency
assert states.size() == cardinality;
// creates node
addNode(new DiscreteVariable(name, states));
} else if (word.equals("probability")) {
// parses CPT. skips next '('
tokenizer.nextToken();
// variables in this family
ArrayList<DiscreteVariable> family =
new ArrayList<DiscreteVariable>();
// gets variable name and node
tokenizer.nextToken();
DiscreteBeliefNode node =
(DiscreteBeliefNode) getNode(tokenizer.sval);
family.add(node.getVariable());
// gets parents and adds edges
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_WORD) {
DiscreteBeliefNode parent =
(DiscreteBeliefNode) getNode(tokenizer.sval);
family.add(parent.getVariable());
// adds edge from parent to node
addEdge(node, parent);
}
} while (value != ')');
// creates CPT
Function cpt = Function.createFunction(family);
// looks for '(' or words
do {
value = tokenizer.nextToken();
} while (value != '(' && value != StreamTokenizer.TT_WORD);
// checks next token: there are two formats, one with
// "table" and the other fills in cells one by one.
if (value == StreamTokenizer.TT_WORD) {
// we only accept "table" but not "default"
assert tokenizer.sval.equals("table");
// probability values
ArrayList<Double> values = new ArrayList<Double>();
// gets numerical tokens
do {
value = tokenizer.nextToken();
if (value == StreamTokenizer.TT_NUMBER) {
values.add(tokenizer.nval);
}
} while (value != ';');
// consistency between family and values will be tested
cpt.setCells(family, values);
} else {
// states array
ArrayList<Integer> states = new ArrayList<Integer>();
states.add(0);
int cardinality = node.getVariable().getCardinality();
// parses row by row
while (value != '}') {
// gets parent states
for (int i = 1; i < family.size(); i++) {
do {
value = tokenizer.nextToken();
} while (value != StreamTokenizer.TT_WORD);
states.add(family.get(i).indexOf(tokenizer.sval));
}
// fills in data
for (int i = 0; i < cardinality; i++) {
states.set(0, i);
do {
value = tokenizer.nextToken();
} while (value != StreamTokenizer.TT_NUMBER);
cpt.setCell(family, states, tokenizer.nval);
}
// looks for next '(' or '}'
while (value != '(' && value != '}') {
value = tokenizer.nextToken();
}
}
}
// normalizes the CPT with respect to the attached variable
cpt.normalize(node.getVariable());
// sets the CPT
node.setCpt(cpt);
}
}
} while (value != StreamTokenizer.TT_EOF);
}
/**
* Randomly sets the parameters of this BN. TODO avoid redundant operations
* on CPTs.
*/
public final void randomlyParameterize() {
for (AbstractNode node : _nodes) {
((DiscreteBeliefNode) node).randomlyParameterize();
}
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Randomly sets the parameters of the specified list of nodes in this BN.
* TODO avoid redundant operations on CPTs.
*
* @param mutableNodes
* list of nodes whose parameters are to be randomized.
*/
public final void randomlyParameterize(
Collection<DiscreteBeliefNode> mutableNodes) {
// mutable nodes must be in this BN
assert _nodes.containsAll(mutableNodes);
for (DiscreteBeliefNode node : mutableNodes) {
node.randomlyParameterize();
}
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Removes the specified edge from this BN. This implementation extends
* <code>AbstractGraph.removeEdge(Edge)</code> such that all loglikelihoods
* will be expired.
*
* @param edge
* edge to be removed from this BN.
*/
@Override
public final void removeEdge(Edge edge) {
super.removeEdge(edge);
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Removes the specified node from this BN. This implementation extends
* <code>AbstractGraph.removeNode(AbstractNode)</code> such that map from
* variables to nodes will be updated and all loglikelihoods will be
* expired.
*
* @param node
* node to be removed from this BN.
*/
public final void removeNode(AbstractNode node) {
super.removeNode(node);
_variables.remove(((BeliefNode) node).getVariable());
// loglikelihoods expire
expireLoglikelihoods();
}
/**
* Generates a batch of samples from this BN.
*
* @param sampleSize
* number of samples to be generated.
* @return a batch of samples from this BN.
*/
public DataSet sample(int sampleSize) {
// initialize data set
int nNodes = getNumberOfNodes();
DataSet samples =
new DataSet(getDiscreteVariables().toArray(
new DiscreteVariable[nNodes]));
// since variables are sorted in data set, find mapping from belief
// nodes to variables
DiscreteVariable[] vars = samples.getVariables();
HashMap<AbstractNode, Integer> map =
new HashMap<AbstractNode, Integer>();
for (AbstractNode node : getNodes()) {
DiscreteVariable var = ((DiscreteBeliefNode) node).getVariable();
int pos = Arrays.binarySearch(vars, var);
map.put(node, pos);
}
// topological sort
AbstractNode[] order = topologicalSort();
for (int i = 0; i < sampleSize; i++) {
int[] states = new int[nNodes];
// forward sampling
for (AbstractNode node : order) {
DiscreteBeliefNode bNode = (DiscreteBeliefNode) node;
// find parents and their states
ArrayList<DiscreteVariable> parents =
new ArrayList<DiscreteVariable>();
ArrayList<Integer> parentStates = new ArrayList<Integer>();
for (DirectedNode parent : bNode.getParents()) {
DiscreteVariable var =
((DiscreteBeliefNode) parent).getVariable();
parents.add(var);
int pos = map.get(parent);
parentStates.add(states[pos]);
}
// instantiate parents
Function cond =
bNode.potential().project(parents, parentStates);
// sample according to the conditional distribution
states[map.get(node)] = cond.sample();
}
// add to samples
samples.addDataCase(states, 1.0);
}
return samples;
}
/**
* Outputs this BN to the specified file in BIF format. See
* http://www.cs.cmu
* .edu/~fgcozman/Research/InterchangeFormat/Old/xmlbif02.html for the
* grammar of BIF format.
*
* @param file
* output of this BN.
* @throws FileNotFoundException
* if the file exists but is a directory rather than a regular
* file, does not exist but cannot be created, or cannot be
* opened for any other reason.
*/
public final void saveAsBif(String file) throws FileNotFoundException {
PrintWriter out = new PrintWriter(file);
// outputs header
out.println("// " + file);
out.println("// Produced by org.latlab at "
+ (new Date(System.currentTimeMillis())));
// outputs name
out.println("network \"" + _name + "\" {");
out.println("}");
out.println();
// outputs nodes
for (AbstractNode node : _nodes) {
DiscreteVariable variable =
((DiscreteBeliefNode) node).getVariable();
// name of variable
out.println("variable \"" + variable.getName() + "\" {");
// states of variable
out.print("\ttype discrete[" + variable.getCardinality() + "] { ");
Iterator<String> iter = variable.getStates().iterator();
while (iter.hasNext()) {
out.print("\"" + iter.next() + "\"");
if (iter.hasNext()) {
out.print(" ");
}
}
out.println(" };");
out.println("}");
out.println();
}
// Output CPTs
for (AbstractNode node : _nodes) {
DiscreteBeliefNode bNode = (DiscreteBeliefNode) node;
// variables in this family. note that the variables in the
// probability block are arranged from the most significant place to
// the least significant place.
ArrayList<DiscreteVariable> vars =
new ArrayList<DiscreteVariable>();
vars.add(bNode.getVariable());
// name of node
out.print("probability ( \"" + bNode.getName() + "\" ");
// names of parents
if (!bNode.isRoot()) {
out.print("| ");
}
Iterator<DirectedNode> iter = bNode.getParents().iterator();
while (iter.hasNext()) {
DiscreteBeliefNode parent = (DiscreteBeliefNode) iter.next();
out.print("\"" + parent.getName() + "\"");
if (iter.hasNext()) {
out.print(", ");
}
vars.add(parent.getVariable());
}
out.println(" ) {");
// cells in CPT
out.print("\ttable");
for (double cell : bNode.potential().getCells(vars)) {
out.print(" " + cell);
}
out.println(";");
out.println("}");
}
out.close();
}
/**
* Replaces the loglikelihood of this BN with respect to the specified data
* set.
*
* @param dataSet
* data set at request.
* @param loglikelihood
* new loglikelihood of this BN.
*/
public final void setLoglikelihood(DataSet dataSet, double loglikelihood) {
// loglikelihood must be non-positive
assert loglikelihood <= 0.0;
_loglikelihoods.put(dataSet, loglikelihood);
}
/**
* Replaces the name of this BN.
*
* @param name
* new name of this BN.
*/
public final void setName(String name) {
name = name.trim();
// name cannot be blank
assert name.length() > 0;
_name = name;
}
/**
* Returns a string representation of this BN. The string representation
* will be indented by the specified amount.
*
* @param amount
* amount by which the string representation is to be indented.
* @return a string representation of this BN.
*/
public String toString(int amount) {
// amount must be non-negative
assert amount >= 0;
// prepares white space for indent
StringBuffer whiteSpace = new StringBuffer();
for (int i = 0; i < amount; i++) {
whiteSpace.append('\t');
}
// builds string representation
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(whiteSpace);
stringBuffer.append(getName() + " {\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tnumber of nodes = " + getNumberOfNodes() + ";\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tnodes = {\n");
for (AbstractNode node : _nodes) {
stringBuffer.append(node.toString(amount + 2));
}
stringBuffer.append(whiteSpace);
stringBuffer.append("\t};\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tnumber of edges = " + getNumberOfEdges() + ";\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("\tedges = {\n");
for (Edge edge : _edges) {
stringBuffer.append(edge.toString(amount + 2));
}
stringBuffer.append(whiteSpace);
stringBuffer.append("\t};\n");
stringBuffer.append(whiteSpace);
stringBuffer.append("};\n");
return stringBuffer.toString();
}
/**
* Finds a variable by name. It supports only singular variable (continuous
* or discrete).
*
* @param name
* name of the variable
* @return variable with the given name, or {@code null} if not found
*/
public Variable findVariableByName(String name) {
return _variables.findVariableByName(name);
}
/**
* Finds a joint continuous variable by the name of one of its singular
* variable.
*
* @param singularVariableName
* name of the singular continuous variable
* @return joint variable containing the given singular variable
*/
public JointContinuousVariable findJointVariableByName(
String singularVariableName) {
SingularContinuousVariable variable =
(SingularContinuousVariable) _variables.findVariableByName(singularVariableName);
ContinuousBeliefNode node = getNode(variable);
return node != null ? node.getVariable() : null;
}
}
| 32,937 | 0.67045 | 0.669297 | 1,220 | 26.009016 | 23.591518 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.15082 | false | false | 10 |
76aa5c92d5201143dccb46f610bf7063b132805a | 1,434,519,102,598 | 7a329b4c4d2ea54e8ee145e2f48dca1ba72f3329 | /AdminPortal/AdminPortal/src/main/java/com/pervacio/adminportal/care/entities/DiagTestCompanyMap.java | 7b30a38fa270ae2ec890445c6f715c1d90cce288 | []
| no_license | kirtiMandwade/internalper | https://github.com/kirtiMandwade/internalper | 5fb62e55e19c971da7c92ede4b46ab4deb8ff302 | 3bd8940fa65d48bb6f066a07450974f83eba85b5 | refs/heads/master | 2021-09-05T05:22:55.599000 | 2018-01-24T11:02:02 | 2018-01-24T11:02:02 | 115,489,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pervacio.adminportal.care.entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.pervacio.adminportal.lookup.entities.LookUp;
@Entity
@Table(name = "diag_test_company_map")
public class DiagTestCompanyMap extends AuditBase implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "companyId", referencedColumnName = "companyId")
private ECompany company;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({ @JoinColumn(name = "productCdType", referencedColumnName = "lookUpType"),
@JoinColumn(name = "productCd", referencedColumnName = "lookUpValue") })
private LookUp productCd;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({ @JoinColumn(name = "severityCdType", referencedColumnName = "lookUpType"),
@JoinColumn(name = "severityCd", referencedColumnName = "lookUpValue") })
private LookUp severityCd;
public LookUp getSeverityCd() {
return severityCd;
}
public void setSeverityCd(LookUp severityCd) {
this.severityCd = severityCd;
}
@ManyToOne
@JoinColumn(name = "issueCd", referencedColumnName = "issueCd")
private DiagIssuesFlow diagIissuesFlow;
@ManyToMany(cascade = { CascadeType.ALL },fetch = FetchType.EAGER)
@JoinTable(
name = "diag_test_diag_test_company_map_rel",
joinColumns = { @JoinColumn(name = "id") },
inverseJoinColumns = { @JoinColumn(name = "testCd") }
)
private Set<DiagTest> diagTests = new HashSet<>();
/*
@ManyToOne
@JoinColumn(name = "testCd", referencedColumnName = "testCd")
private DiagTest diagTest;
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ECompany getCompany() {
return company;
}
public void setCompany(ECompany company) {
this.company = company;
}
public LookUp getProductCd() {
return productCd;
}
public void setProductCd(LookUp productCd) {
this.productCd = productCd;
}
public DiagIssuesFlow getDiagIissuesFlow() {
return diagIissuesFlow;
}
public void setDiagIissuesFlow(DiagIssuesFlow diagIissuesFlow) {
this.diagIissuesFlow = diagIissuesFlow;
}
public Set<DiagTest> getDiagTests() {
return diagTests;
}
public void setDiagTests(Set<DiagTest> diagTests) {
this.diagTests = diagTests;
}
} | UTF-8 | Java | 2,852 | java | DiagTestCompanyMap.java | Java | []
| null | []
| package com.pervacio.adminportal.care.entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.pervacio.adminportal.lookup.entities.LookUp;
@Entity
@Table(name = "diag_test_company_map")
public class DiagTestCompanyMap extends AuditBase implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "companyId", referencedColumnName = "companyId")
private ECompany company;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({ @JoinColumn(name = "productCdType", referencedColumnName = "lookUpType"),
@JoinColumn(name = "productCd", referencedColumnName = "lookUpValue") })
private LookUp productCd;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({ @JoinColumn(name = "severityCdType", referencedColumnName = "lookUpType"),
@JoinColumn(name = "severityCd", referencedColumnName = "lookUpValue") })
private LookUp severityCd;
public LookUp getSeverityCd() {
return severityCd;
}
public void setSeverityCd(LookUp severityCd) {
this.severityCd = severityCd;
}
@ManyToOne
@JoinColumn(name = "issueCd", referencedColumnName = "issueCd")
private DiagIssuesFlow diagIissuesFlow;
@ManyToMany(cascade = { CascadeType.ALL },fetch = FetchType.EAGER)
@JoinTable(
name = "diag_test_diag_test_company_map_rel",
joinColumns = { @JoinColumn(name = "id") },
inverseJoinColumns = { @JoinColumn(name = "testCd") }
)
private Set<DiagTest> diagTests = new HashSet<>();
/*
@ManyToOne
@JoinColumn(name = "testCd", referencedColumnName = "testCd")
private DiagTest diagTest;
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ECompany getCompany() {
return company;
}
public void setCompany(ECompany company) {
this.company = company;
}
public LookUp getProductCd() {
return productCd;
}
public void setProductCd(LookUp productCd) {
this.productCd = productCd;
}
public DiagIssuesFlow getDiagIissuesFlow() {
return diagIissuesFlow;
}
public void setDiagIissuesFlow(DiagIssuesFlow diagIissuesFlow) {
this.diagIissuesFlow = diagIissuesFlow;
}
public Set<DiagTest> getDiagTests() {
return diagTests;
}
public void setDiagTests(Set<DiagTest> diagTests) {
this.diagTests = diagTests;
}
} | 2,852 | 0.745442 | 0.745091 | 118 | 23.177965 | 23.444355 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.09322 | false | false | 10 |
fd7f35a3c2ed36b9262fcb94e16ce76f5845612c | 20,143,396,675,140 | 9f096e7871f2e008bef3a7fa107283e0375c1a3b | /src/main/java/cn/jienhui/next/utils/DeEnCode.java | bc045e433a5bbfe7e7438b5183c6e19a2a76aa24 | []
| no_license | enhui52125/next | https://github.com/enhui52125/next | 3b94edcd352ac8b77d1cf3e9b53f5bad180b554c | 513c782e9c4e54b7585246f97098a84bd39838a7 | refs/heads/master | 2018-02-14T12:35:41.095000 | 2016-12-13T14:26:42 | 2016-12-13T14:26:42 | 62,570,735 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.jienhui.next.utils;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
/**
* 简单Base64加密解密类
* @author ASUS
*
*/
public class DeEnCode {
/**
* 编码
* @param str
* @return
*/
public static String encodeBase64(String str){
String result = null;
try {
result = new String(Base64.encodeBase64(str.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 解码
* @param cookieStr
* @return
*/
public static String decodeBase64(String str){
String result = null;
try {
result = new String(Base64.decodeBase64(str.getBytes()), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}
| UTF-8 | Java | 952 | java | DeEnCode.java | Java | [
{
"context": "dec.binary.Base64;\n/**\n * 简单Base64加密解密类\n * @author ASUS\n *\n */\npublic class DeEnCode {\n\t/** \n * 编码 \n ",
"end": 160,
"score": 0.9992274641990662,
"start": 156,
"tag": "USERNAME",
"value": "ASUS"
}
]
| null | []
| package cn.jienhui.next.utils;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
/**
* 简单Base64加密解密类
* @author ASUS
*
*/
public class DeEnCode {
/**
* 编码
* @param str
* @return
*/
public static String encodeBase64(String str){
String result = null;
try {
result = new String(Base64.encodeBase64(str.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 解码
* @param cookieStr
* @return
*/
public static String decodeBase64(String str){
String result = null;
try {
result = new String(Base64.decodeBase64(str.getBytes()), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}
| 952 | 0.55914 | 0.539785 | 40 | 22.25 | 19.413591 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 14 |
9cb28a5ddc430d8d8df20a8911c77a98a6e2befd | 33,079,838,170,405 | 7bc7addbcabba2393c3f7b0eb2bbd0787ce56607 | /videoPlaylib/src/main/java/com/ydl/videoplaylib/inter/listener/OnVideoBackListener.java | 6503e7fe5deafa1a88c34516c291391df443f615 | []
| no_license | huydl1104/videoPlayer | https://github.com/huydl1104/videoPlayer | e8359b5a6aa52f01aa67371ccc5c9f152832b8fa | 7889bdacee1efd84b32029b36dc6263dcd1ef411 | refs/heads/master | 2022-12-13T19:38:28.020000 | 2020-09-14T14:05:46 | 2020-09-14T14:05:46 | 295,431,104 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ydl.videoplaylib.inter.listener;
/**
* 返回点击事件抽象接口
*/
public interface OnVideoBackListener {
void onBackClick();
}
| UTF-8 | Java | 157 | java | OnVideoBackListener.java | Java | []
| null | []
|
package com.ydl.videoplaylib.inter.listener;
/**
* 返回点击事件抽象接口
*/
public interface OnVideoBackListener {
void onBackClick();
}
| 157 | 0.708029 | 0.708029 | 11 | 11.363636 | 15.598792 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 14 |
b8e3a4573658ad0b7e8b7eaeb1816defd3631e7b | 3,539,053,116,666 | 53a4700ad022d87a5577e68fcdf6bc6ca2ace903 | /src/main/java/com/morelllcrm/entities/AuditTrail.java | 8a6f3019dfd2746e1d857d6037596a82aa68ac4f | []
| no_license | huzaim-umer/gitrepo | https://github.com/huzaim-umer/gitrepo | 472bd27a95746c324866b6e38288b4266d3b80fe | e90660b007b60525d09827cd1be764b22cf03f0c | refs/heads/master | 2023-07-13T22:06:05.890000 | 2021-08-23T17:34:17 | 2021-08-23T17:34:17 | 399,191,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.morelllcrm.entities;
import javax.persistence.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "iam_audit_trail")
public class AuditTrail {
@Id
@GeneratedValue
@Column(name = "guid")
private UUID guid;
@Column(name = "login_timestamp",nullable = false)
private LocalDateTime loginTimeStamp;
@Column(name = "logout_timestamp")
private LocalDateTime logoutTimeStamp;
@Column(name = "is_session_active",nullable = false)
private Boolean isSessionActive;
@Column(name = "reason")
private String reason;
public UUID getGuid() {
return guid;
}
public void setGuid(UUID guid) {
this.guid = guid;
}
public LocalDateTime getLoginTimeStamp() {
return loginTimeStamp;
}
public void setLoginTimeStamp(LocalDateTime loginTimeStamp) {
this.loginTimeStamp = loginTimeStamp;
}
public LocalDateTime getLogoutTimeStamp() {
return logoutTimeStamp;
}
public void setLogoutTimeStamp(LocalDateTime logoutTimeStamp) {
this.logoutTimeStamp = logoutTimeStamp;
}
public Boolean getSessionActive() {
return isSessionActive;
}
public void setSessionActive(Boolean sessionActive) {
isSessionActive = sessionActive;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
| UTF-8 | Java | 1,492 | java | AuditTrail.java | Java | []
| null | []
| package com.morelllcrm.entities;
import javax.persistence.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "iam_audit_trail")
public class AuditTrail {
@Id
@GeneratedValue
@Column(name = "guid")
private UUID guid;
@Column(name = "login_timestamp",nullable = false)
private LocalDateTime loginTimeStamp;
@Column(name = "logout_timestamp")
private LocalDateTime logoutTimeStamp;
@Column(name = "is_session_active",nullable = false)
private Boolean isSessionActive;
@Column(name = "reason")
private String reason;
public UUID getGuid() {
return guid;
}
public void setGuid(UUID guid) {
this.guid = guid;
}
public LocalDateTime getLoginTimeStamp() {
return loginTimeStamp;
}
public void setLoginTimeStamp(LocalDateTime loginTimeStamp) {
this.loginTimeStamp = loginTimeStamp;
}
public LocalDateTime getLogoutTimeStamp() {
return logoutTimeStamp;
}
public void setLogoutTimeStamp(LocalDateTime logoutTimeStamp) {
this.logoutTimeStamp = logoutTimeStamp;
}
public Boolean getSessionActive() {
return isSessionActive;
}
public void setSessionActive(Boolean sessionActive) {
isSessionActive = sessionActive;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
| 1,492 | 0.671582 | 0.671582 | 67 | 21.268656 | 19.062805 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.328358 | false | false | 14 |
151e52e9456569728c161b050afc4d05a6b4d225 | 17,025,250,427,955 | a5af29b8df1d7143a7782d7dd842966cb80a060c | /src/net/dreamingworld/gameplay/manacraft/researches/irontree/IronTreeResearch.java | 5dbe2cc4e31e3d963514c80108cda617ffc8e94d | [
"CC0-1.0"
]
| permissive | DreamingWorldMC/DreamingWorld-old | https://github.com/DreamingWorldMC/DreamingWorld-old | 4738124375097ff796ce15d2a2f2d97b1fe4aa1d | 42914204be59ee19c6d5e171f36d5e93ddf08e12 | refs/heads/master | 2023-04-27T14:06:19.046000 | 2021-05-16T16:04:15 | 2021-05-16T16:04:15 | 309,083,040 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.dreamingworld.gameplay.manacraft.researches.irontree;
import net.dreamingworld.DreamingWorld;
import net.dreamingworld.core.research.Research;
import net.dreamingworld.gameplay.manacraft.researches.manainfusion.ManaInfuser;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.HashMap;
public class IronTreeResearch extends Research {
public IronTreeResearch() {
id = "iron_tree";
name = "Iron tree";
description = "Iron trees and green iron";
items = new HashMap<>();
items.put("Something magical found in ore", "manium");
items.put("hot stones liquid ice on them", Material.OBSIDIAN.toString());
items.put("____ Tree", Material.IRON_INGOT.toString());
book = (BookMeta)(new ItemStack(Material.WRITTEN_BOOK).getItemMeta());
book.addPage( "Making your own tree sapplings maybe out of iron but still this is useful, maybe you could get some special iron out of this");
book.addPage( "Drop any part of an iron tree on green iron maker to make green iron.");
DreamingWorld.getInstance().getResearchManager().addParent("iron_tree", "plants_and_creatures");
DreamingWorld.getInstance().getBlockManager().registerBlock(new IronTreeSapling());
DreamingWorld.getInstance().getBlockManager().registerBlock(new IronLeafBlock());
DreamingWorld.getInstance().getBlockManager().registerBlock(new IronWoodBlock());
DreamingWorld.getInstance().getBlockManager().registerBlock(new GreenIronMaker());
new GreenIron();
new GreenIronArmor();
DreamingWorld.getInstance().getStructureManager().registerStructure("iron_tree", new IronTree());
}
}
| UTF-8 | Java | 1,774 | java | IronTreeResearch.java | Java | []
| null | []
| package net.dreamingworld.gameplay.manacraft.researches.irontree;
import net.dreamingworld.DreamingWorld;
import net.dreamingworld.core.research.Research;
import net.dreamingworld.gameplay.manacraft.researches.manainfusion.ManaInfuser;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.HashMap;
public class IronTreeResearch extends Research {
public IronTreeResearch() {
id = "iron_tree";
name = "Iron tree";
description = "Iron trees and green iron";
items = new HashMap<>();
items.put("Something magical found in ore", "manium");
items.put("hot stones liquid ice on them", Material.OBSIDIAN.toString());
items.put("____ Tree", Material.IRON_INGOT.toString());
book = (BookMeta)(new ItemStack(Material.WRITTEN_BOOK).getItemMeta());
book.addPage( "Making your own tree sapplings maybe out of iron but still this is useful, maybe you could get some special iron out of this");
book.addPage( "Drop any part of an iron tree on green iron maker to make green iron.");
DreamingWorld.getInstance().getResearchManager().addParent("iron_tree", "plants_and_creatures");
DreamingWorld.getInstance().getBlockManager().registerBlock(new IronTreeSapling());
DreamingWorld.getInstance().getBlockManager().registerBlock(new IronLeafBlock());
DreamingWorld.getInstance().getBlockManager().registerBlock(new IronWoodBlock());
DreamingWorld.getInstance().getBlockManager().registerBlock(new GreenIronMaker());
new GreenIron();
new GreenIronArmor();
DreamingWorld.getInstance().getStructureManager().registerStructure("iron_tree", new IronTree());
}
}
| 1,774 | 0.719278 | 0.719278 | 41 | 42.268291 | 38.696457 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.780488 | false | false | 14 |
7f826a4a08625049c6b3e597a241f68fe220b71c | 395,137,031,664 | d9941fd8d0d6eb02491114a1d6e3a9bd8a035e0e | /app/src/main/java/com/chatapp/synchat/app/calls/CallAck.java | b20b308eaaf3abbcef5f8f22ee78f4aceb4f73e3 | []
| no_license | AdhashGopal/Syncchat-MessagingApp | https://github.com/AdhashGopal/Syncchat-MessagingApp | 129e7f6e903ef1101241c98731e8ff1aece0da86 | 964f5d242927182ba905bb9583e51171a0efcc94 | refs/heads/master | 2022-12-27T16:59:49.241000 | 2020-09-17T07:23:36 | 2020-09-17T07:23:36 | 296,345,691 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chatapp.synchat.app.calls;
import android.content.Context;
import com.chatapp.synchat.core.message.BaseMessage;
import com.chatapp.synchat.core.message.Message;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
/**
*
*/
public class CallAck extends BaseMessage implements Message {
public CallAck(Context context) {
super(context);
}
/***
* get Message Object for call state
* @param to to user
* @param doc_id get docid
* @param isSecretchat check secret chat or not
* @return value
*/
@Override
public Object getMessageObject(String to, String doc_id, Boolean isSecretchat) {
this.to = to;
setId(from + "-" + to);
JSONObject object = new JSONObject();
try {
object.put("from", from);
object.put("to", to);
object.put("msgIds", new JSONArray(Arrays.asList(new String[]{id})));
object.put("doc_id", doc_id);
object.put("status", "3");
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
@Override
public Object getGroupMessageObject(String to, String payload, String groupName) {
return null;
}
/**
* get Message Object for call state
*
* @param to to user
* @param doc_id get docid
* @param status put status
* @param _id message id
* @return value
*/
public Object getMessageObject(String to, String doc_id, String status, String _id) {
this.to = to;
setId(from + "-" + to);
JSONObject object = new JSONObject();
try {
object.put("from", from);
object.put("to", to);
object.put("msgIds", new JSONArray(Arrays.asList(new String[]{_id})));
object.put("doc_id", doc_id);
object.put("status", status);
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
}
| UTF-8 | Java | 2,070 | java | CallAck.java | Java | []
| null | []
| package com.chatapp.synchat.app.calls;
import android.content.Context;
import com.chatapp.synchat.core.message.BaseMessage;
import com.chatapp.synchat.core.message.Message;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
/**
*
*/
public class CallAck extends BaseMessage implements Message {
public CallAck(Context context) {
super(context);
}
/***
* get Message Object for call state
* @param to to user
* @param doc_id get docid
* @param isSecretchat check secret chat or not
* @return value
*/
@Override
public Object getMessageObject(String to, String doc_id, Boolean isSecretchat) {
this.to = to;
setId(from + "-" + to);
JSONObject object = new JSONObject();
try {
object.put("from", from);
object.put("to", to);
object.put("msgIds", new JSONArray(Arrays.asList(new String[]{id})));
object.put("doc_id", doc_id);
object.put("status", "3");
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
@Override
public Object getGroupMessageObject(String to, String payload, String groupName) {
return null;
}
/**
* get Message Object for call state
*
* @param to to user
* @param doc_id get docid
* @param status put status
* @param _id message id
* @return value
*/
public Object getMessageObject(String to, String doc_id, String status, String _id) {
this.to = to;
setId(from + "-" + to);
JSONObject object = new JSONObject();
try {
object.put("from", from);
object.put("to", to);
object.put("msgIds", new JSONArray(Arrays.asList(new String[]{_id})));
object.put("doc_id", doc_id);
object.put("status", status);
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
}
| 2,070 | 0.57971 | 0.579227 | 79 | 25.202532 | 22.04907 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594937 | false | false | 14 |
7b00069e0de9ba765fad511e27b12d4fcccd8862 | 32,684,701,142,835 | 7154a7af63a60abb78470450d3a225eac46458be | /app/src/main/java/example/codeclan/com/wordcounter/WordCounterActivity.java | 46aba5e7dce222cec000b0aaf6342f2e69019934 | []
| no_license | Justafigurehead/WordCounter_Lab_HW | https://github.com/Justafigurehead/WordCounter_Lab_HW | e486b1881e9edb413275a7ab4b32b6dba4c4fd92 | 02b552b0ed82ddcf7e430fb613f11115cddff9ed | refs/heads/master | 2021-01-21T08:02:00.001000 | 2017-02-28T08:50:31 | 2017-02-28T08:50:31 | 83,330,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package example.codeclan.com.wordcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class WordCounterActivity extends AppCompatActivity {
EditText editTextBox;
Button countButton;
TextView textViewBox;
WordCounter wordsToCount;
String input;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_counter);
editTextBox = (EditText) findViewById(R.id.EditText_box);
countButton = (Button) findViewById(R.id.CountWord_btn);
textViewBox = (TextView) findViewById(R.id.textView);
}
public void countWhenClick(View Button){
input = editTextBox.getText().toString();
wordsToCount = new WordCounter(input);
int wordCounts = wordsToCount.getStringCount();
// String wordCount = Integer.toString(wordCounts);
textViewBox.setText(Integer.toString(wordCounts));
// int wordCount = wordsToCount.getWordOccur();
// textViewBox.setText(wordsToCount.getWordOccur());
Log.d("Button clicked",input);
}
}
| UTF-8 | Java | 1,302 | java | WordCounterActivity.java | Java | []
| null | []
| package example.codeclan.com.wordcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class WordCounterActivity extends AppCompatActivity {
EditText editTextBox;
Button countButton;
TextView textViewBox;
WordCounter wordsToCount;
String input;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_counter);
editTextBox = (EditText) findViewById(R.id.EditText_box);
countButton = (Button) findViewById(R.id.CountWord_btn);
textViewBox = (TextView) findViewById(R.id.textView);
}
public void countWhenClick(View Button){
input = editTextBox.getText().toString();
wordsToCount = new WordCounter(input);
int wordCounts = wordsToCount.getStringCount();
// String wordCount = Integer.toString(wordCounts);
textViewBox.setText(Integer.toString(wordCounts));
// int wordCount = wordsToCount.getWordOccur();
// textViewBox.setText(wordsToCount.getWordOccur());
Log.d("Button clicked",input);
}
}
| 1,302 | 0.718126 | 0.717358 | 40 | 31.549999 | 22.127979 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.675 | false | false | 14 |
1be70bd14d9aadf54f2791218ebf8a6d257d7af4 | 1,065,151,949,643 | db16fee6cffe5e9cb90f40da459e43e5602b29cd | /Add Digits.java | dc2859cdf96c5f1af88bf9d27d888f8774b17840 | []
| no_license | huijunwu/leetcode.java | https://github.com/huijunwu/leetcode.java | f427d5a2911881fcb1238958dc39c748ba901daf | dcd54ecc3b495b3e1c1a4fc1e75565a32bfcfd80 | refs/heads/master | 2020-12-24T06:54:13.194000 | 2016-01-16T17:31:02 | 2016-01-16T17:31:02 | 12,512,294 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Solution {
public int addDigits(int num) {
while (num > 9) {
num = String.valueOf(num).chars().map(x -> x - '0').reduce((x, y) -> x + y).getAsInt();
}
return num;
}
}
| UTF-8 | Java | 202 | java | Add Digits.java | Java | []
| null | []
| public class Solution {
public int addDigits(int num) {
while (num > 9) {
num = String.valueOf(num).chars().map(x -> x - '0').reduce((x, y) -> x + y).getAsInt();
}
return num;
}
}
| 202 | 0.539604 | 0.529703 | 8 | 24.25 | 27.98102 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 14 |
9824fd3c2d07f582e9b54047aec7ec3051698d9e | 6,390,911,358,047 | b533f62ed5ab14aa3ad754ac06f6236f518ab057 | /src/Game.java | 72e7e84d7dde684f7b44cc7af464101247483b41 | []
| no_license | dsspasov/CodeMinotaurs | https://github.com/dsspasov/CodeMinotaurs | 765c8a01fffc763c1a0164e6b152fe1ee641bf27 | 6bcb4e886f7913c06a5557e10c2568c12c159d05 | refs/heads/master | 2021-01-10T12:22:10.848000 | 2015-07-11T09:19:53 | 2015-07-11T09:19:53 | 36,287,021 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.FileNotFoundException;
import java.util.Random;
import javax.swing.JButton;
public class Game extends JFrame {
/**
*
*/
private static final long serialVersionUID = 4503868451640434191L;
private JPanel contentPane;
private JSONReader x;
private String path = "C:/Users/Simo/Desktop/questions.json";
private static JLabel labelPlayer;
private JRadioButton rdbtnA, rdbtnB, rdbtnC, rdbtnD;
private JButton btnNextQuestion;
private Icon checkIcon = new ImageIcon("C:/Users/Simo/Desktop/pics/kk.png");
private Icon crossIcon = new ImageIcon("C:/Users/Simo/Desktop/pics/cross.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game frame = new Game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
int numberOfQuestions;
public int getLength() {
x = new JSONReader(path);
x.read();
numberOfQuestions = x.read().size();
return numberOfQuestions;
}
public void disableAll() {
rdbtnA.setEnabled(false);
rdbtnB.setEnabled(false);
rdbtnC.setEnabled(false);
rdbtnD.setEnabled(false);
}
Random rand = new Random();
int questionIndex = (int) rand.nextInt(getLength());
int killingSpree = 0;
public JButton getNextQuestionButton() {
return btnNextQuestion;
}
public Game() {
DrawingLogic.drawInitialLabirinth();
setTitle("Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel labelA = new JLabel("");
labelA.setBounds(49, 382, 16, 14);
contentPane.add(labelA);
JLabel labelC = new JLabel("");
labelC.setBounds(49, 437, 16, 14);
contentPane.add(labelC);
JLabel labelB = new JLabel("");
labelB.setBounds(49, 407, 16, 14);
contentPane.add(labelB);
JLabel labelD = new JLabel("");
labelD.setBounds(49, 462, 16, 14);
contentPane.add(labelD);
JLabel labelScore = new JLabel("0");
labelScore.setBounds(413, 348, 91, 14);
contentPane.add(labelScore);
JLabel labelQuestion = new JLabel(x.read().get(questionIndex).getQuestion().toString());
labelQuestion.setBounds(10, 178, 730, 107);
contentPane.add(labelQuestion);
rdbtnA = new JRadioButton(x.read().get(questionIndex).getAnswers().get(0));
rdbtnA.setBounds(71, 376, 565, 23);
rdbtnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnA.isSelected() == true) {
if (rdbtnA.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelA.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelA.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnA);
rdbtnB = new JRadioButton(x.read().get(questionIndex).getAnswers().get(1));
rdbtnB.setBounds(71, 402, 565, 23);
rdbtnB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnB.isSelected() == true) {
if (rdbtnB.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelB.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelB.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnB);
rdbtnC = new JRadioButton(x.read().get(questionIndex).getAnswers().get(2));
rdbtnC.setBounds(71, 428, 565, 23);
labelC.setIcon(null);
rdbtnC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnC.isSelected() == true) {
if (rdbtnC.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelC.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelC.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnC);
rdbtnD = new JRadioButton(x.read().get(questionIndex).getAnswers().get(3));
rdbtnD.setBounds(71, 454, 565, 23);
rdbtnD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnD.isSelected() == true) {
if (rdbtnD.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelD.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelD.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnD);
labelPlayer = new JLabel("New label");
labelPlayer.setBounds(71, 348, 230, 14);
contentPane.add(labelPlayer);
btnNextQuestion = new JButton("Next question");
btnNextQuestion.setBounds(514, 507, 125, 23);
btnNextQuestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
questionIndex = rand.nextInt(getLength());
labelQuestion.setText(x.read().get(questionIndex).getQuestion().toString());
rdbtnA.setText(x.read().get(questionIndex).getAnswers().get(0).toString());
rdbtnB.setText(x.read().get(questionIndex).getAnswers().get(1).toString());
rdbtnC.setText(x.read().get(questionIndex).getAnswers().get(2).toString());
rdbtnD.setText(x.read().get(questionIndex).getAnswers().get(3).toString());
labelA.setIcon(null);
labelB.setIcon(null);
labelC.setIcon(null);
labelD.setIcon(null);
rdbtnA.setEnabled(true);
rdbtnA.setSelected(false);
rdbtnB.setEnabled(true);
rdbtnB.setSelected(false);
rdbtnC.setEnabled(true);
rdbtnC.setSelected(false);
rdbtnD.setEnabled(true);
rdbtnD.setSelected(false);
DrawingLogic.closeLabirinthFrame();
btnNextQuestion.setVisible(false);
}
});
contentPane.add(btnNextQuestion);
}
public static JLabel getPlayer() {
return labelPlayer;
}
} | UTF-8 | Java | 11,260 | java | Game.java | Java | []
| null | []
| import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.FileNotFoundException;
import java.util.Random;
import javax.swing.JButton;
public class Game extends JFrame {
/**
*
*/
private static final long serialVersionUID = 4503868451640434191L;
private JPanel contentPane;
private JSONReader x;
private String path = "C:/Users/Simo/Desktop/questions.json";
private static JLabel labelPlayer;
private JRadioButton rdbtnA, rdbtnB, rdbtnC, rdbtnD;
private JButton btnNextQuestion;
private Icon checkIcon = new ImageIcon("C:/Users/Simo/Desktop/pics/kk.png");
private Icon crossIcon = new ImageIcon("C:/Users/Simo/Desktop/pics/cross.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game frame = new Game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
int numberOfQuestions;
public int getLength() {
x = new JSONReader(path);
x.read();
numberOfQuestions = x.read().size();
return numberOfQuestions;
}
public void disableAll() {
rdbtnA.setEnabled(false);
rdbtnB.setEnabled(false);
rdbtnC.setEnabled(false);
rdbtnD.setEnabled(false);
}
Random rand = new Random();
int questionIndex = (int) rand.nextInt(getLength());
int killingSpree = 0;
public JButton getNextQuestionButton() {
return btnNextQuestion;
}
public Game() {
DrawingLogic.drawInitialLabirinth();
setTitle("Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel labelA = new JLabel("");
labelA.setBounds(49, 382, 16, 14);
contentPane.add(labelA);
JLabel labelC = new JLabel("");
labelC.setBounds(49, 437, 16, 14);
contentPane.add(labelC);
JLabel labelB = new JLabel("");
labelB.setBounds(49, 407, 16, 14);
contentPane.add(labelB);
JLabel labelD = new JLabel("");
labelD.setBounds(49, 462, 16, 14);
contentPane.add(labelD);
JLabel labelScore = new JLabel("0");
labelScore.setBounds(413, 348, 91, 14);
contentPane.add(labelScore);
JLabel labelQuestion = new JLabel(x.read().get(questionIndex).getQuestion().toString());
labelQuestion.setBounds(10, 178, 730, 107);
contentPane.add(labelQuestion);
rdbtnA = new JRadioButton(x.read().get(questionIndex).getAnswers().get(0));
rdbtnA.setBounds(71, 376, 565, 23);
rdbtnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnA.isSelected() == true) {
if (rdbtnA.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelA.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelA.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnA);
rdbtnB = new JRadioButton(x.read().get(questionIndex).getAnswers().get(1));
rdbtnB.setBounds(71, 402, 565, 23);
rdbtnB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnB.isSelected() == true) {
if (rdbtnB.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelB.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelB.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnB);
rdbtnC = new JRadioButton(x.read().get(questionIndex).getAnswers().get(2));
rdbtnC.setBounds(71, 428, 565, 23);
labelC.setIcon(null);
rdbtnC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnC.isSelected() == true) {
if (rdbtnC.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelC.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelC.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnC);
rdbtnD = new JRadioButton(x.read().get(questionIndex).getAnswers().get(3));
rdbtnD.setBounds(71, 454, 565, 23);
rdbtnD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rdbtnD.isSelected() == true) {
if (rdbtnD.getText()
.equals(x.read().get(questionIndex).getCorrectAnswer().toString())) {
disableAll();
labelD.setIcon(checkIcon);
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
killingSpree++;
if (killingSpree == 3) {
try {
Audio.playThatTrack();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
labelScore.setText(String.valueOf(Integer.parseInt(labelScore.getText()) + 300));
btnNextQuestion.setVisible(true);
} else {
killingSpree = 0;
disableAll();
DrawingLogic.closeLabirinthFrame();
DrawingLogic.drawInitialLabirinth();
labelD.setIcon(crossIcon);
btnNextQuestion.setVisible(true);
}
}
}
});
contentPane.add(rdbtnD);
labelPlayer = new JLabel("New label");
labelPlayer.setBounds(71, 348, 230, 14);
contentPane.add(labelPlayer);
btnNextQuestion = new JButton("Next question");
btnNextQuestion.setBounds(514, 507, 125, 23);
btnNextQuestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
questionIndex = rand.nextInt(getLength());
labelQuestion.setText(x.read().get(questionIndex).getQuestion().toString());
rdbtnA.setText(x.read().get(questionIndex).getAnswers().get(0).toString());
rdbtnB.setText(x.read().get(questionIndex).getAnswers().get(1).toString());
rdbtnC.setText(x.read().get(questionIndex).getAnswers().get(2).toString());
rdbtnD.setText(x.read().get(questionIndex).getAnswers().get(3).toString());
labelA.setIcon(null);
labelB.setIcon(null);
labelC.setIcon(null);
labelD.setIcon(null);
rdbtnA.setEnabled(true);
rdbtnA.setSelected(false);
rdbtnB.setEnabled(true);
rdbtnB.setSelected(false);
rdbtnC.setEnabled(true);
rdbtnC.setSelected(false);
rdbtnD.setEnabled(true);
rdbtnD.setSelected(false);
DrawingLogic.closeLabirinthFrame();
btnNextQuestion.setVisible(false);
}
});
contentPane.add(btnNextQuestion);
}
public static JLabel getPlayer() {
return labelPlayer;
}
} | 11,260 | 0.500888 | 0.483925 | 299 | 36.662209 | 24.337982 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719064 | false | false | 14 |
4bb50c0366962813129d85d6bb69af592e86247c | 27,169,963,157,805 | f2176ee4bd618a0265fbc6920f76e0e983fa2b56 | /code/MImusic/src/vnp/com/mimusic/view/MoiDvChoNhieuNguoiItemView.java | 029ae8bb6e338f5bff1f233b3c28ca248406682e | []
| no_license | fordream/viet-t-a-thang | https://github.com/fordream/viet-t-a-thang | 350790102055e8e7a3fc69513c5f772be6a47b06 | e5cc7521fc4f9fbe77bf047ee96248c902c1f624 | refs/heads/master | 2021-01-21T08:01:24.646000 | 2015-05-12T21:21:25 | 2015-05-12T21:21:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vnp.com.mimusic.view;
import vnp.com.db.VasContact;
import vnp.com.mimusic.util.Conts;
import android.content.Context;
import android.database.Cursor;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.viettel.vtt.vdealer.R;
public class MoiDvChoNhieuNguoiItemView extends LinearLayout {
public MoiDvChoNhieuNguoiItemView(Context context) {
super(context);
init();
}
public MoiDvChoNhieuNguoiItemView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.moidvchonhieunguoi_item, this);
}
public void initData(Cursor cursor, String textSearch, String service_code) {
String name = "";
if (cursor.getString(cursor.getColumnIndex(VasContact.NAME)) != null) {
name = cursor.getString(cursor.getColumnIndex(VasContact.NAME));
}
if (cursor.getString(cursor.getColumnIndex(VasContact.NAME_CONTACT)) != null) {
if (name == null || name != null && name.trim().equals("")) {
name = cursor.getString(cursor.getColumnIndex(VasContact.NAME_CONTACT));
}
}
if (name == null || name != null && name.trim().equals("")) {
name = cursor.getString(cursor.getColumnIndex(VasContact.PHONE));
}
if (name == null)
name = "";
View main = findViewById(R.id.menurightitem_main);
main.setVisibility(Conts.xDontains(textSearch, false, new String[] { name }) ? View.VISIBLE : View.GONE);
boolean needShow = Conts.xDontains(textSearch, true, new String[] { name, Conts.getStringCursor(cursor, VasContact.PHONE) });
main.setVisibility(needShow ? View.VISIBLE : View.GONE);
((TextView) findViewById(R.id.menu_right_item_tv_name)).setText(name);
String avatar = cursor.getString(cursor.getColumnIndex(VasContact.AVATAR));
String contact_id = Conts.getStringCursor(cursor, VasContact.contact_id);
Conts.showAvatarContact(((ImageView) findViewById(R.id.menu_right_item_img_icon)), avatar, contact_id, Conts.resavatar()[cursor.getPosition() % Conts.resavatar().length]);
Conts.setTextViewCursor(findViewById(R.id.menu_right_item_tv_link), cursor, VasContact.PHONE);
Conts.getSDT(findViewById(R.id.menu_right_item_tv_link));
Conts.getSDT(findViewById(R.id.menu_right_item_tv_name));
findViewById(R.id.menu_right_item_tv_link).setVisibility(View.VISIBLE);
}
public void initData(String name) {
((TextView) findViewById(R.id.menu_right_item_tv_name)).setText(name);
((ImageView) findViewById(R.id.menu_right_item_img_icon)).setVisibility(View.GONE);
CheckBox menu_right_detail_checkbox = (CheckBox) findViewById(R.id.menu_right_detail_checkbox);
menu_right_detail_checkbox.setOnCheckedChangeListener(null);
menu_right_detail_checkbox.setVisibility(View.GONE);
}
public void updateBackground(int position) {
findViewById(R.id.menurightitem_main).setBackgroundColor(getContext().getResources().getColor(position % 2 == 0 ? R.color.f6f6f6 : R.color.ffffff));
}
} | UTF-8 | Java | 3,248 | java | MoiDvChoNhieuNguoiItemView.java | Java | []
| null | []
| package vnp.com.mimusic.view;
import vnp.com.db.VasContact;
import vnp.com.mimusic.util.Conts;
import android.content.Context;
import android.database.Cursor;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.viettel.vtt.vdealer.R;
public class MoiDvChoNhieuNguoiItemView extends LinearLayout {
public MoiDvChoNhieuNguoiItemView(Context context) {
super(context);
init();
}
public MoiDvChoNhieuNguoiItemView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.moidvchonhieunguoi_item, this);
}
public void initData(Cursor cursor, String textSearch, String service_code) {
String name = "";
if (cursor.getString(cursor.getColumnIndex(VasContact.NAME)) != null) {
name = cursor.getString(cursor.getColumnIndex(VasContact.NAME));
}
if (cursor.getString(cursor.getColumnIndex(VasContact.NAME_CONTACT)) != null) {
if (name == null || name != null && name.trim().equals("")) {
name = cursor.getString(cursor.getColumnIndex(VasContact.NAME_CONTACT));
}
}
if (name == null || name != null && name.trim().equals("")) {
name = cursor.getString(cursor.getColumnIndex(VasContact.PHONE));
}
if (name == null)
name = "";
View main = findViewById(R.id.menurightitem_main);
main.setVisibility(Conts.xDontains(textSearch, false, new String[] { name }) ? View.VISIBLE : View.GONE);
boolean needShow = Conts.xDontains(textSearch, true, new String[] { name, Conts.getStringCursor(cursor, VasContact.PHONE) });
main.setVisibility(needShow ? View.VISIBLE : View.GONE);
((TextView) findViewById(R.id.menu_right_item_tv_name)).setText(name);
String avatar = cursor.getString(cursor.getColumnIndex(VasContact.AVATAR));
String contact_id = Conts.getStringCursor(cursor, VasContact.contact_id);
Conts.showAvatarContact(((ImageView) findViewById(R.id.menu_right_item_img_icon)), avatar, contact_id, Conts.resavatar()[cursor.getPosition() % Conts.resavatar().length]);
Conts.setTextViewCursor(findViewById(R.id.menu_right_item_tv_link), cursor, VasContact.PHONE);
Conts.getSDT(findViewById(R.id.menu_right_item_tv_link));
Conts.getSDT(findViewById(R.id.menu_right_item_tv_name));
findViewById(R.id.menu_right_item_tv_link).setVisibility(View.VISIBLE);
}
public void initData(String name) {
((TextView) findViewById(R.id.menu_right_item_tv_name)).setText(name);
((ImageView) findViewById(R.id.menu_right_item_img_icon)).setVisibility(View.GONE);
CheckBox menu_right_detail_checkbox = (CheckBox) findViewById(R.id.menu_right_detail_checkbox);
menu_right_detail_checkbox.setOnCheckedChangeListener(null);
menu_right_detail_checkbox.setVisibility(View.GONE);
}
public void updateBackground(int position) {
findViewById(R.id.menurightitem_main).setBackgroundColor(getContext().getResources().getColor(position % 2 == 0 ? R.color.f6f6f6 : R.color.ffffff));
}
} | 3,248 | 0.730911 | 0.729372 | 82 | 37.634148 | 39.174877 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.890244 | false | false | 14 |
5b09ad6cab9847ea9899d67af52190b7efe8b19a | 28,784,870,854,056 | f63db780fdeec6ec326f824733ae0899f54be801 | /app/src/main/java/com/mifind/shiyinote/model/ShiyiPoem.java | 3bc2d86382fe19c83abeed50afb1391c2fc89b2a | []
| no_license | MIFind/ShiYiNote | https://github.com/MIFind/ShiYiNote | 6fe783672741e8ca632f372069c2d343afedd718 | 7effd2768fcf399fdecd84ce164cfa85e0497410 | refs/heads/master | 2017-10-02T16:51:04.579000 | 2017-02-27T10:18:11 | 2017-02-27T10:18:11 | 82,894,695 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mifind.shiyinote.model;
import com.litesuits.orm.db.annotation.PrimaryKey;
import com.litesuits.orm.db.annotation.Table;
import com.litesuits.orm.db.enums.AssignType;
/**
* Created by wei on 2017/2/23.
*/
@Table("shi_yi_poem")
public class ShiyiPoem {
// 指定自增,每个对象需要有一个主键
@PrimaryKey(AssignType.AUTO_INCREMENT)
private int _id;
private String title;
private String line1;
private String line2;
private String line3;
private String modify_time;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getLine3() {
return line3;
}
public void setLine3(String line3) {
this.line3 = line3;
}
public String getModify_time() {
return modify_time;
}
public void setModify_time(String modify_time) {
this.modify_time = modify_time;
}
@Override
public String toString() {
return "_id" + _id + "title:" + title + "\n " + line1 + "\n " + line2 + "\n " + line3
+ "\n " + modify_time;
}
} | UTF-8 | Java | 1,429 | java | ShiyiPoem.java | Java | [
{
"context": "esuits.orm.db.enums.AssignType;\n\n/**\n * Created by wei on 2017/2/23.\n */\n\n@Table(\"shi_yi_poem\")\npublic c",
"end": 202,
"score": 0.9610507488250732,
"start": 199,
"tag": "USERNAME",
"value": "wei"
}
]
| null | []
| package com.mifind.shiyinote.model;
import com.litesuits.orm.db.annotation.PrimaryKey;
import com.litesuits.orm.db.annotation.Table;
import com.litesuits.orm.db.enums.AssignType;
/**
* Created by wei on 2017/2/23.
*/
@Table("shi_yi_poem")
public class ShiyiPoem {
// 指定自增,每个对象需要有一个主键
@PrimaryKey(AssignType.AUTO_INCREMENT)
private int _id;
private String title;
private String line1;
private String line2;
private String line3;
private String modify_time;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getLine3() {
return line3;
}
public void setLine3(String line3) {
this.line3 = line3;
}
public String getModify_time() {
return modify_time;
}
public void setModify_time(String modify_time) {
this.modify_time = modify_time;
}
@Override
public String toString() {
return "_id" + _id + "title:" + title + "\n " + line1 + "\n " + line2 + "\n " + line3
+ "\n " + modify_time;
}
} | 1,429 | 0.598425 | 0.576235 | 69 | 19.26087 | 18.136082 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 14 |
08d0a2b946464a7dffd34603be7fa037fed59840 | 21,534,966,088,075 | d24d8d85eb2be922b3fcfdfb2e770ee974cc25a1 | /src/com/nightout/slidingmenu/HomeFragment.java | 011a7ab014d97c60efa23a3b623d98a692d800e2 | []
| no_license | manev15/Night-Out | https://github.com/manev15/Night-Out | cfa33503d6237f8e3ac0844d0805dd34f543df1a | 779089fc6603fe7c3c1ee849810feef2b7ddb1a0 | refs/heads/master | 2021-01-25T04:08:58.894000 | 2015-08-20T14:32:27 | 2015-08-20T14:32:27 | 40,510,224 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nightout.slidingmenu;
import com.google.android.gms.common.internal.IAccountAccessor;
import com.nightout.FacebookActivity;
import com.nightout.R;
import com.nightout.Singleton;
import com.nightout.foursquare.AndroidFoursquare;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class HomeFragment extends Fragment {
private TextView user;
private Button kopce;
private Button fblogin;
final Context cont=getActivity();
Singleton lol;
public HomeFragment(){}
public int ace;
private String Item="",ae;
private Button post;
private ImageButton login;
private ImageButton post1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
user=(TextView)rootView.findViewById(R.id.textView2);
fblogin=(Button)rootView.findViewById(R.id.fblogin);
post=(Button)rootView.findViewById(R.id.button1);
post1=(ImageButton)rootView.findViewById(R.id.imageButton2);
login=(ImageButton)rootView.findViewById(R.id.imageButton1);
String ime = Singleton.getInstance().ime;
int ace1=ime.length();
if(ace1==0)
{
user.setText("You are not logged in");
login.setVisibility(View.VISIBLE);
post1.setVisibility(View.GONE);
}
else
{
user.setText("Logged as: "+ime);
login.setVisibility(View.GONE);
post1.setVisibility(View.VISIBLE);
}
/*
fblogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// create class object
ace++;
Intent i = new Intent(getActivity(),FacebookActivity.class);
startActivity(i);
}
});
*/
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(getActivity(),FacebookActivity.class);
startActivity(i);
}
});
post.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// create class object
Intent i = new Intent(getActivity(),FacebookActivity.class);
startActivity(i);
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
/* Log.e("kolkoo", "kolko");
int io=Singleton.getInstance().br;
if(io!=0)
{
String imee=Singleton.getInstance().ime;
// Intent i = getActivity().getIntent();
// Item=i.getExtras().getString("name");
user.setText("Logged as: "+imee);
fblogin.setVisibility(View.GONE);
post.setVisibility(View.VISIBLE);
}
else
{
user.setText("You are not logged in");
}
*/
}
}
| UTF-8 | Java | 3,495 | java | HomeFragment.java | Java | [
{
"context": "onResume() {\n\t super.onResume();\n\t/* Log.e(\"kolkoo\", \"kolko\");\n\t \n\t int io=Singleton.getInstan",
"end": 3043,
"score": 0.8904738426208496,
"start": 3037,
"tag": "USERNAME",
"value": "kolkoo"
}
]
| null | []
| package com.nightout.slidingmenu;
import com.google.android.gms.common.internal.IAccountAccessor;
import com.nightout.FacebookActivity;
import com.nightout.R;
import com.nightout.Singleton;
import com.nightout.foursquare.AndroidFoursquare;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class HomeFragment extends Fragment {
private TextView user;
private Button kopce;
private Button fblogin;
final Context cont=getActivity();
Singleton lol;
public HomeFragment(){}
public int ace;
private String Item="",ae;
private Button post;
private ImageButton login;
private ImageButton post1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
user=(TextView)rootView.findViewById(R.id.textView2);
fblogin=(Button)rootView.findViewById(R.id.fblogin);
post=(Button)rootView.findViewById(R.id.button1);
post1=(ImageButton)rootView.findViewById(R.id.imageButton2);
login=(ImageButton)rootView.findViewById(R.id.imageButton1);
String ime = Singleton.getInstance().ime;
int ace1=ime.length();
if(ace1==0)
{
user.setText("You are not logged in");
login.setVisibility(View.VISIBLE);
post1.setVisibility(View.GONE);
}
else
{
user.setText("Logged as: "+ime);
login.setVisibility(View.GONE);
post1.setVisibility(View.VISIBLE);
}
/*
fblogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// create class object
ace++;
Intent i = new Intent(getActivity(),FacebookActivity.class);
startActivity(i);
}
});
*/
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(getActivity(),FacebookActivity.class);
startActivity(i);
}
});
post.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// create class object
Intent i = new Intent(getActivity(),FacebookActivity.class);
startActivity(i);
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
/* Log.e("kolkoo", "kolko");
int io=Singleton.getInstance().br;
if(io!=0)
{
String imee=Singleton.getInstance().ime;
// Intent i = getActivity().getIntent();
// Item=i.getExtras().getString("name");
user.setText("Logged as: "+imee);
fblogin.setVisibility(View.GONE);
post.setVisibility(View.VISIBLE);
}
else
{
user.setText("You are not logged in");
}
*/
}
}
| 3,495 | 0.608584 | 0.604292 | 138 | 24.311594 | 20.229052 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.673913 | false | false | 14 |
847120529ec786d9dda3b7596aada753d9b971a7 | 8,272,107,026,221 | 311dd5b403931b56c96fb6337a3805be10ca6ce3 | /java/ehr-automation/src/main/java/com/pensee/utils/Utils.java | e20079b20e34ed1109bf49a351832bc73cfbd9b0 | []
| no_license | wjmrr/OnlyDemo | https://github.com/wjmrr/OnlyDemo | 0ccb4ac065e4e22ef0be89679021a9508b23f819 | cc8db1bfa8780e96aa8e4212f26f1296ec063262 | refs/heads/master | 2020-03-26T05:10:48.910000 | 2020-03-16T09:20:43 | 2020-03-16T09:20:43 | 144,542,019 | 0 | 1 | null | false | 2021-03-05T13:55:28 | 2018-08-13T07:06:19 | 2021-03-05T13:00:37 | 2021-03-05T13:55:27 | 102,957 | 0 | 1 | 0 | JavaScript | false | false | package com.pensee.utils;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
public class Utils {
public static String getImportExcelFilePath(String fileName) {
return System.getProperty("user.dir") + "\\src\\test\\resources\\" + fileName + ".xlsx";
}
public static String getDefaultFilePath(String fileName) {
return System.getProperty("user.dir") + "\\src\\test\\resources\\" + fileName;
}
public static void waitABit(long ms) {
try {
Thread.sleep(ms);
} catch(InterruptedException e) {
}
}
/**
*
* @param dateStr: @today, @today+5, @today-5, @tomorrow
* @throws Exception
*/
public static String getDate(String dateStr) throws Exception {
if (dateStr==null) {
return null;
} else if (dateStr.equals("@today")) {
return getTodayDate();
} else if (dateStr.equals("@yesterday")) {
return getYesterdayDate();
} else if (dateStr.equals("@tomorrow")) {
return getYesterdayDate();
} else if (dateStr.contains("+") && dateStr.contains("@")){
return shiftDate(Integer.valueOf(dateStr.substring(dateStr.indexOf("+"))));
} else if (dateStr.contains("-") && dateStr.contains("@")){
return shiftDate(Integer.valueOf(dateStr.substring(dateStr.indexOf("-"))));
} else if (dateStr.equals("@nextWorkDay")){
return getNextWorkingDay();
} else if (dateStr.equals("@tomorrow_workday")){
return getNextDayofWorkingDay();
} else if (dateStr.equals("@preWorkDay")){
return getPreWorkingDay();
} else {
return dateStr;
}
}
/**
* 计算2个日期之间相差的天数
* @param startDate
* @param endDate
* @return
* @throws Exception
*/
public static String getDaysNo(String startDate, String endDate) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(startDate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(endDate));
long time2 = cal.getTimeInMillis();
long between_days = (time2-time1)/(1000*3600*24);
return String.valueOf(between_days);
}
/**
* 指定日期加天数得到新的日期
* @param date
* @param day
* @return
* @throws ParseException
*/
public static String addDate(String dateStr, int num) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(dateStr); // 指定日期
//得到指定日期的毫秒数
long time = date.getTime();
// 要加上的天数转换成毫秒数
num = num*24*60*60*1000;
time+= num; // 相加得到新的毫秒数
//return new Date(time); // 将毫秒数转换成日期
return (new SimpleDateFormat("yyyy-MM-dd").format(time));
}
/**
*
* @return 2017-07-12
*/
public static String getTodayDate() {
return shiftDate(0);
}
public static String getYesterdayDate() {
return shiftDate(-1);
}
public static String getTomorrowDate() {
return shiftDate(1);
}
/**
*
* @param n: +3, -5
* @return
*/
public static String shiftDate(int n) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, n);
Date time = cal.getTime();
return (new SimpleDateFormat("yyyy-MM-dd").format(time));
}
public static String getRandString(int length) {
return RandomStringUtils.randomAlphabetic(length);
}
public static String getRandNumeric(int n) {
return RandomStringUtils.randomNumeric(n);
}
/**
* 生成随机数0- max, 不包括max
* @param max
* @return
*/
public static int getRandInt(int max) {
Random ran = new Random();
return ran.nextInt(max);
}
/**
* 生成随机数 min- max, 包括min, 不包括max
* @param max
* @return
*/
public static int getRandInt(int min, int max) {
Random ran = new Random();
return min + ran.nextInt(max);
}
/**
* 取n个不重复的数,这些数范围是在min 和max 之间
* @param min 指定范围最小值
* @param max 指定范围最大值
* @param n 随机数个数
* @return
*/
public static int[] getRandArray(int min, int max, int n) {
int len = max-min+1;
int[] result = new int[n];
int count = 0;
while(count<n) {
int num = (int) (Math.random()*(max-min))+min;
boolean flag = true;
for (int j=0; j<n; j++){
if (num==result[j]) {
flag = false;
break;
}
}
if (flag) {
result[count] = num;
count++;
}
}
return result;
}
/**
* 使用用户格式提取字符串星期
* @param strDate 星期
* @param pattern 日期格式
* @return getWeek(new Date())
*/
public static String getWeek(Date date){
String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
if(week_index<0){
week_index = 0;
}
return weeks[week_index];
}
//@nextWorkDay
//取到最近的一個工作日日期,如果今天是周六或者周日,则返回下周一 日期,如今天是周一至周五,则反回当天日期
public static String getNextWorkingDay() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(getDate("@today"));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK);
String value = getDate("@today");
if (week_index ==1) { //周日
value = getDate("@today+1");
} else if (week_index ==7) { //周六
value = getDate("@today+2");
}
return value;
}
//@preWorkDay
//取到之前最近的一個工作日日期,如果今天是周六或者周日,则返回上周五 日期,如今天是周一至周五,则反回当天日期
public static String getPreWorkingDay() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(getDate("@today"));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK);
String value = getDate("@today");
if (week_index ==1) { //周日
value = getDate("@today-2");
} else if (week_index ==7) { //周六
value = getDate("@today-1");
}
return value;
}
//取到最近的一個工作日次日日期,如果今天是周五,周六或者周日,则返回下周一 日期,如今天是周一至周四,则反回第二天日期
public static String getNextDayofWorkingDay() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(getDate("@today"));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK);
String value = getDate("@tomorrow");
if (week_index ==1) {
value = getDate("@today+1");
} else if (week_index ==7) {
value = getDate("@today+2");
} else if (week_index ==6) {
value = getDate("@today+3");
}
return value;
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
//String prefix @random + prefix string ,e,g @random + E529
public static String getRandStr(String prefix) {
if (prefix.contains("@random")) {
String randomStr = Utils.getRandString(5);
return prefix.substring(prefix.indexOf("+")+1).trim() + randomStr;
} else {
return prefix;
}
}
public static int compare_date(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static void updateTestDataProperty(String key, String value) throws Exception {
PropertyUtil.updateProperties(System.getProperty("user.dir") + "\\src\\test\\resources\\property\\testData.properties", key, value);
}
public static String getTestDataProperty(String key) throws Exception {
if (key.startsWith("@@")) {
return PropertyUtil.getValueByKey(System.getProperty("user.dir") + "\\src\\test\\resources\\property\\testData.properties", key);
} else {
return key;
}
}
public String covertDateToFormat(String format, String value) throws ParseException {
if (value.contains("/")) { //数据格式yyyy/mm/dd
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date = sdf.parse(value);
value = (new SimpleDateFormat("yyyy-MM-dd")).format(date);
}
return value;
}
}
| UTF-8 | Java | 10,066 | java | Utils.java | Java | []
| null | []
| package com.pensee.utils;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
public class Utils {
public static String getImportExcelFilePath(String fileName) {
return System.getProperty("user.dir") + "\\src\\test\\resources\\" + fileName + ".xlsx";
}
public static String getDefaultFilePath(String fileName) {
return System.getProperty("user.dir") + "\\src\\test\\resources\\" + fileName;
}
public static void waitABit(long ms) {
try {
Thread.sleep(ms);
} catch(InterruptedException e) {
}
}
/**
*
* @param dateStr: @today, @today+5, @today-5, @tomorrow
* @throws Exception
*/
public static String getDate(String dateStr) throws Exception {
if (dateStr==null) {
return null;
} else if (dateStr.equals("@today")) {
return getTodayDate();
} else if (dateStr.equals("@yesterday")) {
return getYesterdayDate();
} else if (dateStr.equals("@tomorrow")) {
return getYesterdayDate();
} else if (dateStr.contains("+") && dateStr.contains("@")){
return shiftDate(Integer.valueOf(dateStr.substring(dateStr.indexOf("+"))));
} else if (dateStr.contains("-") && dateStr.contains("@")){
return shiftDate(Integer.valueOf(dateStr.substring(dateStr.indexOf("-"))));
} else if (dateStr.equals("@nextWorkDay")){
return getNextWorkingDay();
} else if (dateStr.equals("@tomorrow_workday")){
return getNextDayofWorkingDay();
} else if (dateStr.equals("@preWorkDay")){
return getPreWorkingDay();
} else {
return dateStr;
}
}
/**
* 计算2个日期之间相差的天数
* @param startDate
* @param endDate
* @return
* @throws Exception
*/
public static String getDaysNo(String startDate, String endDate) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(startDate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(endDate));
long time2 = cal.getTimeInMillis();
long between_days = (time2-time1)/(1000*3600*24);
return String.valueOf(between_days);
}
/**
* 指定日期加天数得到新的日期
* @param date
* @param day
* @return
* @throws ParseException
*/
public static String addDate(String dateStr, int num) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(dateStr); // 指定日期
//得到指定日期的毫秒数
long time = date.getTime();
// 要加上的天数转换成毫秒数
num = num*24*60*60*1000;
time+= num; // 相加得到新的毫秒数
//return new Date(time); // 将毫秒数转换成日期
return (new SimpleDateFormat("yyyy-MM-dd").format(time));
}
/**
*
* @return 2017-07-12
*/
public static String getTodayDate() {
return shiftDate(0);
}
public static String getYesterdayDate() {
return shiftDate(-1);
}
public static String getTomorrowDate() {
return shiftDate(1);
}
/**
*
* @param n: +3, -5
* @return
*/
public static String shiftDate(int n) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, n);
Date time = cal.getTime();
return (new SimpleDateFormat("yyyy-MM-dd").format(time));
}
public static String getRandString(int length) {
return RandomStringUtils.randomAlphabetic(length);
}
public static String getRandNumeric(int n) {
return RandomStringUtils.randomNumeric(n);
}
/**
* 生成随机数0- max, 不包括max
* @param max
* @return
*/
public static int getRandInt(int max) {
Random ran = new Random();
return ran.nextInt(max);
}
/**
* 生成随机数 min- max, 包括min, 不包括max
* @param max
* @return
*/
public static int getRandInt(int min, int max) {
Random ran = new Random();
return min + ran.nextInt(max);
}
/**
* 取n个不重复的数,这些数范围是在min 和max 之间
* @param min 指定范围最小值
* @param max 指定范围最大值
* @param n 随机数个数
* @return
*/
public static int[] getRandArray(int min, int max, int n) {
int len = max-min+1;
int[] result = new int[n];
int count = 0;
while(count<n) {
int num = (int) (Math.random()*(max-min))+min;
boolean flag = true;
for (int j=0; j<n; j++){
if (num==result[j]) {
flag = false;
break;
}
}
if (flag) {
result[count] = num;
count++;
}
}
return result;
}
/**
* 使用用户格式提取字符串星期
* @param strDate 星期
* @param pattern 日期格式
* @return getWeek(new Date())
*/
public static String getWeek(Date date){
String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
if(week_index<0){
week_index = 0;
}
return weeks[week_index];
}
//@nextWorkDay
//取到最近的一個工作日日期,如果今天是周六或者周日,则返回下周一 日期,如今天是周一至周五,则反回当天日期
public static String getNextWorkingDay() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(getDate("@today"));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK);
String value = getDate("@today");
if (week_index ==1) { //周日
value = getDate("@today+1");
} else if (week_index ==7) { //周六
value = getDate("@today+2");
}
return value;
}
//@preWorkDay
//取到之前最近的一個工作日日期,如果今天是周六或者周日,则返回上周五 日期,如今天是周一至周五,则反回当天日期
public static String getPreWorkingDay() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(getDate("@today"));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK);
String value = getDate("@today");
if (week_index ==1) { //周日
value = getDate("@today-2");
} else if (week_index ==7) { //周六
value = getDate("@today-1");
}
return value;
}
//取到最近的一個工作日次日日期,如果今天是周五,周六或者周日,则返回下周一 日期,如今天是周一至周四,则反回第二天日期
public static String getNextDayofWorkingDay() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse(getDate("@today"));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK);
String value = getDate("@tomorrow");
if (week_index ==1) {
value = getDate("@today+1");
} else if (week_index ==7) {
value = getDate("@today+2");
} else if (week_index ==6) {
value = getDate("@today+3");
}
return value;
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
//String prefix @random + prefix string ,e,g @random + E529
public static String getRandStr(String prefix) {
if (prefix.contains("@random")) {
String randomStr = Utils.getRandString(5);
return prefix.substring(prefix.indexOf("+")+1).trim() + randomStr;
} else {
return prefix;
}
}
public static int compare_date(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static void updateTestDataProperty(String key, String value) throws Exception {
PropertyUtil.updateProperties(System.getProperty("user.dir") + "\\src\\test\\resources\\property\\testData.properties", key, value);
}
public static String getTestDataProperty(String key) throws Exception {
if (key.startsWith("@@")) {
return PropertyUtil.getValueByKey(System.getProperty("user.dir") + "\\src\\test\\resources\\property\\testData.properties", key);
} else {
return key;
}
}
public String covertDateToFormat(String format, String value) throws ParseException {
if (value.contains("/")) { //数据格式yyyy/mm/dd
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date = sdf.parse(value);
value = (new SimpleDateFormat("yyyy-MM-dd")).format(date);
}
return value;
}
}
| 10,066 | 0.589925 | 0.581243 | 314 | 27.713375 | 23.53397 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.60828 | false | false | 14 |
8814cd1140ecb15b92dc5d62e6a319fe9acd5476 | 12,086,037,973,636 | 1fc5ebbb72ae8250416b8a96ed4384969e089465 | /src/main/java/com/mentoring/domain/entity/Card.java | f696f823a8df42c13d1e0e416310ef1cb00fa4eb | []
| no_license | ivanovaolya/mentoring-project | https://github.com/ivanovaolya/mentoring-project | c15c06b3bc57b2ae2875f5c3aff42ad9e63538ca | d1854790904493e7d107b8e96cf0f1d2e6e9e7de | refs/heads/master | 2020-12-02T19:27:37.832000 | 2017-12-04T14:53:30 | 2017-12-04T14:53:30 | 96,343,626 | 1 | 0 | null | false | 2017-12-04T14:53:31 | 2017-07-05T17:17:57 | 2017-08-16T17:08:55 | 2017-12-04T14:53:31 | 323 | 0 | 0 | 0 | Java | false | null | package com.mentoring.domain.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author ivanovaolyaa
* @version 9/26/2017
*/
@Entity
@Table(name = "cards")
@Getter
@Setter
@EqualsAndHashCode(exclude = "cardPk")
public class Card {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "card_pk")
private Long cardPk;
@Column(name = "card_number")
private String cardNumber;
private String cvd;
@Column(name = "exp_month")
private String expiredMonth;
@Column(name = "exp_year")
private String expiredYear;
}
| UTF-8 | Java | 830 | java | Card.java | Java | [
{
"context": "d;\nimport javax.persistence.Table;\n\n/**\n * @author ivanovaolyaa\n * @version 9/26/2017\n */\n@Entity\n@Table(name = \"",
"end": 353,
"score": 0.9983854293823242,
"start": 341,
"tag": "USERNAME",
"value": "ivanovaolyaa"
}
]
| null | []
| package com.mentoring.domain.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author ivanovaolyaa
* @version 9/26/2017
*/
@Entity
@Table(name = "cards")
@Getter
@Setter
@EqualsAndHashCode(exclude = "cardPk")
public class Card {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "card_pk")
private Long cardPk;
@Column(name = "card_number")
private String cardNumber;
private String cvd;
@Column(name = "exp_month")
private String expiredMonth;
@Column(name = "exp_year")
private String expiredYear;
}
| 830 | 0.73012 | 0.721687 | 41 | 19.243902 | 15.054017 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365854 | false | false | 14 |
9d0b82c07f26739ef8da000a1cbae3ae368687af | 23,192,823,425,317 | f151bc97bad1e071b66ccdaa5e0518651e16d49f | /src/com/fifino/patterns/observer/Player.java | ffadbf6821ce50f4e113271e979a9b69dcbcae95 | [
"Apache-2.0"
]
| permissive | ppartida/jdesign-patterns | https://github.com/ppartida/jdesign-patterns | c04e6e545e73c255cf20f9363684eed09f0f364f | c0c079fa310d73647749551c3f16240f333641b8 | refs/heads/master | 2018-01-10T19:46:43.141000 | 2016-02-22T23:33:42 | 2016-02-22T23:33:42 | 51,676,189 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fifino.patterns.observer;
/**
* Created by porfiriopartida on 2/13/16.
*/
public class Player extends Subject {
int hp = 100;
Enemy lastEnemy;
public void dmg(Enemy dmgDealer, int dmg){
if(this.hp <= 0){
System.out.println("Player is already dead. Not notyfing.");
return; //already dead.
}
this.lastEnemy = dmgDealer;
this.hp -= dmg;
this.notifyObservers();
}
public int getHp(){
return this.hp;
}
public Enemy getLastEnemy(){
return lastEnemy;
}
}
| UTF-8 | Java | 578 | java | Player.java | Java | [
{
"context": "e com.fifino.patterns.observer;\n\n/**\n * Created by porfiriopartida on 2/13/16.\n */\npublic class Player extends Subje",
"end": 72,
"score": 0.9991129040718079,
"start": 57,
"tag": "USERNAME",
"value": "porfiriopartida"
}
]
| null | []
| package com.fifino.patterns.observer;
/**
* Created by porfiriopartida on 2/13/16.
*/
public class Player extends Subject {
int hp = 100;
Enemy lastEnemy;
public void dmg(Enemy dmgDealer, int dmg){
if(this.hp <= 0){
System.out.println("Player is already dead. Not notyfing.");
return; //already dead.
}
this.lastEnemy = dmgDealer;
this.hp -= dmg;
this.notifyObservers();
}
public int getHp(){
return this.hp;
}
public Enemy getLastEnemy(){
return lastEnemy;
}
}
| 578 | 0.579585 | 0.564014 | 25 | 22.120001 | 17.461546 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 14 |
31459c991e29734af618d6a6587c1b2a2ce2895f | 22,643,067,585,466 | eca4a253fe0eba19f60d28363b10c433c57ab7a1 | /eclipse/de.tif.jacob.rule/src/de/tif/jacob/rule/editor/rules/actions/ShowJavaSourceCodeAction.java | 8418a95b79301d91c13d1272fbcf299273c03982 | []
| no_license | freegroup/Open-jACOB | https://github.com/freegroup/Open-jACOB | 632f20575092516f449591bf6f251772f599e5fc | 84f0a6af83876bd21c453132ca6f98a46609f1f4 | refs/heads/master | 2021-01-10T11:08:03.604000 | 2015-05-25T10:25:49 | 2015-05-25T10:25:49 | 36,183,560 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Created on 12.01.2005
*
*/
package de.tif.jacob.rule.editor.rules.actions;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import de.tif.jacob.designer.JacobDesigner;
import de.tif.jacob.rule.RulePlugin;
import de.tif.jacob.rule.editor.rules.editpart.RuleModelEditPart;
/**
*
*/
public class ShowJavaSourceCodeAction implements IObjectActionDelegate
{
String model ;
/*
* @see de.tif.jacob.designer.actions.ShowObjectModelHookAction#getObjectModel()
*/
public String getClassName()
{
return model;
}
public void selectionChanged(IAction action, ISelection selection)
{
if(((IStructuredSelection)selection).getFirstElement()!=null)
{
RuleModelEditPart editPart = (RuleModelEditPart)((IStructuredSelection)selection).getFirstElement();
model = editPart.getRuleModel().getImplementationClass();
}
else
model=null;
}
/**
* @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart)
{
}
/**
* @see IActionDelegate#run(IAction)
*/
public final void run(IAction action)
{
try
{
String model=getClassName();
if (model != null)
{
IJavaProject myJavaProject = JavaCore.create(RulePlugin.getDefault().getSelectedProject());
IType type = myJavaProject.findType(model);
if (type != null)
{
IJavaElement element = JavaCore.create(type.getResource());
JavaUI.openInEditor(element);
}
}
}
catch (Exception e)
{
RulePlugin.showException(e);
}
}
}
| UTF-8 | Java | 2,033 | java | ShowJavaSourceCodeAction.java | Java | []
| null | []
| /*
* Created on 12.01.2005
*
*/
package de.tif.jacob.rule.editor.rules.actions;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import de.tif.jacob.designer.JacobDesigner;
import de.tif.jacob.rule.RulePlugin;
import de.tif.jacob.rule.editor.rules.editpart.RuleModelEditPart;
/**
*
*/
public class ShowJavaSourceCodeAction implements IObjectActionDelegate
{
String model ;
/*
* @see de.tif.jacob.designer.actions.ShowObjectModelHookAction#getObjectModel()
*/
public String getClassName()
{
return model;
}
public void selectionChanged(IAction action, ISelection selection)
{
if(((IStructuredSelection)selection).getFirstElement()!=null)
{
RuleModelEditPart editPart = (RuleModelEditPart)((IStructuredSelection)selection).getFirstElement();
model = editPart.getRuleModel().getImplementationClass();
}
else
model=null;
}
/**
* @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart)
{
}
/**
* @see IActionDelegate#run(IAction)
*/
public final void run(IAction action)
{
try
{
String model=getClassName();
if (model != null)
{
IJavaProject myJavaProject = JavaCore.create(RulePlugin.getDefault().getSelectedProject());
IType type = myJavaProject.findType(model);
if (type != null)
{
IJavaElement element = JavaCore.create(type.getResource());
JavaUI.openInEditor(element);
}
}
}
catch (Exception e)
{
RulePlugin.showException(e);
}
}
}
| 2,033 | 0.708313 | 0.704378 | 79 | 24.734177 | 26.101414 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405063 | false | false | 14 |
bb7e3f9437b2da3c6f1db8d5c174dcb3d60995c0 | 7,310,034,392,102 | 0721305fd9b1c643a7687b6382dccc56a82a2dad | /src/app.zenly.locator_4.8.0_base_source_from_JADX/sources/p213co/znly/models/core/TypesProto$HeadingOrBuilder.java | 70533002d7b8d21c1e5c63b143ed9dfd4366a1f4 | []
| no_license | a2en/Zenly_re | https://github.com/a2en/Zenly_re | 09c635ad886c8285f70a8292ae4f74167a4ad620 | f87af0c2dd0bc14fd772c69d5bc70cd8aa727516 | refs/heads/master | 2020-12-13T17:07:11.442000 | 2020-01-17T04:32:44 | 2020-01-17T04:32:44 | 234,470,083 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package p213co.znly.models.core;
import p213co.znly.core.vendor.com.google.protobuf.MessageLiteOrBuilder;
import p213co.znly.core.vendor.com.google.protobuf.Timestamp;
/* renamed from: co.znly.models.core.TypesProto$HeadingOrBuilder */
public interface TypesProto$HeadingOrBuilder extends MessageLiteOrBuilder {
double getAccuracy();
Timestamp getCreatedAt();
double getHeading();
double getMagneticHeading();
boolean hasCreatedAt();
}
| UTF-8 | Java | 462 | java | TypesProto$HeadingOrBuilder.java | Java | []
| null | []
| package p213co.znly.models.core;
import p213co.znly.core.vendor.com.google.protobuf.MessageLiteOrBuilder;
import p213co.znly.core.vendor.com.google.protobuf.Timestamp;
/* renamed from: co.znly.models.core.TypesProto$HeadingOrBuilder */
public interface TypesProto$HeadingOrBuilder extends MessageLiteOrBuilder {
double getAccuracy();
Timestamp getCreatedAt();
double getHeading();
double getMagneticHeading();
boolean hasCreatedAt();
}
| 462 | 0.779221 | 0.75974 | 17 | 26.17647 | 26.778471 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.