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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
df5cc54502b1b8de33a0bfacfe4509396e4480e4 | 34,591,666,638,722 | e60d4580ccfb7d57356b189d7142c8b7083b751b | /DesignPatternCreationalAbstractFactory/src/MusicDescription.java | 3d82f4f4aa2444c1a68baed53b14148cbedfb72b | [] | no_license | ayogikrnwn/mochidp | https://github.com/ayogikrnwn/mochidp | 4cc045488ddcaa0e0fb8c0f9703f75a0224ff079 | 1815bf75288c9379047e302b576bff014f817039 | refs/heads/master | 2023-06-30T17:01:11.358000 | 2021-08-03T09:11:34 | 2021-08-03T09:11:34 | 390,737,787 | 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.
*/
public class MusicDescription implements Description {
@Override
public void create() {
System.out.println("======================");
System.out.println("Filter Kategori By Music");
System.out.println("Deskripsi : ");
System.out.println("Artis : ");
System.out.println("Judul Lagu : ");
}
}
| UTF-8 | Java | 532 | java | MusicDescription.java | Java | [] | 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.
*/
public class MusicDescription implements Description {
@Override
public void create() {
System.out.println("======================");
System.out.println("Filter Kategori By Music");
System.out.println("Deskripsi : ");
System.out.println("Artis : ");
System.out.println("Judul Lagu : ");
}
}
| 532 | 0.62594 | 0.62594 | 19 | 27 | 25.235731 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 2 |
845447f344ed9699fdfb5fb4ec4488343b69bbc5 | 35,433,480,227,986 | 2e53b1e78ceb2014acb99dfbdd4e5af671da7971 | /app/src/main/java/com/meiku/dev/views/MyRectDraweeView.java | 8b31082ff89f19a5b707205833ffdd29ef8186db | [] | no_license | hs5240leihuang/MrrckApplication | https://github.com/hs5240leihuang/MrrckApplication | 7960cb2278a1a8098c5bc908b3c5d7b241869c5d | aef126d4876e3e45b0984c1b829c38aa326ba598 | refs/heads/master | 2021-01-12T02:47:13.236000 | 2017-01-05T11:13:11 | 2017-01-05T11:14:05 | 78,102,342 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.meiku.dev.views;
import android.content.Context;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.meiku.dev.R;
import com.meiku.dev.utils.ScreenUtil;
public class MyRectDraweeView extends SimpleDraweeView {
public MyRectDraweeView(Context context) {
super(context);
GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(
getResources());
builder.setPlaceholderImage(
ContextCompat.getDrawable(context, R.drawable.gg_icon),
ScalingUtils.ScaleType.CENTER_CROP);
builder.setFailureImage(
ContextCompat.getDrawable(context, R.drawable.gg_icon),
ScalingUtils.ScaleType.CENTER_CROP);
RoundingParams roundingParams = RoundingParams
.fromCornersRadius(ScreenUtil.dip2px(context, 10));
builder.setRoundingParams(roundingParams);
setHierarchy(builder.build());
}
public void setUrlOfImage(String uriString) {
Uri uri = (uriString != null) ? Uri.parse(uriString) : null;
setImageURI(uri);
}
}
| UTF-8 | Java | 1,217 | java | MyRectDraweeView.java | Java | [] | null | [] | package com.meiku.dev.views;
import android.content.Context;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.meiku.dev.R;
import com.meiku.dev.utils.ScreenUtil;
public class MyRectDraweeView extends SimpleDraweeView {
public MyRectDraweeView(Context context) {
super(context);
GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(
getResources());
builder.setPlaceholderImage(
ContextCompat.getDrawable(context, R.drawable.gg_icon),
ScalingUtils.ScaleType.CENTER_CROP);
builder.setFailureImage(
ContextCompat.getDrawable(context, R.drawable.gg_icon),
ScalingUtils.ScaleType.CENTER_CROP);
RoundingParams roundingParams = RoundingParams
.fromCornersRadius(ScreenUtil.dip2px(context, 10));
builder.setRoundingParams(roundingParams);
setHierarchy(builder.build());
}
public void setUrlOfImage(String uriString) {
Uri uri = (uriString != null) ? Uri.parse(uriString) : null;
setImageURI(uri);
}
}
| 1,217 | 0.795399 | 0.792112 | 36 | 32.805557 | 21.821014 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.944444 | false | false | 2 |
32ceec5249e48044fc7b642e347adeb9847eb29d | 33,818,572,535,813 | f77d04f1e0f64a6a5e720ce24b65b1ccb3c546d2 | /zyj-hec-master/zyj-hec/src/main/java/com/hand/hec/exp/dto/ExpMoWriteCaptionHd.java | 6cb4bed8bfd3af7cc10f59eebb056e430428abdd | [] | no_license | floodboad/zyj-hssp | https://github.com/floodboad/zyj-hssp | 3139a4e73ec599730a67360cd04aa34bc9eaf611 | dc0ef445935fa48b7a6e86522ec64da0042dc0f3 | refs/heads/master | 2023-05-27T21:28:01.290000 | 2020-01-03T06:21:59 | 2020-01-03T06:29:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hand.hec.exp.dto;
import com.hand.hap.core.annotation.MultiLanguage;
import com.hand.hap.core.annotation.MultiLanguageField;
import com.hand.hap.mybatis.annotation.ExtensionAttribute;
import com.hand.hap.mybatis.common.query.Where;
import com.hand.hap.system.dto.BaseDTO;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
/**
* <p>
* ExpMoWriteCaptionHd
* </p>
*
* @author yang.duan 2019/02/12 9:34
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@MultiLanguage
@ExtensionAttribute(disable=true)
@Table(name = "exp_mo_write_caption_hd")
public class ExpMoWriteCaptionHd extends BaseDTO {
public static final String FIELD_CAPTION_HDS_ID = "captionHdsId";
public static final String FIELD_CAPTION_CODE = "captionCode";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_MAG_ORG_ID = "magOrgId";
public static final String FIELD_DOC_CATEGORY_CODE = "docCategoryCode";
@Id
@GeneratedValue
private Long captionHdsId;
/**
* 填写说明代码
*/
@NotEmpty
@Length(max = 30)
@Where
private String captionCode;
/**
* 填写说明描述
*/
@Length(max = 500)
@MultiLanguageField
@Where
private String description;
/**
* 管理组织ID
*/
@NotNull
@Where
private Long magOrgId;
/**
* 单据类别
*/
@NotEmpty
@Length(max = 30)
@Where
private String docCategoryCode;
}
| UTF-8 | Java | 1,809 | java | ExpMoWriteCaptionHd.java | Java | [
{
"context": "* <p>\n * ExpMoWriteCaptionHd\n * </p>\n *\n * @author yang.duan 2019/02/12 9:34\n */\n@Getter\n@Setter\n@ToString\n@No",
"end": 703,
"score": 0.9967738389968872,
"start": 694,
"tag": "NAME",
"value": "yang.duan"
}
] | null | [] | package com.hand.hec.exp.dto;
import com.hand.hap.core.annotation.MultiLanguage;
import com.hand.hap.core.annotation.MultiLanguageField;
import com.hand.hap.mybatis.annotation.ExtensionAttribute;
import com.hand.hap.mybatis.common.query.Where;
import com.hand.hap.system.dto.BaseDTO;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
/**
* <p>
* ExpMoWriteCaptionHd
* </p>
*
* @author yang.duan 2019/02/12 9:34
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@MultiLanguage
@ExtensionAttribute(disable=true)
@Table(name = "exp_mo_write_caption_hd")
public class ExpMoWriteCaptionHd extends BaseDTO {
public static final String FIELD_CAPTION_HDS_ID = "captionHdsId";
public static final String FIELD_CAPTION_CODE = "captionCode";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_MAG_ORG_ID = "magOrgId";
public static final String FIELD_DOC_CATEGORY_CODE = "docCategoryCode";
@Id
@GeneratedValue
private Long captionHdsId;
/**
* 填写说明代码
*/
@NotEmpty
@Length(max = 30)
@Where
private String captionCode;
/**
* 填写说明描述
*/
@Length(max = 500)
@MultiLanguageField
@Where
private String description;
/**
* 管理组织ID
*/
@NotNull
@Where
private Long magOrgId;
/**
* 单据类别
*/
@NotEmpty
@Length(max = 30)
@Where
private String docCategoryCode;
}
| 1,809 | 0.700396 | 0.69022 | 77 | 21.974026 | 19.742481 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.337662 | false | false | 2 |
b6cdf873ed9d99b39def88a35803d47903091268 | 5,892,695,133,454 | b1fba61fec0df5f2208b616e9e1b8f52671c6990 | /app/src/main/java/com/example/twentyone/restapi/BloodWeightPointDataApiManager.java | 16aa8d4a2adb31e293986f3e118d497fd9df808a | [] | no_license | wsxyz/TwentyOne | https://github.com/wsxyz/TwentyOne | 9e52f499452f8a490343829fecae039a4bf68f74 | 6c8ddc2c0762b57a5f6fefed6db34c29e084e0f6 | refs/heads/master | 2020-05-05T07:41:09.199000 | 2019-04-14T21:53:55 | 2019-04-14T21:53:55 | 179,833,959 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.twentyone.restapi;
import com.example.twentyone.model.data.UserToken;
import com.example.twentyone.restapi.callback.BloodWeightPointsGPSDAPICallBack;
import java.util.LinkedList;
import java.util.List;
public class BloodWeightPointDataApiManager {
protected UserToken userToken;
protected RestAPIService restApiService;
protected List<Object> genList,getGenListByUser;
public BloodWeightPointDataApiManager(UserToken userToken, RestAPIService restApiService){
this.userToken = userToken;
this.restApiService = restApiService;
}
/*
public synchronized void getAll(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack){
genList = new LinkedList<>();
getAll(bwpgpsdapiCallBack,0);
}
protected synchronized void getAll(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack,final int level){
}
public synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack){
getGenListByUser = new LinkedList<>();
getAllByUser(bwpgpsdapiCallBack,0);
}
protected synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack, final int level) {
}
public synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack,String search){
getGenListByUser = new LinkedList<>();
getAllByUser(bwpgpsdapiCallBack,0,search);
}
protected synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack, final int level,final String search){
}
*/
}
| UTF-8 | Java | 1,607 | java | BloodWeightPointDataApiManager.java | Java | [] | null | [] | package com.example.twentyone.restapi;
import com.example.twentyone.model.data.UserToken;
import com.example.twentyone.restapi.callback.BloodWeightPointsGPSDAPICallBack;
import java.util.LinkedList;
import java.util.List;
public class BloodWeightPointDataApiManager {
protected UserToken userToken;
protected RestAPIService restApiService;
protected List<Object> genList,getGenListByUser;
public BloodWeightPointDataApiManager(UserToken userToken, RestAPIService restApiService){
this.userToken = userToken;
this.restApiService = restApiService;
}
/*
public synchronized void getAll(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack){
genList = new LinkedList<>();
getAll(bwpgpsdapiCallBack,0);
}
protected synchronized void getAll(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack,final int level){
}
public synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack){
getGenListByUser = new LinkedList<>();
getAllByUser(bwpgpsdapiCallBack,0);
}
protected synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack, final int level) {
}
public synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack,String search){
getGenListByUser = new LinkedList<>();
getAllByUser(bwpgpsdapiCallBack,0,search);
}
protected synchronized void getAllByUser(final BloodWeightPointsGPSDAPICallBack bwpgpsdapiCallBack, final int level,final String search){
}
*/
}
| 1,607 | 0.773491 | 0.771624 | 46 | 33.934784 | 39.055927 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586957 | false | false | 2 |
6441a1b8b830b608fc434ac19a4ceaad223eb2d0 | 18,760,417,208,562 | a79f4a0176732f48871390c2adde52b31f292ac1 | /src/main/java/homework/romanivanov/javacore/jc20hw/executor/ExecutorApp.java | 8ce38da87763125172675640a67d675b7901ef70 | [] | no_license | masliynataliya/logos-java-core-13-02-2020 | https://github.com/masliynataliya/logos-java-core-13-02-2020 | cb6bedd71f167bfa8aa26f56d79bfd013178a38a | bb77baf7c812f038e515d10cec3d16c7da79d5f4 | refs/heads/master | 2021-01-16T09:37:09.782000 | 2020-09-13T11:44:40 | 2020-09-13T11:44:40 | 243,063,025 | 1 | 0 | null | false | 2020-09-13T11:44:41 | 2020-02-25T17:48:58 | 2020-09-13T11:17:51 | 2020-09-13T11:44:41 | 570 | 0 | 0 | 2 | Java | false | false | package homework.romanivanov.javacore.jc20hw.executor;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static homework.romanivanov.javacore.jc20hw.thread.Fibonachi.getNumbers;
public class ExecutorApp {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(new MyThread());
executorService.execute(new RunnableThread());
executorService.shutdown();
}
}
class RunnableThread implements Runnable {
private final Scanner sc = new Scanner(System.in);
@Override
public void run() {
System.out.println("Введіть скільки ви хочете побачити чисел фібаночі у зворотньому порядку");
int size = sc.nextInt();
List<Integer> fibonochiBack = getNumbers(size);
Collections.reverse(fibonochiBack);
for (int i = 0; i < fibonochiBack.size(); i++) {
try {
Thread.sleep(1000);
System.out.println(fibonochiBack.get(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread extends Thread {
private final Scanner sc = new Scanner(System.in);
@Override
public synchronized void run() {
System.out.println("Введіть скільки чисел ви хочете фібаночі переглянути");
int size = sc.nextInt();
List<Integer> fibonachi = getNumbers(size);
for (int i = 0; i < fibonachi.size(); i++) {
try {
Thread.sleep(1000);
System.out.println(fibonachi.get(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 1,952 | java | ExecutorApp.java | Java | [] | null | [] | package homework.romanivanov.javacore.jc20hw.executor;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static homework.romanivanov.javacore.jc20hw.thread.Fibonachi.getNumbers;
public class ExecutorApp {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(new MyThread());
executorService.execute(new RunnableThread());
executorService.shutdown();
}
}
class RunnableThread implements Runnable {
private final Scanner sc = new Scanner(System.in);
@Override
public void run() {
System.out.println("Введіть скільки ви хочете побачити чисел фібаночі у зворотньому порядку");
int size = sc.nextInt();
List<Integer> fibonochiBack = getNumbers(size);
Collections.reverse(fibonochiBack);
for (int i = 0; i < fibonochiBack.size(); i++) {
try {
Thread.sleep(1000);
System.out.println(fibonochiBack.get(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread extends Thread {
private final Scanner sc = new Scanner(System.in);
@Override
public synchronized void run() {
System.out.println("Введіть скільки чисел ви хочете фібаночі переглянути");
int size = sc.nextInt();
List<Integer> fibonachi = getNumbers(size);
for (int i = 0; i < fibonachi.size(); i++) {
try {
Thread.sleep(1000);
System.out.println(fibonachi.get(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 1,952 | 0.62961 | 0.621475 | 60 | 29.733334 | 24.440313 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
b9d7f7dd25df713bf9d3cb64d875a76661e6029c | 27,522,150,463,861 | 178a203049dd4117cd14b7c6177e69fcbc763fd5 | /cpsc250l-lab05/src/LockWithResetTest.java | a9e8dba776fbda57c26ff5e68332de53188d2745 | [] | no_license | avery-logue/CPSC250 | https://github.com/avery-logue/CPSC250 | 04ba5669a2d061e7b3909f603f5b6cfd495bc7e3 | 4162df64605becf078de807d16ba402e95cdd873 | refs/heads/main | 2023-07-19T01:30:51.793000 | 2021-09-03T00:54:09 | 2021-09-03T00:54:09 | 399,286,659 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.concurrent.TimeUnit;
import javax.swing.JDialog;
import javax.swing.JTextField;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import edu.cnu.cs.gooey.Gooey;
import edu.cnu.cs.gooey.GooeyDialog;
public class LockWithResetTest {
@Rule
public Timeout globalTimeout= new Timeout(5, TimeUnit.SECONDS);
@Test
public void testReflection() {
Class<?> iClass = Lock.class;
Field[] iFields = iClass.getDeclaredFields();
for (Field f : iFields) {
if (!f.isSynthetic()) {
assertFalse( "Field \""+f.getName()+"\" can't be static", Modifier.isStatic ( f.getModifiers() ));
assertFalse( "Field \""+f.getName()+"\" can't be public", Modifier.isPublic ( f.getModifiers() ));
if (!(Modifier.isPrivate( f.getModifiers() ) || Modifier.isProtected( f.getModifiers() ))) {
fail( "Field \""+f.getName()+"\" should be private or protected" );
}
}
}
}
@Test(expected=InvalidLockCombinationException.class)
public void testNewLockThrowsExceptionWhenCombinationNotWithinLimits() {
Combination comb = new Combination( 1, 2, 3 );
new Lock( 2, comb ); // invalid combination. should throw exception.
}
/**
* Testing "resetNaive" method
*/
@Test
public void testResetNaive_ValidCombinationChangesExistingCombination() {
Combination comb = new Combination ( 7, 8, 9 );
final Lock lock = new Lock( 10, comb );
// dialog with input "0 9 2": input OK
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "0 9 2" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
// new combination should open lock
lock.close();
Combination now = new Combination( 0, 9, 2 );
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetNaive_ClosingDialogDoesNotChangeCombination() {
Combination now = new Combination( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with empty input
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test(expected=java.util.NoSuchElementException.class)
public void testResetNaive_CombinationWithLessThanThreeNumbersThrowsException() {
Combination comb = new Combination ( 42, 16, 72 );
final Lock lock = new Lock( 100, comb );
// dialog with input "42 88": missing one number throws exception
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getComponent( dialog, JTextField.class ).setText( "42 88" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
fail( "Exception should have been thrown" );
}
@Test(expected=java.util.NoSuchElementException.class)
public void testResetNaive_CombinationWithNonNumbericValuesThrowsException() {
Combination comb = new Combination ( 42, 16, 72 );
final Lock lock = new Lock( 100, comb );
// dialog with input "1 two 3": non-numeric input throws exception
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getComponent( dialog, JTextField.class ).setText( "1 two 3" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
fail( "Exception should have been thrown" );
}
@Test
public void testResetNaive_InvalidCombinationThrowsExceptionAndDoesNotChangeExistingCombination() {
Combination old = new Combination ( 9, 8, 7 );
final Lock lock = new Lock( 10, old );
// dialog with input "10 11 12": input outside lock dial throws exception
try {
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getComponent( dialog, JTextField.class ).setText( "10 11 12" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
fail( "Exception should have been thrown" );
} catch (InvalidLockCombinationException e) {
// combination shouldn't change
lock.close();
lock.open ( old );
assertTrue( "Incorrect result", lock.isOpen() );
}
}
/**
* Testing "resetRetry" method
*/
@Test
public void testResetRetry_ClosingDialogDoesNotChangeCombination() {
Combination now = new Combination( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with empty input
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(JDialog dialog) {
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_SeveralDialogsDoNotChangeExistingCombination() {
Combination now = new Combination ( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with input "42" (but two other numbers needed): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "42" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel ( dialog, "Type 3 integers separated by spaces" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
}
});
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_ClosingDialogAfterNonNumericInputDoesNotChangeExistingCombination() {
Combination now = new Combination( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with input "3 2 one" (last one is non-numeric): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "3 2 one" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel ( dialog, "Type 3 integers separated by spaces" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
}
});
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_ValidCombinationAfterInvalidCombinationChangesExistingCombination() {
Combination comb = new Combination ( 4, 4, 4 );
final Lock lock = new Lock( 5, comb );
// dialog with input "9 8 2" (first two are not valid): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "9 8 2" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel( dialog, "Type 3 integers in the range [0..5]" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "3 2 1" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
}
});
}
});
// new combination should open lock
lock.close();
Combination now = new Combination( 3, 2, 1 );
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_ValidCombinationAfterTwoInvalidCombinations() {
Combination comb = new Combination ( 8, 0, 1 );
final Lock lock = new Lock( 9, comb );
// dialog with input "0 10 0" (second is not valid): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "0 10 0" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel( dialog, "Type 3 integers in the range [0..9]" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "5 2 4" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
}
});
}
});
// new combination should open lock
lock.close();
Combination now = new Combination( 5, 2, 4 );
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
}
| UTF-8 | Java | 11,078 | java | LockWithResetTest.java | Java | [] | null | [] |
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.concurrent.TimeUnit;
import javax.swing.JDialog;
import javax.swing.JTextField;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import edu.cnu.cs.gooey.Gooey;
import edu.cnu.cs.gooey.GooeyDialog;
public class LockWithResetTest {
@Rule
public Timeout globalTimeout= new Timeout(5, TimeUnit.SECONDS);
@Test
public void testReflection() {
Class<?> iClass = Lock.class;
Field[] iFields = iClass.getDeclaredFields();
for (Field f : iFields) {
if (!f.isSynthetic()) {
assertFalse( "Field \""+f.getName()+"\" can't be static", Modifier.isStatic ( f.getModifiers() ));
assertFalse( "Field \""+f.getName()+"\" can't be public", Modifier.isPublic ( f.getModifiers() ));
if (!(Modifier.isPrivate( f.getModifiers() ) || Modifier.isProtected( f.getModifiers() ))) {
fail( "Field \""+f.getName()+"\" should be private or protected" );
}
}
}
}
@Test(expected=InvalidLockCombinationException.class)
public void testNewLockThrowsExceptionWhenCombinationNotWithinLimits() {
Combination comb = new Combination( 1, 2, 3 );
new Lock( 2, comb ); // invalid combination. should throw exception.
}
/**
* Testing "resetNaive" method
*/
@Test
public void testResetNaive_ValidCombinationChangesExistingCombination() {
Combination comb = new Combination ( 7, 8, 9 );
final Lock lock = new Lock( 10, comb );
// dialog with input "0 9 2": input OK
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "0 9 2" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
// new combination should open lock
lock.close();
Combination now = new Combination( 0, 9, 2 );
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetNaive_ClosingDialogDoesNotChangeCombination() {
Combination now = new Combination( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with empty input
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test(expected=java.util.NoSuchElementException.class)
public void testResetNaive_CombinationWithLessThanThreeNumbersThrowsException() {
Combination comb = new Combination ( 42, 16, 72 );
final Lock lock = new Lock( 100, comb );
// dialog with input "42 88": missing one number throws exception
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getComponent( dialog, JTextField.class ).setText( "42 88" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
fail( "Exception should have been thrown" );
}
@Test(expected=java.util.NoSuchElementException.class)
public void testResetNaive_CombinationWithNonNumbericValuesThrowsException() {
Combination comb = new Combination ( 42, 16, 72 );
final Lock lock = new Lock( 100, comb );
// dialog with input "1 two 3": non-numeric input throws exception
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getComponent( dialog, JTextField.class ).setText( "1 two 3" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
fail( "Exception should have been thrown" );
}
@Test
public void testResetNaive_InvalidCombinationThrowsExceptionAndDoesNotChangeExistingCombination() {
Combination old = new Combination ( 9, 8, 7 );
final Lock lock = new Lock( 10, old );
// dialog with input "10 11 12": input outside lock dial throws exception
try {
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetNaive();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getComponent( dialog, JTextField.class ).setText( "10 11 12" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
fail( "Exception should have been thrown" );
} catch (InvalidLockCombinationException e) {
// combination shouldn't change
lock.close();
lock.open ( old );
assertTrue( "Incorrect result", lock.isOpen() );
}
}
/**
* Testing "resetRetry" method
*/
@Test
public void testResetRetry_ClosingDialogDoesNotChangeCombination() {
Combination now = new Combination( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with empty input
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(JDialog dialog) {
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_SeveralDialogsDoNotChangeExistingCombination() {
Combination now = new Combination ( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with input "42" (but two other numbers needed): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "42" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel ( dialog, "Type 3 integers separated by spaces" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
}
});
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_ClosingDialogAfterNonNumericInputDoesNotChangeExistingCombination() {
Combination now = new Combination( 1, 2, 3 );
final Lock lock = new Lock( 5, now );
// dialog with input "3 2 one" (last one is non-numeric): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "3 2 one" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel ( dialog, "Type 3 integers separated by spaces" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(JDialog dialog) {
Gooey.getLabel ( dialog, "Type a new combination" );
Gooey.getButton( dialog, "Cancel" ).doClick();
}
});
}
});
}
});
// combination shouldn't change
lock.close();
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_ValidCombinationAfterInvalidCombinationChangesExistingCombination() {
Combination comb = new Combination ( 4, 4, 4 );
final Lock lock = new Lock( 5, comb );
// dialog with input "9 8 2" (first two are not valid): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "9 8 2" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel( dialog, "Type 3 integers in the range [0..5]" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "3 2 1" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
}
});
}
});
// new combination should open lock
lock.close();
Combination now = new Combination( 3, 2, 1 );
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
@Test
public void testResetRetry_ValidCombinationAfterTwoInvalidCombinations() {
Combination comb = new Combination ( 8, 0, 1 );
final Lock lock = new Lock( 9, comb );
// dialog with input "0 10 0" (second is not valid): error dialog displayed
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
lock.resetRetry();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "0 10 0" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getLabel( dialog, "Type 3 integers in the range [0..9]" );
Gooey.capture( new GooeyDialog() {
@Override
public void invoke() {
Gooey.getButton( dialog, "OK" ).doClick();
}
@Override
public void test(final JDialog dialog) {
Gooey.getComponent( dialog, JTextField.class ).setText( "5 2 4" );
Gooey.getButton ( dialog, "OK" ).doClick();
}
});
}
});
}
});
// new combination should open lock
lock.close();
Combination now = new Combination( 5, 2, 4 );
lock.open ( now );
assertTrue( "Incorrect result", lock.isOpen() );
}
}
| 11,078 | 0.62096 | 0.609045 | 345 | 30.104347 | 24.080797 | 104 | false | false | 0 | 0 | 0 | 0 | 68 | 0.017873 | 3.8 | false | false | 2 |
20ccd6194cd743b8edfc1498bf055d8f313519ab | 4,870,492,975,322 | 43322b3d5529f267b9c3cead51a1f2fa243fad46 | /app/src/main/java/mx/com/trader/TareaAsync.java | 1ce2fa378e96dba9aad06c9fa794e15b0af396b1 | [] | no_license | cryptonative/price-follow | https://github.com/cryptonative/price-follow | 4ba56ad833c481b6115697902eaa46c572385e3d | 2aa0a8c7211e990af5c33b1da18cbf21c8aa5540 | refs/heads/master | 2020-04-08T11:29:15.469000 | 2018-11-28T08:51:53 | 2018-11-28T08:51:53 | 159,307,879 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mx.com.trader;
import android.os.AsyncTask;
import android.util.Log;
import com.binance.api.client.BinanceApiClientFactory;
import com.binance.api.client.BinanceApiRestClient;
import com.binance.api.client.BinanceApiWebSocketClient;
import com.binance.api.client.domain.event.CandlestickEvent;
import com.binance.api.client.domain.market.Candlestick;
import com.binance.api.client.domain.market.CandlestickInterval;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import mx.com.trader.constante.Constante;
import mx.com.trader.vo.SoporteResistenciaVO;
/**
* Created by Admin on 15/05/2017.
*/
public class TareaAsync extends AsyncTask<BinanceApiWebSocketClient, String, Void> {
/**
* Variables para el envio desde la actividad origen.
*/
private MainActivity activity;
private String pair;
private List<SoporteResistenciaVO> soporteResistenciaVO;
private Integer indiceSoporte;
/**
* Variables para el uso de la clase.
*/
private Map<Long, Candlestick> candlesticksCache;
private Long openTimeAnterior;
Integer volAnt = 0;
Integer contador = 0;
@Override
protected Void doInBackground(BinanceApiWebSocketClient... client) {
this.candlesticksCache = new TreeMap<>();
client[0].onCandlestickEvent(pair.toLowerCase(), CandlestickInterval.ONE_MINUTE, response -> {
Long openTime = response.getOpenTime();
Long inc = 0L;
Candlestick candlestick = candlesticksCache.get(openTime);
if (candlestick == null) {
// new candlestick
if (candlesticksCache.size()>0) {
Candlestick candleStickAnterior = candlesticksCache.get(this.openTimeAnterior);
String [] parteEntera = candleStickAnterior.getVolume().split("\\.");
volAnt = Integer.parseInt(parteEntera[0]);
}
candlestick = new Candlestick();
contador = 0;
}
// update candlestick with the stream data
setCandlestick(candlestick, response);
this.openTimeAnterior = response.getOpenTime();
String [] parteEnteraNew = response.getVolume().split("\\.");
Integer volNew = Integer.parseInt(parteEnteraNew[0]);
if (volAnt.compareTo(0)>0) {
inc = Long.valueOf((((100 * volNew) / volAnt) - 100));
}
// Store the updated candlestick in the cache
candlesticksCache.put(openTime, candlestick);
contador++;
// Analiza el precio actual.
String cercania = validaPrecioActual(candlestick.getClose());
Double variacion = getPorcetanjeVariacion(BigDecimal.ZERO, BigDecimal.ZERO);
this.publishProgress(pair + ": " + candlestick.getClose(), contador.toString(), candlestick.getNumberOfTrades().toString());
});
return null;
}
@Override
protected void onProgressUpdate(String... values) {
this.activity.mTextMessage.setText("Trades: " + values[2]);
this.activity.mTextContador.setText("Cont: " + values[1]);
if (this.pair.endsWith("USDT")) {
this.activity.mTextVolumen.setText(formatUSD(values[0], Constante.xrp));
} else {
this.activity.mTextVolumen.setText(values[0]);
}
}
@Override
protected void onPostExecute(Void avoid) {
}
/**
* Formatea a los decimales indicados.
* @param cadenaOriginal
* @param decimales
* @return
*/
private String formatUSD(String cadenaOriginal, int decimales) {
return cadenaOriginal.substring(0,cadenaOriginal.indexOf(".")+decimales);
}
private String validaPrecioActual(String precioActual) {
BigDecimal precio = new BigDecimal(precioActual);
return "Se acerca a soporte y resistencia a los " ;
}
// Codigo para getters & setters de la clase.
public void setSoporteResistenciaVO(List<SoporteResistenciaVO> soporteResistenciaVO) {
this.soporteResistenciaVO = soporteResistenciaVO;
}
public void setActivity(MainActivity activity) {
this.activity = activity;
}
public void setPair(String pair) {
this.pair = pair;
}
public void setIndiceSoporte(Integer indiceSoporte) {
this.indiceSoporte = indiceSoporte;
}
/**
*
* Obtiene el porcentaje en el cual varia un precioIngreso, respecto al precio actual,
* valores de precioActual mayores a porcetajeIngreso dan porcentaje positivo.
* valores de precioActual menores a porcetajeIngreso dan porcentaje negativo.
*
* @param precioIngreso
* @param precioActual
* @return
*/
private Double getPorcetanjeVariacion(BigDecimal precioIngreso, BigDecimal precioActual) {
return 100.0 - precioActual.multiply(BigDecimal.valueOf(100.0)).divide(precioIngreso).doubleValue();
}
private Candlestick setCandlestick(Candlestick candlestick, CandlestickEvent response) {
candlestick.setOpenTime(response.getOpenTime());
candlestick.setOpen(response.getOpen());
candlestick.setLow(response.getLow());
candlestick.setHigh(response.getHigh());
candlestick.setClose(response.getClose());
candlestick.setCloseTime(response.getCloseTime());
candlestick.setVolume(response.getVolume());
candlestick.setNumberOfTrades(response.getNumberOfTrades());
candlestick.setQuoteAssetVolume(response.getQuoteAssetVolume());
candlestick.setTakerBuyQuoteAssetVolume(response.getTakerBuyQuoteAssetVolume());
candlestick.setTakerBuyBaseAssetVolume(response.getTakerBuyQuoteAssetVolume());
return candlestick;
}
}
| UTF-8 | Java | 5,882 | java | TareaAsync.java | Java | [
{
"context": "trader.vo.SoporteResistenciaVO;\n\n/**\n * Created by Admin on 15/05/2017.\n */\npublic class TareaAsync exten",
"end": 672,
"score": 0.7031206488609314,
"start": 667,
"tag": "USERNAME",
"value": "Admin"
}
] | null | [] | package mx.com.trader;
import android.os.AsyncTask;
import android.util.Log;
import com.binance.api.client.BinanceApiClientFactory;
import com.binance.api.client.BinanceApiRestClient;
import com.binance.api.client.BinanceApiWebSocketClient;
import com.binance.api.client.domain.event.CandlestickEvent;
import com.binance.api.client.domain.market.Candlestick;
import com.binance.api.client.domain.market.CandlestickInterval;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import mx.com.trader.constante.Constante;
import mx.com.trader.vo.SoporteResistenciaVO;
/**
* Created by Admin on 15/05/2017.
*/
public class TareaAsync extends AsyncTask<BinanceApiWebSocketClient, String, Void> {
/**
* Variables para el envio desde la actividad origen.
*/
private MainActivity activity;
private String pair;
private List<SoporteResistenciaVO> soporteResistenciaVO;
private Integer indiceSoporte;
/**
* Variables para el uso de la clase.
*/
private Map<Long, Candlestick> candlesticksCache;
private Long openTimeAnterior;
Integer volAnt = 0;
Integer contador = 0;
@Override
protected Void doInBackground(BinanceApiWebSocketClient... client) {
this.candlesticksCache = new TreeMap<>();
client[0].onCandlestickEvent(pair.toLowerCase(), CandlestickInterval.ONE_MINUTE, response -> {
Long openTime = response.getOpenTime();
Long inc = 0L;
Candlestick candlestick = candlesticksCache.get(openTime);
if (candlestick == null) {
// new candlestick
if (candlesticksCache.size()>0) {
Candlestick candleStickAnterior = candlesticksCache.get(this.openTimeAnterior);
String [] parteEntera = candleStickAnterior.getVolume().split("\\.");
volAnt = Integer.parseInt(parteEntera[0]);
}
candlestick = new Candlestick();
contador = 0;
}
// update candlestick with the stream data
setCandlestick(candlestick, response);
this.openTimeAnterior = response.getOpenTime();
String [] parteEnteraNew = response.getVolume().split("\\.");
Integer volNew = Integer.parseInt(parteEnteraNew[0]);
if (volAnt.compareTo(0)>0) {
inc = Long.valueOf((((100 * volNew) / volAnt) - 100));
}
// Store the updated candlestick in the cache
candlesticksCache.put(openTime, candlestick);
contador++;
// Analiza el precio actual.
String cercania = validaPrecioActual(candlestick.getClose());
Double variacion = getPorcetanjeVariacion(BigDecimal.ZERO, BigDecimal.ZERO);
this.publishProgress(pair + ": " + candlestick.getClose(), contador.toString(), candlestick.getNumberOfTrades().toString());
});
return null;
}
@Override
protected void onProgressUpdate(String... values) {
this.activity.mTextMessage.setText("Trades: " + values[2]);
this.activity.mTextContador.setText("Cont: " + values[1]);
if (this.pair.endsWith("USDT")) {
this.activity.mTextVolumen.setText(formatUSD(values[0], Constante.xrp));
} else {
this.activity.mTextVolumen.setText(values[0]);
}
}
@Override
protected void onPostExecute(Void avoid) {
}
/**
* Formatea a los decimales indicados.
* @param cadenaOriginal
* @param decimales
* @return
*/
private String formatUSD(String cadenaOriginal, int decimales) {
return cadenaOriginal.substring(0,cadenaOriginal.indexOf(".")+decimales);
}
private String validaPrecioActual(String precioActual) {
BigDecimal precio = new BigDecimal(precioActual);
return "Se acerca a soporte y resistencia a los " ;
}
// Codigo para getters & setters de la clase.
public void setSoporteResistenciaVO(List<SoporteResistenciaVO> soporteResistenciaVO) {
this.soporteResistenciaVO = soporteResistenciaVO;
}
public void setActivity(MainActivity activity) {
this.activity = activity;
}
public void setPair(String pair) {
this.pair = pair;
}
public void setIndiceSoporte(Integer indiceSoporte) {
this.indiceSoporte = indiceSoporte;
}
/**
*
* Obtiene el porcentaje en el cual varia un precioIngreso, respecto al precio actual,
* valores de precioActual mayores a porcetajeIngreso dan porcentaje positivo.
* valores de precioActual menores a porcetajeIngreso dan porcentaje negativo.
*
* @param precioIngreso
* @param precioActual
* @return
*/
private Double getPorcetanjeVariacion(BigDecimal precioIngreso, BigDecimal precioActual) {
return 100.0 - precioActual.multiply(BigDecimal.valueOf(100.0)).divide(precioIngreso).doubleValue();
}
private Candlestick setCandlestick(Candlestick candlestick, CandlestickEvent response) {
candlestick.setOpenTime(response.getOpenTime());
candlestick.setOpen(response.getOpen());
candlestick.setLow(response.getLow());
candlestick.setHigh(response.getHigh());
candlestick.setClose(response.getClose());
candlestick.setCloseTime(response.getCloseTime());
candlestick.setVolume(response.getVolume());
candlestick.setNumberOfTrades(response.getNumberOfTrades());
candlestick.setQuoteAssetVolume(response.getQuoteAssetVolume());
candlestick.setTakerBuyQuoteAssetVolume(response.getTakerBuyQuoteAssetVolume());
candlestick.setTakerBuyBaseAssetVolume(response.getTakerBuyQuoteAssetVolume());
return candlestick;
}
}
| 5,882 | 0.6712 | 0.66491 | 171 | 33.397659 | 30.422461 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.502924 | false | false | 2 |
fb5210cfa3386d1a01a1049471a6e292743a5924 | 12,395,275,679,263 | 43c0b48f061f55e429a50ff54986c4eb9c39c6e8 | /lib/src/test/java/com/snap/ui/seeking/ReversingSeekableTest.java | d7ffdacb2288cd563e26581b056174f43336e7a9 | [
"BSD-3-Clause"
] | permissive | nirmal912/recycling-center | https://github.com/nirmal912/recycling-center | 0cd60e53d15b165e0656ab5ff6e1ae5251d40618 | eb8aa162934a3f6366488a3cbaf96106f541abf9 | refs/heads/master | 2022-11-10T09:32:44.773000 | 2020-06-16T18:08:47 | 2020-06-16T18:08:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.snap.ui.seeking;
import java.util.List;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ReversingSeekableTest {
Seekable<Integer> seekable;
@Before
public void setup() {
seekable = new ListSeekable<>(Lists.newArrayList(1, 2, 3));
}
@Test
public void basic_test() throws Exception {
Seekable<Integer> reversed = Seekables.reverse(seekable);
List<Integer> list = Lists.newArrayList(reversed);
assertEquals(Lists.newArrayList(3, 2, 1), list);
Seekable<Integer> forward = Seekables.reverse(list);
List<Integer> list2 = Lists.newArrayList(forward);
assertEquals(Lists.newArrayList(1, 2, 3), list2);
}
} | UTF-8 | Java | 799 | java | ReversingSeekableTest.java | Java | [] | null | [] | package com.snap.ui.seeking;
import java.util.List;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ReversingSeekableTest {
Seekable<Integer> seekable;
@Before
public void setup() {
seekable = new ListSeekable<>(Lists.newArrayList(1, 2, 3));
}
@Test
public void basic_test() throws Exception {
Seekable<Integer> reversed = Seekables.reverse(seekable);
List<Integer> list = Lists.newArrayList(reversed);
assertEquals(Lists.newArrayList(3, 2, 1), list);
Seekable<Integer> forward = Seekables.reverse(list);
List<Integer> list2 = Lists.newArrayList(forward);
assertEquals(Lists.newArrayList(1, 2, 3), list2);
}
} | 799 | 0.687109 | 0.673342 | 30 | 25.666666 | 23.659153 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 2 |
d50fc76ec8d24aae95d9f92b1b211c8772a0f812 | 22,282,290,362,976 | 64adee3a95be2fdac7a84011e27fa47289dc85a0 | /src/main/java/com/creditharmony/loan/borrow/contractAudit/dao/AssistDao.java | 54225de153c923b4cec69a0ee9cf1c8ff7866357 | [] | no_license | sengeiou/chp-loan | https://github.com/sengeiou/chp-loan | f07f200143200a094b2214af05e65a6b223e0334 | e3721669a73f2c5ca4ecc7076ed9ae99409ee5a4 | refs/heads/master | 2020-05-16T02:55:59.463000 | 2017-07-05T10:17:04 | 2017-07-05T10:17:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.creditharmony.loan.borrow.contractAudit.dao;
import com.creditharmony.core.persistence.CrudDao;
import com.creditharmony.core.persistence.annotation.LoanBatisDao;
import com.creditharmony.loan.borrow.contractAudit.entity.Assist;
@LoanBatisDao
public interface AssistDao extends CrudDao<Assist>{
void updateAssist(Assist assist);
void updateAuditOperator(Assist assist);
}
| UTF-8 | Java | 405 | java | AssistDao.java | Java | [] | null | [] | package com.creditharmony.loan.borrow.contractAudit.dao;
import com.creditharmony.core.persistence.CrudDao;
import com.creditharmony.core.persistence.annotation.LoanBatisDao;
import com.creditharmony.loan.borrow.contractAudit.entity.Assist;
@LoanBatisDao
public interface AssistDao extends CrudDao<Assist>{
void updateAssist(Assist assist);
void updateAuditOperator(Assist assist);
}
| 405 | 0.809877 | 0.809877 | 13 | 29.153847 | 26.135288 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 2 |
337136a713405a4864abd031ae20fa9ca6da00df | 3,272,765,101,182 | 161609f2bbbee817ccf9b6fe8aad4bc6fa320f99 | /trunk/obsolete/LFEVCell/app/src/main/java/com/lafayette/lfevcell/DashFragment.java | 39b343e57e7f93130cd34e567b0b19f5eed105a7 | [] | no_license | LafayetteFormulaElectricVehicle/Cell-Phone-App | https://github.com/LafayetteFormulaElectricVehicle/Cell-Phone-App | 881b399a756c3f5404b50bbd4fd537e6a0d3cdb2 | 3ce4af8bfea1a2e0b0a14aff256338d150193cac | refs/heads/master | 2021-01-11T15:09:24.672000 | 2017-04-26T15:25:45 | 2017-04-26T15:25:45 | 80,302,085 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lafayette.lfevcell;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by birrur on 3/7/2017.
*/
public class DashFragment extends Fragment {
TextView mainText;
DataGetter dg = new DataGetter();
String json = "PAR";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dash_layout,null);
mainText = (TextView) view.findViewById(R.id.textView);
Log.d("GG", json+"HHHHHHHHHH");
Log.d("GOT", "GOT HERE");
new Rush().execute();
return view;
}
private class Rush extends AsyncTask <Void, Void, String> {
@Override
protected String doInBackground(Void... arg0) {
return makePostRequest();
}
private String makePostRequest() {
StringBuilder result = null;
HttpURLConnection conn;
BufferedReader rd;
URL url;
String line;
try {
url = new URL("http://139.147.205.144:3000/dbquery/recent");
Log.d("GOT", "PAST URL");
result = new StringBuilder();
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException i){
i.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
json = result.toString();
Log.d("RESPONSE: ", json);
if(json != null){
mainText.setText(json);
}
return json;
}
protected void onPostExecute(String json){
super.onPostExecute(json);
}
}
} | UTF-8 | Java | 2,544 | java | DashFragment.java | Java | [
{
"context": "Exception;\nimport java.net.URL;\n\n/**\n * Created by birrur on 3/7/2017.\n */\n\npublic class DashFragment exten",
"end": 536,
"score": 0.9997100830078125,
"start": 530,
"tag": "USERNAME",
"value": "birrur"
},
{
"context": " try {\n url = new URL(\"http://139.147.205.144:3000/dbquery/recent\");\n Log.d(\"GOT",
"end": 1538,
"score": 0.9926870465278625,
"start": 1523,
"tag": "IP_ADDRESS",
"value": "139.147.205.144"
}
] | null | [] | package com.lafayette.lfevcell;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by birrur on 3/7/2017.
*/
public class DashFragment extends Fragment {
TextView mainText;
DataGetter dg = new DataGetter();
String json = "PAR";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dash_layout,null);
mainText = (TextView) view.findViewById(R.id.textView);
Log.d("GG", json+"HHHHHHHHHH");
Log.d("GOT", "GOT HERE");
new Rush().execute();
return view;
}
private class Rush extends AsyncTask <Void, Void, String> {
@Override
protected String doInBackground(Void... arg0) {
return makePostRequest();
}
private String makePostRequest() {
StringBuilder result = null;
HttpURLConnection conn;
BufferedReader rd;
URL url;
String line;
try {
url = new URL("http://172.16.17.32:3000/dbquery/recent");
Log.d("GOT", "PAST URL");
result = new StringBuilder();
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException i){
i.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
json = result.toString();
Log.d("RESPONSE: ", json);
if(json != null){
mainText.setText(json);
}
return json;
}
protected void onPostExecute(String json){
super.onPostExecute(json);
}
}
} | 2,541 | 0.585299 | 0.575865 | 85 | 28.941177 | 20.634268 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.658824 | false | false | 2 |
79f586557c8db7eec9ed3bf00b7e7b0ae1228df2 | 13,262,859,039,013 | b2962f24a4aad3369c8699e3d93457dede26053e | /TreinamentoFundamentos/src/java/objetos/Produto.java | d4ad6cf5373d6bddd6741f6717c903b47b6e2ed9 | [] | no_license | albinoueg/Java-Primefaces | https://github.com/albinoueg/Java-Primefaces | 388652ce9007e7c23a10e1c7a81b3c5d90b819a1 | 5bd0b91b2eeed01190a85fc44bb11cda7e3b1f18 | refs/heads/master | 2016-05-12T23:16:52.973000 | 2015-10-02T02:02:19 | 2015-10-02T02:02:19 | 43,514,653 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package objetos;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@RequestScoped
public class Produto {
private String dbUrl = "jdbc:mysql://localhost/teste";
private Connection con = null;
private String nome;
private String usuario = "root";
private String senha = "root";
private Produto selecionado;
public Produto() {
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<String> retornaProdutosString(String query){
try {
List<String> nomes = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(dbUrl, usuario, senha);
Statement stmt = con.createStatement();
String sqlStmt = "SELECT nome "
+ "FROM produtos "
+ "ORDER BY NOME";
ResultSet rSet = stmt.executeQuery(sqlStmt);
ResultSetMetaData rsMetaData = (ResultSetMetaData)rSet.getMetaData();
while(rSet.next()){
for(int i = 1; i <= rsMetaData.getColumnCount(); i++){
nomes.add(query+rSet.getObject(i));}
}
return nomes;
} catch (Exception e) {
System.out.println("Erro -> " + e.getMessage());
return null;
}
}
public String retornaId(){
try {
String id = new String();
Class.forName("com.mysqljdbcDriver").newInstance();
con = DriverManager.getConnection(dbUrl, usuario, senha);
Statement stmt = con.createStatement();
String sqlStmt = "SELECT id_produto "
+ " FROM produtos "
+ "WHERE nome= '"+getNome()+"'";
ResultSet rSet = stmt.executeQuery(sqlStmt);
while (rSet.next()){
id = rSet.getString("id_produto");
}
return id;
} catch (Exception e) {
System.out.println("Erro -> " + e.getMessage());
return null;
}
}
public void showId(ActionEvent actionEvent){
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "O código do produto " + nome, " = " + retornaId()));
}
public Produto getSelecionado(){
return selecionado;
}
public void setSelecionado(Produto selecionado){
this.selecionado = selecionado;
}
}
| UTF-8 | Java | 2,994 | java | Produto.java | Java | [
{
"context": "rivate String nome;\n private String usuario = \"root\";\n private String senha = \"root\";\n private ",
"end": 629,
"score": 0.5766016840934753,
"start": 625,
"tag": "USERNAME",
"value": "root"
},
{
"context": "ing usuario = \"root\";\n private String senha = \"root\";\n private Produto selecionado;\n\n public Pr",
"end": 664,
"score": 0.9990532994270325,
"start": 660,
"tag": "PASSWORD",
"value": "root"
}
] | null | [] | package objetos;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@RequestScoped
public class Produto {
private String dbUrl = "jdbc:mysql://localhost/teste";
private Connection con = null;
private String nome;
private String usuario = "root";
private String senha = "<PASSWORD>";
private Produto selecionado;
public Produto() {
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<String> retornaProdutosString(String query){
try {
List<String> nomes = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(dbUrl, usuario, senha);
Statement stmt = con.createStatement();
String sqlStmt = "SELECT nome "
+ "FROM produtos "
+ "ORDER BY NOME";
ResultSet rSet = stmt.executeQuery(sqlStmt);
ResultSetMetaData rsMetaData = (ResultSetMetaData)rSet.getMetaData();
while(rSet.next()){
for(int i = 1; i <= rsMetaData.getColumnCount(); i++){
nomes.add(query+rSet.getObject(i));}
}
return nomes;
} catch (Exception e) {
System.out.println("Erro -> " + e.getMessage());
return null;
}
}
public String retornaId(){
try {
String id = new String();
Class.forName("com.mysqljdbcDriver").newInstance();
con = DriverManager.getConnection(dbUrl, usuario, senha);
Statement stmt = con.createStatement();
String sqlStmt = "SELECT id_produto "
+ " FROM produtos "
+ "WHERE nome= '"+getNome()+"'";
ResultSet rSet = stmt.executeQuery(sqlStmt);
while (rSet.next()){
id = rSet.getString("id_produto");
}
return id;
} catch (Exception e) {
System.out.println("Erro -> " + e.getMessage());
return null;
}
}
public void showId(ActionEvent actionEvent){
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "O código do produto " + nome, " = " + retornaId()));
}
public Produto getSelecionado(){
return selecionado;
}
public void setSelecionado(Produto selecionado){
this.selecionado = selecionado;
}
}
| 3,000 | 0.57434 | 0.574006 | 96 | 30.177084 | 21.947853 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 2 |
02e5b948ac2862e4778511a5c153f0cd60512288 | 12,386,685,703,304 | cb3f4d4d0782f1f8ec038dafd21ad186ed00fc4c | /notifier-model/src/main/java/notifier/HighPriority.java | 94dec893bf27322f924591dc7811b47b73f8adfe | [] | no_license | to2-mosti/Notifier | https://github.com/to2-mosti/Notifier | 3473bf02e20039dd31d565838831b89f0bc6ac2b | 2cd83ab883342e757f2a17938c8800713d27b181 | refs/heads/master | 2018-01-11T18:08:44.606000 | 2015-11-19T20:24:26 | 2015-11-19T20:24:26 | 45,401,223 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package notifier;
import comparator.DiffRepresentation;
/**
* Created by anna on 19.11.15.
*/
public class HighPriority extends NotifierFactory {
public HighPriority(DiffRepresentation diff) {
super(diff);
}
@Override
public void createMessage() {
if(diff.getMessageType() == "email"){
Sender sender = new EmailSender();
sender.send(diff);
} else if (diff.getMessageType() == "sms"){
Sender sender = new SmsSender();
sender.send(diff);
}
}
}
| UTF-8 | Java | 550 | java | HighPriority.java | Java | [
{
"context": " comparator.DiffRepresentation;\n\n/**\n * Created by anna on 19.11.15.\n */\npublic class HighPriority extend",
"end": 80,
"score": 0.9421771168708801,
"start": 76,
"tag": "USERNAME",
"value": "anna"
}
] | null | [] | package notifier;
import comparator.DiffRepresentation;
/**
* Created by anna on 19.11.15.
*/
public class HighPriority extends NotifierFactory {
public HighPriority(DiffRepresentation diff) {
super(diff);
}
@Override
public void createMessage() {
if(diff.getMessageType() == "email"){
Sender sender = new EmailSender();
sender.send(diff);
} else if (diff.getMessageType() == "sms"){
Sender sender = new SmsSender();
sender.send(diff);
}
}
}
| 550 | 0.590909 | 0.58 | 26 | 20.153847 | 19.060011 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false | 2 |
bd5f82e968a5065b9a3f48108f033d10d26667d5 | 11,227,044,563,213 | 5aacb2b8ae820562606ef4c29a3a6ee3f263be21 | /app/src/main/java/com/along/android/healthmanagement/fragments/vitalsigns/VitalSignTabFragment.java | 043c17992965d27340484b17c27869521664cbb3 | [] | no_license | cqlzx/health-management | https://github.com/cqlzx/health-management | 370b820f83cee45a47028f14dd430a26b2eb6295 | 6d0a363a647c81c49269fd26b2b371ac9facf26e | refs/heads/master | 2021-09-10T20:06:42.191000 | 2017-05-01T16:51:26 | 2017-05-01T16:51:26 | 80,044,563 | 3 | 1 | null | false | 2018-03-18T07:52:07 | 2017-01-25T18:36:12 | 2017-10-01T06:47:16 | 2017-05-01T16:51:31 | 25,760 | 1 | 2 | 1 | Java | false | null | package com.along.android.healthmanagement.fragments.vitalsigns;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.along.android.healthmanagement.R;
import com.along.android.healthmanagement.activities.VitalSignDetailsActivity;
import com.along.android.healthmanagement.adapters.VitalSignsHistoryAdapter;
import com.along.android.healthmanagement.entities.User;
import com.along.android.healthmanagement.entities.VitalSign;
import com.along.android.healthmanagement.fragments.BasicFragment;
import com.along.android.healthmanagement.fragments.DatePickerFragment;
import com.along.android.healthmanagement.helpers.EntityManager;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class VitalSignTabFragment extends BasicFragment {
TextView tvStartDateVitalSignInMillis;
TextView tvEndDateVitalSignInMillis;
VitalSignsHistoryAdapter vitalSignsHistoryAdapter;
public VitalSignTabFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_vital_signs, container, false);
tvStartDateVitalSignInMillis = (TextView) view.findViewById(R.id.tvStartDateVitalSignInMillis);
tvEndDateVitalSignInMillis = (TextView) view.findViewById(R.id.tvEndDateVitalSignInMillis);
//Dummy data, comment when demo
SharedPreferences sp = getActivity().getSharedPreferences("Login", Context.MODE_PRIVATE);
long uid = sp.getLong("uid", 0);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
EntityManager.deleteAll(VitalSign.class);
for (int i = 1; i < 10; i++) {
VitalSign vs = new VitalSign();
vs.setUid(uid);
vs.setHeight("5.6");
vs.setWeight("170");
vs.setBloodGlucose("22");
vs.setBloodPressure("120/80");
vs.setHeartRate("70");
vs.setBodyTemperature("104");
calendar.clear();
calendar.set(year, month, day - i * i);
vs.setDate(calendar.getTimeInMillis());
vs.save();
}
List<VitalSign> vitalSignList;
try {
vitalSignList = EntityManager.listAll(VitalSign.class);
} catch (SQLiteException e) {
vitalSignList = new ArrayList<>();
}
LinearLayout llStartDateVitalSign = (LinearLayout) view.findViewById(R.id.llStartDateVitalSign);
llStartDateVitalSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle data = new Bundle();
data.putString("whichDate", "startDateVitalSign");
newFragment.setArguments(data);
newFragment.show(getFragmentManager(), "startDatePicker");
}
});
LinearLayout llEndDateVitalSign = (LinearLayout) view.findViewById(R.id.llEndDateVitalSign);
llEndDateVitalSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle data = new Bundle();
data.putString("whichDate", "endDateVitalSign");
newFragment.setArguments(data);
newFragment.show(getFragmentManager(), "endDatePicker");
}
});
Button btnVitalSignSearch = (Button) view.findViewById(R.id.btnVitalSignSearch);
btnVitalSignSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeVitalSignList();
}
});
ImageView fab = (ImageView) view.findViewById(R.id.add_medication_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Invoke the fragment to add new Vital Signs form
createFragment(new AddVitalSignFormFragment(), "addVitalSignFormFragment");
}
});
if (vitalSignsHistoryAdapter == null) {
vitalSignsHistoryAdapter = new VitalSignsHistoryAdapter(getActivity(), vitalSignList);
} else {
vitalSignsHistoryAdapter.clear();
vitalSignsHistoryAdapter.addAll(vitalSignList);
vitalSignsHistoryAdapter.notifyDataSetChanged();
}
ListView listView = (ListView) view.findViewById(R.id.vital_signs_history_list);
TextView tvEmptyMsg = (TextView) view.findViewById(R.id.tvVSEmptyMsg);
listView.setEmptyView(tvEmptyMsg);
listView.setAdapter(vitalSignsHistoryAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView vitalSignId = (TextView) view.findViewById(R.id.tvXLVSHId);
TextView vitalSignDate = (TextView) view.findViewById(R.id.tvXLVSHDate);
Intent vitalSignDetailsIntent = new Intent(getActivity(), VitalSignDetailsActivity.class);
vitalSignDetailsIntent.putExtra("selectedVitalSignItemId", vitalSignId.getText().toString());
vitalSignDetailsIntent.putExtra("selectedVitalSignItemDate", vitalSignDate.getText().toString());
startActivity(vitalSignDetailsIntent);
}
});
return view;
}
private void changeVitalSignList() {
String startTime = tvStartDateVitalSignInMillis.getText().toString();
String endTime = tvEndDateVitalSignInMillis.getText().toString();
List<VitalSign> vitalSigns;
if (!startTime.equals("Start date in millis") && !endTime.equals("End date in millis")) {
vitalSigns = EntityManager.findWithQuery(VitalSign.class, "SELECT * FROM VITAL_SIGN WHERE date >= ? AND date <= ?", startTime, endTime);
} else if (!startTime.equals("Start date in millis")) {
vitalSigns = EntityManager.findWithQuery(VitalSign.class, "SELECT * FROM VITAL_SIGN WHERE date >= ?", startTime);
} else if (!endTime.equals("End date in millis")) {
vitalSigns = EntityManager.findWithQuery(VitalSign.class, "SELECT * FROM VITAL_SIGN WHERE date <= ?", endTime);
} else {
vitalSigns = EntityManager.listAll(VitalSign.class);
}
vitalSignsHistoryAdapter.clear();
vitalSignsHistoryAdapter.addAll(vitalSigns);
vitalSignsHistoryAdapter.notifyDataSetChanged();
}
}
| UTF-8 | Java | 7,701 | java | VitalSignTabFragment.java | Java | [] | null | [] | package com.along.android.healthmanagement.fragments.vitalsigns;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.along.android.healthmanagement.R;
import com.along.android.healthmanagement.activities.VitalSignDetailsActivity;
import com.along.android.healthmanagement.adapters.VitalSignsHistoryAdapter;
import com.along.android.healthmanagement.entities.User;
import com.along.android.healthmanagement.entities.VitalSign;
import com.along.android.healthmanagement.fragments.BasicFragment;
import com.along.android.healthmanagement.fragments.DatePickerFragment;
import com.along.android.healthmanagement.helpers.EntityManager;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class VitalSignTabFragment extends BasicFragment {
TextView tvStartDateVitalSignInMillis;
TextView tvEndDateVitalSignInMillis;
VitalSignsHistoryAdapter vitalSignsHistoryAdapter;
public VitalSignTabFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_vital_signs, container, false);
tvStartDateVitalSignInMillis = (TextView) view.findViewById(R.id.tvStartDateVitalSignInMillis);
tvEndDateVitalSignInMillis = (TextView) view.findViewById(R.id.tvEndDateVitalSignInMillis);
//Dummy data, comment when demo
SharedPreferences sp = getActivity().getSharedPreferences("Login", Context.MODE_PRIVATE);
long uid = sp.getLong("uid", 0);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
EntityManager.deleteAll(VitalSign.class);
for (int i = 1; i < 10; i++) {
VitalSign vs = new VitalSign();
vs.setUid(uid);
vs.setHeight("5.6");
vs.setWeight("170");
vs.setBloodGlucose("22");
vs.setBloodPressure("120/80");
vs.setHeartRate("70");
vs.setBodyTemperature("104");
calendar.clear();
calendar.set(year, month, day - i * i);
vs.setDate(calendar.getTimeInMillis());
vs.save();
}
List<VitalSign> vitalSignList;
try {
vitalSignList = EntityManager.listAll(VitalSign.class);
} catch (SQLiteException e) {
vitalSignList = new ArrayList<>();
}
LinearLayout llStartDateVitalSign = (LinearLayout) view.findViewById(R.id.llStartDateVitalSign);
llStartDateVitalSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle data = new Bundle();
data.putString("whichDate", "startDateVitalSign");
newFragment.setArguments(data);
newFragment.show(getFragmentManager(), "startDatePicker");
}
});
LinearLayout llEndDateVitalSign = (LinearLayout) view.findViewById(R.id.llEndDateVitalSign);
llEndDateVitalSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle data = new Bundle();
data.putString("whichDate", "endDateVitalSign");
newFragment.setArguments(data);
newFragment.show(getFragmentManager(), "endDatePicker");
}
});
Button btnVitalSignSearch = (Button) view.findViewById(R.id.btnVitalSignSearch);
btnVitalSignSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeVitalSignList();
}
});
ImageView fab = (ImageView) view.findViewById(R.id.add_medication_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Invoke the fragment to add new Vital Signs form
createFragment(new AddVitalSignFormFragment(), "addVitalSignFormFragment");
}
});
if (vitalSignsHistoryAdapter == null) {
vitalSignsHistoryAdapter = new VitalSignsHistoryAdapter(getActivity(), vitalSignList);
} else {
vitalSignsHistoryAdapter.clear();
vitalSignsHistoryAdapter.addAll(vitalSignList);
vitalSignsHistoryAdapter.notifyDataSetChanged();
}
ListView listView = (ListView) view.findViewById(R.id.vital_signs_history_list);
TextView tvEmptyMsg = (TextView) view.findViewById(R.id.tvVSEmptyMsg);
listView.setEmptyView(tvEmptyMsg);
listView.setAdapter(vitalSignsHistoryAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView vitalSignId = (TextView) view.findViewById(R.id.tvXLVSHId);
TextView vitalSignDate = (TextView) view.findViewById(R.id.tvXLVSHDate);
Intent vitalSignDetailsIntent = new Intent(getActivity(), VitalSignDetailsActivity.class);
vitalSignDetailsIntent.putExtra("selectedVitalSignItemId", vitalSignId.getText().toString());
vitalSignDetailsIntent.putExtra("selectedVitalSignItemDate", vitalSignDate.getText().toString());
startActivity(vitalSignDetailsIntent);
}
});
return view;
}
private void changeVitalSignList() {
String startTime = tvStartDateVitalSignInMillis.getText().toString();
String endTime = tvEndDateVitalSignInMillis.getText().toString();
List<VitalSign> vitalSigns;
if (!startTime.equals("Start date in millis") && !endTime.equals("End date in millis")) {
vitalSigns = EntityManager.findWithQuery(VitalSign.class, "SELECT * FROM VITAL_SIGN WHERE date >= ? AND date <= ?", startTime, endTime);
} else if (!startTime.equals("Start date in millis")) {
vitalSigns = EntityManager.findWithQuery(VitalSign.class, "SELECT * FROM VITAL_SIGN WHERE date >= ?", startTime);
} else if (!endTime.equals("End date in millis")) {
vitalSigns = EntityManager.findWithQuery(VitalSign.class, "SELECT * FROM VITAL_SIGN WHERE date <= ?", endTime);
} else {
vitalSigns = EntityManager.listAll(VitalSign.class);
}
vitalSignsHistoryAdapter.clear();
vitalSignsHistoryAdapter.addAll(vitalSigns);
vitalSignsHistoryAdapter.notifyDataSetChanged();
}
}
| 7,701 | 0.67251 | 0.669523 | 197 | 38.09137 | 32.195183 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.690355 | false | false | 2 |
e861d2d1c29864cb4cc538d66da95d7351b34ced | 6,743,098,701,327 | c3a1ff3575ade0310f92909797594392fb517278 | /src/main/java/com/servicemanager/tasks/TaskAttachBlockVolumesToVM.java | 57d0a35957ccfbb150df6ad9a77199af4a558b51 | [] | no_license | gmhoolageri/Helidon_TX | https://github.com/gmhoolageri/Helidon_TX | 49ffe087c7474a1ffab204af1b6d6636f2d28123 | 379e3967febb914031dcd51cccdf854f2d512a4c | refs/heads/master | 2022-01-01T08:19:28.291000 | 2020-02-27T17:02:24 | 2020-02-27T17:02:24 | 243,558,937 | 0 | 0 | null | false | 2021-12-14T20:47:32 | 2020-02-27T16:11:23 | 2020-02-27T17:02:26 | 2021-12-14T20:47:30 | 45,161 | 0 | 0 | 2 | Java | false | false | package com.servicemanager.tasks;
import com.servicemanager.valueobjects.ResponsePayloadVO;
public class TaskAttachBlockVolumesToVM extends Task {
@Override
protected boolean canThisTaskBeSkipped() {
// TODO Auto-generated method stub
return false;
}
@Override
protected ResponsePayloadVO callTask() throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
protected void rollback() {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 529 | java | TaskAttachBlockVolumesToVM.java | Java | [] | null | [] | package com.servicemanager.tasks;
import com.servicemanager.valueobjects.ResponsePayloadVO;
public class TaskAttachBlockVolumesToVM extends Task {
@Override
protected boolean canThisTaskBeSkipped() {
// TODO Auto-generated method stub
return false;
}
@Override
protected ResponsePayloadVO callTask() throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
protected void rollback() {
// TODO Auto-generated method stub
}
}
| 529 | 0.68242 | 0.68242 | 25 | 20.16 | 20.598408 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.16 | false | false | 3 |
cc597af6d647c4cbb5d3c4867ed8f08b634be842 | 33,285,996,585,597 | 1eded95950e95dc2a1dd782dbb9c0862ab1e5234 | /TestEstructuras1/c15.s1380.kaosako.P4C_15-2.java.0.Main.java | 0c8c0bd07a6360f30ae558f2a5a94f30a9876960 | [] | no_license | LaurAlejandraC/AutomaticPlagiarismDetection | https://github.com/LaurAlejandraC/AutomaticPlagiarismDetection | 140c2b4828b04bf2ae41654ca1422bc13ed0ae85 | fca410fe6eea05ad5d8c82332bad06a9ef872c7c | refs/heads/master | 2021-01-10T16:54:48.146000 | 2016-04-28T05:32:36 | 2016-04-28T05:32:36 | 51,723,869 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
static class TreeNode{
private int value;
private TreeNode childR;
private TreeNode childL;
private TreeNode(){
value=0;
childR=null;
childL=null;
}
public boolean isSheet(){
return (childR==null&&childL==null);
}
public int addCompare(int val, int compare, TreeNode node) {
if(node.isSheet()&&node.value==0){
node.value= val;
return compare;
}else if(val<node.value){
if(node.childL==null) node.childL= new TreeNode();
return 1+addCompare(val, compare, node.childL);
}else if(val>node.value){
if(node.childR==null) node.childR= new TreeNode();
return 1+addCompare(val, compare, node.childR);
}else{
return 0;
}
}
}
public static void main(String[] args){
String line = "";
int cases=0;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
line = br.readLine();
cases = Integer.parseInt(line);
for(int i=1;i<=cases;i++){
System.out.println("Case #"+i+":");
ArrayList numbers = new ArrayList<>(Integer.parseInt(br.readLine()));
numbers = addElements(br.readLine());
int firstCompared=0;
int secoundCompared=0;
firstCompared = compare(numbers);
numbers=order(numbers);
ArrayList newNumbers = new ArrayList<Integer>();
bestOrder(numbers, newNumbers,0,numbers.size()-1);
secoundCompared = compare(newNumbers);
System.out.println(firstCompared+" "+secoundCompared);
}
}catch(Exception e){
e.printStackTrace();
}
}
private static int compare(ArrayList numbers) {
TreeNode node=new TreeNode();
int quantit=0;
for(int i=0; i<numbers.size();i++){
quantit = quantit + node.addCompare((int) numbers.get(i), 0, node);
}
return quantit;
}
private static void bestOrder(ArrayList<Integer> numbers, ArrayList<Integer> n, int min, int max ) {
if(max==min){
n.add(numbers.get(min));
}else if((max-min)==1){
n.add(numbers.get(min));
n.add(numbers.get(max));
}else{
int mitad = (int)Math.ceil( (double)(max-min)/2 ) + min;
n.add(numbers.get(mitad));
bestOrder(numbers, n, min, mitad-1);
bestOrder(numbers, n, mitad+1, max);
}
}
private static ArrayList order(ArrayList<Integer> numbers) {
for(int i=0;i<(numbers.size()-1);i++){
for(int j=i+1;j<numbers.size();j++){
if(numbers.get(i)>numbers.get(j)){
int temp=numbers.get(i);
numbers.set(i,numbers.get(j));
numbers.set(j,temp);
}
}
}
return numbers;
}
private static ArrayList addElements(String numbers) {
String[] elements = numbers.split(" ");
ArrayList finalList = new ArrayList(elements.length);
for(int i=0;i<elements.length;i++){
finalList.add(Integer.parseInt(elements[i]));
}
return finalList;
}
} | UTF-8 | Java | 3,600 | java | c15.s1380.kaosako.P4C_15-2.java.0.Main.java | Java | [] | null | [] | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
static class TreeNode{
private int value;
private TreeNode childR;
private TreeNode childL;
private TreeNode(){
value=0;
childR=null;
childL=null;
}
public boolean isSheet(){
return (childR==null&&childL==null);
}
public int addCompare(int val, int compare, TreeNode node) {
if(node.isSheet()&&node.value==0){
node.value= val;
return compare;
}else if(val<node.value){
if(node.childL==null) node.childL= new TreeNode();
return 1+addCompare(val, compare, node.childL);
}else if(val>node.value){
if(node.childR==null) node.childR= new TreeNode();
return 1+addCompare(val, compare, node.childR);
}else{
return 0;
}
}
}
public static void main(String[] args){
String line = "";
int cases=0;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
line = br.readLine();
cases = Integer.parseInt(line);
for(int i=1;i<=cases;i++){
System.out.println("Case #"+i+":");
ArrayList numbers = new ArrayList<>(Integer.parseInt(br.readLine()));
numbers = addElements(br.readLine());
int firstCompared=0;
int secoundCompared=0;
firstCompared = compare(numbers);
numbers=order(numbers);
ArrayList newNumbers = new ArrayList<Integer>();
bestOrder(numbers, newNumbers,0,numbers.size()-1);
secoundCompared = compare(newNumbers);
System.out.println(firstCompared+" "+secoundCompared);
}
}catch(Exception e){
e.printStackTrace();
}
}
private static int compare(ArrayList numbers) {
TreeNode node=new TreeNode();
int quantit=0;
for(int i=0; i<numbers.size();i++){
quantit = quantit + node.addCompare((int) numbers.get(i), 0, node);
}
return quantit;
}
private static void bestOrder(ArrayList<Integer> numbers, ArrayList<Integer> n, int min, int max ) {
if(max==min){
n.add(numbers.get(min));
}else if((max-min)==1){
n.add(numbers.get(min));
n.add(numbers.get(max));
}else{
int mitad = (int)Math.ceil( (double)(max-min)/2 ) + min;
n.add(numbers.get(mitad));
bestOrder(numbers, n, min, mitad-1);
bestOrder(numbers, n, mitad+1, max);
}
}
private static ArrayList order(ArrayList<Integer> numbers) {
for(int i=0;i<(numbers.size()-1);i++){
for(int j=i+1;j<numbers.size();j++){
if(numbers.get(i)>numbers.get(j)){
int temp=numbers.get(i);
numbers.set(i,numbers.get(j));
numbers.set(j,temp);
}
}
}
return numbers;
}
private static ArrayList addElements(String numbers) {
String[] elements = numbers.split(" ");
ArrayList finalList = new ArrayList(elements.length);
for(int i=0;i<elements.length;i++){
finalList.add(Integer.parseInt(elements[i]));
}
return finalList;
}
} | 3,600 | 0.519722 | 0.513611 | 98 | 35.734695 | 21.493498 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.867347 | false | false | 3 |
f9ce7c54f896f3f651a4bbbb3cfd8be4dcbbcda9 | 22,960,895,230,622 | b81f47f166fb69787bafc5f1e34a6f9d4fa86164 | /src/inventoryManager/InventorySQLTable.java | bea0546cc2db3e3205360a8c10dff8e005489898 | [] | no_license | rt778/myERP | https://github.com/rt778/myERP | a63bdad0b3a6524933e2cab44435fd9bd5fd0b64 | dcc6e792e28b2ec5674e009fc82e2c6c4b8886ea | refs/heads/main | 2023-04-03T22:50:45.877000 | 2021-04-22T14:21:22 | 2021-04-22T14:21:22 | 360,544,867 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package inventoryManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import connectionManager.MySQLConnection;
import interfaceManager.AllocateToContractForm;
import interfaceManager.InventoryJTable;
public class InventorySQLTable {
private static Connection myConnection;
public void createInventorySQLTable(){
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
String sqlCommand = "CREATE TABLE if not exists Inventory"
+ "(LotNumber VARCHAR(20) PRIMARY KEY NOT NULL, "
+ "ProductStored VARCHAR(20) NOT NULL, "
+ "QuantityStored DOUBLE UNSIGNED NOT NULL, "
+ "EntryDate DATE NOT NULL,"
+ "ExitDate DATE DEFAULT NULL,"
+ "StorageLocation VARCHAR(50) NOT NULL, "
+ "SoldToContractNumber VARCHAR(20));";
try{
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
sqle.printStackTrace();
}
}
public void addInventoryToSQLTable (Inventory inv){
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
String sqlCommand = "INSERT INTO Inventory ("
+ "LotNumber, "
+ "ProductStored, "
+ "QuantityStored, "
+ "EntryDate, "
+ "ExitDate, "
+ "StorageLocation, "
+ "SoldToContractNumber) "
+ "VALUES (\""
+ inv.getLotNumber() + "\", \""
+ inv.getProductStored() + "\",\""
+ inv.getQuantityStored() + "\",\""
+ inv.getEntryDate() + "\","
+ inv.getExitDate() + ",\""
+ inv.getStorageLocation() + "\", \""
+ inv.getSoldToContractNumber() + "\")";
try{
System.out.println(sqlCommand);
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
//sqle.printStackTrace();
JOptionPane.showMessageDialog(null, "Something went wrong. Please verify your inputs.");
}
}
public void deleteInventoryFromSQLTable (Inventory inv){
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
String sqlCommand = "DELETE FROM Inventory WHERE LotNumber = \"" + inv.getLotNumber() + "\";";
System.out.println(sqlCommand);
try{
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
//sqle.printStackTrace();
}
}
public static void allocateLotToSales(){
System.out.println("Calling allocateLotToSales from inventoryManager.InventorySQLTable.");
System.out.println("Sales Contract to allocate: " + AllocateToContractForm.contractId);
System.out.println("Lot number being allocated: " + InventoryJTable.valueInventoryJTableColumn0);
String sqlCommand = "UPDATE Inventory SET SoldToContractNumber = \""
+ AllocateToContractForm.contractId + "\" WHERE LotNumber = \""
+ InventoryJTable.valueInventoryJTableColumn0 + "\";";
System.out.println(sqlCommand);
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
try{
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
//sqle.printStackTrace();
}
}
public List<Inventory> readDbInventoryTable(){
String sqlCommand = "SELECT * FROM Inventory";
List<Inventory> listOfInventory = new ArrayList<Inventory>();
try{
Statement statement1 = myConnection.createStatement();
ResultSet resultSet1 = statement1.executeQuery(sqlCommand);
while (resultSet1.next()){
String lotNumber = resultSet1.getString("LotNumber");
String productStored = resultSet1.getString("ProductStored");
double quantityStored = resultSet1.getDouble("QuantityStored");
String entryDate = resultSet1.getString("EntryDate");
String exitDate = resultSet1.getString("ExitDate");
String storageLocation = resultSet1.getString("StorageLocation");
String soldToContractNumber = resultSet1.getString("SoldToContractNumber");
Inventory inv = new Inventory();
inv.setLotNumber(lotNumber);
inv.setProductStored(productStored);
inv.setQuantityStored(quantityStored);
inv.setEntryDate(entryDate);
inv.setExitDate(exitDate);
inv.setStorageLocation(storageLocation);
inv.setSoldToContractNumber(soldToContractNumber);
listOfInventory.add(inv);
}
resultSet1.close();
statement1.close();
return listOfInventory ;
}
catch (SQLException sqle){
sqle.printStackTrace();
return listOfInventory;
}
}
public static void main(String[] args) {
try{
InventorySQLTable inventoryTable = new InventorySQLTable();
inventoryTable.createInventorySQLTable();
Inventory inv1 = new Inventory();
inv1.setEntryDate("2017-07-21");
//inv1.setExitDate("'2017-07-22'");// we need to quote 2 times here like this: "''";
inv1.setLotNumber("17-07211143");
inv1.setProductStored("BK");
inv1.setQuantityStored(25.92);
inv1.setStorageLocation("STP");
inventoryTable.addInventoryToSQLTable(inv1);
}
catch (Exception e)
{
//e.printStackTrace();
}
}
}
| UTF-8 | Java | 5,449 | java | InventorySQLTable.java | Java | [] | null | [] | package inventoryManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import connectionManager.MySQLConnection;
import interfaceManager.AllocateToContractForm;
import interfaceManager.InventoryJTable;
public class InventorySQLTable {
private static Connection myConnection;
public void createInventorySQLTable(){
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
String sqlCommand = "CREATE TABLE if not exists Inventory"
+ "(LotNumber VARCHAR(20) PRIMARY KEY NOT NULL, "
+ "ProductStored VARCHAR(20) NOT NULL, "
+ "QuantityStored DOUBLE UNSIGNED NOT NULL, "
+ "EntryDate DATE NOT NULL,"
+ "ExitDate DATE DEFAULT NULL,"
+ "StorageLocation VARCHAR(50) NOT NULL, "
+ "SoldToContractNumber VARCHAR(20));";
try{
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
sqle.printStackTrace();
}
}
public void addInventoryToSQLTable (Inventory inv){
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
String sqlCommand = "INSERT INTO Inventory ("
+ "LotNumber, "
+ "ProductStored, "
+ "QuantityStored, "
+ "EntryDate, "
+ "ExitDate, "
+ "StorageLocation, "
+ "SoldToContractNumber) "
+ "VALUES (\""
+ inv.getLotNumber() + "\", \""
+ inv.getProductStored() + "\",\""
+ inv.getQuantityStored() + "\",\""
+ inv.getEntryDate() + "\","
+ inv.getExitDate() + ",\""
+ inv.getStorageLocation() + "\", \""
+ inv.getSoldToContractNumber() + "\")";
try{
System.out.println(sqlCommand);
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
//sqle.printStackTrace();
JOptionPane.showMessageDialog(null, "Something went wrong. Please verify your inputs.");
}
}
public void deleteInventoryFromSQLTable (Inventory inv){
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
String sqlCommand = "DELETE FROM Inventory WHERE LotNumber = \"" + inv.getLotNumber() + "\";";
System.out.println(sqlCommand);
try{
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
//sqle.printStackTrace();
}
}
public static void allocateLotToSales(){
System.out.println("Calling allocateLotToSales from inventoryManager.InventorySQLTable.");
System.out.println("Sales Contract to allocate: " + AllocateToContractForm.contractId);
System.out.println("Lot number being allocated: " + InventoryJTable.valueInventoryJTableColumn0);
String sqlCommand = "UPDATE Inventory SET SoldToContractNumber = \""
+ AllocateToContractForm.contractId + "\" WHERE LotNumber = \""
+ InventoryJTable.valueInventoryJTableColumn0 + "\";";
System.out.println(sqlCommand);
try {
myConnection = new MySQLConnection().getConnection();
} catch (Exception e) {
//e.printStackTrace();
}
try{
Statement st = myConnection.createStatement();
st.executeUpdate(sqlCommand);
st.close();
}
catch (SQLException sqle){
//sqle.printStackTrace();
}
}
public List<Inventory> readDbInventoryTable(){
String sqlCommand = "SELECT * FROM Inventory";
List<Inventory> listOfInventory = new ArrayList<Inventory>();
try{
Statement statement1 = myConnection.createStatement();
ResultSet resultSet1 = statement1.executeQuery(sqlCommand);
while (resultSet1.next()){
String lotNumber = resultSet1.getString("LotNumber");
String productStored = resultSet1.getString("ProductStored");
double quantityStored = resultSet1.getDouble("QuantityStored");
String entryDate = resultSet1.getString("EntryDate");
String exitDate = resultSet1.getString("ExitDate");
String storageLocation = resultSet1.getString("StorageLocation");
String soldToContractNumber = resultSet1.getString("SoldToContractNumber");
Inventory inv = new Inventory();
inv.setLotNumber(lotNumber);
inv.setProductStored(productStored);
inv.setQuantityStored(quantityStored);
inv.setEntryDate(entryDate);
inv.setExitDate(exitDate);
inv.setStorageLocation(storageLocation);
inv.setSoldToContractNumber(soldToContractNumber);
listOfInventory.add(inv);
}
resultSet1.close();
statement1.close();
return listOfInventory ;
}
catch (SQLException sqle){
sqle.printStackTrace();
return listOfInventory;
}
}
public static void main(String[] args) {
try{
InventorySQLTable inventoryTable = new InventorySQLTable();
inventoryTable.createInventorySQLTable();
Inventory inv1 = new Inventory();
inv1.setEntryDate("2017-07-21");
//inv1.setExitDate("'2017-07-22'");// we need to quote 2 times here like this: "''";
inv1.setLotNumber("17-07211143");
inv1.setProductStored("BK");
inv1.setQuantityStored(25.92);
inv1.setStorageLocation("STP");
inventoryTable.addInventoryToSQLTable(inv1);
}
catch (Exception e)
{
//e.printStackTrace();
}
}
}
| 5,449 | 0.686364 | 0.674986 | 214 | 24.462616 | 23.139076 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.785047 | false | false | 3 |
c5a753e5521162e9e5833ccd73b86d9017e036a6 | 1,906,965,530,017 | 6112351988dd8461c6d6d150b0258a1c6c8a3891 | /src/main/java/com/javaheroku/javasummery/controllers/week03/Digits_Sum.java | 91b606ed47c002b5c39c02dec65474f537b80d25 | [] | no_license | yoyoisaboy/Java_Summery | https://github.com/yoyoisaboy/Java_Summery | a9731715febe98c3a7271f7f1e32063152d9829e | 7f7e3d6d4ce3936881a3846a962e759373abe20a | refs/heads/master | 2023-07-07T05:13:01.864000 | 2021-08-05T04:36:45 | 2021-08-05T04:36:45 | 383,133,422 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Scanner;
public class Digits_Sum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Integer count = input.nextInt();
while(count-->0){
Long target = input.nextLong();
System.out.println( Math.max( (int)(target+1)/10 , target/10) );
}
}
}
| UTF-8 | Java | 427 | java | Digits_Sum.java | Java | [] | null | [] | import java.util.ArrayList;
import java.util.Scanner;
public class Digits_Sum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Integer count = input.nextInt();
while(count-->0){
Long target = input.nextLong();
System.out.println( Math.max( (int)(target+1)/10 , target/10) );
}
}
}
| 427 | 0.526932 | 0.512881 | 18 | 22.722221 | 20.236946 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 3 |
bb7e01da94c8f6f3cb3666a74f27034fc5e08a4d | 15,496,242,054,540 | 6253283b67c01a0d7395e38aeeea65e06f62504b | /decompile/app/Mms/src/main/java/cn/com/xy/sms/sdk/mms/ui/menu/SmartSmsComposeManager.java | d25ea458da35b99d916b0d0e09b9910cf9bdf586 | [] | no_license | sufadi/decompile-hw | https://github.com/sufadi/decompile-hw | 2e0457a0a7ade103908a6a41757923a791248215 | 4c3efd95f3e997b44dd4ceec506de6164192eca3 | refs/heads/master | 2023-03-15T15:56:03.968000 | 2017-11-08T03:29:10 | 2017-11-08T03:29:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.com.xy.sms.sdk.mms.ui.menu;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.SmartSmsSdkUtil;
import cn.com.xy.sms.sdk.db.entity.IccidInfoManager;
import cn.com.xy.sms.sdk.db.entity.PhoneSmsParseManager;
import cn.com.xy.sms.sdk.iccid.IccidLocationUtil;
import cn.com.xy.sms.sdk.ui.bubbleview.DuoquBubbleViewManager;
import cn.com.xy.sms.sdk.ui.menu.PopMenus;
import cn.com.xy.sms.sdk.ui.popu.util.ContentUtil;
import cn.com.xy.sms.sdk.ui.settings.SimCardUtil;
import cn.com.xy.sms.sdk.util.DuoquUtils;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.util.ParseBubbleManager;
import cn.com.xy.sms.util.ParseManager;
import cn.com.xy.sms.util.SdkCallBack;
import com.android.mms.data.Contact;
import com.android.mms.ui.MessageUtils;
import com.android.mms.ui.SmartSmsBubbleManager;
import com.google.android.gms.R;
import com.huawei.cspcommon.MLog;
import com.huawei.mms.util.ResEx;
import com.huawei.mms.util.StatisticalHelper;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SmartSmsComposeManager implements ISmartSmsMenuManager {
private static final String ACTION_DATA = "action_data";
private static final String LOCATION_KEY = "code";
private static final String LOCATION_VALUE_CN = "CN";
private static final String SECONDMENU = "secondmenu";
public static final short SMART_SMS_DUOQU_EVENT_HIDE_EDIT_LAYOUT = (short) 4;
public static final short SMART_SMS_DUOQU_EVENT_HIDE_EDIT_LAYOUT_FIRST_IN = (short) 6;
public static final short SMART_SMS_DUOQU_EVENT_SHOW_EDIT_LAYOUT = (short) 1;
public static final short SMART_SMS_DUOQU_EVENT_SHOW_EDIT_LAYOUT_WITHOUT_ANIMATION = (short) 7;
public static final short SMART_SMS_DUOQU_EVENT_SHOW_VIEW_MENU = (short) 5;
public static final short SMART_SMS_SHOW_MENU_IN_CONVERSATION = (short) 2;
public static final short SMART_SMS_SHOW_MENU_NEW_CONVERSATION = (short) 1;
private final String TAG = "XIAOYUAN";
private LinearLayout mButtonToEditMenu;
private LinearLayout mButtonToSmartMenu;
private Activity mCtx;
private Map<String, String> mExtraMenuDataMap = new HashMap();
private String mFormatNumber;
private Handler mHandler = null;
private ISmartSmsUIHolder mISmartSmsUIHolder;
private boolean mIsInitMenuView = false;
private boolean mIsLoad = false;
private boolean mIsNotifyComposeMessage = true;
private boolean mIsUsedTheme = false;
private LayoutInflater mLayoutInflater = null;
private String mMenuJsonData = null;
private View mMenuRootLayout = null;
private ViewStub mMenuRootStub = null;
LinkedList<SmartSmsBubbleManager> mNeedRefreshBubbleItem = new LinkedList();
private int mNumOperator;
private String mNumber = null;
private PopMenus mPopupWindowCustommenu;
private int mSelectedSimIndex = 0;
private LinearLayout mSmartMenuContent;
private RelativeLayout mSmartMenuLayout;
private static class BeforeInitBubbleRunnable implements Runnable {
private JSONObject mObj = null;
private String mPhoneNumber = null;
private WeakReference<Activity> mReference = null;
public BeforeInitBubbleRunnable(Activity ctx, String num, JSONObject obj) {
this.mPhoneNumber = num;
this.mReference = new WeakReference(ctx);
this.mObj = obj;
}
public void run() {
try {
Activity activity = (Activity) this.mReference.get();
if (!SmartSmsSdkUtil.activityIsFinish(activity)) {
DuoquBubbleViewManager.beforeInitBubbleView(activity, this.mPhoneNumber, this.mObj);
this.mReference = null;
this.mPhoneNumber = null;
this.mObj = null;
}
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("BeforeInitBubbleRunnable run error: " + e.getMessage(), e);
}
}
}
public static class ComposeManagerHandler extends Handler {
private WeakReference<SmartSmsComposeManager> mReference = null;
public ComposeManagerHandler(SmartSmsComposeManager smartSmsComposeManager) {
this.mReference = new WeakReference(smartSmsComposeManager);
}
public void handleMessage(Message msg) {
try {
SmartSmsComposeManager smartSmsComposeManager = (SmartSmsComposeManager) this.mReference.get();
if (smartSmsComposeManager != null && !SmartSmsSdkUtil.activityIsFinish(smartSmsComposeManager.mCtx)) {
smartSmsComposeManager.bindMenuView(msg.getData().getString("JSON"), smartSmsComposeManager.mCtx);
super.handleMessage(msg);
}
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("ComposeManagerHandler handleMessage error:" + e.getMessage(), e);
}
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
try {
SmartSmsComposeManager smartSmsComposeManager = (SmartSmsComposeManager) this.mReference.get();
if (smartSmsComposeManager == null || SmartSmsSdkUtil.activityIsFinish(smartSmsComposeManager.mCtx)) {
return false;
}
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("ComposeManagerHandler sendMessageAtTime error:" + e.getMessage(), e);
}
return super.sendMessageAtTime(msg, uptimeMillis);
}
}
public View getMenuRootView() {
return this.mMenuRootLayout;
}
public LinearLayout getButtonToSmartMenu() {
return this.mButtonToSmartMenu;
}
public SmartSmsComposeManager(ISmartSmsUIHolder iSmartSmsUIHolder) {
this.mISmartSmsUIHolder = iSmartSmsUIHolder;
this.mCtx = iSmartSmsUIHolder.getActivityContext();
this.mHandler = new ComposeManagerHandler(this);
}
public void queryMenu(ISmartSmsUIHolder iSmartSmsUIHolder, String recipientNumber, short conversationType) {
if (StringUtils.isPhoneNumber(recipientNumber)) {
this.mIsNotifyComposeMessage = false;
this.mIsLoad = true;
return;
}
ContentUtil.observerFontSize();
ContentUtil.observerTheme();
reloadContact(recipientNumber);
if (recipientNumber == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComposeManager queryMenu recipientNumber is null", null);
} else if (this.mCtx != null) {
SmartSmsSdkUtil.setBubbleActivityResumePhoneNum(iSmartSmsUIHolder.hashCode(), recipientNumber);
if (this.mNumber == null || !this.mNumber.equals(recipientNumber)) {
this.mNumber = recipientNumber;
this.mIsLoad = false;
queryMenu(recipientNumber, this.mCtx, iSmartSmsUIHolder, conversationType);
}
}
}
public boolean onSmartSmsEvent(short eventType) {
switch (eventType) {
case (short) 5:
ContentUtil.setViewVisibility(this.mMenuRootLayout, 0);
break;
}
return false;
}
public boolean getIsNotifyComposeMessage() {
return this.mIsNotifyComposeMessage;
}
private void initSmartSmsMenu() {
if (this.mISmartSmsUIHolder == null) {
MLog.w("XIAOYUAN", SmartSmsComposeManager.class.getName() + " initSmartSmsMenuManager iSmartSmsUIHolder is null");
} else if (this.mCtx == null) {
MLog.w("XIAOYUAN", SmartSmsComposeManager.class.getName() + " initSmartSmsMenuManager iSmartSmsUIHolder.getActivityContext() is null");
} else {
this.mIsUsedTheme = ResEx.init(this.mCtx).isUseThemeBackground(this.mCtx);
this.mLayoutInflater = (LayoutInflater) this.mCtx.getSystemService("layout_inflater");
initBottomMenuView(this.mCtx, this.mISmartSmsUIHolder);
this.mIsInitMenuView = true;
}
}
private void initBottomMenuView(final Activity ctx, final ISmartSmsUIHolder iSmartSmsUIHolder) {
if (this.mMenuRootLayout == null) {
this.mMenuRootStub = (ViewStub) iSmartSmsUIHolder.findViewById(R.id.duoqu_menu_layout_stub);
if (this.mMenuRootStub == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager initBottomMenu menuRootStub is null.", null);
return;
}
this.mMenuRootLayout = this.mMenuRootStub.inflate();
}
if (this.mMenuRootLayout == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager initBottomMenu mMenuRootLayout is null.", null);
return;
}
this.mButtonToSmartMenu = (LinearLayout) iSmartSmsUIHolder.findViewById(R.id.duoqu_button_menu);
this.mSmartMenuLayout = (RelativeLayout) this.mMenuRootLayout.findViewById(R.id.layout_bottom_menu);
this.mSmartMenuContent = (LinearLayout) this.mMenuRootLayout.findViewById(R.id.layout_menu);
this.mButtonToEditMenu = (LinearLayout) this.mMenuRootLayout.findViewById(R.id.layout_exchange);
this.mButtonToEditMenu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SmartSmsComposeManager.this.toEditMenu(iSmartSmsUIHolder, true);
StatisticalHelper.incrementReportCount(ctx, 2265);
}
});
if (this.mIsUsedTheme) {
this.mButtonToEditMenu.setBackgroundResource(R.color.duoqu_all_transparent);
}
}
private boolean isSameOperators() {
boolean isSameOperator = true;
try {
IccidLocationUtil.changeIccidAreaCode(false);
HashMap<String, String[]> iccidMap = IccidLocationUtil.getIccidAreaCodeMap();
if (iccidMap == null || iccidMap.isEmpty() || iccidMap.size() < 2) {
return false;
}
Set<Entry<String, String[]>> setEntery = ((HashMap) iccidMap.clone()).entrySet();
for (Entry<String, String[]> entry : setEntery) {
try {
if (this.mNumOperator != Integer.parseInt(((String[]) entry.getValue())[2])) {
isSameOperator = false;
break;
}
} catch (Exception e) {
SmartSmsSdkUtil.smartSdkExceptionLog("isShowSelectSimPop error: " + e.getMessage(), e);
}
}
if (isSameOperator) {
if (setEntery.size() >= 2) {
return true;
}
}
return false;
} catch (Exception e2) {
SmartSmsSdkUtil.smartSdkExceptionLog("isSameOperators error: " + e2.getMessage(), e2);
return false;
}
}
private void queryMenu(String recipientNumber, Activity ctx, ISmartSmsUIHolder iSmartSmsUIHolder, short conversationType) {
if (!this.mIsLoad && !TextUtils.isEmpty(recipientNumber)) {
final String str = recipientNumber;
final Activity activity = ctx;
final ISmartSmsUIHolder iSmartSmsUIHolder2 = iSmartSmsUIHolder;
final short s = conversationType;
new Thread() {
public void run() {
try {
Process.setThreadPriority(-4);
SmartSmsComposeManager.this.mFormatNumber = MessageUtils.parseMmsAddress(str, true);
SmartSmsComposeManager.this.mNumOperator = ParseManager.getOperatorNumByPubNum(SmartSmsComposeManager.this.mFormatNumber);
SmartSmsComposeManager.this.mSelectedSimIndex = SimCardUtil.getDefaultSimCardIndex();
if (SimCardUtil.isChangeSimCard()) {
DuoquUtils.getSdkDoAction().simChange();
} else if (SimCardUtil.needUpdateAllIccidInfo(SmartSmsComposeManager.this.mCtx)) {
SimCardUtil.loadLocation();
}
final boolean isSameOperators = SmartSmsComposeManager.this.isSameOperators();
final Activity activity = activity;
final ISmartSmsUIHolder iSmartSmsUIHolder = iSmartSmsUIHolder2;
final String str = str;
final short s = s;
SdkCallBack callBack = new SdkCallBack() {
public void execute(Object... dataArr) {
try {
if (!SmartSmsSdkUtil.activityIsFinish(activity) && SmartSmsComposeManager.this.isValidData(dataArr)) {
final String menuJson = dataArr[0].toString();
if (SmartSmsComposeManager.this.mIsInitMenuView) {
SmartSmsComposeManager.this.reShowMenuInHandle(menuJson);
} else {
Activity activity = activity;
final Activity activity2 = activity;
final ISmartSmsUIHolder iSmartSmsUIHolder = iSmartSmsUIHolder;
final String str = str;
final short s = s;
activity.runOnUiThread(new Runnable() {
public void run() {
SmartSmsComposeManager.this.bindMenu(activity2, iSmartSmsUIHolder, str, menuJson, 0, s);
}
});
if (isSameOperators) {
SmartSmsComposeManager.this.querySameOperatorsMenuData(menuJson);
}
}
}
} catch (Exception e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComponseManager queryMenu callBack error: " + e.getMessage(), e);
}
}
};
if (isSameOperators) {
Map<String, String> extend = new HashMap();
extend.put(SmartSmsComposeManager.LOCATION_KEY, SmartSmsComposeManager.LOCATION_VALUE_CN);
ParseManager.queryMenuByPhoneNum(SmartSmsComposeManager.this.mCtx, SmartSmsComposeManager.this.mFormatNumber, 1, null, extend, callBack);
return;
}
ParseManager.queryMenuByPhoneNum(SmartSmsComposeManager.this.mCtx, SmartSmsComposeManager.this.mFormatNumber, 1, null, null, callBack);
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComponseManager queryDoubleSimMenuByPhoneNum error: " + e.getMessage(), e);
}
}
}.start();
loadBubbleData(recipientNumber);
}
}
public void setSmartMenuClickListener(final ISmartSmsUIHolder iSmartSmsUIHolder) {
this.mButtonToSmartMenu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SmartSmsComposeManager.this.toSmartMenu(iSmartSmsUIHolder, true);
}
});
}
private void bindMenu(Activity ctx, final ISmartSmsUIHolder iSmartSmsUIHolder, String recipientNumber, String result, long start, short conversationType) {
String json = result;
if (TextUtils.isEmpty(result)) {
this.mIsLoad = true;
return;
}
try {
if (new JSONArray(result).length() != 3) {
this.mIsLoad = true;
return;
}
initSmartSmsMenu();
if (this.mMenuRootLayout == null || this.mButtonToSmartMenu == null || this.mSmartMenuContent == null || this.mLayoutInflater == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComposeManager queryMenu onPostExecute mMenuRootLayout is null", null);
return;
}
bindMenuView(result, ctx);
if (iSmartSmsUIHolder.editorHasContent()) {
iSmartSmsUIHolder.onSmartSmsEvent((short) 7);
this.mMenuRootLayout.setVisibility(8);
} else if (iSmartSmsUIHolder.isIntentHasSmsBody() || conversationType == (short) 1) {
iSmartSmsUIHolder.onSmartSmsEvent((short) 1);
this.mMenuRootLayout.setVisibility(8);
} else {
iSmartSmsUIHolder.onSmartSmsEvent((short) 6);
this.mMenuRootLayout.setVisibility(0);
}
this.mButtonToSmartMenu.setVisibility(0);
this.mButtonToSmartMenu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SmartSmsComposeManager.this.toSmartMenu(iSmartSmsUIHolder, true);
}
});
this.mIsLoad = true;
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager queryMenu onPostExecute error." + e.getMessage(), e);
this.mIsLoad = false;
}
}
public void toSmartMenu(ISmartSmsUIHolder iSmartSmsUIHolder, boolean isShowAnim) {
iSmartSmsUIHolder.onSmartSmsEvent((short) 4);
if (this.mMenuRootLayout != null) {
if (isShowAnim) {
this.mMenuRootLayout.setAnimation(AnimationUtils.loadAnimation(this.mCtx, R.anim.translate_fade_in));
} else {
this.mMenuRootLayout.setAnimation(null);
}
this.mMenuRootLayout.setVisibility(0);
}
}
public void toEditMenu(ISmartSmsUIHolder iSmartSmsUIHolder, boolean isShowAnim) {
if (this.mMenuRootLayout != null && this.mButtonToSmartMenu != null) {
if (isShowAnim) {
Animation showAnim = AnimationUtils.loadAnimation(this.mCtx, R.anim.translate_fade_in);
this.mMenuRootLayout.setAnimation(AnimationUtils.loadAnimation(this.mCtx, R.anim.translate));
this.mButtonToSmartMenu.setAnimation(showAnim);
iSmartSmsUIHolder.onSmartSmsEvent((short) 1);
} else {
this.mMenuRootLayout.setAnimation(null);
this.mButtonToSmartMenu.setAnimation(null);
iSmartSmsUIHolder.onSmartSmsEvent((short) 7);
}
this.mMenuRootLayout.setVisibility(8);
this.mButtonToSmartMenu.setVisibility(0);
}
}
private void loadBubbleData(final String recipientNumber) {
if (this.mCtx != null) {
new Thread() {
public void run() {
try {
SmartSmsComposeManager.this.mIsNotifyComposeMessage = ParseManager.isEnterpriseSms(SmartSmsComposeManager.this.mCtx, recipientNumber, null, null);
ParseBubbleManager.loadBubbleDataByPhoneNum(recipientNumber, true);
SmartSmsComposeManager.this.mHandler.postDelayed(new BeforeInitBubbleRunnable(SmartSmsComposeManager.this.mCtx, recipientNumber, PhoneSmsParseManager.findObjectByPhone(recipientNumber)), 2000);
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager bindMenuView onClick error.", e);
}
}
}.start();
}
}
private void bindMenuView(String json, Activity ctx) throws JSONException {
if ((!StringUtils.isNull(json) && json.equals(this.mMenuJsonData)) || this.mMenuRootLayout == null) {
return;
}
if (StringUtils.isNull(json) || this.mSmartMenuContent == null) {
ContentUtil.setViewVisibility(this.mMenuRootLayout, 8);
this.mMenuJsonData = null;
return;
}
this.mMenuJsonData = json;
JSONArray jsonCustomMenu = new JSONArray(json);
if (jsonCustomMenu.length() == 3) {
this.mSmartMenuContent.removeAllViews();
if (this.mPopupWindowCustommenu != null) {
this.mPopupWindowCustommenu.dismiss();
}
for (int i = 0; i < jsonCustomMenu.length(); i++) {
final JSONObject ob = jsonCustomMenu.getJSONObject(i);
final LinearLayout layout = (LinearLayout) this.mLayoutInflater.inflate(R.layout.duoqu_item_custommenu, null);
layout.setLayoutParams(new LayoutParams(-1, -1, ContentUtil.FONT_SIZE_NORMAL));
final String menuName = ob.getString("name");
((TextView) layout.findViewById(R.id.duoqu_custommenu_name)).setText(menuName);
if (this.mIsUsedTheme) {
layout.setBackgroundResource(R.drawable.duoqu_item_menu_select);
}
final Activity activity = ctx;
layout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Object obj = layout.getTag();
if (obj == null || SmartSmsComposeManager.this.mPopupWindowCustommenu == null || SmartSmsComposeManager.this.mPopupWindowCustommenu != ((PopMenus) obj)) {
final JSONObject jSONObject = ob;
final Activity activity = activity;
final LinearLayout linearLayout = layout;
final String str = menuName;
new XyCallBack() {
public void execute(Object... backData) {
if (!SmartSmsComposeManager.this.isSameOperators()) {
SmartSmsComposeManager.this.mSelectedSimIndex = SimCardUtil.getIndexbyOperator(SmartSmsComposeManager.this.mNumOperator, SmartSmsComposeManager.this.mSelectedSimIndex);
}
try {
if (!jSONObject.has(SmartSmsComposeManager.SECONDMENU) || jSONObject.getJSONArray(SmartSmsComposeManager.SECONDMENU).length() <= 0) {
Map<String, String> extend = new HashMap();
extend.put("simIndex", String.valueOf(SmartSmsComposeManager.this.mSelectedSimIndex));
ParseManager.doAction(activity, jSONObject.get(SmartSmsComposeManager.ACTION_DATA).toString(), extend);
PopMenus.menuActionReport(SmartSmsComposeManager.this.mFormatNumber, str);
return;
}
if (SmartSmsComposeManager.this.mPopupWindowCustommenu != null) {
SmartSmsComposeManager.this.mPopupWindowCustommenu.dismiss();
}
SmartSmsComposeManager.this.mExtraMenuDataMap.put(IccidInfoManager.NUM, SmartSmsComposeManager.this.mFormatNumber);
SmartSmsComposeManager.this.mPopupWindowCustommenu = new PopMenus(activity, jSONObject.getJSONArray(SmartSmsComposeManager.SECONDMENU), 0, 0, SmartSmsComposeManager.this.mSelectedSimIndex, SmartSmsComposeManager.this.mExtraMenuDataMap);
SmartSmsComposeManager.this.mPopupWindowCustommenu.showAtLocation(linearLayout);
linearLayout.setTag(SmartSmsComposeManager.this.mPopupWindowCustommenu);
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager bindMenuView onClick error." + e.getMessage(), e);
}
}
}.execute(new Object[0]);
return;
}
SmartSmsComposeManager.this.mPopupWindowCustommenu = null;
}
});
this.mSmartMenuContent.addView(layout);
}
} else {
this.mMenuRootLayout.setVisibility(8);
}
}
private boolean isValidData(Object... dataArr) {
if (dataArr == null || dataArr.length == 0 || dataArr[0] == null || !dataArr[0].toString().contains(ACTION_DATA)) {
return false;
}
return true;
}
private void reShowMenuInHandle(String json) {
Message message = this.mHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("JSON", json);
message.setData(bundle);
this.mHandler.sendMessage(message);
}
public void hideSmartsmsMenu() {
ContentUtil.setViewVisibility(this.mSmartMenuLayout, 8);
}
@SuppressLint({"NewApi"})
public void addNeedRefreshSmartBubbleItem(SmartSmsBubbleManager bubbleItem) {
if (bubbleItem != null) {
this.mNeedRefreshBubbleItem.offerLast(bubbleItem);
if (this.mNeedRefreshBubbleItem.size() > 10) {
this.mNeedRefreshBubbleItem.removeFirst();
}
}
}
public void notifyCheckRefresh(final BaseAdapter adpater) {
new AsyncTask() {
protected Boolean doInBackground(Object... arg0) {
return Boolean.valueOf(SmartSmsComposeManager.this.isNeedRefreshSmartBubbleItem());
}
protected void onPostExecute(Object result) {
if (adpater != null && result != null && ((Boolean) result).booleanValue()) {
adpater.notifyDataSetChanged();
}
}
}.execute(new Object[0]);
}
private boolean isNeedRefreshSmartBubbleItem() {
boolean res = false;
int cnt = 0;
while (!this.mNeedRefreshBubbleItem.isEmpty()) {
if (!((SmartSmsBubbleManager) this.mNeedRefreshBubbleItem.removeLast()).isNeedRefresh()) {
cnt++;
if (cnt > 10) {
break;
}
}
res = true;
break;
}
this.mNeedRefreshBubbleItem.clear();
return res;
}
public boolean isShowMenu() {
if (this.mPopupWindowCustommenu == null) {
return false;
}
boolean isShow = this.mPopupWindowCustommenu.isShow();
if (isShow) {
this.mPopupWindowCustommenu.dismiss();
}
return isShow;
}
public void reShowMenu() {
if (this.mPopupWindowCustommenu != null && this.mPopupWindowCustommenu.isShow() && this.mButtonToEditMenu != null) {
this.mButtonToEditMenu.postDelayed(new Runnable() {
public void run() {
SmartSmsComposeManager.this.mPopupWindowCustommenu.dismiss();
SmartSmsComposeManager.this.mPopupWindowCustommenu.showPopupAccordingParentView();
}
}, 100);
}
}
private void querySameOperatorsMenuData(final String json) {
if (!StringUtils.isNull(json)) {
try {
ParseManager.queryAllSimCardTrafficAndChargeActionData(this.mCtx, this.mFormatNumber, new SdkCallBack() {
public void execute(Object... dataArr) {
if (dataArr != null && dataArr.length >= 3 && dataArr[2] != null) {
try {
SmartSmsComposeManager.this.mExtraMenuDataMap.put(dataArr[1].toString(), dataArr[2].toString());
if (SmartSmsComposeManager.this.mExtraMenuDataMap.size() > 1) {
String menuData = ParseManager.addQueryTrafficAndChargeToMenuData(json, SmartSmsComposeManager.this.mExtraMenuDataMap);
if (!StringUtils.isNull(menuData) && menuData.contains(SmartSmsComposeManager.ACTION_DATA)) {
SmartSmsComposeManager.this.reShowMenuInHandle(menuData);
}
}
} catch (Exception e) {
SmartSmsSdkUtil.smartSdkExceptionLog("querySameOperatorsMenuData error: " + e.getMessage(), e);
}
}
}
});
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("querySameOperatorsMenuData error: " + e.getMessage(), e);
}
}
}
private void reloadContact(String recipientNumber) {
if (!StringUtils.isNull(recipientNumber)) {
Contact contact = Contact.get(recipientNumber, false);
if (contact != null && StringUtils.isNull(contact.getXiaoyuanPhotoUri())) {
contact.reload();
}
}
}
}
| UTF-8 | Java | 30,450 | java | SmartSmsComposeManager.java | Java | [
{
"context": "ION = (short) 1;\n private final String TAG = \"XIAOYUAN\";\n private LinearLayout mButtonToEditMenu;\n ",
"end": 2812,
"score": 0.6010030508041382,
"start": 2805,
"tag": "USERNAME",
"value": "IAOYUAN"
}
] | null | [] | package cn.com.xy.sms.sdk.mms.ui.menu;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.SmartSmsSdkUtil;
import cn.com.xy.sms.sdk.db.entity.IccidInfoManager;
import cn.com.xy.sms.sdk.db.entity.PhoneSmsParseManager;
import cn.com.xy.sms.sdk.iccid.IccidLocationUtil;
import cn.com.xy.sms.sdk.ui.bubbleview.DuoquBubbleViewManager;
import cn.com.xy.sms.sdk.ui.menu.PopMenus;
import cn.com.xy.sms.sdk.ui.popu.util.ContentUtil;
import cn.com.xy.sms.sdk.ui.settings.SimCardUtil;
import cn.com.xy.sms.sdk.util.DuoquUtils;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.util.ParseBubbleManager;
import cn.com.xy.sms.util.ParseManager;
import cn.com.xy.sms.util.SdkCallBack;
import com.android.mms.data.Contact;
import com.android.mms.ui.MessageUtils;
import com.android.mms.ui.SmartSmsBubbleManager;
import com.google.android.gms.R;
import com.huawei.cspcommon.MLog;
import com.huawei.mms.util.ResEx;
import com.huawei.mms.util.StatisticalHelper;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SmartSmsComposeManager implements ISmartSmsMenuManager {
private static final String ACTION_DATA = "action_data";
private static final String LOCATION_KEY = "code";
private static final String LOCATION_VALUE_CN = "CN";
private static final String SECONDMENU = "secondmenu";
public static final short SMART_SMS_DUOQU_EVENT_HIDE_EDIT_LAYOUT = (short) 4;
public static final short SMART_SMS_DUOQU_EVENT_HIDE_EDIT_LAYOUT_FIRST_IN = (short) 6;
public static final short SMART_SMS_DUOQU_EVENT_SHOW_EDIT_LAYOUT = (short) 1;
public static final short SMART_SMS_DUOQU_EVENT_SHOW_EDIT_LAYOUT_WITHOUT_ANIMATION = (short) 7;
public static final short SMART_SMS_DUOQU_EVENT_SHOW_VIEW_MENU = (short) 5;
public static final short SMART_SMS_SHOW_MENU_IN_CONVERSATION = (short) 2;
public static final short SMART_SMS_SHOW_MENU_NEW_CONVERSATION = (short) 1;
private final String TAG = "XIAOYUAN";
private LinearLayout mButtonToEditMenu;
private LinearLayout mButtonToSmartMenu;
private Activity mCtx;
private Map<String, String> mExtraMenuDataMap = new HashMap();
private String mFormatNumber;
private Handler mHandler = null;
private ISmartSmsUIHolder mISmartSmsUIHolder;
private boolean mIsInitMenuView = false;
private boolean mIsLoad = false;
private boolean mIsNotifyComposeMessage = true;
private boolean mIsUsedTheme = false;
private LayoutInflater mLayoutInflater = null;
private String mMenuJsonData = null;
private View mMenuRootLayout = null;
private ViewStub mMenuRootStub = null;
LinkedList<SmartSmsBubbleManager> mNeedRefreshBubbleItem = new LinkedList();
private int mNumOperator;
private String mNumber = null;
private PopMenus mPopupWindowCustommenu;
private int mSelectedSimIndex = 0;
private LinearLayout mSmartMenuContent;
private RelativeLayout mSmartMenuLayout;
private static class BeforeInitBubbleRunnable implements Runnable {
private JSONObject mObj = null;
private String mPhoneNumber = null;
private WeakReference<Activity> mReference = null;
public BeforeInitBubbleRunnable(Activity ctx, String num, JSONObject obj) {
this.mPhoneNumber = num;
this.mReference = new WeakReference(ctx);
this.mObj = obj;
}
public void run() {
try {
Activity activity = (Activity) this.mReference.get();
if (!SmartSmsSdkUtil.activityIsFinish(activity)) {
DuoquBubbleViewManager.beforeInitBubbleView(activity, this.mPhoneNumber, this.mObj);
this.mReference = null;
this.mPhoneNumber = null;
this.mObj = null;
}
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("BeforeInitBubbleRunnable run error: " + e.getMessage(), e);
}
}
}
public static class ComposeManagerHandler extends Handler {
private WeakReference<SmartSmsComposeManager> mReference = null;
public ComposeManagerHandler(SmartSmsComposeManager smartSmsComposeManager) {
this.mReference = new WeakReference(smartSmsComposeManager);
}
public void handleMessage(Message msg) {
try {
SmartSmsComposeManager smartSmsComposeManager = (SmartSmsComposeManager) this.mReference.get();
if (smartSmsComposeManager != null && !SmartSmsSdkUtil.activityIsFinish(smartSmsComposeManager.mCtx)) {
smartSmsComposeManager.bindMenuView(msg.getData().getString("JSON"), smartSmsComposeManager.mCtx);
super.handleMessage(msg);
}
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("ComposeManagerHandler handleMessage error:" + e.getMessage(), e);
}
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
try {
SmartSmsComposeManager smartSmsComposeManager = (SmartSmsComposeManager) this.mReference.get();
if (smartSmsComposeManager == null || SmartSmsSdkUtil.activityIsFinish(smartSmsComposeManager.mCtx)) {
return false;
}
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("ComposeManagerHandler sendMessageAtTime error:" + e.getMessage(), e);
}
return super.sendMessageAtTime(msg, uptimeMillis);
}
}
public View getMenuRootView() {
return this.mMenuRootLayout;
}
public LinearLayout getButtonToSmartMenu() {
return this.mButtonToSmartMenu;
}
public SmartSmsComposeManager(ISmartSmsUIHolder iSmartSmsUIHolder) {
this.mISmartSmsUIHolder = iSmartSmsUIHolder;
this.mCtx = iSmartSmsUIHolder.getActivityContext();
this.mHandler = new ComposeManagerHandler(this);
}
public void queryMenu(ISmartSmsUIHolder iSmartSmsUIHolder, String recipientNumber, short conversationType) {
if (StringUtils.isPhoneNumber(recipientNumber)) {
this.mIsNotifyComposeMessage = false;
this.mIsLoad = true;
return;
}
ContentUtil.observerFontSize();
ContentUtil.observerTheme();
reloadContact(recipientNumber);
if (recipientNumber == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComposeManager queryMenu recipientNumber is null", null);
} else if (this.mCtx != null) {
SmartSmsSdkUtil.setBubbleActivityResumePhoneNum(iSmartSmsUIHolder.hashCode(), recipientNumber);
if (this.mNumber == null || !this.mNumber.equals(recipientNumber)) {
this.mNumber = recipientNumber;
this.mIsLoad = false;
queryMenu(recipientNumber, this.mCtx, iSmartSmsUIHolder, conversationType);
}
}
}
public boolean onSmartSmsEvent(short eventType) {
switch (eventType) {
case (short) 5:
ContentUtil.setViewVisibility(this.mMenuRootLayout, 0);
break;
}
return false;
}
public boolean getIsNotifyComposeMessage() {
return this.mIsNotifyComposeMessage;
}
private void initSmartSmsMenu() {
if (this.mISmartSmsUIHolder == null) {
MLog.w("XIAOYUAN", SmartSmsComposeManager.class.getName() + " initSmartSmsMenuManager iSmartSmsUIHolder is null");
} else if (this.mCtx == null) {
MLog.w("XIAOYUAN", SmartSmsComposeManager.class.getName() + " initSmartSmsMenuManager iSmartSmsUIHolder.getActivityContext() is null");
} else {
this.mIsUsedTheme = ResEx.init(this.mCtx).isUseThemeBackground(this.mCtx);
this.mLayoutInflater = (LayoutInflater) this.mCtx.getSystemService("layout_inflater");
initBottomMenuView(this.mCtx, this.mISmartSmsUIHolder);
this.mIsInitMenuView = true;
}
}
private void initBottomMenuView(final Activity ctx, final ISmartSmsUIHolder iSmartSmsUIHolder) {
if (this.mMenuRootLayout == null) {
this.mMenuRootStub = (ViewStub) iSmartSmsUIHolder.findViewById(R.id.duoqu_menu_layout_stub);
if (this.mMenuRootStub == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager initBottomMenu menuRootStub is null.", null);
return;
}
this.mMenuRootLayout = this.mMenuRootStub.inflate();
}
if (this.mMenuRootLayout == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager initBottomMenu mMenuRootLayout is null.", null);
return;
}
this.mButtonToSmartMenu = (LinearLayout) iSmartSmsUIHolder.findViewById(R.id.duoqu_button_menu);
this.mSmartMenuLayout = (RelativeLayout) this.mMenuRootLayout.findViewById(R.id.layout_bottom_menu);
this.mSmartMenuContent = (LinearLayout) this.mMenuRootLayout.findViewById(R.id.layout_menu);
this.mButtonToEditMenu = (LinearLayout) this.mMenuRootLayout.findViewById(R.id.layout_exchange);
this.mButtonToEditMenu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SmartSmsComposeManager.this.toEditMenu(iSmartSmsUIHolder, true);
StatisticalHelper.incrementReportCount(ctx, 2265);
}
});
if (this.mIsUsedTheme) {
this.mButtonToEditMenu.setBackgroundResource(R.color.duoqu_all_transparent);
}
}
private boolean isSameOperators() {
boolean isSameOperator = true;
try {
IccidLocationUtil.changeIccidAreaCode(false);
HashMap<String, String[]> iccidMap = IccidLocationUtil.getIccidAreaCodeMap();
if (iccidMap == null || iccidMap.isEmpty() || iccidMap.size() < 2) {
return false;
}
Set<Entry<String, String[]>> setEntery = ((HashMap) iccidMap.clone()).entrySet();
for (Entry<String, String[]> entry : setEntery) {
try {
if (this.mNumOperator != Integer.parseInt(((String[]) entry.getValue())[2])) {
isSameOperator = false;
break;
}
} catch (Exception e) {
SmartSmsSdkUtil.smartSdkExceptionLog("isShowSelectSimPop error: " + e.getMessage(), e);
}
}
if (isSameOperator) {
if (setEntery.size() >= 2) {
return true;
}
}
return false;
} catch (Exception e2) {
SmartSmsSdkUtil.smartSdkExceptionLog("isSameOperators error: " + e2.getMessage(), e2);
return false;
}
}
private void queryMenu(String recipientNumber, Activity ctx, ISmartSmsUIHolder iSmartSmsUIHolder, short conversationType) {
if (!this.mIsLoad && !TextUtils.isEmpty(recipientNumber)) {
final String str = recipientNumber;
final Activity activity = ctx;
final ISmartSmsUIHolder iSmartSmsUIHolder2 = iSmartSmsUIHolder;
final short s = conversationType;
new Thread() {
public void run() {
try {
Process.setThreadPriority(-4);
SmartSmsComposeManager.this.mFormatNumber = MessageUtils.parseMmsAddress(str, true);
SmartSmsComposeManager.this.mNumOperator = ParseManager.getOperatorNumByPubNum(SmartSmsComposeManager.this.mFormatNumber);
SmartSmsComposeManager.this.mSelectedSimIndex = SimCardUtil.getDefaultSimCardIndex();
if (SimCardUtil.isChangeSimCard()) {
DuoquUtils.getSdkDoAction().simChange();
} else if (SimCardUtil.needUpdateAllIccidInfo(SmartSmsComposeManager.this.mCtx)) {
SimCardUtil.loadLocation();
}
final boolean isSameOperators = SmartSmsComposeManager.this.isSameOperators();
final Activity activity = activity;
final ISmartSmsUIHolder iSmartSmsUIHolder = iSmartSmsUIHolder2;
final String str = str;
final short s = s;
SdkCallBack callBack = new SdkCallBack() {
public void execute(Object... dataArr) {
try {
if (!SmartSmsSdkUtil.activityIsFinish(activity) && SmartSmsComposeManager.this.isValidData(dataArr)) {
final String menuJson = dataArr[0].toString();
if (SmartSmsComposeManager.this.mIsInitMenuView) {
SmartSmsComposeManager.this.reShowMenuInHandle(menuJson);
} else {
Activity activity = activity;
final Activity activity2 = activity;
final ISmartSmsUIHolder iSmartSmsUIHolder = iSmartSmsUIHolder;
final String str = str;
final short s = s;
activity.runOnUiThread(new Runnable() {
public void run() {
SmartSmsComposeManager.this.bindMenu(activity2, iSmartSmsUIHolder, str, menuJson, 0, s);
}
});
if (isSameOperators) {
SmartSmsComposeManager.this.querySameOperatorsMenuData(menuJson);
}
}
}
} catch (Exception e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComponseManager queryMenu callBack error: " + e.getMessage(), e);
}
}
};
if (isSameOperators) {
Map<String, String> extend = new HashMap();
extend.put(SmartSmsComposeManager.LOCATION_KEY, SmartSmsComposeManager.LOCATION_VALUE_CN);
ParseManager.queryMenuByPhoneNum(SmartSmsComposeManager.this.mCtx, SmartSmsComposeManager.this.mFormatNumber, 1, null, extend, callBack);
return;
}
ParseManager.queryMenuByPhoneNum(SmartSmsComposeManager.this.mCtx, SmartSmsComposeManager.this.mFormatNumber, 1, null, null, callBack);
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComponseManager queryDoubleSimMenuByPhoneNum error: " + e.getMessage(), e);
}
}
}.start();
loadBubbleData(recipientNumber);
}
}
public void setSmartMenuClickListener(final ISmartSmsUIHolder iSmartSmsUIHolder) {
this.mButtonToSmartMenu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SmartSmsComposeManager.this.toSmartMenu(iSmartSmsUIHolder, true);
}
});
}
private void bindMenu(Activity ctx, final ISmartSmsUIHolder iSmartSmsUIHolder, String recipientNumber, String result, long start, short conversationType) {
String json = result;
if (TextUtils.isEmpty(result)) {
this.mIsLoad = true;
return;
}
try {
if (new JSONArray(result).length() != 3) {
this.mIsLoad = true;
return;
}
initSmartSmsMenu();
if (this.mMenuRootLayout == null || this.mButtonToSmartMenu == null || this.mSmartMenuContent == null || this.mLayoutInflater == null) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsComposeManager queryMenu onPostExecute mMenuRootLayout is null", null);
return;
}
bindMenuView(result, ctx);
if (iSmartSmsUIHolder.editorHasContent()) {
iSmartSmsUIHolder.onSmartSmsEvent((short) 7);
this.mMenuRootLayout.setVisibility(8);
} else if (iSmartSmsUIHolder.isIntentHasSmsBody() || conversationType == (short) 1) {
iSmartSmsUIHolder.onSmartSmsEvent((short) 1);
this.mMenuRootLayout.setVisibility(8);
} else {
iSmartSmsUIHolder.onSmartSmsEvent((short) 6);
this.mMenuRootLayout.setVisibility(0);
}
this.mButtonToSmartMenu.setVisibility(0);
this.mButtonToSmartMenu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SmartSmsComposeManager.this.toSmartMenu(iSmartSmsUIHolder, true);
}
});
this.mIsLoad = true;
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager queryMenu onPostExecute error." + e.getMessage(), e);
this.mIsLoad = false;
}
}
public void toSmartMenu(ISmartSmsUIHolder iSmartSmsUIHolder, boolean isShowAnim) {
iSmartSmsUIHolder.onSmartSmsEvent((short) 4);
if (this.mMenuRootLayout != null) {
if (isShowAnim) {
this.mMenuRootLayout.setAnimation(AnimationUtils.loadAnimation(this.mCtx, R.anim.translate_fade_in));
} else {
this.mMenuRootLayout.setAnimation(null);
}
this.mMenuRootLayout.setVisibility(0);
}
}
public void toEditMenu(ISmartSmsUIHolder iSmartSmsUIHolder, boolean isShowAnim) {
if (this.mMenuRootLayout != null && this.mButtonToSmartMenu != null) {
if (isShowAnim) {
Animation showAnim = AnimationUtils.loadAnimation(this.mCtx, R.anim.translate_fade_in);
this.mMenuRootLayout.setAnimation(AnimationUtils.loadAnimation(this.mCtx, R.anim.translate));
this.mButtonToSmartMenu.setAnimation(showAnim);
iSmartSmsUIHolder.onSmartSmsEvent((short) 1);
} else {
this.mMenuRootLayout.setAnimation(null);
this.mButtonToSmartMenu.setAnimation(null);
iSmartSmsUIHolder.onSmartSmsEvent((short) 7);
}
this.mMenuRootLayout.setVisibility(8);
this.mButtonToSmartMenu.setVisibility(0);
}
}
private void loadBubbleData(final String recipientNumber) {
if (this.mCtx != null) {
new Thread() {
public void run() {
try {
SmartSmsComposeManager.this.mIsNotifyComposeMessage = ParseManager.isEnterpriseSms(SmartSmsComposeManager.this.mCtx, recipientNumber, null, null);
ParseBubbleManager.loadBubbleDataByPhoneNum(recipientNumber, true);
SmartSmsComposeManager.this.mHandler.postDelayed(new BeforeInitBubbleRunnable(SmartSmsComposeManager.this.mCtx, recipientNumber, PhoneSmsParseManager.findObjectByPhone(recipientNumber)), 2000);
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager bindMenuView onClick error.", e);
}
}
}.start();
}
}
private void bindMenuView(String json, Activity ctx) throws JSONException {
if ((!StringUtils.isNull(json) && json.equals(this.mMenuJsonData)) || this.mMenuRootLayout == null) {
return;
}
if (StringUtils.isNull(json) || this.mSmartMenuContent == null) {
ContentUtil.setViewVisibility(this.mMenuRootLayout, 8);
this.mMenuJsonData = null;
return;
}
this.mMenuJsonData = json;
JSONArray jsonCustomMenu = new JSONArray(json);
if (jsonCustomMenu.length() == 3) {
this.mSmartMenuContent.removeAllViews();
if (this.mPopupWindowCustommenu != null) {
this.mPopupWindowCustommenu.dismiss();
}
for (int i = 0; i < jsonCustomMenu.length(); i++) {
final JSONObject ob = jsonCustomMenu.getJSONObject(i);
final LinearLayout layout = (LinearLayout) this.mLayoutInflater.inflate(R.layout.duoqu_item_custommenu, null);
layout.setLayoutParams(new LayoutParams(-1, -1, ContentUtil.FONT_SIZE_NORMAL));
final String menuName = ob.getString("name");
((TextView) layout.findViewById(R.id.duoqu_custommenu_name)).setText(menuName);
if (this.mIsUsedTheme) {
layout.setBackgroundResource(R.drawable.duoqu_item_menu_select);
}
final Activity activity = ctx;
layout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Object obj = layout.getTag();
if (obj == null || SmartSmsComposeManager.this.mPopupWindowCustommenu == null || SmartSmsComposeManager.this.mPopupWindowCustommenu != ((PopMenus) obj)) {
final JSONObject jSONObject = ob;
final Activity activity = activity;
final LinearLayout linearLayout = layout;
final String str = menuName;
new XyCallBack() {
public void execute(Object... backData) {
if (!SmartSmsComposeManager.this.isSameOperators()) {
SmartSmsComposeManager.this.mSelectedSimIndex = SimCardUtil.getIndexbyOperator(SmartSmsComposeManager.this.mNumOperator, SmartSmsComposeManager.this.mSelectedSimIndex);
}
try {
if (!jSONObject.has(SmartSmsComposeManager.SECONDMENU) || jSONObject.getJSONArray(SmartSmsComposeManager.SECONDMENU).length() <= 0) {
Map<String, String> extend = new HashMap();
extend.put("simIndex", String.valueOf(SmartSmsComposeManager.this.mSelectedSimIndex));
ParseManager.doAction(activity, jSONObject.get(SmartSmsComposeManager.ACTION_DATA).toString(), extend);
PopMenus.menuActionReport(SmartSmsComposeManager.this.mFormatNumber, str);
return;
}
if (SmartSmsComposeManager.this.mPopupWindowCustommenu != null) {
SmartSmsComposeManager.this.mPopupWindowCustommenu.dismiss();
}
SmartSmsComposeManager.this.mExtraMenuDataMap.put(IccidInfoManager.NUM, SmartSmsComposeManager.this.mFormatNumber);
SmartSmsComposeManager.this.mPopupWindowCustommenu = new PopMenus(activity, jSONObject.getJSONArray(SmartSmsComposeManager.SECONDMENU), 0, 0, SmartSmsComposeManager.this.mSelectedSimIndex, SmartSmsComposeManager.this.mExtraMenuDataMap);
SmartSmsComposeManager.this.mPopupWindowCustommenu.showAtLocation(linearLayout);
linearLayout.setTag(SmartSmsComposeManager.this.mPopupWindowCustommenu);
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("SmartSmsMenuManager bindMenuView onClick error." + e.getMessage(), e);
}
}
}.execute(new Object[0]);
return;
}
SmartSmsComposeManager.this.mPopupWindowCustommenu = null;
}
});
this.mSmartMenuContent.addView(layout);
}
} else {
this.mMenuRootLayout.setVisibility(8);
}
}
private boolean isValidData(Object... dataArr) {
if (dataArr == null || dataArr.length == 0 || dataArr[0] == null || !dataArr[0].toString().contains(ACTION_DATA)) {
return false;
}
return true;
}
private void reShowMenuInHandle(String json) {
Message message = this.mHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("JSON", json);
message.setData(bundle);
this.mHandler.sendMessage(message);
}
public void hideSmartsmsMenu() {
ContentUtil.setViewVisibility(this.mSmartMenuLayout, 8);
}
@SuppressLint({"NewApi"})
public void addNeedRefreshSmartBubbleItem(SmartSmsBubbleManager bubbleItem) {
if (bubbleItem != null) {
this.mNeedRefreshBubbleItem.offerLast(bubbleItem);
if (this.mNeedRefreshBubbleItem.size() > 10) {
this.mNeedRefreshBubbleItem.removeFirst();
}
}
}
public void notifyCheckRefresh(final BaseAdapter adpater) {
new AsyncTask() {
protected Boolean doInBackground(Object... arg0) {
return Boolean.valueOf(SmartSmsComposeManager.this.isNeedRefreshSmartBubbleItem());
}
protected void onPostExecute(Object result) {
if (adpater != null && result != null && ((Boolean) result).booleanValue()) {
adpater.notifyDataSetChanged();
}
}
}.execute(new Object[0]);
}
private boolean isNeedRefreshSmartBubbleItem() {
boolean res = false;
int cnt = 0;
while (!this.mNeedRefreshBubbleItem.isEmpty()) {
if (!((SmartSmsBubbleManager) this.mNeedRefreshBubbleItem.removeLast()).isNeedRefresh()) {
cnt++;
if (cnt > 10) {
break;
}
}
res = true;
break;
}
this.mNeedRefreshBubbleItem.clear();
return res;
}
public boolean isShowMenu() {
if (this.mPopupWindowCustommenu == null) {
return false;
}
boolean isShow = this.mPopupWindowCustommenu.isShow();
if (isShow) {
this.mPopupWindowCustommenu.dismiss();
}
return isShow;
}
public void reShowMenu() {
if (this.mPopupWindowCustommenu != null && this.mPopupWindowCustommenu.isShow() && this.mButtonToEditMenu != null) {
this.mButtonToEditMenu.postDelayed(new Runnable() {
public void run() {
SmartSmsComposeManager.this.mPopupWindowCustommenu.dismiss();
SmartSmsComposeManager.this.mPopupWindowCustommenu.showPopupAccordingParentView();
}
}, 100);
}
}
private void querySameOperatorsMenuData(final String json) {
if (!StringUtils.isNull(json)) {
try {
ParseManager.queryAllSimCardTrafficAndChargeActionData(this.mCtx, this.mFormatNumber, new SdkCallBack() {
public void execute(Object... dataArr) {
if (dataArr != null && dataArr.length >= 3 && dataArr[2] != null) {
try {
SmartSmsComposeManager.this.mExtraMenuDataMap.put(dataArr[1].toString(), dataArr[2].toString());
if (SmartSmsComposeManager.this.mExtraMenuDataMap.size() > 1) {
String menuData = ParseManager.addQueryTrafficAndChargeToMenuData(json, SmartSmsComposeManager.this.mExtraMenuDataMap);
if (!StringUtils.isNull(menuData) && menuData.contains(SmartSmsComposeManager.ACTION_DATA)) {
SmartSmsComposeManager.this.reShowMenuInHandle(menuData);
}
}
} catch (Exception e) {
SmartSmsSdkUtil.smartSdkExceptionLog("querySameOperatorsMenuData error: " + e.getMessage(), e);
}
}
}
});
} catch (Throwable e) {
SmartSmsSdkUtil.smartSdkExceptionLog("querySameOperatorsMenuData error: " + e.getMessage(), e);
}
}
}
private void reloadContact(String recipientNumber) {
if (!StringUtils.isNull(recipientNumber)) {
Contact contact = Contact.get(recipientNumber, false);
if (contact != null && StringUtils.isNull(contact.getXiaoyuanPhotoUri())) {
contact.reload();
}
}
}
}
| 30,450 | 0.592479 | 0.589951 | 614 | 48.592834 | 38.997208 | 276 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.729642 | false | false | 3 |
43e30a2387629f8c137d5caced13e6d4af412a53 | 18,837,726,608,848 | a5343073427d7f694a872c1bd3da9dd7f349f2b8 | /SeleniumJavaFramework/src/test/java/com/kdp/SeleniumJavaFramework/Pages/SiteSettingPage.java | 3b4c54a70b3f81e72370bf53845062bbd3e54880 | [] | no_license | kuldeepkdp/GithubSeleniumJavaFramework | https://github.com/kuldeepkdp/GithubSeleniumJavaFramework | 74dfbe6e11c1462771ce0bb31e727407741437e3 | b1c11547805d9319348f5078eee3febb1570d281 | refs/heads/master | 2020-03-08T10:10:33.154000 | 2018-09-08T18:30:25 | 2018-09-08T18:30:25 | 128,065,717 | 0 | 0 | null | false | 2018-09-08T18:30:25 | 2018-04-04T13:25:47 | 2018-05-05T09:22:56 | 2018-09-08T18:30:25 | 6,076 | 0 | 0 | 0 | HTML | false | null | package com.kdp.SeleniumJavaFramework.Pages;
import org.openqa.selenium.By;
public class SiteSettingPage {
public static By sfwPlazaAdministration = By.linkText("SFW Plaza Administration");
public static By sitePermissions = By.linkText("Site permissions");
}
| UTF-8 | Java | 267 | java | SiteSettingPage.java | Java | [] | null | [] | package com.kdp.SeleniumJavaFramework.Pages;
import org.openqa.selenium.By;
public class SiteSettingPage {
public static By sfwPlazaAdministration = By.linkText("SFW Plaza Administration");
public static By sitePermissions = By.linkText("Site permissions");
}
| 267 | 0.794007 | 0.794007 | 10 | 25.700001 | 29.404251 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 3 |
329549b2f893fe109faec4e4b31a688d4c2b08c2 | 20,349,555,106,365 | d11c34d7e092267be6fbf26edd308a29f42970fb | /src/main/java/com/marcin/mail_application/domain/SentMessage.java | 5a2bb17f3534ab7db9d004f4bd9125c813daf284 | [] | no_license | MarcinSkrzecz/Mail_Application | https://github.com/MarcinSkrzecz/Mail_Application | 1f5ee8a4097c1d19c376a069f72d486c6439cc78 | 663c4d9d06693644b3e81a22740026b060c15c59 | refs/heads/master | 2023-03-07T03:32:46.325000 | 2021-02-13T13:59:56 | 2021-02-13T13:59:56 | 338,586,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.marcin.mail_application.domain;
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity(name = "SentMessages")
public class SentMessage {
@Id
@EqualsAndHashCode.Include
@GeneratedValue
@NotNull
@Column(name = "MESSAGE_ID")
private Long id;
@NotNull
@Column(name = "EMAIL")
private String email;
@NotNull
@Column(name = "TITLE")
private String title;
@NotNull
@Column(name = "CONTENT")
private String content;
@NotNull
@Column(name = "MAGIC_NUMBER")
private String magicNumber;
@NotNull
@Column(name = "WHEN_WAS_SENT")
private LocalDate whenWasSent = LocalDate.now();
public SentMessage(String email, String title, String content, String magicNumber) {
this.email = email;
this.title = title;
this.content = content;
this.magicNumber = magicNumber;
}
}
| UTF-8 | Java | 1,181 | java | SentMessage.java | Java | [] | null | [] | package com.marcin.mail_application.domain;
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity(name = "SentMessages")
public class SentMessage {
@Id
@EqualsAndHashCode.Include
@GeneratedValue
@NotNull
@Column(name = "MESSAGE_ID")
private Long id;
@NotNull
@Column(name = "EMAIL")
private String email;
@NotNull
@Column(name = "TITLE")
private String title;
@NotNull
@Column(name = "CONTENT")
private String content;
@NotNull
@Column(name = "MAGIC_NUMBER")
private String magicNumber;
@NotNull
@Column(name = "WHEN_WAS_SENT")
private LocalDate whenWasSent = LocalDate.now();
public SentMessage(String email, String title, String content, String magicNumber) {
this.email = email;
this.title = title;
this.content = content;
this.magicNumber = magicNumber;
}
}
| 1,181 | 0.697714 | 0.697714 | 53 | 21.283018 | 17.149044 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396226 | false | false | 3 |
13e90851c94500cad1d9bcddc77fe86e7723aca8 | 39,341,900,433,089 | 488a522c86c4c5ce9a58b0bb936e2010462a39b5 | /smart-code-generate/src/main/java/org/smartframework/cloud/code/generate/bo/template/CommonBO.java | 50a6f4ab52b991075f7adb8db55aa93c4e90297f | [
"Apache-2.0"
] | permissive | FanWenTao-Felix/smart-cloud | https://github.com/FanWenTao-Felix/smart-cloud | 0510220afdc2184b9cfd9c9d45bcc17b1842fd5d | 9075843a4ff2d591dc204fbbce89a6f0bb384918 | refs/heads/master | 2023-07-08T05:28:22.674000 | 2021-01-28T15:39:11 | 2021-01-29T07:55:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.smartframework.cloud.code.generate.bo.template;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* 公共信息
*
* @author liyulin
* @date 2019-07-13
*/
@Getter
@Setter
@ToString
public class CommonBO {
/** 包名 */
private String packageName;
/** 需要导入的包名 */
private List<String> importPackages;
/** 类名 */
private String className;
/** 表备注 */
private String tableComment;
/** 类注释信息 */
private ClassCommentBO classComment;
} | UTF-8 | Java | 537 | java | CommonBO.java | Java | [
{
"context": "import lombok.ToString;\n\n/**\n * 公共信息\n *\n * @author liyulin\n * @date 2019-07-13\n */\n@Getter\n@Setter\n@ToString",
"end": 187,
"score": 0.9993307590484619,
"start": 180,
"tag": "USERNAME",
"value": "liyulin"
}
] | null | [] | package org.smartframework.cloud.code.generate.bo.template;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* 公共信息
*
* @author liyulin
* @date 2019-07-13
*/
@Getter
@Setter
@ToString
public class CommonBO {
/** 包名 */
private String packageName;
/** 需要导入的包名 */
private List<String> importPackages;
/** 类名 */
private String className;
/** 表备注 */
private String tableComment;
/** 类注释信息 */
private ClassCommentBO classComment;
} | 537 | 0.706721 | 0.690428 | 31 | 14.870968 | 13.606787 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false | 3 |
c28b6e47e36a4419fa16e969d46768023a76ac81 | 35,003,983,515,226 | c7b6772905c227cd0d449ca49a383ee0cb334650 | /src/com/derToaster/Main.java | cb193a61c5cc98d2cc21de8068ffb0e0600b814f | [] | no_license | derToaster/PizzaProjectOOP | https://github.com/derToaster/PizzaProjectOOP | 09a90deeeef931a9b1d96bc54deba5101d5f6cb7 | d9aadfca46cca90a16204e84d027821e5340f712 | refs/heads/master | 2022-10-03T22:17:47.628000 | 2020-06-10T12:42:06 | 2020-06-10T12:42:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.derToaster;
public class Main {
public static void main(String[] args) {
Hamburger hamburger = new Hamburger("Burger","Angus Beef",4.50,"Cheeseoregano");
hamburger.addHamburgerAddition1("Cheddar",0.50);
hamburger.addHamburgerAddition2("Jalapenos",0.55);
hamburger.addHamburgerAddition3("Beef Patty",1.00);
hamburger.addHamburgerAddition4("Bacon",0.55);
System.out.println("the full price is " + hamburger.itemizeHamburger());
HealthyBurger healthyBurger = new HealthyBurger("bacon",5.50);
healthyBurger.itemizeHamburger();
healthyBurger.addHealthyExtra1("Egg",2.00);
healthyBurger.addHealthyExtra2("Lettuce",0.50);
System.out.println("Full price for the HealthyBurger = " + healthyBurger.itemizeHamburger());
DeluxeHamburger deluxeHamburger = new DeluxeHamburger();
System.out.println("The total price is " + deluxeHamburger.itemizeHamburger());
}
}
| UTF-8 | Java | 988 | java | Main.java | Java | [
{
"context": " Hamburger hamburger = new Hamburger(\"Burger\",\"Angus Beef\",4.50,\"Cheeseoregano\");\n\n\n hamburger.addHa",
"end": 157,
"score": 0.9569586515426636,
"start": 147,
"tag": "NAME",
"value": "Angus Beef"
}
] | null | [] | package com.derToaster;
public class Main {
public static void main(String[] args) {
Hamburger hamburger = new Hamburger("Burger","<NAME>",4.50,"Cheeseoregano");
hamburger.addHamburgerAddition1("Cheddar",0.50);
hamburger.addHamburgerAddition2("Jalapenos",0.55);
hamburger.addHamburgerAddition3("Beef Patty",1.00);
hamburger.addHamburgerAddition4("Bacon",0.55);
System.out.println("the full price is " + hamburger.itemizeHamburger());
HealthyBurger healthyBurger = new HealthyBurger("bacon",5.50);
healthyBurger.itemizeHamburger();
healthyBurger.addHealthyExtra1("Egg",2.00);
healthyBurger.addHealthyExtra2("Lettuce",0.50);
System.out.println("Full price for the HealthyBurger = " + healthyBurger.itemizeHamburger());
DeluxeHamburger deluxeHamburger = new DeluxeHamburger();
System.out.println("The total price is " + deluxeHamburger.itemizeHamburger());
}
}
| 984 | 0.687247 | 0.656883 | 32 | 29.875 | 33.26292 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 3 |
90e0d7f947514894378d0fd9d89a6bdc9226578f | 38,714,835,228,713 | 922caf782fb40ce4af6fc1497cd6429bf0c2431c | /src/main/java/com/apap/tutorial6/service/UserRoleService.java | a3ef15b50021abfa2032e667ce1d0656320b40d2 | [] | no_license | Apap-2018/tutorial8_1606890561 | https://github.com/Apap-2018/tutorial8_1606890561 | 0db9c481121a3ca21f6ba042d29d0e329e64121a | 30f6b515a87fdae900a78803bbb71647d128a153 | refs/heads/master | 2020-04-05T04:38:05.203000 | 2018-11-07T14:32:31 | 2018-11-07T14:32:31 | 156,559,146 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.apap.tutorial6.service;
import com.apap.tutorial6.model.UserRoleModel;
public interface UserRoleService {
UserRoleModel addUser(UserRoleModel user);
public String encrypt(String password);
UserRoleModel updatePassword(String username, String oldPass, String newPass);
}
| UTF-8 | Java | 287 | java | UserRoleService.java | Java | [] | null | [] | package com.apap.tutorial6.service;
import com.apap.tutorial6.model.UserRoleModel;
public interface UserRoleService {
UserRoleModel addUser(UserRoleModel user);
public String encrypt(String password);
UserRoleModel updatePassword(String username, String oldPass, String newPass);
}
| 287 | 0.825784 | 0.818815 | 9 | 30.888889 | 24.946362 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.111111 | false | false | 3 |
d2dc19744984665e229c18d3272a0241bf2b56a2 | 39,178,691,705,398 | e4836d2521a56a6c891546e40af3d7fa51199605 | /RERSLearning/src/RERSlearner/CacheInconsistencyException.java | 9c7e4cd9cff31af5594bb352eb82b3a0f57945d3 | [] | no_license | TUDelft-CS4110-20162017/syllabus | https://github.com/TUDelft-CS4110-20162017/syllabus | eb824906f9a41d3c94574bf81479861265da79a3 | 1ad6c8b76a65695acc79f5ea1753f4a6515af4eb | refs/heads/master | 2017-12-01T00:37:16.195000 | 2017-05-24T18:40:52 | 2017-05-24T18:40:52 | 81,927,634 | 11 | 7 | null | false | 2017-02-14T12:31:09 | 2017-02-14T09:20:21 | 2017-02-14T09:20:21 | 2017-02-14T12:31:09 | 0 | 0 | 1 | 0 | null | null | null | package RERSlearner;
import net.automatalib.words.Word;
/**
* Contains the full input for which non-determinism was observed, as well as the full new output
* and the (possibly shorter) old output with which it disagrees
*
* @author Ramon Janssen
*/
public class CacheInconsistencyException extends RuntimeException {
private final Word oldOutput, newOutput, input;
public CacheInconsistencyException(Word input, Word oldOutput, Word newOutput) {
this.input = input;
this.oldOutput = oldOutput;
this.newOutput = newOutput;
}
public CacheInconsistencyException(String message, Word input, Word oldOutput, Word newOutput) {
super(message);
this.input = input;
this.oldOutput = oldOutput;
this.newOutput = newOutput;
}
/**
* The shortest cached output word which does not correspond with the new output
* @return
*/
public Word getOldOutput() {
return this.oldOutput;
}
/**
* The full new output word
* @return
*/
public Word getNewOutput() {
return this.newOutput;
}
/**
* The shortest sublist of the input word which still shows non-determinism
* @return
*/
public Word getShortestInconsistentInput() {
int indexOfInconsistency = 0;
while (oldOutput.getSymbol(indexOfInconsistency).equals(newOutput.getSymbol(indexOfInconsistency))) {
indexOfInconsistency ++;
}
return this.input.subWord(0, indexOfInconsistency);
}
@Override
public String toString() {
return "Non-determinism detected\nfull input:\n" + this.input + "\nfull new output:\n" + this.newOutput + "\nold output:\n" + this.oldOutput;
}
}
| UTF-8 | Java | 1,602 | java | CacheInconsistencyException.java | Java | [
{
"context": " old output with which it disagrees\n * \n * @author Ramon Janssen\n */\npublic class CacheInconsistencyException exte",
"end": 253,
"score": 0.9998270273208618,
"start": 240,
"tag": "NAME",
"value": "Ramon Janssen"
}
] | null | [] | package RERSlearner;
import net.automatalib.words.Word;
/**
* Contains the full input for which non-determinism was observed, as well as the full new output
* and the (possibly shorter) old output with which it disagrees
*
* @author <NAME>
*/
public class CacheInconsistencyException extends RuntimeException {
private final Word oldOutput, newOutput, input;
public CacheInconsistencyException(Word input, Word oldOutput, Word newOutput) {
this.input = input;
this.oldOutput = oldOutput;
this.newOutput = newOutput;
}
public CacheInconsistencyException(String message, Word input, Word oldOutput, Word newOutput) {
super(message);
this.input = input;
this.oldOutput = oldOutput;
this.newOutput = newOutput;
}
/**
* The shortest cached output word which does not correspond with the new output
* @return
*/
public Word getOldOutput() {
return this.oldOutput;
}
/**
* The full new output word
* @return
*/
public Word getNewOutput() {
return this.newOutput;
}
/**
* The shortest sublist of the input word which still shows non-determinism
* @return
*/
public Word getShortestInconsistentInput() {
int indexOfInconsistency = 0;
while (oldOutput.getSymbol(indexOfInconsistency).equals(newOutput.getSymbol(indexOfInconsistency))) {
indexOfInconsistency ++;
}
return this.input.subWord(0, indexOfInconsistency);
}
@Override
public String toString() {
return "Non-determinism detected\nfull input:\n" + this.input + "\nfull new output:\n" + this.newOutput + "\nold output:\n" + this.oldOutput;
}
}
| 1,595 | 0.720974 | 0.719725 | 60 | 25.700001 | 31.552233 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.35 | false | false | 3 |
b726be9d5a14e199def6877e0ff9397ac139776d | 34,986,803,645,702 | 94f583659d414852dbbd95fafc67adf93fed593f | /LZWmod.java | 4ff7b7ccf76d7ddbd46ae3503bcdc5c110f7db8e | [] | no_license | ZachBaker/LZW-Compression | https://github.com/ZachBaker/LZW-Compression | bd9ecce0517d21bad5bfac8bb3cda21298b26aec | 3d942bdd206be7e4779671e57e270382e19beede | refs/heads/master | 2021-01-20T10:41:26.906000 | 2014-09-29T16:41:02 | 2014-09-29T16:41:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.math.*;
public class LZWmod {
//R stays the same. Only used to load ASCII vals into Dictionary
private static final int R = 256; // number of input chars
//The range of bit lengths for the codewords. Starts at minW and does not exceed maxW
private static final int minW = 9; // codeword width
private static final int maxW = 16;
private static int currW = minW;
private static int currL = 512;
public static String dictOption;
public static void compress() {
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char) i, i);
int code = R+1; // R is codeword for EOF
boolean maxReached = false;
while (input.length() > 0) {
String s = st.longestPrefixOf(input);
//System.err.println(s);
BinaryStdOut.write(st.get(s),currW);
//System.err.println(s + " " + st.get(s) + " written to file at " + currW + " bits");
int t = s.length();
if (t < input.length() && code < currL){
st.put(input.substring(0, t + 1), code);
// System.err.println(input.substring(0, t+1) + " " + code + " added to dictionary");
code++;
input = input.substring(t);
}
if(t>=input.length())
break;
else if(t<input.length() && code == currL)
{
if(currW < maxW){
currW++;
currL = (int) Math.pow(2,currW);
}
else if(currW == maxW)
{
if(dictOption.equals("r"))
{
TST<Integer> temper = new TST<Integer>();
for(int i = 0; i < R; i++)
temper.put("" + (char) i, i);
code = R + 1;
st = temper;
currW = minW;
currL = (int) Math.pow(2, currW);
}
else if(dictOption.equals("m"))
{
}
else if(dictOption.equals("n"))
{
if(maxReached == true){
//BinaryStdOut.write(st.get(s),currW); // Scan past s in input.
//System.err.println(s + " " + st.get(s) + " written to file at " + currW + " bits");
input = input.substring(t);
}
else
maxReached = true;
}
}
}
}
BinaryStdOut.write(R, currW);
BinaryStdOut.close();
}
public static void expand() {
String[] st = new String[(int)Math.pow(2, maxW)];
int i; // next available codeword value
// initialize symbol table with all 1-character strings
for (i = 0; i < R; i++)
st[i] = "" + (char) i;
st[i++] = "";
int codeword = BinaryStdIn.readInt(currW); //Reads in codeword from file at current width
String val = st[codeword];
//System.err.println(val + " " + codeword + " found at " + currW);
while (true)
{
BinaryStdOut.write(val);
//System.err.println(val + " " + codeword + " was written to file");
codeword = BinaryStdIn.readInt(currW);
if (codeword == R) break;
String s = st[codeword];
if (i == codeword)
s = val + val.charAt(0); // special case hack
if (i < currL-1)
{
//System.err.println(val + " " + s.charAt(0) + " " + i);
st[i] = val + s.charAt(0);
//System.err.println(st[i] + " " + i + " added");
i++;
}
if(i == currL-1)
{
if(currW < maxW)
{
val = s;
st[i] = val + s.charAt(0);
currW++;
currL = (int) Math.pow(2,currW);
}
else if(currW == maxW)
{
if(dictOption.equals("n")){
val =s;
BinaryStdOut.write(val);
//System.err.println(val + " " + codeword + " was written");
codeword = BinaryStdIn.readInt(currW);
s = st[codeword];
st[i] = val + s.charAt(0);
//System.err.println(st[i] + " " + i + " " + " added");
i = (int) Math.pow(2,maxW) +1;
}
else if(dictOption.equals("r"))
{
val =s;
BinaryStdOut.write(val);
//System.err.println(val + " " + codeword + " was written");
codeword = BinaryStdIn.readInt(minW);
s = st[codeword];
st[i] = val + s.charAt(0);
//.err.println(st[i] + " " + i + " " + " added");
String [] newST = new String [(int) Math.pow(2,maxW)];
for(i = 0; i<R; i++)
{
st[i] = "" + (char) i;
}
st[i++] = "";
currW = minW;
currL = (int) Math.pow(2,currW);
}
}
}
val = s;
}
BinaryStdOut.close();
}
public static void main(String[] args) {
if(args[1].equals("r"))
dictOption = "r";
else if(args[1].equals("m"))
dictOption = "m";
else if(args[1].equals("n"))
dictOption = "n";
else throw new RuntimeException("Illegal command line argument");
if (args[0].equals("-")) compress();
else if (args[0].equals("+")) expand();
else throw new RuntimeException("Illegal command line argument");
}
} | UTF-8 | Java | 6,314 | java | LZWmod.java | Java | [] | null | [] | import java.math.*;
public class LZWmod {
//R stays the same. Only used to load ASCII vals into Dictionary
private static final int R = 256; // number of input chars
//The range of bit lengths for the codewords. Starts at minW and does not exceed maxW
private static final int minW = 9; // codeword width
private static final int maxW = 16;
private static int currW = minW;
private static int currL = 512;
public static String dictOption;
public static void compress() {
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char) i, i);
int code = R+1; // R is codeword for EOF
boolean maxReached = false;
while (input.length() > 0) {
String s = st.longestPrefixOf(input);
//System.err.println(s);
BinaryStdOut.write(st.get(s),currW);
//System.err.println(s + " " + st.get(s) + " written to file at " + currW + " bits");
int t = s.length();
if (t < input.length() && code < currL){
st.put(input.substring(0, t + 1), code);
// System.err.println(input.substring(0, t+1) + " " + code + " added to dictionary");
code++;
input = input.substring(t);
}
if(t>=input.length())
break;
else if(t<input.length() && code == currL)
{
if(currW < maxW){
currW++;
currL = (int) Math.pow(2,currW);
}
else if(currW == maxW)
{
if(dictOption.equals("r"))
{
TST<Integer> temper = new TST<Integer>();
for(int i = 0; i < R; i++)
temper.put("" + (char) i, i);
code = R + 1;
st = temper;
currW = minW;
currL = (int) Math.pow(2, currW);
}
else if(dictOption.equals("m"))
{
}
else if(dictOption.equals("n"))
{
if(maxReached == true){
//BinaryStdOut.write(st.get(s),currW); // Scan past s in input.
//System.err.println(s + " " + st.get(s) + " written to file at " + currW + " bits");
input = input.substring(t);
}
else
maxReached = true;
}
}
}
}
BinaryStdOut.write(R, currW);
BinaryStdOut.close();
}
public static void expand() {
String[] st = new String[(int)Math.pow(2, maxW)];
int i; // next available codeword value
// initialize symbol table with all 1-character strings
for (i = 0; i < R; i++)
st[i] = "" + (char) i;
st[i++] = "";
int codeword = BinaryStdIn.readInt(currW); //Reads in codeword from file at current width
String val = st[codeword];
//System.err.println(val + " " + codeword + " found at " + currW);
while (true)
{
BinaryStdOut.write(val);
//System.err.println(val + " " + codeword + " was written to file");
codeword = BinaryStdIn.readInt(currW);
if (codeword == R) break;
String s = st[codeword];
if (i == codeword)
s = val + val.charAt(0); // special case hack
if (i < currL-1)
{
//System.err.println(val + " " + s.charAt(0) + " " + i);
st[i] = val + s.charAt(0);
//System.err.println(st[i] + " " + i + " added");
i++;
}
if(i == currL-1)
{
if(currW < maxW)
{
val = s;
st[i] = val + s.charAt(0);
currW++;
currL = (int) Math.pow(2,currW);
}
else if(currW == maxW)
{
if(dictOption.equals("n")){
val =s;
BinaryStdOut.write(val);
//System.err.println(val + " " + codeword + " was written");
codeword = BinaryStdIn.readInt(currW);
s = st[codeword];
st[i] = val + s.charAt(0);
//System.err.println(st[i] + " " + i + " " + " added");
i = (int) Math.pow(2,maxW) +1;
}
else if(dictOption.equals("r"))
{
val =s;
BinaryStdOut.write(val);
//System.err.println(val + " " + codeword + " was written");
codeword = BinaryStdIn.readInt(minW);
s = st[codeword];
st[i] = val + s.charAt(0);
//.err.println(st[i] + " " + i + " " + " added");
String [] newST = new String [(int) Math.pow(2,maxW)];
for(i = 0; i<R; i++)
{
st[i] = "" + (char) i;
}
st[i++] = "";
currW = minW;
currL = (int) Math.pow(2,currW);
}
}
}
val = s;
}
BinaryStdOut.close();
}
public static void main(String[] args) {
if(args[1].equals("r"))
dictOption = "r";
else if(args[1].equals("m"))
dictOption = "m";
else if(args[1].equals("n"))
dictOption = "n";
else throw new RuntimeException("Illegal command line argument");
if (args[0].equals("-")) compress();
else if (args[0].equals("+")) expand();
else throw new RuntimeException("Illegal command line argument");
}
} | 6,314 | 0.399588 | 0.392936 | 199 | 30.733669 | 25.337608 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557789 | false | false | 3 |
e1e892a3d5f213f7b7acc38bd9f4a685aa6a0bc0 | 39,084,202,408,521 | b02d3e76726b2d838639f1547602f15ef26b42f9 | /src/main/java/com/surekam/modules/tracemodel/dao/TraceModelDatalDao.java | 5ba8f199785ca9dbf870e448cf29f3ac025d2869 | [] | no_license | yycGitHub/sourceTracing | https://github.com/yycGitHub/sourceTracing | 88dbe48d26fe4979aa0e58bb806ed58e2707dcb0 | 9a1050ef0264184baca3d9af1a294179d24a4e18 | refs/heads/master | 2022-12-04T12:59:30.712000 | 2020-08-27T08:50:59 | 2020-08-27T08:51:01 | 290,443,272 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.surekam.modules.tracemodel.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.surekam.common.persistence.BaseDao;
import com.surekam.common.persistence.Parameter;
import com.surekam.modules.tracemodel.entity.TraceModelData;
/**
* 溯源模块数据DAO接口
*
* @author liuyi
* @version 2018-09-25
*/
@Repository
public class TraceModelDatalDao extends BaseDao<TraceModelData> {
public List<TraceModelData> findByBatchid(String batchId) {
String sql = "select * from t_trace_model_data a where a.batch_id =:p1";
List<TraceModelData> findBySql = findBySql(sql, new Parameter(batchId), TraceModelData.class);
return findBySql;
}
}
| UTF-8 | Java | 699 | java | TraceModelDatalDao.java | Java | [
{
"context": "TraceModelData;\n\n/**\n * 溯源模块数据DAO接口\n * \n * @author liuyi\n * @version 2018-09-25\n */\n@Repository\npublic cla",
"end": 317,
"score": 0.9993419647216797,
"start": 312,
"tag": "USERNAME",
"value": "liuyi"
}
] | null | [] | package com.surekam.modules.tracemodel.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.surekam.common.persistence.BaseDao;
import com.surekam.common.persistence.Parameter;
import com.surekam.modules.tracemodel.entity.TraceModelData;
/**
* 溯源模块数据DAO接口
*
* @author liuyi
* @version 2018-09-25
*/
@Repository
public class TraceModelDatalDao extends BaseDao<TraceModelData> {
public List<TraceModelData> findByBatchid(String batchId) {
String sql = "select * from t_trace_model_data a where a.batch_id =:p1";
List<TraceModelData> findBySql = findBySql(sql, new Parameter(batchId), TraceModelData.class);
return findBySql;
}
}
| 699 | 0.775988 | 0.762811 | 26 | 25.26923 | 27.817478 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.730769 | false | false | 3 |
14ff07398664fa4a0f63586be2346913890f4b26 | 34,926,674,101,618 | 477c05b76a2bcd221e3c25372d1c56ec37d98c15 | /moe.apple/moe.platform.ios/src/main/java/apple/security/enums/SSLSessionOption.java | 6ff5732ce0cf23067dcbf665b7b399d3b160e4bc | [
"Apache-2.0",
"ICU",
"W3C"
] | permissive | multi-os-engine/moe-core | https://github.com/multi-os-engine/moe-core | 4ef065f4c292b46e27a59da5d6d7faa22773b035 | dcc886030f9ba999d42e2f4f1a562e15f7772cca | refs/heads/moe-master | 2023-07-09T17:49:49.935000 | 2023-06-13T17:34:08 | 2023-06-13T17:34:08 | 65,316,489 | 35 | 8 | Apache-2.0 | false | 2023-06-13T17:34:09 | 2016-08-09T17:54:29 | 2023-01-25T09:19:58 | 2023-06-13T17:34:08 | 46,514 | 28 | 6 | 1 | Java | false | false | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.security.enums;
import org.moe.natj.general.ann.Generated;
/**
* SSL session options
*/
@Generated
public final class SSLSessionOption {
/**
* Set this option to enable returning from SSLHandshake (with a result of
* errSSLServerAuthCompleted) when the server authentication portion of the
* handshake is complete. This disable certificate verification and
* provides an opportunity to perform application-specific server
* verification before deciding to continue.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnServerAuth = 0x00000000;
/**
* Set this option to enable returning from SSLHandshake (with a result of
* errSSLClientCertRequested) when the server requests a client certificate.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnCertRequested = 0x00000001;
/**
* This option is the same as kSSLSessionOptionBreakOnServerAuth but applies
* to the case where SecureTransport is the server and the client has presented
* its certificates allowing the server to verify whether these should be
* allowed to authenticate.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnClientAuth = 0x00000002;
/**
* Enable/Disable TLS False Start
* When enabled, False Start will only be performed if a adequate cipher-suite is
* negotiated.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int FalseStart = 0x00000003;
/**
* Enable/Disable 1/n-1 record splitting for BEAST attack mitigation.
* When enabled, record splitting will only be performed for TLS 1.0 connections
* using a block cipher.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int SendOneByteRecord = 0x00000004;
/**
* Allow/Disallow server identity change on renegotiation. Disallow by default
* to avoid Triple Handshake attack.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int AllowServerIdentityChange = 0x00000005;
/**
* Enable fallback countermeasures. Use this option when retyring a SSL connection
* with a lower protocol version because of failure to connect.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int Fallback = 0x00000006;
/**
* Set this option to break from a client hello in order to check for SNI
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnClientHello = 0x00000007;
/**
* Set this option to Allow renegotations. False by default.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int AllowRenegotiation = 0x00000008;
@Generated
private SSLSessionOption() {
}
/**
* Set this option to enable session tickets. False by default.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int EnableSessionTickets = 0x00000009;
}
| UTF-8 | Java | 3,979 | java | SSLSessionOption.java | Java | [] | null | [] | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.security.enums;
import org.moe.natj.general.ann.Generated;
/**
* SSL session options
*/
@Generated
public final class SSLSessionOption {
/**
* Set this option to enable returning from SSLHandshake (with a result of
* errSSLServerAuthCompleted) when the server authentication portion of the
* handshake is complete. This disable certificate verification and
* provides an opportunity to perform application-specific server
* verification before deciding to continue.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnServerAuth = 0x00000000;
/**
* Set this option to enable returning from SSLHandshake (with a result of
* errSSLClientCertRequested) when the server requests a client certificate.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnCertRequested = 0x00000001;
/**
* This option is the same as kSSLSessionOptionBreakOnServerAuth but applies
* to the case where SecureTransport is the server and the client has presented
* its certificates allowing the server to verify whether these should be
* allowed to authenticate.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnClientAuth = 0x00000002;
/**
* Enable/Disable TLS False Start
* When enabled, False Start will only be performed if a adequate cipher-suite is
* negotiated.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int FalseStart = 0x00000003;
/**
* Enable/Disable 1/n-1 record splitting for BEAST attack mitigation.
* When enabled, record splitting will only be performed for TLS 1.0 connections
* using a block cipher.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int SendOneByteRecord = 0x00000004;
/**
* Allow/Disallow server identity change on renegotiation. Disallow by default
* to avoid Triple Handshake attack.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int AllowServerIdentityChange = 0x00000005;
/**
* Enable fallback countermeasures. Use this option when retyring a SSL connection
* with a lower protocol version because of failure to connect.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int Fallback = 0x00000006;
/**
* Set this option to break from a client hello in order to check for SNI
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int BreakOnClientHello = 0x00000007;
/**
* Set this option to Allow renegotations. False by default.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int AllowRenegotiation = 0x00000008;
@Generated
private SSLSessionOption() {
}
/**
* Set this option to enable session tickets. False by default.
*
* API-Since: 2.0
* Deprecated-Since: 13.0
*/
@Deprecated @Generated public static final int EnableSessionTickets = 0x00000009;
}
| 3,979 | 0.688867 | 0.649661 | 115 | 33.599998 | 30.073187 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.165217 | false | false | 3 |
6560d9d436454c99188f993ffd666c1a8f1db405 | 16,415,365,069,625 | 881baca95d0379cbc136efceb91575fa2c167cbe | /codemaster-bat50question/src/main/java/tech/codemaster/bat50question/apachecommons/IOUtilsTest.java | 4381687fb10931a02a1f52809c171c1f1d226fdf | [
"MIT"
] | permissive | xianrendzw/CodeMaster | https://github.com/xianrendzw/CodeMaster | 0cb3063baf87af77e224c0756055de1aa505fb81 | ab755b23645e58fd7ba2e7a90e855fb4f0de99e9 | refs/heads/master | 2021-01-11T02:54:01.607000 | 2017-06-04T09:07:46 | 2017-06-04T09:07:46 | 70,885,411 | 4 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tech.codemaster.bat50question.apachecommons;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.IOUtils;
/**
* @author Tom Deng
* @date 2017-03-30
**/
public class IOUtilsTest {
public static void main(String... args) {
String file = "/Users/tomdeng/Downloads/test.txt";
try {
List<String> lines = IOUtils.readLines(new FileInputStream(file), StandardCharsets.UTF_8);
lines.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 659 | java | IOUtilsTest.java | Java | [
{
"context": "ort org.apache.commons.io.IOUtils;\n\n/**\n * @author Tom Deng\n * @date 2017-03-30\n **/\npublic class IOUtilsTest",
"end": 242,
"score": 0.9998862147331238,
"start": 234,
"tag": "NAME",
"value": "Tom Deng"
},
{
"context": "n(String... args) {\n String file = \"/Users/tomdeng/Downloads/test.txt\";\n try {\n Li",
"end": 378,
"score": 0.8590171933174133,
"start": 371,
"tag": "USERNAME",
"value": "tomdeng"
}
] | null | [] | package tech.codemaster.bat50question.apachecommons;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.IOUtils;
/**
* @author <NAME>
* @date 2017-03-30
**/
public class IOUtilsTest {
public static void main(String... args) {
String file = "/Users/tomdeng/Downloads/test.txt";
try {
List<String> lines = IOUtils.readLines(new FileInputStream(file), StandardCharsets.UTF_8);
lines.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 657 | 0.667678 | 0.650986 | 24 | 26.458334 | 24.038128 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 3 |
d133a901c62637536d0c86355f8a944e71b4bb5e | 39,479,339,396,376 | 34eba630757ec218b8ad14cd68379af78b878571 | /(0015) PhysicEngine/src/com/tawin/physicEngine/main/listener/Mouse.java | 015a1e7730fd545c7a677c27074c65d1c2f83f4a | [
"Apache-2.0"
] | permissive | Gabriel-Baril/java-projects | https://github.com/Gabriel-Baril/java-projects | 698c23af37837d5334dcdd5ca5eb57b2b188c3e5 | fa56431ca4b20f86e64d24d9d61986c1bc77123f | refs/heads/master | 2023-08-24T21:28:21.461000 | 2021-10-13T04:39:56 | 2021-10-13T04:39:56 | 416,586,200 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tawin.physicEngine.main.listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import com.tawin.physicEngine.debug.Debug;
import com.tawin.physicEngine.entity.shape.Polygon2D;
import com.tawin.physicEngine.main.Fenetre;
import com.tawin.physicEngine.main.Main;
import com.tawin.physicEngine.rendering.Panneau;
import com.tawin.physicEngine.toolKit.Collider2D;
import com.tawin.physicEngine.toolKit.Util;
import com.tawin.physicEngine.toolKit.Vec2;
public class Mouse implements MouseListener, MouseMotionListener{
private static Mouse instance;
public void mouseDragged(MouseEvent e) {
if(false){
Vec2 mouse = new Vec2(e.getX() - 3,e.getY() - 22);
for(int i = 0;i < Main.engine.getPolygons().size();i++){
if(Collider2D.POLY_POINT(Main.engine.getPolygons().get(i), mouse)){
Main.engine.getPolygons().get(i).vel.set(0, 0);
Main.engine.getPolygons().get(i).acc.set(0, 0);
for(int j = 0;j < Main.engine.getPolygons().get(i).vertices.size();j++){
Vec2 cVertex = Main.engine.getPolygons().get(i).vertices.get(j);
Vec2 diff = new Vec2(cVertex.x - mouse.x,cVertex.y - mouse.y);
Panneau.getInstance().getG2D().drawLine((int)mouse.x, (int)mouse.y, (int)(mouse.x - diff.x), (int)(mouse.y - diff.y));
cVertex.set(mouse.x - diff.x, mouse.y - diff.y);
}
}
}
}
if(true){ // EDIT MANUALLY THE VERTICES OF A POLYGON
ArrayList<Polygon2D> polygons = Main.engine.getPolygons();
boolean taken = false;
for(int i = 0;i < polygons.size();i++) {
for(int j = 0;j < polygons.get(i).vertices.size();j++) {
Vec2 cPoint = polygons.get(i).vertices.get(j);
if(Util.dist(cPoint, new Vec2(e.getX() - 3,e.getY() - 22)) < 10 && !taken) {
cPoint.set(e.getX() - 3,e.getY() - 22);
taken = true;
}
}
}
}
}
public void mouseMoved(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
if(Fenetre.running){
for(int i = 0;i < 10;i++){
Polygon2D p = new Polygon2D(new Vec2(e.getX() - 3,e.getY() - 22), 10, Util.rand(3, 6));
p.setColor(Util.rand(0, 255), Util.rand(0, 255), Util.rand(0, 255));
Main.engine.addEntity(p);
}
}
ArrayList<Polygon2D> shapes = Main.engine.getPolygons();
for(int i = 0;i < shapes.size();i++) {
if(shapes.get(i).isClicked(e.getX() - 3,e.getY() - 22)) {
Panneau.getInstance().getG2D().drawOval(e.getX() - 3,e.getY() - 22, 4, 4);
System.out.println("Entity : " + i + " touched");
}
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public static Mouse getInstance(){
if(instance == null){
instance = new Mouse();
}
return instance;
}
}
| UTF-8 | Java | 2,863 | java | Mouse.java | Java | [] | null | [] | package com.tawin.physicEngine.main.listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import com.tawin.physicEngine.debug.Debug;
import com.tawin.physicEngine.entity.shape.Polygon2D;
import com.tawin.physicEngine.main.Fenetre;
import com.tawin.physicEngine.main.Main;
import com.tawin.physicEngine.rendering.Panneau;
import com.tawin.physicEngine.toolKit.Collider2D;
import com.tawin.physicEngine.toolKit.Util;
import com.tawin.physicEngine.toolKit.Vec2;
public class Mouse implements MouseListener, MouseMotionListener{
private static Mouse instance;
public void mouseDragged(MouseEvent e) {
if(false){
Vec2 mouse = new Vec2(e.getX() - 3,e.getY() - 22);
for(int i = 0;i < Main.engine.getPolygons().size();i++){
if(Collider2D.POLY_POINT(Main.engine.getPolygons().get(i), mouse)){
Main.engine.getPolygons().get(i).vel.set(0, 0);
Main.engine.getPolygons().get(i).acc.set(0, 0);
for(int j = 0;j < Main.engine.getPolygons().get(i).vertices.size();j++){
Vec2 cVertex = Main.engine.getPolygons().get(i).vertices.get(j);
Vec2 diff = new Vec2(cVertex.x - mouse.x,cVertex.y - mouse.y);
Panneau.getInstance().getG2D().drawLine((int)mouse.x, (int)mouse.y, (int)(mouse.x - diff.x), (int)(mouse.y - diff.y));
cVertex.set(mouse.x - diff.x, mouse.y - diff.y);
}
}
}
}
if(true){ // EDIT MANUALLY THE VERTICES OF A POLYGON
ArrayList<Polygon2D> polygons = Main.engine.getPolygons();
boolean taken = false;
for(int i = 0;i < polygons.size();i++) {
for(int j = 0;j < polygons.get(i).vertices.size();j++) {
Vec2 cPoint = polygons.get(i).vertices.get(j);
if(Util.dist(cPoint, new Vec2(e.getX() - 3,e.getY() - 22)) < 10 && !taken) {
cPoint.set(e.getX() - 3,e.getY() - 22);
taken = true;
}
}
}
}
}
public void mouseMoved(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
if(Fenetre.running){
for(int i = 0;i < 10;i++){
Polygon2D p = new Polygon2D(new Vec2(e.getX() - 3,e.getY() - 22), 10, Util.rand(3, 6));
p.setColor(Util.rand(0, 255), Util.rand(0, 255), Util.rand(0, 255));
Main.engine.addEntity(p);
}
}
ArrayList<Polygon2D> shapes = Main.engine.getPolygons();
for(int i = 0;i < shapes.size();i++) {
if(shapes.get(i).isClicked(e.getX() - 3,e.getY() - 22)) {
Panneau.getInstance().getG2D().drawOval(e.getX() - 3,e.getY() - 22, 4, 4);
System.out.println("Entity : " + i + " touched");
}
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public static Mouse getInstance(){
if(instance == null){
instance = new Mouse();
}
return instance;
}
}
| 2,863 | 0.657003 | 0.633252 | 96 | 28.822916 | 27.267195 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.75 | false | false | 3 |
3e92140450530af35463c7296e0b2ef5c7c2ce06 | 39,556,648,829,721 | 2aeface07bc780ece7867bbb09486b9392207961 | /lxdjavalib/src/main/java/de/serversenke/lxd/client/core/model/InstantConverter.java | c62ac048967d5e25df8b0fd59c3196200d3f0936 | [
"Apache-2.0"
] | permissive | durai145/lxdjava | https://github.com/durai145/lxdjava | cddf87cf0fe29d47e95b9004ec7315183abb7b1c | d75d04b4b58b6b5d670d3b8f754a11d66e5c3957 | refs/heads/master | 2022-01-06T17:59:51.390000 | 2018-10-06T10:56:12 | 2018-10-06T10:56:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.serversenke.lxd.client.core.model;
import java.lang.reflect.Type;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class InstantConverter implements JsonSerializer<Instant>, JsonDeserializer<Instant> {
private static final DateTimeFormatter FORMATTER_1 = DateTimeFormatter.ISO_INSTANT;
private static final DateTimeFormatter FORMATTER_2 = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
private static final Pattern datePattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})\\.(\\d*)((\\-|\\+)?-\\d{2}:\\d{2})");
public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(FORMATTER_1.format(src));
}
public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return FORMATTER_1.parse(json.getAsString(), Instant::from);
} catch (Exception e) {
String jsonString;
Matcher m = datePattern.matcher(json.getAsString());
if (m.matches()) {
jsonString = m.group(1) + m.group(3);
} else {
jsonString = json.getAsString();
}
return FORMATTER_2.parse(jsonString, Instant::from);
}
}
}
| UTF-8 | Java | 1,697 | java | InstantConverter.java | Java | [] | null | [] | package de.serversenke.lxd.client.core.model;
import java.lang.reflect.Type;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class InstantConverter implements JsonSerializer<Instant>, JsonDeserializer<Instant> {
private static final DateTimeFormatter FORMATTER_1 = DateTimeFormatter.ISO_INSTANT;
private static final DateTimeFormatter FORMATTER_2 = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
private static final Pattern datePattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})\\.(\\d*)((\\-|\\+)?-\\d{2}:\\d{2})");
public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(FORMATTER_1.format(src));
}
public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return FORMATTER_1.parse(json.getAsString(), Instant::from);
} catch (Exception e) {
String jsonString;
Matcher m = datePattern.matcher(json.getAsString());
if (m.matches()) {
jsonString = m.group(1) + m.group(3);
} else {
jsonString = json.getAsString();
}
return FORMATTER_2.parse(jsonString, Instant::from);
}
}
}
| 1,697 | 0.697113 | 0.688273 | 43 | 38.465115 | 35.123932 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72093 | false | false | 3 |
770b446608ec80c6ce40823a48edbd682c8fa830 | 39,024,072,871,159 | 6f5134aab1694cf09f633807222b89ee1198a4c3 | /src/main/java/net/cassite/vproxy/component/exception/NotFoundException.java | a0ff34ead8dbad16f30e23b0b87e30a9dd7e7b03 | [
"MIT"
] | permissive | EightRoute/vproxy | https://github.com/EightRoute/vproxy | 4652c9fbf0e53d645c0c2f738697327f4feaa6b9 | 9d2f23b432101d47d8eb525205934c3164e35262 | refs/heads/master | 2020-04-18T06:12:36.203000 | 2019-01-26T13:21:32 | 2019-01-26T13:21:32 | 167,310,248 | 0 | 0 | MIT | true | 2019-01-24T05:43:05 | 2019-01-24T05:43:05 | 2019-01-24T05:25:33 | 2019-01-23T18:31:12 | 214 | 0 | 0 | 0 | null | false | null | package net.cassite.vproxy.component.exception;
public class NotFoundException extends Exception {
public NotFoundException() {
super(null, null, false, false);
}
}
| UTF-8 | Java | 182 | java | NotFoundException.java | Java | [] | null | [] | package net.cassite.vproxy.component.exception;
public class NotFoundException extends Exception {
public NotFoundException() {
super(null, null, false, false);
}
}
| 182 | 0.71978 | 0.71978 | 7 | 25 | 20.646688 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 3 |
0e23c62a8084335356c6ee1c8a70940e79c966dc | 35,347,580,894,315 | e1d56f3826333b980128f400ca208dd65cb9308f | /spring-boot-01-init-02/src/main/java/com/hxch/springboot/service/EmpService.java | 6c2a673990b3bb22b80d100416ae9f1ffccd2ca6 | [] | no_license | PangZiShenTiHao/springBoot_demo | https://github.com/PangZiShenTiHao/springBoot_demo | 844816d87767b11a85566b1765ae9f060b57524e | a12a33a959a232394b7f7c873e4c772843fe604f | refs/heads/master | 2020-12-09T18:05:25.149000 | 2020-01-22T02:51:28 | 2020-01-22T02:51:28 | 233,378,805 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hxch.springboot.service;
import org.springframework.stereotype.Service;
/**
* @ClassName:EmpService
* @Description:TODO
* @Author:huangxc
* @Date: 2020/1/15 0015 15:15
**/
public class EmpService {
public void add(){
System.out.println("add() ... ");
};
}
| UTF-8 | Java | 292 | java | EmpService.java | Java | [
{
"context": "ssName:EmpService\n * @Description:TODO\n * @Author:huangxc\n * @Date: 2020/1/15 0015 15:15\n **/\n\npublic class",
"end": 154,
"score": 0.9996418356895447,
"start": 147,
"tag": "USERNAME",
"value": "huangxc"
}
] | null | [] | package com.hxch.springboot.service;
import org.springframework.stereotype.Service;
/**
* @ClassName:EmpService
* @Description:TODO
* @Author:huangxc
* @Date: 2020/1/15 0015 15:15
**/
public class EmpService {
public void add(){
System.out.println("add() ... ");
};
}
| 292 | 0.65411 | 0.60274 | 16 | 17.25 | 15.21307 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 3 |
22e889b1656fae18dde825f1a5da2f88214fa11b | 19,430,432,100,200 | 36e33608e4f9a1bfd17d097cecb1ba1763e6a56d | /java/mes_producer/.svn/pristine/22/22e889b1656fae18dde825f1a5da2f88214fa11b.svn-base | 972edbb0c13ae4c9c145d144cf2831dc42705281 | [
"Apache-2.0"
] | permissive | sirsir/TSE-TMEIC | https://github.com/sirsir/TSE-TMEIC | fa8f6eed334f882b1a3d3540b2e926e1d9903ed4 | 9494a9dc05dc43f2353c3855bca4cfcaa67c830a | refs/heads/master | 2020-03-28T17:12:56.572000 | 2018-09-14T09:49:09 | 2018-09-14T09:49:09 | 148,768,600 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jp.co.tmeic.mespd.entity;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
* 役割マスタ
*
*/
@Entity
@Generated(value = {"S2JDBC-Gen 2.4.46", "org.seasar.extension.jdbc.gen.internal.model.EntityModelFactoryImpl"})
public class MRole implements Serializable {
private static final long serialVersionUID = 1L;
/** 追加日 */
@Column(nullable = false, unique = false)
public Timestamp createDate;
/** 更新日 */
@Column(nullable = false, unique = false)
public Timestamp updateDate;
/** 役割ID */
@Id
@Column(length = 10, nullable = false, unique = true)
public String roleId;
/** 役割名 */
@Column(length = 30, nullable = false, unique = false)
public String roleName;
/** MRoleAuthorityList関連プロパティ */
@OneToMany(mappedBy = "MRole")
public List<MRoleAuthority> MRoleAuthorityList;
/** MUsersRoleList関連プロパティ */
@OneToMany(mappedBy = "MRole")
public List<MUsersRole> MUsersRoleList;
} | UTF-8 | Java | 1,268 | 22e889b1656fae18dde825f1a5da2f88214fa11b.svn-base | Java | [] | null | [] | package jp.co.tmeic.mespd.entity;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
* 役割マスタ
*
*/
@Entity
@Generated(value = {"S2JDBC-Gen 2.4.46", "org.seasar.extension.jdbc.gen.internal.model.EntityModelFactoryImpl"})
public class MRole implements Serializable {
private static final long serialVersionUID = 1L;
/** 追加日 */
@Column(nullable = false, unique = false)
public Timestamp createDate;
/** 更新日 */
@Column(nullable = false, unique = false)
public Timestamp updateDate;
/** 役割ID */
@Id
@Column(length = 10, nullable = false, unique = true)
public String roleId;
/** 役割名 */
@Column(length = 30, nullable = false, unique = false)
public String roleName;
/** MRoleAuthorityList関連プロパティ */
@OneToMany(mappedBy = "MRole")
public List<MRoleAuthority> MRoleAuthorityList;
/** MUsersRoleList関連プロパティ */
@OneToMany(mappedBy = "MRole")
public List<MUsersRole> MUsersRoleList;
} | 1,268 | 0.672185 | 0.663907 | 46 | 24.304348 | 22.070904 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
|
77e90be773a194eef5379c7d2396581c5cdf1940 | 24,816,321,075,930 | 15c47b904f9c9a87f7480526bbba416c36f5ca3c | /codegen-maven-plugin/src/main/java/org/unidal/maven/plugin/codegen/WebModuleMojo.java | 8e8c4f7db3f229e2893152ed642113e3430682e4 | [] | no_license | liyinhao/maven-plugins | https://github.com/liyinhao/maven-plugins | f5f1dbd3b5b82a64110e44e589b1c67094760e41 | 97fb7e3a949d8a5d476b44a0e7179016a627c8b7 | refs/heads/master | 2020-03-25T22:57:12.868000 | 2018-03-06T23:31:53 | 2018-03-06T23:31:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.unidal.maven.plugin.codegen;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.unidal.helper.Files;
import org.unidal.helper.Scanners;
import org.unidal.helper.Scanners.FileMatcher;
/**
* Prepare war resource from web modules.
*
* @goal web-module
* @phase prepare-package
* @requiresDependencyResolution compile
* @author Frankie Wu
*/
public class WebModuleMojo extends AbstractMojo {
/**
* Current project
*
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject m_project;
/**
* Verbose information or not
*
* @parameter expression="${verbose}" default-value="false"
*/
protected boolean verbose;
/**
* Verbose information or not
*
* @parameter expression="${debug}" default-value="false"
*/
protected boolean debug;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
String webappDir = m_project.getBuild().getDirectory() + "/" + m_project.getBuild().getFinalName();
List<String> classpathElements = m_project.getCompileClasspathElements();
WebModuleResourceManager manager = new WebModuleResourceManager(webappDir, classpathElements);
manager.process();
} catch (Exception e) {
throw new MojoExecutionException("Error when generating plexus components descriptor!", e);
}
}
class WebModuleResourceManager {
private File m_webappDir;
private List<String> m_classpathElements;
public WebModuleResourceManager(String webappDir, List<String> classpathElements) throws Exception {
m_webappDir = new File(webappDir).getCanonicalFile();
m_classpathElements = classpathElements;
}
public void process() throws Exception {
for (String classpathElement : m_classpathElements) {
processElement(new File(classpathElement).getCanonicalFile());
}
}
private void processElement(File classpathElement) throws IOException {
if (!classpathElement.isDirectory()) {
List<String> entries = Scanners.forJar().scan(classpathElement, new FileMatcher() {
@Override
public Direction matches(File base, String path) {
if (path.startsWith("WEB-MODULE")) {
return Direction.MATCHED;
}
return Direction.DOWN;
}
});
for (String entry : entries) {
URL url = new URL("jar:file:" + classpathElement + "!/" + entry);
File dst = new File(m_webappDir, entry.substring("WEB-MODULE".length()));
dst.getParentFile().mkdirs();
if (!dst.exists()) {
Files.forIO().copy(url.openStream(), new FileOutputStream(dst));
}
}
} else {
File base = new File(classpathElement, "WEB-MODULE");
if (base.exists()) {
final List<String> pathes = new ArrayList<String>();
Scanners.forDir().scan(base, new FileMatcher() {
@Override
public Direction matches(File base, String path) {
pathes.add(path);
return Direction.DOWN;
}
});
for (String path : pathes) {
File src = new File(base, path);
File dst = new File(m_webappDir, path);
if (src.isDirectory()) {
dst.mkdirs();
} else if (!dst.exists()) {
Files.forDir().copyFile(src, dst);
}
}
}
}
}
}
}
| UTF-8 | Java | 4,229 | java | WebModuleMojo.java | Java | [
{
"context": " @requiresDependencyResolution compile\r\n * @author Frankie Wu\r\n */\r\npublic class WebModuleMojo extends Abstract",
"end": 692,
"score": 0.9997133612632751,
"start": 682,
"tag": "NAME",
"value": "Frankie Wu"
}
] | null | [] | package org.unidal.maven.plugin.codegen;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.unidal.helper.Files;
import org.unidal.helper.Scanners;
import org.unidal.helper.Scanners.FileMatcher;
/**
* Prepare war resource from web modules.
*
* @goal web-module
* @phase prepare-package
* @requiresDependencyResolution compile
* @author <NAME>
*/
public class WebModuleMojo extends AbstractMojo {
/**
* Current project
*
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject m_project;
/**
* Verbose information or not
*
* @parameter expression="${verbose}" default-value="false"
*/
protected boolean verbose;
/**
* Verbose information or not
*
* @parameter expression="${debug}" default-value="false"
*/
protected boolean debug;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
String webappDir = m_project.getBuild().getDirectory() + "/" + m_project.getBuild().getFinalName();
List<String> classpathElements = m_project.getCompileClasspathElements();
WebModuleResourceManager manager = new WebModuleResourceManager(webappDir, classpathElements);
manager.process();
} catch (Exception e) {
throw new MojoExecutionException("Error when generating plexus components descriptor!", e);
}
}
class WebModuleResourceManager {
private File m_webappDir;
private List<String> m_classpathElements;
public WebModuleResourceManager(String webappDir, List<String> classpathElements) throws Exception {
m_webappDir = new File(webappDir).getCanonicalFile();
m_classpathElements = classpathElements;
}
public void process() throws Exception {
for (String classpathElement : m_classpathElements) {
processElement(new File(classpathElement).getCanonicalFile());
}
}
private void processElement(File classpathElement) throws IOException {
if (!classpathElement.isDirectory()) {
List<String> entries = Scanners.forJar().scan(classpathElement, new FileMatcher() {
@Override
public Direction matches(File base, String path) {
if (path.startsWith("WEB-MODULE")) {
return Direction.MATCHED;
}
return Direction.DOWN;
}
});
for (String entry : entries) {
URL url = new URL("jar:file:" + classpathElement + "!/" + entry);
File dst = new File(m_webappDir, entry.substring("WEB-MODULE".length()));
dst.getParentFile().mkdirs();
if (!dst.exists()) {
Files.forIO().copy(url.openStream(), new FileOutputStream(dst));
}
}
} else {
File base = new File(classpathElement, "WEB-MODULE");
if (base.exists()) {
final List<String> pathes = new ArrayList<String>();
Scanners.forDir().scan(base, new FileMatcher() {
@Override
public Direction matches(File base, String path) {
pathes.add(path);
return Direction.DOWN;
}
});
for (String path : pathes) {
File src = new File(base, path);
File dst = new File(m_webappDir, path);
if (src.isDirectory()) {
dst.mkdirs();
} else if (!dst.exists()) {
Files.forDir().copyFile(src, dst);
}
}
}
}
}
}
}
| 4,225 | 0.573658 | 0.573658 | 130 | 30.530769 | 27.217978 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438462 | false | false | 3 |
e13d9d0cde519479289091fe8f7802ee8c4d6ee3 | 755,914,312,109 | 30444dd3f472c6ed3b0bdac0b8e07c2ed1bf23c3 | /src/main/java/com/example/springlesson3/interfaces/ProductRepository.java | 780404f6b5b3e0eac8caed65a869cde40819b831 | [] | no_license | CAHbKA-A/SpringLesson3 | https://github.com/CAHbKA-A/SpringLesson3 | 1abafcf7aa18b889bbbce9665ca4a8ecd57c748d | 70ffe020a5f9026b773c0ff0f719760509596587 | refs/heads/master | 2023-08-27T20:06:13.005000 | 2021-11-06T10:44:15 | 2021-11-06T10:44:15 | 416,756,949 | 0 | 0 | null | false | 2021-11-06T11:44:55 | 2021-10-13T13:33:55 | 2021-11-06T10:44:19 | 2021-11-06T11:44:55 | 497 | 0 | 0 | 1 | Java | false | false | package com.example.springlesson3.interfaces;
import com.example.springlesson3.domain.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
//JPQL @Query("select p from Product p where p.title =:title") или
//SQL @Query (nativeQuery = true,value = "select * from Product p where p.title = :title") или
List<Product> findAllByTitle(String title);
//смотри список ключевых слов
//список пробуктов цена которых >= min и <= max
List<Product> findAllByCostGreaterThanEqualAndCostLessThanEqual(int minCost, int maxCost);
Page<Product> findAllByCostLessThanEqualAndCostGreaterThanEqual(Integer maxPrice, Integer minPrice, Pageable pageable);
//то же смаое
// List<Product> findAllByCostBetweenMinAndMax(int minCost, int maxCost);
//List<Product> findAllByCategories_nameCategory(String name); //_ = join
List<Product> findAllByCategories_PathUrl(String alias);
}
| UTF-8 | Java | 1,366 | java | ProductRepository.java | Java | [] | null | [] | package com.example.springlesson3.interfaces;
import com.example.springlesson3.domain.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
//JPQL @Query("select p from Product p where p.title =:title") или
//SQL @Query (nativeQuery = true,value = "select * from Product p where p.title = :title") или
List<Product> findAllByTitle(String title);
//смотри список ключевых слов
//список пробуктов цена которых >= min и <= max
List<Product> findAllByCostGreaterThanEqualAndCostLessThanEqual(int minCost, int maxCost);
Page<Product> findAllByCostLessThanEqualAndCostGreaterThanEqual(Integer maxPrice, Integer minPrice, Pageable pageable);
//то же смаое
// List<Product> findAllByCostBetweenMinAndMax(int minCost, int maxCost);
//List<Product> findAllByCategories_nameCategory(String name); //_ = join
List<Product> findAllByCategories_PathUrl(String alias);
}
| 1,366 | 0.777692 | 0.776154 | 34 | 37.205883 | 37.001415 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617647 | false | false | 3 |
79f47502042387be1be972577ede0e42edccab70 | 2,662,879,752,406 | d4dbd40c26629f84c5ece8835b354504b3982e08 | /Capstone project1-Varun and Minal/cart/src/main/java/com/springboot/cart/repository/ItemImplementation.java | d97d2ff31d7b7a5441e46a9a12286d938c0ebf84 | [] | no_license | varunmehrotra29/Ecommerce-website-using-spring-boot | https://github.com/varunmehrotra29/Ecommerce-website-using-spring-boot | 6e5827f88ce5755f7d72639b8706744b41fe56ee | 02eb5ffc45b0f13491ec210326a63c43b5e6960c | refs/heads/master | 2023-05-25T18:00:48.578000 | 2021-06-08T05:08:37 | 2021-06-08T05:08:37 | 297,249,349 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springboot.cart.repository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.springboot.cart.model.Item;
@Service
@Transactional
public class ItemImplementation {
@Autowired
private ItemDao itemdao;
public List<Item> findItems(){
return itemdao.findAll();
}
public Item getItem(int id) {
return itemdao.getOne(id);
}
}
| UTF-8 | Java | 541 | java | ItemImplementation.java | Java | [] | null | [] | package com.springboot.cart.repository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.springboot.cart.model.Item;
@Service
@Transactional
public class ItemImplementation {
@Autowired
private ItemDao itemdao;
public List<Item> findItems(){
return itemdao.findAll();
}
public Item getItem(int id) {
return itemdao.getOne(id);
}
}
| 541 | 0.744917 | 0.744917 | 27 | 18.037037 | 19.439329 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.851852 | false | false | 3 |
4492363cfc10e32b77fc75f6b6ee21213e8e77f1 | 13,211,319,451,175 | 45fa392274f154771b5d9364b62bc8cb741ddd94 | /backend/backend-impl/src/main/java/at/fhj/swd14/pse/tag/TagServiceImpl.java | b6ab64d3a37bd7e16061f9e11fe3380e6bf183d5 | [
"MIT"
] | permissive | Stefano1993/chr-krenn-fhj-ws2016-sd14-pse | https://github.com/Stefano1993/chr-krenn-fhj-ws2016-sd14-pse | b6c1445f453d94f6ef146140a8efb9c357d55605 | f20dc3f7759089b7cc63c4b613df28146193da03 | refs/heads/master | 2020-07-28T13:22:00.254000 | 2016-11-10T18:21:19 | 2016-11-10T18:21:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package at.fhj.swd14.pse.tag;
import javax.ejb.Stateless;
//Todo: implement methods
@Stateless
public class TagServiceImpl implements TagService{
@Override
public long save(TagDto tag) {
return 0;
}
@Override
public TagDto find(long id) {
return null;
}
@Override
public TagDto findByName(String name) {
return null;
}
}
| UTF-8 | Java | 388 | java | TagServiceImpl.java | Java | [] | null | [] | package at.fhj.swd14.pse.tag;
import javax.ejb.Stateless;
//Todo: implement methods
@Stateless
public class TagServiceImpl implements TagService{
@Override
public long save(TagDto tag) {
return 0;
}
@Override
public TagDto find(long id) {
return null;
}
@Override
public TagDto findByName(String name) {
return null;
}
}
| 388 | 0.639175 | 0.631443 | 25 | 14.52 | 14.546807 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 3 |
53b4713fbb90de3dd4987fe35b7c15609886f752 | 455,266,573,811 | 1c53ce0ecef4147c883362253e4f7fc44f420164 | /FinalProject/src/DemoClass.java | ac5b7f4651ba75f3061708af694b6047cc89242f | [] | no_license | Sam-Makman/Algorithms_Homework | https://github.com/Sam-Makman/Algorithms_Homework | 6c58f4fbf861b6f39f46cd99780f117f07bf8744 | 56614f2e8ab98997f20a57a99c1167ec59d40ec9 | refs/heads/master | 2021-01-17T19:25:38.167000 | 2015-12-11T21:21:30 | 2015-12-11T21:21:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class DemoClass implements AdvancedCompare<DemoClass>{
double dval;
public DemoClass(double d){
dval=d;
}
public double getValue(){
return dval;
}
@Override
public double advancedCompare(DemoClass cTo) {
return dval - cTo.getValue();
}
}
| UTF-8 | Java | 270 | java | DemoClass.java | Java | [] | null | [] |
public class DemoClass implements AdvancedCompare<DemoClass>{
double dval;
public DemoClass(double d){
dval=d;
}
public double getValue(){
return dval;
}
@Override
public double advancedCompare(DemoClass cTo) {
return dval - cTo.getValue();
}
}
| 270 | 0.7 | 0.7 | 18 | 13.944445 | 17.347662 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 3 |
ba023299a8dd7fa7b84438cc3b853fef5c46bbb9 | 21,629,455,350,025 | 64136cb242d067bc488991b9633bac7d474208a4 | /app/src/main/java/pizware/evaluapp/adapters/UserAdapter.java | ed3d88301935ac9b0785da0cfc120478f9c38c6d | [] | no_license | ErickPiz/EvaluApp | https://github.com/ErickPiz/EvaluApp | e5f2ca301ce6bfcba95c8ba59d26fd5f3dc78a82 | 672f9127ad1701330748023544c906e6b71e8f37 | refs/heads/master | 2021-09-07T12:24:50.527000 | 2018-02-22T21:58:20 | 2018-02-22T21:58:20 | 119,791,515 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pizware.evaluapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import io.realm.RealmResults;
import pizware.evaluapp.Models.User;
import pizware.evaluapp.R;
/**
* Created by Piz on 02/02/2018.
*/
public class UserAdapter extends BaseAdapter {
private Context context;
private RealmResults<User> users;
private int layout;
public UserAdapter(Context context, RealmResults<User> users, int layout) {
this.context = context;
this.users = users;
this.layout = layout;
}
@Override
public int getCount() {
return users.size();
}
@Override
public User getItem(int position) {
return users.get(position);
}
@Override
public long getItemId(int id) {
return id;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ViewHolder vh;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(layout, null);
vh = new ViewHolder();
vh.lblUser = (TextView) convertView.findViewById(R.id.lblUser);
vh.lblPassword = (TextView) convertView.findViewById(R.id.lblPassword);
vh.lblEmail = (TextView) convertView.findViewById(R.id.lblEmail);
vh.lblAdmin = (TextView) convertView.findViewById(R.id.lblAdmin);
vh.lblHint = (TextView) convertView.findViewById(R.id.lblHint);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
User user = users.get(position);
vh.lblUser.setText(user.getUser());
vh.lblPassword.setText(user.getPassword());
vh.lblEmail.setText(user.getEmail());
if (user.isAdmin())
vh.lblAdmin.setText("Admin");
else
vh.lblAdmin.setText("Not admin");
vh.lblHint.setText(user.getHint());
return convertView;
}
public class ViewHolder {
TextView lblUser;
TextView lblPassword;
TextView lblEmail;
TextView lblAdmin;
TextView lblHint;
}
}
| UTF-8 | Java | 2,299 | java | UserAdapter.java | Java | [
{
"context": "ser;\nimport pizware.evaluapp.R;\n\n/**\n * Created by Piz on 02/02/2018.\n */\n\npublic class UserAdapter exte",
"end": 369,
"score": 0.9941023588180542,
"start": 366,
"tag": "USERNAME",
"value": "Piz"
}
] | null | [] | package pizware.evaluapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import io.realm.RealmResults;
import pizware.evaluapp.Models.User;
import pizware.evaluapp.R;
/**
* Created by Piz on 02/02/2018.
*/
public class UserAdapter extends BaseAdapter {
private Context context;
private RealmResults<User> users;
private int layout;
public UserAdapter(Context context, RealmResults<User> users, int layout) {
this.context = context;
this.users = users;
this.layout = layout;
}
@Override
public int getCount() {
return users.size();
}
@Override
public User getItem(int position) {
return users.get(position);
}
@Override
public long getItemId(int id) {
return id;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ViewHolder vh;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(layout, null);
vh = new ViewHolder();
vh.lblUser = (TextView) convertView.findViewById(R.id.lblUser);
vh.lblPassword = (TextView) convertView.findViewById(R.id.lblPassword);
vh.lblEmail = (TextView) convertView.findViewById(R.id.lblEmail);
vh.lblAdmin = (TextView) convertView.findViewById(R.id.lblAdmin);
vh.lblHint = (TextView) convertView.findViewById(R.id.lblHint);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
User user = users.get(position);
vh.lblUser.setText(user.getUser());
vh.lblPassword.setText(user.getPassword());
vh.lblEmail.setText(user.getEmail());
if (user.isAdmin())
vh.lblAdmin.setText("Admin");
else
vh.lblAdmin.setText("Not admin");
vh.lblHint.setText(user.getHint());
return convertView;
}
public class ViewHolder {
TextView lblUser;
TextView lblPassword;
TextView lblEmail;
TextView lblAdmin;
TextView lblHint;
}
}
| 2,299 | 0.638104 | 0.634624 | 83 | 26.662651 | 22.227886 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578313 | false | false | 3 |
2b4edba444d62462e4b043828e74ca4abb0aa9f2 | 9,405,978,445,231 | 0b9fb22a19a1a19d246a5124145755d53d7c350e | /app/src/main/java/com/example/huynhvinh/applazada_java/Presenter/SanPhamDaMua/IPresenterSanPhamDaMua.java | 4f22514372829d2274f51a2f9702a81899ced311 | [] | no_license | HuynhVinh123/UngDungMuaSamTrucTuyen | https://github.com/HuynhVinh123/UngDungMuaSamTrucTuyen | 495b2c9f8826478384c4c54eee4b637ab3bc3cc2 | a771e4ded4a7aadebde9a86712eeaff64c86525c | refs/heads/master | 2020-05-24T15:34:10.495000 | 2019-07-28T01:50:35 | 2019-07-28T01:50:35 | 187,334,481 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.huynhvinh.applazada_java.Presenter.SanPhamDaMua;
import com.example.huynhvinh.applazada_java.model.ObjectClass.HoaDon;
import java.util.List;
public interface IPresenterSanPhamDaMua {
void LayDanhSachSanPhamDaMua(String trangthai,String manguoinhan);
}
| UTF-8 | Java | 280 | java | IPresenterSanPhamDaMua.java | Java | [] | null | [] | package com.example.huynhvinh.applazada_java.Presenter.SanPhamDaMua;
import com.example.huynhvinh.applazada_java.model.ObjectClass.HoaDon;
import java.util.List;
public interface IPresenterSanPhamDaMua {
void LayDanhSachSanPhamDaMua(String trangthai,String manguoinhan);
}
| 280 | 0.835714 | 0.835714 | 9 | 30.111111 | 30.351439 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 3 |
08b5e89c2cef4fcc6c4d7e0d811a914ccc792a6a | 8,220,567,470,591 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/9/9_a414f6cd10167ee3139bbbd5498ca0dd279fd6b5/Application/9_a414f6cd10167ee3139bbbd5498ca0dd279fd6b5_Application_s.java | 9da048e3be6aba11a56b5fa3d956a1f494e0e400 | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Application extends Controller {
public static void index() {
render();
}
public static void optionscalc() {
render(params);
}
public static void sayHello(String myName) {
//System.out.println("Rendering");
Map<String, Double> renderMap = null;
List<Map<String,Double>> m = new ArrayList<Map<String,Double>>();
try {
String buyOrSell = null;
String contracts = null;
String expirationDate = null;
String strike = null;
String callOrPut = null;
String premium= null;
String ticker = params.get("ticker");
String stockPrice = params.get("stockPrice");
Iterator<String> keyItr = params.data.keySet().iterator();
// int size = params.data.size() - 2;
// System.out.println("size is "+size);
//ok its multiple of 6 then
int noOfIndexes = Integer.parseInt(params.get("POITableCount"));
//System.out.println(("POITableCount is "+noOfIndexes));
List<Map<String,String>> positionsList = new ArrayList<Map<String,String>>();
//System.out.println("index is "+noOfIndexes);
// System.out.println(params.toString());
//now loop over
for(int i =1;i<=noOfIndexes;i++)
{
Map<String,String> map = new HashMap<String, String>();
buyOrSell = params.get("longshort_"+i);
if(buyOrSell == null || buyOrSell.trim().equals("--")) continue;
//System.out.println("buyOrSell is "+buyOrSell);
map.put("buyOrSell", buyOrSell);
contracts = params.get("contracts_"+i);
//System.out.println("Contracts is "+contracts);
map.put("contracts", contracts);
expirationDate = params.get("expiration_1");
map.put("expiration", expirationDate);
strike = params.get("strike_"+i);
map.put("strike", strike);
callOrPut = params.get("type_"+i);
map.put("callOrPut", callOrPut);
premium=params.get("premium_"+i);
map.put("premium", premium);
//System.out.println("map is "+map);
positionsList.add(map);
}
OptionsCalculator calculator = new OptionsCalculator();
renderMap = calculator.process(positionsList,ticker,stockPrice);
renderMap.put("inv", calculator.getInvestment());
m.add(renderMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String compare = params.get("compare");
//System.out.println("compare is "+compare);
if(compare !=null && compare.equals("compare"))
{
try {
String buyOrSell = null;
String contracts = null;
String expirationDate = null;
String strike = null;
String callOrPut = null;
String premium= null;
String ticker = params.get("ticker");
String stockPrice = params.get("stockPrice");
Iterator<String> keyItr = params.data.keySet().iterator();
// int size = params.data.size() - 2;
List<Map<String,String>> positionsList = new ArrayList<Map<String,String>>();
// System.out.println("size is "+size);
//ok its multiple of 6 then
int noOfIndexes = Integer.parseInt(params.get("POITable1Count"));
// System.out.println("POITable1Count is "+noOfIndexes);
// System.out.println(params.toString());
//now loop over
for(int i =1;i<=noOfIndexes;i++)
{
Map<String,String> map = new HashMap<String, String>();
buyOrSell = params.get("longshort_"+i+"c");
// System.out.println("b "+buyOrSell);
if(buyOrSell == null || buyOrSell.trim().equals("--")) continue;
//System.out.println("buyOrSell is "+buyOrSell);
map.put("buyOrSell", buyOrSell);
contracts = params.get("contracts_"+i+"c");
//System.out.println("Contracts is "+contracts);
map.put("contracts", contracts);
expirationDate = params.get("expiration_1");
map.put("expiration", expirationDate);
strike = params.get("strike_"+i+"c");
map.put("strike", strike);
callOrPut = params.get("type_"+i+"c");
map.put("callOrPut", callOrPut);
premium=params.get("premium_"+i+"c");
map.put("premium", premium);
//System.out.println("map is "+map);
positionsList.add(map);
}
if(!positionsList.isEmpty())
{
OptionsCalculator calculator = new OptionsCalculator();
renderMap = calculator.process(positionsList,ticker,stockPrice);
renderMap.put("inv_c",calculator.getInvestment());
//System.out.println("rendermap "+renderMap);
m.add(renderMap);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//System.out.println("M is "+m);
render(m);
}
public static void share() {
//System.out.println(params);
render(params);
}
}
| UTF-8 | Java | 5,090 | java | 9_a414f6cd10167ee3139bbbd5498ca0dd279fd6b5_Application_s.java | Java | [] | null | [] | package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Application extends Controller {
public static void index() {
render();
}
public static void optionscalc() {
render(params);
}
public static void sayHello(String myName) {
//System.out.println("Rendering");
Map<String, Double> renderMap = null;
List<Map<String,Double>> m = new ArrayList<Map<String,Double>>();
try {
String buyOrSell = null;
String contracts = null;
String expirationDate = null;
String strike = null;
String callOrPut = null;
String premium= null;
String ticker = params.get("ticker");
String stockPrice = params.get("stockPrice");
Iterator<String> keyItr = params.data.keySet().iterator();
// int size = params.data.size() - 2;
// System.out.println("size is "+size);
//ok its multiple of 6 then
int noOfIndexes = Integer.parseInt(params.get("POITableCount"));
//System.out.println(("POITableCount is "+noOfIndexes));
List<Map<String,String>> positionsList = new ArrayList<Map<String,String>>();
//System.out.println("index is "+noOfIndexes);
// System.out.println(params.toString());
//now loop over
for(int i =1;i<=noOfIndexes;i++)
{
Map<String,String> map = new HashMap<String, String>();
buyOrSell = params.get("longshort_"+i);
if(buyOrSell == null || buyOrSell.trim().equals("--")) continue;
//System.out.println("buyOrSell is "+buyOrSell);
map.put("buyOrSell", buyOrSell);
contracts = params.get("contracts_"+i);
//System.out.println("Contracts is "+contracts);
map.put("contracts", contracts);
expirationDate = params.get("expiration_1");
map.put("expiration", expirationDate);
strike = params.get("strike_"+i);
map.put("strike", strike);
callOrPut = params.get("type_"+i);
map.put("callOrPut", callOrPut);
premium=params.get("premium_"+i);
map.put("premium", premium);
//System.out.println("map is "+map);
positionsList.add(map);
}
OptionsCalculator calculator = new OptionsCalculator();
renderMap = calculator.process(positionsList,ticker,stockPrice);
renderMap.put("inv", calculator.getInvestment());
m.add(renderMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String compare = params.get("compare");
//System.out.println("compare is "+compare);
if(compare !=null && compare.equals("compare"))
{
try {
String buyOrSell = null;
String contracts = null;
String expirationDate = null;
String strike = null;
String callOrPut = null;
String premium= null;
String ticker = params.get("ticker");
String stockPrice = params.get("stockPrice");
Iterator<String> keyItr = params.data.keySet().iterator();
// int size = params.data.size() - 2;
List<Map<String,String>> positionsList = new ArrayList<Map<String,String>>();
// System.out.println("size is "+size);
//ok its multiple of 6 then
int noOfIndexes = Integer.parseInt(params.get("POITable1Count"));
// System.out.println("POITable1Count is "+noOfIndexes);
// System.out.println(params.toString());
//now loop over
for(int i =1;i<=noOfIndexes;i++)
{
Map<String,String> map = new HashMap<String, String>();
buyOrSell = params.get("longshort_"+i+"c");
// System.out.println("b "+buyOrSell);
if(buyOrSell == null || buyOrSell.trim().equals("--")) continue;
//System.out.println("buyOrSell is "+buyOrSell);
map.put("buyOrSell", buyOrSell);
contracts = params.get("contracts_"+i+"c");
//System.out.println("Contracts is "+contracts);
map.put("contracts", contracts);
expirationDate = params.get("expiration_1");
map.put("expiration", expirationDate);
strike = params.get("strike_"+i+"c");
map.put("strike", strike);
callOrPut = params.get("type_"+i+"c");
map.put("callOrPut", callOrPut);
premium=params.get("premium_"+i+"c");
map.put("premium", premium);
//System.out.println("map is "+map);
positionsList.add(map);
}
if(!positionsList.isEmpty())
{
OptionsCalculator calculator = new OptionsCalculator();
renderMap = calculator.process(positionsList,ticker,stockPrice);
renderMap.put("inv_c",calculator.getInvestment());
//System.out.println("rendermap "+renderMap);
m.add(renderMap);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//System.out.println("M is "+m);
render(m);
}
public static void share() {
//System.out.println(params);
render(params);
}
}
| 5,090 | 0.595678 | 0.593713 | 165 | 29.842424 | 20.86463 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.309091 | false | false | 3 |
d3cb75c210bf865df86dea4744f799de301211b7 | 27,238,682,607,158 | 62831a1fa8ab2d298dc8fa4940577c6e7eee6d42 | /JavaTrainingSession/src/JavaBasics/DataTypes.java | c150983c93ae6d4f05427ea9cd38d5ac59937681 | [] | no_license | sumanece2019/Sumanece2019 | https://github.com/sumanece2019/Sumanece2019 | fc8069f4e4faca6a8e8621b4f8847fd667791099 | 4525c49a6ef46650cb500bad69823a2c09fd2d3d | refs/heads/master | 2020-05-01T05:41:16.985000 | 2019-03-23T20:16:54 | 2019-03-23T20:16:54 | 177,309,155 | 0 | 0 | null | false | 2019-03-23T20:16:55 | 2019-03-23T15:56:38 | 2019-03-23T19:26:53 | 2019-03-23T20:16:54 | 0 | 0 | 0 | 0 | Java | false | null | package JavaBasics;
public class DataTypes {
//GLOBAL VARIABLES
static int my_int;
static byte my_byte;
static short my_short;
static long my_long;
static float my_float;
static double my_double;
static boolean my_boolean;
static char my_char;
public static void main(String[] args) {
//1. int
byte i = 10;//(1 byte,range -128 to 127,default value 0)
i=20;
System.out.println(i);
short j = 150;//2 bytes,range -32768 to 32767,default value 0
int k = 2147483647;//4 bytes,default value 0
long l = 1234567891234567891L;//8 bytes,default value 0
int String = 888;//String is a PreDefned Class Identifier,But it reduces readability
int Runnable = 999;//Runnable is a PreDefined Interface Identifier,But it reduces readability
//int 123ABC = 1; invalid as we can't use number at the beginning
System.out.println(j+" "+k+" "+l+" "+String+" "+Runnable);
//2. float
float marks = 89.45f;
//3. double
double d =12.33;
double d1 = 34.44;
double d2 =100; //I can store int in double but not double in int
System.out.println(d+" "+d1+" "+d2);
//4. char --> Only single digit value and should be written within single quote
char c = 'a';
System.out.println(c);
//5. boolean
boolean b1;
//System.out.println(b1);
b1 = true;
System.out.println(b1);
//down casting
int a = (int) 63.21;
System.out.println(a);
//int p = 65;
char h = 90;//will convert value as per unicode table
System.out.println(h);
System.out.println("Static byte:" + my_byte);
System.out.println("Static short:" + my_short);
System.out.println("Static int:" + my_int);
System.out.println("Static long:" + my_long);
System.out.println("Static float:" + my_float);
System.out.println("Static double:" + my_double);
System.out.println("Static boolean:" + my_boolean);
System.out.println("Static char:" + my_char);//prints null
}
}
| UTF-8 | Java | 1,935 | java | DataTypes.java | Java | [] | null | [] | package JavaBasics;
public class DataTypes {
//GLOBAL VARIABLES
static int my_int;
static byte my_byte;
static short my_short;
static long my_long;
static float my_float;
static double my_double;
static boolean my_boolean;
static char my_char;
public static void main(String[] args) {
//1. int
byte i = 10;//(1 byte,range -128 to 127,default value 0)
i=20;
System.out.println(i);
short j = 150;//2 bytes,range -32768 to 32767,default value 0
int k = 2147483647;//4 bytes,default value 0
long l = 1234567891234567891L;//8 bytes,default value 0
int String = 888;//String is a PreDefned Class Identifier,But it reduces readability
int Runnable = 999;//Runnable is a PreDefined Interface Identifier,But it reduces readability
//int 123ABC = 1; invalid as we can't use number at the beginning
System.out.println(j+" "+k+" "+l+" "+String+" "+Runnable);
//2. float
float marks = 89.45f;
//3. double
double d =12.33;
double d1 = 34.44;
double d2 =100; //I can store int in double but not double in int
System.out.println(d+" "+d1+" "+d2);
//4. char --> Only single digit value and should be written within single quote
char c = 'a';
System.out.println(c);
//5. boolean
boolean b1;
//System.out.println(b1);
b1 = true;
System.out.println(b1);
//down casting
int a = (int) 63.21;
System.out.println(a);
//int p = 65;
char h = 90;//will convert value as per unicode table
System.out.println(h);
System.out.println("Static byte:" + my_byte);
System.out.println("Static short:" + my_short);
System.out.println("Static int:" + my_int);
System.out.println("Static long:" + my_long);
System.out.println("Static float:" + my_float);
System.out.println("Static double:" + my_double);
System.out.println("Static boolean:" + my_boolean);
System.out.println("Static char:" + my_char);//prints null
}
}
| 1,935 | 0.658398 | 0.603618 | 76 | 24.460526 | 23.456814 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.394737 | false | false | 3 |
1e1e4e11c4d2989910ec34db0a727a726f3964b8 | 20,650,202,797,423 | 78ca46f242667b9ea20af6142ab54a96b15c5233 | /src/presenter/MainController.java | e712445427ee90f230256d8560caa18efdfdfe11 | [] | no_license | Maximvolk/ws-exam-project | https://github.com/Maximvolk/ws-exam-project | 992fb55da93ffee2bdff5ef87128ace083734e73 | 76d5e6137d71087f4f354deccac8825fe5922e93 | refs/heads/master | 2022-11-13T13:32:08.458000 | 2020-06-30T13:21:48 | 2020-06-30T13:21:48 | 276,103,508 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package presenter;
import core.entities.*;
import core.usecases.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MainController {
private LoginView loginView;
private MainView mainView;
private ProductUseCase productUseCase;
private ComponentUseCase componentUseCase;
public MainController(LoginView loginView, MainView mainView,
ProductUseCase productUseCase, ComponentUseCase componentUseCase) {
this.loginView = loginView;
this.mainView = mainView;
this.productUseCase = productUseCase;
this.componentUseCase = componentUseCase;
fillProductsData();
fillComponentsData();
setUpHandlers();
}
private void fillProductsData() {
List<Product> products = new ArrayList<>();
try {
products = productUseCase.getProducts();
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
mainView.fillProductsList(products);
mainView.fillProductNameComboBoxOptions(products);
}
private void fillComponentsData() {
List<Component> components = new ArrayList<>();
try {
components = componentUseCase.getComponents();
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
mainView.fillComponentsTable(components);
}
private void setUpHandlers() {
mainView.getLogoutButton().addActionListener(actionEvent -> handleLogoutButton());
mainView.getAddProductButton().addActionListener(actionEvent -> handleAddProductButton());
mainView.getAddComponentButton().addActionListener(actionEvent -> handleAddComponentButton());
mainView.getDeleteComponentButton().addActionListener(actionEvent -> handleDeleteComponentButton());
mainView.getEditComponentButton().addActionListener(actionEvent -> handleEditComponentButton());
mainView.getComponentsTable().getSelectionModel()
.addListSelectionListener(actionEvent -> handleComponentSelected());
}
private void handleLogoutButton() {
mainView.setVisible(false);
loginView.clearInputs();
loginView.setVisible(true);
}
private void handleAddProductButton() {
String name = mainView.getProductName();
String label = mainView.getProductLabel();
if (name.length() == 0 || label.length() == 0) {
JOptionPane.showMessageDialog(mainView, "Data must not be empty",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
int status;
try {
status = productUseCase.addProduct(name, label);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
return;
}
if (status == 0) {
fillProductsData();
mainView.clearProductInputs();
}
else if (status == 1)
JOptionPane.showMessageDialog(mainView, "Product exists", "Error", JOptionPane.ERROR_MESSAGE);
}
private void handleAddComponentButton() {
String name = mainView.getComponentName();
String serialNumber = mainView.getComponentSerialNumber();
Product product = mainView.getProductNameComboBoxValue();
if (!checkEnteredComponentData(name, serialNumber))
return;
int status;
try {
status = componentUseCase.addComponent(name, Long.parseLong(serialNumber), product.id);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
return;
}
if (status == 0) {
mainView.getComponentsTableModel().addRow(new Object[] {name, serialNumber, product.name});
mainView.clearComponentInputs();
}
else
JOptionPane.showMessageDialog(mainView, "Component exists", "Error", JOptionPane.ERROR_MESSAGE);
}
private void handleDeleteComponentButton() {
int selectedRow = mainView.getComponentsTable().getSelectedRow();
if (!checkComponentSelected(selectedRow))
return;
try {
componentUseCase.deleteComponent(
mainView.getComponentsTable().getValueAt(selectedRow, 0).toString());
mainView.getComponentsTableModel().removeRow(selectedRow);
mainView.clearComponentInputs();
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
}
private void handleEditComponentButton() {
int selectedRow = mainView.getComponentsTable().getSelectedRow();
String name = mainView.getComponentName();
String serialNumber = mainView.getComponentSerialNumber();
Product componentProduct = mainView.getProductNameComboBoxValue();
if (!checkComponentSelected(selectedRow) || !checkEnteredComponentData(name, serialNumber))
return;
int status;
try {
status = componentUseCase.editComponent(
mainView.getComponentsTable().getValueAt(selectedRow, 0).toString(),
name, Long.parseLong(serialNumber), componentProduct.id
);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
return;
}
if (status == 0) {
mainView.getComponentsTableModel().insertRow(
selectedRow, new Object[] {name, serialNumber, componentProduct.name});
mainView.getComponentsTableModel().removeRow(selectedRow + 1);
mainView.clearComponentInputs();
} else
JOptionPane.showMessageDialog(
mainView, "New component name equals name of already existing component",
"Error", JOptionPane.ERROR_MESSAGE
);
}
private void handleComponentSelected() {
JTable componentsTable = mainView.getComponentsTable();
int selectedRow = componentsTable.getSelectedRow();
// Avoid event handling after component deletion
if (selectedRow == -1)
return;
mainView.setComponentName(
componentsTable.getValueAt(selectedRow, 0).toString());
mainView.setComponentSerialNumber(
Long.parseLong(componentsTable.getValueAt(selectedRow, 1).toString()));
// This db query (every time) will cause much less performance overhead
// than storing all products objects in table (memory)
try {
Product product = productUseCase.getProductByName(
componentsTable.getValueAt(selectedRow, 2).toString());
mainView.setProductNameComboBoxValue(product);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
}
private boolean checkComponentSelected(int selectedRow) {
if (selectedRow < 0) {
JOptionPane.showMessageDialog(mainView, "No component selected", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private boolean checkEnteredComponentData(String name, String serialNumber) {
if (name.length() == 0 || serialNumber.length() == 0) {
JOptionPane.showMessageDialog(mainView, "Data must not be empty",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
if (!serialNumber.matches("[0-9]+")) {
JOptionPane.showMessageDialog(mainView, "Serial number must be a number",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
}
| UTF-8 | Java | 8,072 | java | MainController.java | Java | [] | null | [] | package presenter;
import core.entities.*;
import core.usecases.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MainController {
private LoginView loginView;
private MainView mainView;
private ProductUseCase productUseCase;
private ComponentUseCase componentUseCase;
public MainController(LoginView loginView, MainView mainView,
ProductUseCase productUseCase, ComponentUseCase componentUseCase) {
this.loginView = loginView;
this.mainView = mainView;
this.productUseCase = productUseCase;
this.componentUseCase = componentUseCase;
fillProductsData();
fillComponentsData();
setUpHandlers();
}
private void fillProductsData() {
List<Product> products = new ArrayList<>();
try {
products = productUseCase.getProducts();
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
mainView.fillProductsList(products);
mainView.fillProductNameComboBoxOptions(products);
}
private void fillComponentsData() {
List<Component> components = new ArrayList<>();
try {
components = componentUseCase.getComponents();
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
mainView.fillComponentsTable(components);
}
private void setUpHandlers() {
mainView.getLogoutButton().addActionListener(actionEvent -> handleLogoutButton());
mainView.getAddProductButton().addActionListener(actionEvent -> handleAddProductButton());
mainView.getAddComponentButton().addActionListener(actionEvent -> handleAddComponentButton());
mainView.getDeleteComponentButton().addActionListener(actionEvent -> handleDeleteComponentButton());
mainView.getEditComponentButton().addActionListener(actionEvent -> handleEditComponentButton());
mainView.getComponentsTable().getSelectionModel()
.addListSelectionListener(actionEvent -> handleComponentSelected());
}
private void handleLogoutButton() {
mainView.setVisible(false);
loginView.clearInputs();
loginView.setVisible(true);
}
private void handleAddProductButton() {
String name = mainView.getProductName();
String label = mainView.getProductLabel();
if (name.length() == 0 || label.length() == 0) {
JOptionPane.showMessageDialog(mainView, "Data must not be empty",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
int status;
try {
status = productUseCase.addProduct(name, label);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
return;
}
if (status == 0) {
fillProductsData();
mainView.clearProductInputs();
}
else if (status == 1)
JOptionPane.showMessageDialog(mainView, "Product exists", "Error", JOptionPane.ERROR_MESSAGE);
}
private void handleAddComponentButton() {
String name = mainView.getComponentName();
String serialNumber = mainView.getComponentSerialNumber();
Product product = mainView.getProductNameComboBoxValue();
if (!checkEnteredComponentData(name, serialNumber))
return;
int status;
try {
status = componentUseCase.addComponent(name, Long.parseLong(serialNumber), product.id);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
return;
}
if (status == 0) {
mainView.getComponentsTableModel().addRow(new Object[] {name, serialNumber, product.name});
mainView.clearComponentInputs();
}
else
JOptionPane.showMessageDialog(mainView, "Component exists", "Error", JOptionPane.ERROR_MESSAGE);
}
private void handleDeleteComponentButton() {
int selectedRow = mainView.getComponentsTable().getSelectedRow();
if (!checkComponentSelected(selectedRow))
return;
try {
componentUseCase.deleteComponent(
mainView.getComponentsTable().getValueAt(selectedRow, 0).toString());
mainView.getComponentsTableModel().removeRow(selectedRow);
mainView.clearComponentInputs();
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
}
private void handleEditComponentButton() {
int selectedRow = mainView.getComponentsTable().getSelectedRow();
String name = mainView.getComponentName();
String serialNumber = mainView.getComponentSerialNumber();
Product componentProduct = mainView.getProductNameComboBoxValue();
if (!checkComponentSelected(selectedRow) || !checkEnteredComponentData(name, serialNumber))
return;
int status;
try {
status = componentUseCase.editComponent(
mainView.getComponentsTable().getValueAt(selectedRow, 0).toString(),
name, Long.parseLong(serialNumber), componentProduct.id
);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
return;
}
if (status == 0) {
mainView.getComponentsTableModel().insertRow(
selectedRow, new Object[] {name, serialNumber, componentProduct.name});
mainView.getComponentsTableModel().removeRow(selectedRow + 1);
mainView.clearComponentInputs();
} else
JOptionPane.showMessageDialog(
mainView, "New component name equals name of already existing component",
"Error", JOptionPane.ERROR_MESSAGE
);
}
private void handleComponentSelected() {
JTable componentsTable = mainView.getComponentsTable();
int selectedRow = componentsTable.getSelectedRow();
// Avoid event handling after component deletion
if (selectedRow == -1)
return;
mainView.setComponentName(
componentsTable.getValueAt(selectedRow, 0).toString());
mainView.setComponentSerialNumber(
Long.parseLong(componentsTable.getValueAt(selectedRow, 1).toString()));
// This db query (every time) will cause much less performance overhead
// than storing all products objects in table (memory)
try {
Product product = productUseCase.getProductByName(
componentsTable.getValueAt(selectedRow, 2).toString());
mainView.setProductNameComboBoxValue(product);
} catch (SQLException ex) {
ExceptionHandlingUtil.handleUnexpectedError(ex, mainView);
}
}
private boolean checkComponentSelected(int selectedRow) {
if (selectedRow < 0) {
JOptionPane.showMessageDialog(mainView, "No component selected", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private boolean checkEnteredComponentData(String name, String serialNumber) {
if (name.length() == 0 || serialNumber.length() == 0) {
JOptionPane.showMessageDialog(mainView, "Data must not be empty",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
if (!serialNumber.matches("[0-9]+")) {
JOptionPane.showMessageDialog(mainView, "Serial number must be a number",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
}
| 8,072 | 0.641477 | 0.639247 | 224 | 35.035713 | 30.034334 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.683036 | false | false | 3 |
52b4d6b0e96353337f0eb93e54f44078367d52f5 | 28,870,770,174,848 | 7fedacfa9cddff5e1d1c647c215564a94a62cd41 | /java/Backjoon/src/etc/no42576.java | 97d39f22587c7f5d07a612a095028f6fcf1fddbb | [] | no_license | Lee-Hyoeun/WepforJava | https://github.com/Lee-Hyoeun/WepforJava | e2e44cdb23b3175acbc52d3c6bf63f1d0a910508 | 086389ae1cd339ade42a3b09df578e1d2d3bcf50 | refs/heads/main | 2023-07-27T06:48:44.163000 | 2023-07-20T14:58:56 | 2023-07-20T14:58:56 | 403,904,691 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package etc;
import java.util.HashSet;
class no42576 {
public boolean solution(String[] phone_book) {
HashSet<String> set = new HashSet<>();
for(String num : phone_book){
set.add(num);
}
for(int i =0; i< set.size(); i++){
for(int j=0; j<phone_book[i].length(); j++){
if(set.contains(phone_book[i].substring(0,j))) return false;
}
}
return true;
}
}
| UTF-8 | Java | 505 | java | no42576.java | Java | [] | null | [] | package etc;
import java.util.HashSet;
class no42576 {
public boolean solution(String[] phone_book) {
HashSet<String> set = new HashSet<>();
for(String num : phone_book){
set.add(num);
}
for(int i =0; i< set.size(); i++){
for(int j=0; j<phone_book[i].length(); j++){
if(set.contains(phone_book[i].substring(0,j))) return false;
}
}
return true;
}
}
| 505 | 0.461386 | 0.445545 | 23 | 20.913044 | 20.106052 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 3 |
306d750e54d8936bc098c24411c00d52d23f4c3b | 14,121,852,529,643 | 119dab1ea39dbd318e7940df7abe23554cf0aca1 | /src/p37/P37_TruncatablePrimes.java | 7ad99bb84849ab687427a8c7dbaa2774f7dbf7e5 | [] | no_license | sonhuytran/project_euler_net | https://github.com/sonhuytran/project_euler_net | 459b88498ec8b50ab71b1bdc75b178ceefe4b1b3 | c67af335d45acef872b303ecf1831da72b28ea95 | refs/heads/master | 2021-01-19T20:23:04.643000 | 2014-02-03T09:07:23 | 2014-02-03T09:07:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package p37;
import java.util.ArrayList;
/**
* @author Son-Huy TRAN
*
*/
public class P37_TruncatablePrimes {
private static boolean isPrime(int number, ArrayList<Integer> primes) {
int low = 0, high = primes.size() - 1, mid = (low + high) / 2;
while (low <= high) {
if (primes.get(mid) == number) {
return true;
} else if (primes.get(mid) > number) {
high = mid - 1;
} else {
low = mid + 1;
}
mid = (low + high) / 2;
}
return false;
}
private static boolean isTruncatableLeft(int prime,
ArrayList<Integer> primes) {
int ten = 10;
int temp = prime % ten;
while (temp < prime) {
if (!isPrime(temp, primes)) {
return false;
}
ten *= 10;
temp = prime % ten;
}
return true;
}
private static boolean isTruncatableRight(int prime,
ArrayList<Integer> primes) {
prime /= 10;
while (prime > 0) {
if (!isPrime(prime, primes)) {
return false;
}
prime /= 10;
}
return true;
}
private static boolean isTruncatablePrime(int prime,
ArrayList<Integer> primes) {
if (isTruncatableLeft(prime, primes)
&& isTruncatableRight(prime, primes)) {
return true;
}
return false;
}
private static Integer[] generatePrimes(int max) {
ArrayList<Integer> result = new ArrayList<Integer>();
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= 10; i++) {
double sqrt = Math.sqrt(i);
boolean isPrime = true;
for (int j = 0; primes.get(j) <= sqrt; j++) {
if (i % primes.get(j) == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(i);
}
}
for (int i = 11; i <= max; i++) {
double sqrt = Math.sqrt(i);
boolean isPrime = true;
for (int j = 0; primes.get(j) <= sqrt; j++) {
if (i % primes.get(j) == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(i);
if (isTruncatablePrime(i, primes)) {
System.out.println(i);
result.add(i);
}
}
}
Integer[] resultsArray = new Integer[result.size()];
return result.toArray(resultsArray);
}
/**
* @param args
*/
public static void main(String[] args) {
Integer[] truncatablePrimes = generatePrimes(1000000);
long sum = 0;
for (int i = 0; i < truncatablePrimes.length; i++) {
sum += truncatablePrimes[i];
}
System.out.println(sum);
}
}
| UTF-8 | Java | 2,400 | java | P37_TruncatablePrimes.java | Java | [
{
"context": " p37;\n\nimport java.util.ArrayList;\n\n/**\n * @author Son-Huy TRAN\n * \n */\npublic class P37_TruncatablePrimes {\n\n\tpr",
"end": 82,
"score": 0.9997725486755371,
"start": 70,
"tag": "NAME",
"value": "Son-Huy TRAN"
}
] | null | [] | /**
*
*/
package p37;
import java.util.ArrayList;
/**
* @author <NAME>
*
*/
public class P37_TruncatablePrimes {
private static boolean isPrime(int number, ArrayList<Integer> primes) {
int low = 0, high = primes.size() - 1, mid = (low + high) / 2;
while (low <= high) {
if (primes.get(mid) == number) {
return true;
} else if (primes.get(mid) > number) {
high = mid - 1;
} else {
low = mid + 1;
}
mid = (low + high) / 2;
}
return false;
}
private static boolean isTruncatableLeft(int prime,
ArrayList<Integer> primes) {
int ten = 10;
int temp = prime % ten;
while (temp < prime) {
if (!isPrime(temp, primes)) {
return false;
}
ten *= 10;
temp = prime % ten;
}
return true;
}
private static boolean isTruncatableRight(int prime,
ArrayList<Integer> primes) {
prime /= 10;
while (prime > 0) {
if (!isPrime(prime, primes)) {
return false;
}
prime /= 10;
}
return true;
}
private static boolean isTruncatablePrime(int prime,
ArrayList<Integer> primes) {
if (isTruncatableLeft(prime, primes)
&& isTruncatableRight(prime, primes)) {
return true;
}
return false;
}
private static Integer[] generatePrimes(int max) {
ArrayList<Integer> result = new ArrayList<Integer>();
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= 10; i++) {
double sqrt = Math.sqrt(i);
boolean isPrime = true;
for (int j = 0; primes.get(j) <= sqrt; j++) {
if (i % primes.get(j) == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(i);
}
}
for (int i = 11; i <= max; i++) {
double sqrt = Math.sqrt(i);
boolean isPrime = true;
for (int j = 0; primes.get(j) <= sqrt; j++) {
if (i % primes.get(j) == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(i);
if (isTruncatablePrime(i, primes)) {
System.out.println(i);
result.add(i);
}
}
}
Integer[] resultsArray = new Integer[result.size()];
return result.toArray(resultsArray);
}
/**
* @param args
*/
public static void main(String[] args) {
Integer[] truncatablePrimes = generatePrimes(1000000);
long sum = 0;
for (int i = 0; i < truncatablePrimes.length; i++) {
sum += truncatablePrimes[i];
}
System.out.println(sum);
}
}
| 2,394 | 0.578333 | 0.5625 | 134 | 16.910448 | 17.453333 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.447761 | false | false | 3 |
904c207423ea28abc710a85304728ba66658c523 | 39,024,072,852,708 | 793286d9f9a35b949b592a0d1eb47486c04f86ca | /src/main/java/com/futao/springbootdemo/model/entity/Article.java | 107a73e3ebca73c0b7a74f026fc61c85bbd221a1 | [
"MIT"
] | permissive | gingerredjade/SpringBootStudy | https://github.com/gingerredjade/SpringBootStudy | 7bd8346aa08a00e38d70164cbf2dcf95f6f18723 | 4b026d1fc76c0cfa994e0b31f924cea74b9b42c6 | refs/heads/master | 2020-05-26T13:39:36.326000 | 2019-05-17T06:59:02 | 2019-05-17T06:59:02 | 188,250,815 | 3 | 0 | MIT | true | 2019-05-23T14:31:55 | 2019-05-23T14:31:55 | 2019-05-23T14:31:53 | 2019-05-17T06:59:10 | 64,771 | 0 | 0 | 0 | null | false | false | package com.futao.springbootdemo.model.entity;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* 文章
* indexName=database
* type=table
* row=document
* colnum=field
* <p>
*
* @author futao
* Created on 2018/10/20.
*/
@EqualsAndHashCode(callSuper = true)
@Validated
@Document(indexName = Article.ES_INDEX_NAME, type = Article.ES_TYPE)
public class Article extends BaseEntity {
public static final String ES_TYPE = "article";
public static final String ES_INDEX_NAME = "futao";
/**
* 标题
*/
@Length(min = 1, max = 20)
private String title;
/**
* 简介
*/
@Length(max = 200)
private String description;
/**
* 内容
*/
@Length(min = 1, max = 5000)
private String content;
/**
* 作者用户
*/
@NotNull
private User author;
/**
* 浏览量
*/
private int visitTimes;
/**
* 标签
*/
private List<Tag> tagList;
public Article() {
}
public Article(@Length(min = 1, max = 20) String title, @Length(max = 200) String description, @Length(min = 1, max = 5000) String content, @NotNull User author, int visitTimes, List<Tag> tagList) {
this.title = title;
this.description = description;
this.content = content;
this.author = author;
this.visitTimes = visitTimes;
this.tagList = tagList;
}
public static String getEsType() {
return ES_TYPE;
}
public static String getEsIndexName() {
return ES_INDEX_NAME;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public int getVisitTimes() {
return visitTimes;
}
public void setVisitTimes(int visitTimes) {
this.visitTimes = visitTimes;
}
public List<Tag> getTagList() {
return tagList;
}
public void setTagList(List<Tag> tagList) {
this.tagList = tagList;
}
}
| UTF-8 | Java | 2,702 | java | Article.java | Java | [
{
"context": " row=document\n * colnum=field\n * <p>\n *\n * @author futao\n * Created on 2018/10/20.\n */\n@EqualsAndHashCode(",
"end": 434,
"score": 0.99931401014328,
"start": 429,
"tag": "USERNAME",
"value": "futao"
}
] | null | [] | package com.futao.springbootdemo.model.entity;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* 文章
* indexName=database
* type=table
* row=document
* colnum=field
* <p>
*
* @author futao
* Created on 2018/10/20.
*/
@EqualsAndHashCode(callSuper = true)
@Validated
@Document(indexName = Article.ES_INDEX_NAME, type = Article.ES_TYPE)
public class Article extends BaseEntity {
public static final String ES_TYPE = "article";
public static final String ES_INDEX_NAME = "futao";
/**
* 标题
*/
@Length(min = 1, max = 20)
private String title;
/**
* 简介
*/
@Length(max = 200)
private String description;
/**
* 内容
*/
@Length(min = 1, max = 5000)
private String content;
/**
* 作者用户
*/
@NotNull
private User author;
/**
* 浏览量
*/
private int visitTimes;
/**
* 标签
*/
private List<Tag> tagList;
public Article() {
}
public Article(@Length(min = 1, max = 20) String title, @Length(max = 200) String description, @Length(min = 1, max = 5000) String content, @NotNull User author, int visitTimes, List<Tag> tagList) {
this.title = title;
this.description = description;
this.content = content;
this.author = author;
this.visitTimes = visitTimes;
this.tagList = tagList;
}
public static String getEsType() {
return ES_TYPE;
}
public static String getEsIndexName() {
return ES_INDEX_NAME;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public int getVisitTimes() {
return visitTimes;
}
public void setVisitTimes(int visitTimes) {
this.visitTimes = visitTimes;
}
public List<Tag> getTagList() {
return tagList;
}
public void setTagList(List<Tag> tagList) {
this.tagList = tagList;
}
}
| 2,702 | 0.614693 | 0.603448 | 130 | 19.523077 | 23.387774 | 202 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346154 | false | false | 3 |
089cb4db07e71be6e7939744ece1fe0f22ebdc83 | 34,875,134,483,653 | f8e553f445ac6e13d6bf0b1e70e2f99d31496c93 | /src/main/java/com/buchner/auction/model/core/entity/Bidder.java | 31a482e3dfe45c7a19073bfa565cd84047846e11 | [
"MIT"
] | permissive | divid3byzero/awection | https://github.com/divid3byzero/awection | dc7e27dda50db0058296174b9602da82c9c82eac | 85cce263e5af9447ee195eca78ea680da56185df | refs/heads/master | 2020-03-27T19:50:38.471000 | 2015-04-10T20:11:27 | 2015-04-10T20:11:27 | 33,741,702 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.buchner.auction.model.core.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Bidder entity with definition of named queries for
* better performance.
*/
@Entity
@Table(name = "bidder")
@NamedQueries({
@NamedQuery(name = "Bidder.findBidByBidder", query = "select b from Bidder b join b.bids bb where b.userId = :userId"),
})
public class Bidder {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "auction_bidder", joinColumns = {
@JoinColumn(name = "bidder_id")},
inverseJoinColumns = {@JoinColumn(name = "auction_id")})
private List<Auction> auctions;
@OneToMany(mappedBy = "bidder", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private List<Bid> bids;
private long userId;
public Bidder() {
auctions = new ArrayList<>();
}
public int getId() {
return id;
}
public List<Auction> getAuctions() {
return auctions;
}
public void addAuction(Auction auction) {
auctions.add(auction);
}
public List<Bid> getBids() {
return bids;
}
public void addBid(Bid bid) {
bids.add(bid);
if (!this.equals(bid.getBidder())) {
bid.setBidder(this);
}
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
| UTF-8 | Java | 1,525 | java | Bidder.java | Java | [] | null | [] | package com.buchner.auction.model.core.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Bidder entity with definition of named queries for
* better performance.
*/
@Entity
@Table(name = "bidder")
@NamedQueries({
@NamedQuery(name = "Bidder.findBidByBidder", query = "select b from Bidder b join b.bids bb where b.userId = :userId"),
})
public class Bidder {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "auction_bidder", joinColumns = {
@JoinColumn(name = "bidder_id")},
inverseJoinColumns = {@JoinColumn(name = "auction_id")})
private List<Auction> auctions;
@OneToMany(mappedBy = "bidder", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private List<Bid> bids;
private long userId;
public Bidder() {
auctions = new ArrayList<>();
}
public int getId() {
return id;
}
public List<Auction> getAuctions() {
return auctions;
}
public void addAuction(Auction auction) {
auctions.add(auction);
}
public List<Bid> getBids() {
return bids;
}
public void addBid(Bid bid) {
bids.add(bid);
if (!this.equals(bid.getBidder())) {
bid.setBidder(this);
}
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
| 1,525 | 0.612459 | 0.612459 | 75 | 19.333334 | 22.909872 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.306667 | false | false | 3 |
eb866ca6af500282d17eba3a655717eeda8da330 | 36,773,510,013,945 | 0fbd285ba378b8f5c39648d52f39e7a1b1cf2b4c | /equipment_crane/admin/src/main/java/com/xingyun/equipment/admin/modular/remotesetting/service/impl/ProjectDeviceRestartRecordServiceImpl.java | cc200de54347414e8772c44edb49cc2022dc1e61 | [] | no_license | bellmit/crane | https://github.com/bellmit/crane | 04b5008ca46f04bf4eeb1cb9559d12f16872c83b | a9ed1e45279346b9f2aedd5d31e10bf052194fca | refs/heads/master | 2023-08-26T17:57:18.564000 | 2019-10-22T13:38:43 | 2019-10-22T13:38:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xingyun.equipment.admin.modular.remotesetting.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xingyun.equipment.admin.core.dto.DataDTO;
import com.xingyun.equipment.admin.core.dto.RequestDTO;
import com.xingyun.equipment.admin.core.dto.ResultDTO;
import com.xingyun.equipment.admin.modular.remotesetting.dao.ProjectDeviceRestartRecordMapper;
import com.xingyun.equipment.admin.modular.remotesetting.model.ProjectDeviceRestartRecord;
import com.xingyun.equipment.admin.modular.remotesetting.service.ProjectDeviceRestartRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author hjy
* @since 2018-09-30
*/
@Service
public class ProjectDeviceRestartRecordServiceImpl extends ServiceImpl<ProjectDeviceRestartRecordMapper, ProjectDeviceRestartRecord> implements ProjectDeviceRestartRecordService {
@Override
public ResultDTO<DataDTO<List<ProjectDeviceRestartRecord>>> getPageList(RequestDTO<ProjectDeviceRestartRecord> request) {
Page<ProjectDeviceRestartRecord> page = new Page<>(request.getPageNum(), request.getPageSize());
ProjectDeviceRestartRecord restartRecord = request.getBody();
EntityWrapper<RequestDTO> ew = new EntityWrapper<>();
ew.eq("r.is_del", 0);
if (StringUtils.isNotBlank(restartRecord.getDeviceNo())) {
ew.eq("r.device_no", restartRecord.getDeviceNo());
}
if (StringUtils.isNotBlank(restartRecord.getType())) {
ew.eq("r.type", restartRecord.getType());
}
if (restartRecord.getProjectId() != null) {
ew.eq("r.project_id", restartRecord.getProjectId());
}
List<ProjectDeviceRestartRecord> list = baseMapper.getPageList(page, ew);
return new ResultDTO<>(true, DataDTO.factory(list, page.getTotal()));
}
}
| UTF-8 | Java | 2,038 | java | ProjectDeviceRestartRecordServiceImpl.java | Java | [
{
"context": "l.List;\n\n/**\n * <p>\n * 服务实现类\n * </p>\n *\n * @author hjy\n * @since 2018-09-30\n */\n@Service\npublic class Pr",
"end": 843,
"score": 0.9997215270996094,
"start": 840,
"tag": "USERNAME",
"value": "hjy"
}
] | null | [] | package com.xingyun.equipment.admin.modular.remotesetting.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xingyun.equipment.admin.core.dto.DataDTO;
import com.xingyun.equipment.admin.core.dto.RequestDTO;
import com.xingyun.equipment.admin.core.dto.ResultDTO;
import com.xingyun.equipment.admin.modular.remotesetting.dao.ProjectDeviceRestartRecordMapper;
import com.xingyun.equipment.admin.modular.remotesetting.model.ProjectDeviceRestartRecord;
import com.xingyun.equipment.admin.modular.remotesetting.service.ProjectDeviceRestartRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author hjy
* @since 2018-09-30
*/
@Service
public class ProjectDeviceRestartRecordServiceImpl extends ServiceImpl<ProjectDeviceRestartRecordMapper, ProjectDeviceRestartRecord> implements ProjectDeviceRestartRecordService {
@Override
public ResultDTO<DataDTO<List<ProjectDeviceRestartRecord>>> getPageList(RequestDTO<ProjectDeviceRestartRecord> request) {
Page<ProjectDeviceRestartRecord> page = new Page<>(request.getPageNum(), request.getPageSize());
ProjectDeviceRestartRecord restartRecord = request.getBody();
EntityWrapper<RequestDTO> ew = new EntityWrapper<>();
ew.eq("r.is_del", 0);
if (StringUtils.isNotBlank(restartRecord.getDeviceNo())) {
ew.eq("r.device_no", restartRecord.getDeviceNo());
}
if (StringUtils.isNotBlank(restartRecord.getType())) {
ew.eq("r.type", restartRecord.getType());
}
if (restartRecord.getProjectId() != null) {
ew.eq("r.project_id", restartRecord.getProjectId());
}
List<ProjectDeviceRestartRecord> list = baseMapper.getPageList(page, ew);
return new ResultDTO<>(true, DataDTO.factory(list, page.getTotal()));
}
}
| 2,038 | 0.751972 | 0.747041 | 46 | 43.086956 | 39.220016 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673913 | false | false | 3 |
26430f38511083ecc0c8176d0f5d1d8d611157cb | 38,259,568,692,112 | 94c57d9a73ef8facc659b2420f17c7af421039ff | /src/org/quick/framework/hibernate/annotation/EntityScanPackage.java | ffe0b7fc44afa75fbcf3ce2bb9b4e80675ddf4e0 | [] | no_license | holdfuture2013/quick | https://github.com/holdfuture2013/quick | 09fb66619f8e9763f3854b51f976ca85d285d22c | 1f23e69b339ee9ee73bd31a83bed525fa36acd06 | refs/heads/master | 2021-01-10T18:29:53.910000 | 2013-12-19T16:45:53 | 2013-12-19T16:45:53 | 15,288,349 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.quick.framework.hibernate.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @title:EntityScanPackage
* @describe: 用来标记那些包下面实体需要初始化数据库
* @author: yong.runningboy@gmail.com
* @datetime: Dec 13, 20139:27:51 AM
* @version V1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface EntityScanPackage {
String name(); //整个项目标识符名称
String basePackage(); //实体包
String[] basePackages() default {}; //实体包数组
}
| UTF-8 | Java | 744 | java | EntityScanPackage.java | Java | [
{
"context": "ge\r\n * @describe: 用来标记那些包下面实体需要初始化数据库\r\n * @author: yong.runningboy@gmail.com\r\n * @datetime: Dec 13, 20139:27:51 AM\r\n * @versio",
"end": 372,
"score": 0.9999280571937561,
"start": 347,
"tag": "EMAIL",
"value": "yong.runningboy@gmail.com"
}
] | null | [] | package org.quick.framework.hibernate.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @title:EntityScanPackage
* @describe: 用来标记那些包下面实体需要初始化数据库
* @author: <EMAIL>
* @datetime: Dec 13, 20139:27:51 AM
* @version V1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface EntityScanPackage {
String name(); //整个项目标识符名称
String basePackage(); //实体包
String[] basePackages() default {}; //实体包数组
}
| 726 | 0.72619 | 0.706845 | 27 | 22.888889 | 17.058361 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.740741 | false | false | 3 |
87a23f5126c61cb7199868dc646b5ed036987f36 | 38,259,568,693,879 | 8735b9a67a7f982bf5e5d09c87805181808aac2c | /src/main/java/pl/edu/wat/model/EngineNumber.java | ce9e1b8c57df53b4c570998146ae2086f891e618 | [] | no_license | i5b6s1policja/mwsi | https://github.com/i5b6s1policja/mwsi | c4b8fc7eed56cc720a57caa9fb2d62596110f12f | c2467f162e15eb910300b2b404cb03646d1cf0ea | refs/heads/master | 2021-09-05T15:10:14.640000 | 2018-01-29T05:57:04 | 2018-01-29T05:57:04 | 110,460,826 | 0 | 0 | null | false | 2018-01-29T05:57:17 | 2017-11-12T19:10:36 | 2017-12-11T16:50:59 | 2018-01-29T05:57:05 | 7,794 | 0 | 0 | 3 | Java | false | null | package pl.edu.wat.model;
public class EngineNumber {
private String engineNumber;
public EngineNumber() {
}
public String getEngineNumber() {
return engineNumber;
}
public void setEngineNumber(String engineNumber) {
this.engineNumber = engineNumber;
}
public EngineNumber(String engineNumber) {
this.engineNumber = engineNumber;
}
}
| UTF-8 | Java | 400 | java | EngineNumber.java | Java | [] | null | [] | package pl.edu.wat.model;
public class EngineNumber {
private String engineNumber;
public EngineNumber() {
}
public String getEngineNumber() {
return engineNumber;
}
public void setEngineNumber(String engineNumber) {
this.engineNumber = engineNumber;
}
public EngineNumber(String engineNumber) {
this.engineNumber = engineNumber;
}
}
| 400 | 0.665 | 0.665 | 21 | 18.047619 | 18.14617 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.238095 | false | false | 3 |
4c43ccab01d916f7c603c6f6e7234bbf08b11a9d | 26,396,869,049,950 | ad36e7069c4cbc90b8cf1ca99dae3af2108e1923 | /src/main/java/com/bs/bsbank/entity/AccountEntity.java | aaaff3d0d3f76107b6311a0cdd98fcff717172d1 | [] | no_license | TracyLXC/BSBank_BackEnd | https://github.com/TracyLXC/BSBank_BackEnd | a15d6b83740c0ef424dbb900659cb9fc63a03fdf | 4bcdbccd064726104cd82af6bebf5b21915a6e64 | refs/heads/master | 2020-06-20T14:44:37.178000 | 2019-07-11T01:35:26 | 2019-07-11T01:35:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bs.bsbank.entity;
import javax.persistence.*;
/**
* Created by hadoop on 2019/7/10.
*/
@Entity
@Table(name = "account", schema = "bank", catalog = "")
public class AccountEntity {
private String accountId;
private String accountGroup;
@Id
@Column(name = "accountId")
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
@Basic
@Column(name = "accountGroup")
public String getAccountGroup() {
return accountGroup;
}
public void setAccountGroup(String accountGroup) {
this.accountGroup = accountGroup;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AccountEntity that = (AccountEntity) o;
if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) return false;
if (accountGroup != null ? !accountGroup.equals(that.accountGroup) : that.accountGroup != null) return false;
return true;
}
@Override
public int hashCode() {
int result = accountId != null ? accountId.hashCode() : 0;
result = 31 * result + (accountGroup != null ? accountGroup.hashCode() : 0);
return result;
}
}
| UTF-8 | Java | 1,367 | java | AccountEntity.java | Java | [
{
"context": "y;\n\nimport javax.persistence.*;\n\n/**\n * Created by hadoop on 2019/7/10.\n */\n@Entity\n@Table(name = \"account\"",
"end": 84,
"score": 0.9705978631973267,
"start": 78,
"tag": "USERNAME",
"value": "hadoop"
}
] | null | [] | package com.bs.bsbank.entity;
import javax.persistence.*;
/**
* Created by hadoop on 2019/7/10.
*/
@Entity
@Table(name = "account", schema = "bank", catalog = "")
public class AccountEntity {
private String accountId;
private String accountGroup;
@Id
@Column(name = "accountId")
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
@Basic
@Column(name = "accountGroup")
public String getAccountGroup() {
return accountGroup;
}
public void setAccountGroup(String accountGroup) {
this.accountGroup = accountGroup;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AccountEntity that = (AccountEntity) o;
if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) return false;
if (accountGroup != null ? !accountGroup.equals(that.accountGroup) : that.accountGroup != null) return false;
return true;
}
@Override
public int hashCode() {
int result = accountId != null ? accountId.hashCode() : 0;
result = 31 * result + (accountGroup != null ? accountGroup.hashCode() : 0);
return result;
}
}
| 1,367 | 0.622531 | 0.614484 | 53 | 24.792454 | 26.636164 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396226 | false | false | 3 |
9eb4e11c31ac32dbc128651f9ccdc3623a50959e | 28,810,640,652,937 | 4ecd7a780ecbb9c3375d95360eaac0e1638185c8 | /Java/StarPattern2.java | 19e55d12417c7b8cc1e175d9bad58d5b979e31ae | [
"MIT"
] | permissive | Sasmita-cloud/Hacktoberfest2021_PatternMaking | https://github.com/Sasmita-cloud/Hacktoberfest2021_PatternMaking | dd50c8a81bce9da25650b3b497330a9c150d54da | af48c242c10b08b74cf42c35b8550a45f1d9cbff | refs/heads/main | 2023-08-29T22:56:59.953000 | 2021-10-14T11:49:43 | 2021-10-14T11:49:43 | 415,092,226 | 0 | 0 | MIT | true | 2021-10-08T18:38:33 | 2021-10-08T18:38:32 | 2021-10-08T18:00:16 | 2021-10-08T18:33:36 | 581 | 0 | 0 | 0 | null | false | false | package LOOPS;
import java.util.Scanner;
//Q.To print *
// * *
// * * *
// * * * *
public class StarPattern2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = 5;
for (int i=0;i<=n;i++){
for( int j=0;j<=i;j++){
System.out.print("* ");
}
System.out.println("");
}
}
}
| UTF-8 | Java | 451 | java | StarPattern2.java | Java | [] | null | [] | package LOOPS;
import java.util.Scanner;
//Q.To print *
// * *
// * * *
// * * * *
public class StarPattern2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = 5;
for (int i=0;i<=n;i++){
for( int j=0;j<=i;j++){
System.out.print("* ");
}
System.out.println("");
}
}
}
| 451 | 0.394679 | 0.385809 | 21 | 19.476191 | 14.14422 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 3 |
8c76e462de0e94d4c199867f3c409e1e8ac564de | 32,427,003,093,570 | be1849ce432acf7d9a768f3f7d1898243456a4f1 | /BookListLoader.java | da1239841b2c234da3c3e64e6d25e2f42e745142 | [] | no_license | wnkterry/bookList_App | https://github.com/wnkterry/bookList_App | e87aaa903f901ce49f31ac0af48a60ca4b371c8f | caa0f0fee1eaa45a333637e722237764e793a5c7 | refs/heads/master | 2021-05-04T02:46:47.635000 | 2018-02-07T02:54:46 | 2018-02-07T02:54:46 | 120,366,623 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.kathy.booklist;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
/**
* Created by Kathy on 11/22/2017.
*/
public class BookListLoader extends AsyncTaskLoader<List<bookInfo>> {
/** Tag for log messages */
private static final String LOG_TAG = BookListAdapter.class.getName();
/** Query URL */
private String mUrl;
/**
* Constructs a new {@link BookListLoader}.
*
* @param context of the activity
* @param url to load data from
*/
public BookListLoader(Context context, String url) {
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public List<bookInfo> loadInBackground() {
if(mUrl==null){ return null;}
List<bookInfo> bookInfos = QueryUtils.fetchbookInfoData(mUrl);
return bookInfos;
}
}
| UTF-8 | Java | 947 | java | BookListLoader.java | Java | [
{
"context": "ontext;\n\nimport java.util.List;\n\n/**\n * Created by Kathy on 11/22/2017.\n */\n\npublic class BookListLoader e",
"end": 157,
"score": 0.9911971688270569,
"start": 152,
"tag": "NAME",
"value": "Kathy"
}
] | null | [] | package com.example.kathy.booklist;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
/**
* Created by Kathy on 11/22/2017.
*/
public class BookListLoader extends AsyncTaskLoader<List<bookInfo>> {
/** Tag for log messages */
private static final String LOG_TAG = BookListAdapter.class.getName();
/** Query URL */
private String mUrl;
/**
* Constructs a new {@link BookListLoader}.
*
* @param context of the activity
* @param url to load data from
*/
public BookListLoader(Context context, String url) {
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public List<bookInfo> loadInBackground() {
if(mUrl==null){ return null;}
List<bookInfo> bookInfos = QueryUtils.fetchbookInfoData(mUrl);
return bookInfos;
}
}
| 947 | 0.639916 | 0.631468 | 46 | 19.543478 | 20.916716 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.282609 | false | false | 3 |
3a121d5d142847d87c6e9deacef7054b343191d0 | 32,427,003,092,009 | 88d656b2d30b2679b43a4bf89defccae92bb7691 | /imagej/imagej-ops2/src/test/java/net/imagej/ops2/filter/mean/MeanFilterTest.java | 3a111ebf01e025f3b5c72ddb1157cfc274d71667 | [
"BSD-2-Clause"
] | permissive | scijava/incubator | https://github.com/scijava/incubator | 52f53e0c662e6d54ee55bc3f54b7cb4e0110ebe2 | 105acb4fd5aaccac673ef7ed23f9b6b5acba17e9 | refs/heads/main | 2023-09-03T15:01:41.674000 | 2023-08-31T14:09:30 | 2023-08-31T14:09:30 | 246,112,998 | 6 | 7 | null | false | 2023-09-14T18:56:20 | 2020-03-09T18:32:25 | 2023-01-31T17:58:14 | 2023-09-14T18:56:18 | 9,130 | 5 | 6 | 12 | Java | false | false | /*-
* #%L
* ImageJ2 software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2022 ImageJ2 developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.ops2.filter.mean;
import net.imagej.ops2.AbstractOpTest;
import net.imglib2.FinalInterval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.algorithm.neighborhood.RectangleShape;
import net.imglib2.img.Img;
import net.imglib2.outofbounds.OutOfBoundsBorderFactory;
import net.imglib2.outofbounds.OutOfBoundsFactory;
import net.imglib2.type.numeric.integer.ByteType;
import org.junit.jupiter.api.Test;
import org.scijava.types.Nil;
public class MeanFilterTest extends AbstractOpTest{
@Test
public void meanFilterTest() {
Img<ByteType> img = ops.op("create.img").arity2().input(new FinalInterval(5, 5), new ByteType()).outType(new Nil<Img<ByteType>>() {}).apply();
RectangleShape shape = new RectangleShape(1, false);
OutOfBoundsFactory<ByteType, RandomAccessibleInterval<ByteType>> oobf = new OutOfBoundsBorderFactory<>();
Img<ByteType> output = ops.op("create.img").arity1().input(img).outType(new Nil<Img<ByteType>>() {}).apply();
ops.op("filter.mean").arity3().input(img, shape, oobf).output(output).compute();
// Try with no OutOfBoundsFactory
ops.op("filter.mean").arity2().input(img, shape).output(output).compute();
}
@Test
public void rawTypeAdaptationTest() {
Img<ByteType> img = ops.op("create.img").arity2().input(new FinalInterval(5, 5), new ByteType()).outType(new Nil<Img<ByteType>>() {}).apply();
RectangleShape shape = new RectangleShape(1, false);
OutOfBoundsFactory<ByteType, RandomAccessibleInterval<ByteType>> oobf = new OutOfBoundsBorderFactory<>();
var result = ops.op("filter.mean").arity3().input(img, shape, oobf).outType(Img.class).apply();
}
}
| UTF-8 | Java | 3,103 | java | MeanFilterTest.java | Java | [] | null | [] | /*-
* #%L
* ImageJ2 software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2022 ImageJ2 developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.ops2.filter.mean;
import net.imagej.ops2.AbstractOpTest;
import net.imglib2.FinalInterval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.algorithm.neighborhood.RectangleShape;
import net.imglib2.img.Img;
import net.imglib2.outofbounds.OutOfBoundsBorderFactory;
import net.imglib2.outofbounds.OutOfBoundsFactory;
import net.imglib2.type.numeric.integer.ByteType;
import org.junit.jupiter.api.Test;
import org.scijava.types.Nil;
public class MeanFilterTest extends AbstractOpTest{
@Test
public void meanFilterTest() {
Img<ByteType> img = ops.op("create.img").arity2().input(new FinalInterval(5, 5), new ByteType()).outType(new Nil<Img<ByteType>>() {}).apply();
RectangleShape shape = new RectangleShape(1, false);
OutOfBoundsFactory<ByteType, RandomAccessibleInterval<ByteType>> oobf = new OutOfBoundsBorderFactory<>();
Img<ByteType> output = ops.op("create.img").arity1().input(img).outType(new Nil<Img<ByteType>>() {}).apply();
ops.op("filter.mean").arity3().input(img, shape, oobf).output(output).compute();
// Try with no OutOfBoundsFactory
ops.op("filter.mean").arity2().input(img, shape).output(output).compute();
}
@Test
public void rawTypeAdaptationTest() {
Img<ByteType> img = ops.op("create.img").arity2().input(new FinalInterval(5, 5), new ByteType()).outType(new Nil<Img<ByteType>>() {}).apply();
RectangleShape shape = new RectangleShape(1, false);
OutOfBoundsFactory<ByteType, RandomAccessibleInterval<ByteType>> oobf = new OutOfBoundsBorderFactory<>();
var result = ops.op("filter.mean").arity3().input(img, shape, oobf).outType(Img.class).apply();
}
}
| 3,103 | 0.756687 | 0.746052 | 67 | 45.313435 | 37.397903 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.298507 | false | false | 3 |
15adbd059089decb0982850e3fcdceb8a407dd8d | 32,427,003,091,328 | 65a22a2f6f64eafdc470e93f9c7b3570b4d00193 | /gx/gx-vaadin7/src/main/java/io/graphenee/vaadin/component/FloatingActionButton.java | 44710216e94b578c3da2adbd55b1b4e3b4a5f87a | [
"Apache-2.0"
] | permissive | ijazfx/graphenee | https://github.com/ijazfx/graphenee | 06dd1e77cb678d2ae204b6ae9fa249a04144074d | 9e9df4d6e22a5d02712764a61b825d9b120d8ad0 | refs/heads/master | 2023-08-11T17:17:57.360000 | 2023-07-24T22:32:06 | 2023-07-24T22:32:06 | 132,866,972 | 13 | 31 | Apache-2.0 | false | 2023-07-24T16:00:54 | 2018-05-10T07:48:50 | 2023-02-12T18:08:00 | 2023-07-24T16:00:54 | 29,643 | 13 | 13 | 1 | Java | false | false | /*******************************************************************************
* Copyright (c) 2016, 2018 Farrukh Ijaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package io.graphenee.vaadin.component;
import java.util.List;
import org.vaadin.viritin.button.MButton;
import org.vaadin.viritin.layouts.MVerticalLayout;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Resource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.themes.ValoTheme;
public class FloatingActionButton extends CssLayout {
private MButton actionButton;
private MVerticalLayout actionListLayout;
private Resource defaultIcon;
public FloatingActionButton() {
actionButton = new MButton().withStyleName(ValoTheme.BUTTON_ICON_ONLY, "circle", "action-button").withIcon(FontAwesome.ELLIPSIS_V);
actionListLayout = new MVerticalLayout().withDefaultComponentAlignment(Alignment.MIDDLE_RIGHT).withSizeUndefined().withStyleName("action-button-action-list");
actionButton.addClickListener(event -> {
if (!actionListLayout.getStyleName().contains("action-button-action-list-appear")) {
defaultIcon = actionButton.getIcon();
actionButton.setIcon(FontAwesome.PLUS);
actionButton.addStyleName("action-button-rotate");
actionListLayout.addStyleName("action-button-action-list-appear");
} else {
actionButton.setIcon(defaultIcon);
actionButton.removeStyleName("action-button-rotate");
actionListLayout.removeStyleName("action-button-action-list-appear");
}
});
addComponents(actionListLayout, actionButton);
}
public void setActionListButtons(List<Button> actionListButtons) {
actionListLayout.removeAllComponents();
if (actionListButtons != null) {
actionListButtons.forEach(button -> {
button.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
button.addStyleName(ValoTheme.BUTTON_ICON_ALIGN_RIGHT);
button.addStyleName(ValoTheme.BUTTON_SMALL);
button.addClickListener(event -> {
actionButton.setIcon(defaultIcon);
actionButton.removeStyleName("action-button-rotate");
actionListLayout.removeStyleName("action-button-action-list-appear");
});
actionListLayout.add(button);
});
}
actionListLayout.setVisible(true); // actionListButtons != null &&
// !actionListButtons.isEmpty());
}
}
| UTF-8 | Java | 2,940 | java | FloatingActionButton.java | Java | [
{
"context": "**********************\n * Copyright (c) 2016, 2018 Farrukh Ijaz\n *\n * Licensed under the Apache License, Version ",
"end": 121,
"score": 0.9998510479927063,
"start": 109,
"tag": "NAME",
"value": "Farrukh Ijaz"
}
] | null | [] | /*******************************************************************************
* Copyright (c) 2016, 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package io.graphenee.vaadin.component;
import java.util.List;
import org.vaadin.viritin.button.MButton;
import org.vaadin.viritin.layouts.MVerticalLayout;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Resource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.themes.ValoTheme;
public class FloatingActionButton extends CssLayout {
private MButton actionButton;
private MVerticalLayout actionListLayout;
private Resource defaultIcon;
public FloatingActionButton() {
actionButton = new MButton().withStyleName(ValoTheme.BUTTON_ICON_ONLY, "circle", "action-button").withIcon(FontAwesome.ELLIPSIS_V);
actionListLayout = new MVerticalLayout().withDefaultComponentAlignment(Alignment.MIDDLE_RIGHT).withSizeUndefined().withStyleName("action-button-action-list");
actionButton.addClickListener(event -> {
if (!actionListLayout.getStyleName().contains("action-button-action-list-appear")) {
defaultIcon = actionButton.getIcon();
actionButton.setIcon(FontAwesome.PLUS);
actionButton.addStyleName("action-button-rotate");
actionListLayout.addStyleName("action-button-action-list-appear");
} else {
actionButton.setIcon(defaultIcon);
actionButton.removeStyleName("action-button-rotate");
actionListLayout.removeStyleName("action-button-action-list-appear");
}
});
addComponents(actionListLayout, actionButton);
}
public void setActionListButtons(List<Button> actionListButtons) {
actionListLayout.removeAllComponents();
if (actionListButtons != null) {
actionListButtons.forEach(button -> {
button.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
button.addStyleName(ValoTheme.BUTTON_ICON_ALIGN_RIGHT);
button.addStyleName(ValoTheme.BUTTON_SMALL);
button.addClickListener(event -> {
actionButton.setIcon(defaultIcon);
actionButton.removeStyleName("action-button-rotate");
actionListLayout.removeStyleName("action-button-action-list-appear");
});
actionListLayout.add(button);
});
}
actionListLayout.setVisible(true); // actionListButtons != null &&
// !actionListButtons.isEmpty());
}
}
| 2,934 | 0.723129 | 0.719048 | 74 | 38.729729 | 31.113697 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.081081 | false | false | 3 |
255a33d8a7c21b6a26c29d085345c47d32296ed8 | 3,710,851,787,136 | bac9136e4b9f9cb92ba0318a5c1e95d172ea18ac | /src/com/incon/project/common/jcxgxxwh/gwlx/service/GwlxglServiceImpl.java | 1f2e0b63ded3812a7a6a330b78b81f4a8c8e01f4 | [] | no_license | sanhaowuai/wjgl | https://github.com/sanhaowuai/wjgl | 291dc1ee38b5178d23b16abb24c79263e959b5d1 | 3770d3f022ff2e5087333a722ac92f0f0ed47149 | refs/heads/master | 2020-04-08T22:20:54.727000 | 2018-11-30T07:46:51 | 2018-11-30T07:46:51 | 159,473,744 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.incon.project.common.jcxgxxwh.gwlx.service;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.incon.framework.aop.MethodLog;
import com.incon.framework.service.impl.CommServiceImpl;
import com.incon.pojo.common.jcxgxxwh.GwlxbEntity;
/**
*
* @类名: com.incon.project.common.jcxgxxwh.gwlx.service.GwlxglServiceImpl
* @创建人: 杨文龙
* @日期: 2014-4-1
* @修改人:
* @日期:
* @描述:岗位类型接口的实现类
* @版本号:
*/
@SuppressWarnings("all")
@Service(value="gwlxglService")
public class GwlxglServiceImpl extends CommServiceImpl implements GwlxglService{
//增加岗位类型
@Override
@MethodLog(description="增加岗位类型")
public void addGwlx(GwlxbEntity gwlxbEntity) {
dbDao.insert("gwlxgl.addGwlx", gwlxbEntity);
}
//判断岗位类型是否被使用
@Override
public String queryExit(String ids){
Integer j = 0;
String mc = "";
String[] id = ids.split(",");
for (int i = 0; i < id.length; i++) {
j = j + (Integer) dbDao.queryForObject("gwlxgl.queryExit",id[i]);
if(j>0){
String dm = id[i];
GwlxbEntity gwlxbEntity =(GwlxbEntity)dbDao.queryForObject("gwlxgl.queryGwlxByDm",dm);
mc += gwlxbEntity.getMc() + " ";
j=0;
}
}
return mc;
}
//删除岗位类型
@Transactional
@Override
@MethodLog(description="删除岗位类型")
public void delGwlx(String[] ids) {
dbDao.executeBatchOperation("gwlxgl.delGwlx", Arrays.asList(ids), "delete");
}
//查询代码是否重复
@Override
public Integer queryByDmCount(String dm) {
return Integer.parseInt(String.valueOf(dbDao.queryForObject("gwlxgl.queryByDmCount", dm)));
}
//查询岗位类型列表
@Override
public List<GwlxbEntity> queryGwlxList() {
return dbDao.query("gwlxgl.queryGwlxList");
}
//修改岗位类型
@Override
@MethodLog(description="根据代码修改岗位类型")
public void updGwlx(GwlxbEntity gwlxbEntity) {
dbDao.update("gwlxgl.updGwlx", gwlxbEntity);
}
//根据代码查询岗位类型
@Override
public GwlxbEntity queryGwlxByDm(String dm) {
return (GwlxbEntity) dbDao.queryForObject("gwlxgl.queryGwlxByDm", dm);
}
}
| UTF-8 | Java | 2,284 | java | GwlxglServiceImpl.java | Java | [
{
"context": ".jcxgxxwh.gwlx.service.GwlxglServiceImpl\n * @创建人: 杨文龙\n * @日期: 2014-4-1\n * @修改人:\n * @日期:\n * @描述:岗位类型接口的实",
"end": 466,
"score": 0.9997822046279907,
"start": 463,
"tag": "NAME",
"value": "杨文龙"
}
] | null | [] | package com.incon.project.common.jcxgxxwh.gwlx.service;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.incon.framework.aop.MethodLog;
import com.incon.framework.service.impl.CommServiceImpl;
import com.incon.pojo.common.jcxgxxwh.GwlxbEntity;
/**
*
* @类名: com.incon.project.common.jcxgxxwh.gwlx.service.GwlxglServiceImpl
* @创建人: 杨文龙
* @日期: 2014-4-1
* @修改人:
* @日期:
* @描述:岗位类型接口的实现类
* @版本号:
*/
@SuppressWarnings("all")
@Service(value="gwlxglService")
public class GwlxglServiceImpl extends CommServiceImpl implements GwlxglService{
//增加岗位类型
@Override
@MethodLog(description="增加岗位类型")
public void addGwlx(GwlxbEntity gwlxbEntity) {
dbDao.insert("gwlxgl.addGwlx", gwlxbEntity);
}
//判断岗位类型是否被使用
@Override
public String queryExit(String ids){
Integer j = 0;
String mc = "";
String[] id = ids.split(",");
for (int i = 0; i < id.length; i++) {
j = j + (Integer) dbDao.queryForObject("gwlxgl.queryExit",id[i]);
if(j>0){
String dm = id[i];
GwlxbEntity gwlxbEntity =(GwlxbEntity)dbDao.queryForObject("gwlxgl.queryGwlxByDm",dm);
mc += gwlxbEntity.getMc() + " ";
j=0;
}
}
return mc;
}
//删除岗位类型
@Transactional
@Override
@MethodLog(description="删除岗位类型")
public void delGwlx(String[] ids) {
dbDao.executeBatchOperation("gwlxgl.delGwlx", Arrays.asList(ids), "delete");
}
//查询代码是否重复
@Override
public Integer queryByDmCount(String dm) {
return Integer.parseInt(String.valueOf(dbDao.queryForObject("gwlxgl.queryByDmCount", dm)));
}
//查询岗位类型列表
@Override
public List<GwlxbEntity> queryGwlxList() {
return dbDao.query("gwlxgl.queryGwlxList");
}
//修改岗位类型
@Override
@MethodLog(description="根据代码修改岗位类型")
public void updGwlx(GwlxbEntity gwlxbEntity) {
dbDao.update("gwlxgl.updGwlx", gwlxbEntity);
}
//根据代码查询岗位类型
@Override
public GwlxbEntity queryGwlxByDm(String dm) {
return (GwlxbEntity) dbDao.queryForObject("gwlxgl.queryGwlxByDm", dm);
}
}
| 2,284 | 0.718872 | 0.714008 | 88 | 22.363636 | 23.873331 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.397727 | false | false | 3 |
4cef817e5f6cd9639caf896c82df72fecf0ca31e | 10,806,137,726,137 | 233a1db3567418ca30654f9c2271f14302e8ff43 | /BasicGeometries/src/application/CalculateGeom.java | 2343e8ee5802c585169ceeaef5b82cb2c9524891 | [] | no_license | vikneswaran20/BasicGeometries | https://github.com/vikneswaran20/BasicGeometries | c7386c47e03fde498367d301c3279133667b22e4 | 50e58fba74af32e1a49c8e7fbd202d0ddc6a654c | refs/heads/master | 2016-08-08T23:04:48.982000 | 2016-04-09T10:25:12 | 2016-04-09T10:25:12 | 55,837,543 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package application;
import geometry.Square;
import geometry.Rectangle;
public class CalculateGeom {
public void squareCalculations(double side) {
Square s = new Square(side);
System.out.println("-------Square---------");
System.out.println("Area: " + s.area());
System.out.println("Perimeter : " + s.perimeter());
}
public void rectangleCalculation(double length, double breath) {
Rectangle r = new Rectangle(length, breath);
System.out.println("\n------Rectangle--------");
System.out.println("Area: " + r.area());
System.out.println("Perimeter : " + r.perimeter());
}
public static void main(String[] args) {
CalculateGeom cg = new CalculateGeom();
cg.squareCalculations(41.259);
cg.rectangleCalculation(25.64, 32.145);
}
}
| UTF-8 | Java | 790 | java | CalculateGeom.java | Java | [] | null | [] | package application;
import geometry.Square;
import geometry.Rectangle;
public class CalculateGeom {
public void squareCalculations(double side) {
Square s = new Square(side);
System.out.println("-------Square---------");
System.out.println("Area: " + s.area());
System.out.println("Perimeter : " + s.perimeter());
}
public void rectangleCalculation(double length, double breath) {
Rectangle r = new Rectangle(length, breath);
System.out.println("\n------Rectangle--------");
System.out.println("Area: " + r.area());
System.out.println("Perimeter : " + r.perimeter());
}
public static void main(String[] args) {
CalculateGeom cg = new CalculateGeom();
cg.squareCalculations(41.259);
cg.rectangleCalculation(25.64, 32.145);
}
}
| 790 | 0.653165 | 0.635443 | 28 | 26.214285 | 21.156487 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.607143 | false | false | 3 |
64f6e00cdfb8cf830900e51184bb653b2f31d548 | 27,341,761,859,464 | b9edc137c68e2f003135052ae49496d127b6c2c6 | /RestAPI_Implementation/src/main/java/com/service/PersonService.java | c759a1940e314d1bb18ffa4ec6124ebcc52fbcec | [] | no_license | RewatiJadhao/BasicAPI | https://github.com/RewatiJadhao/BasicAPI | 93309e9496c5af41bcedc321d5f00adc51debecf | b58a56bd48dc583422a6e0b6c70b9565dc572d6f | refs/heads/master | 2020-05-22T18:05:27.043000 | 2019-05-13T18:29:01 | 2019-05-13T18:29:01 | 186,466,134 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.service;
import java.util.HashMap;
import org.springframework.stereotype.Service;
import com.model.Person;
@Service
public class PersonService {
HashMap<Integer,Person> persons=new HashMap<>();
public PersonService()
{
Person p=new Person();
p.setPersonNumber(1);
p.setName("Rewa");
p.setAge(20);
Person p1=new Person();
p1.setPersonNumber(2);
p1.setName("Sana");
p1.setAge(25);
persons.put(10, p);
persons.put(20, p1);
}
public Person getPerson(int pNumber) {
if(persons.containsKey(pNumber))
{
return persons.get(pNumber);
}
else {
return null;
}
}
public HashMap<Integer, Person> getAllPerson() {
return persons;
}
}
| UTF-8 | Java | 758 | java | PersonService.java | Java | [
{
"context": " Person();\r\n\t\tp.setPersonNumber(1);\r\n\t\tp.setName(\"Rewa\");\r\n\t\tp.setAge(20);\r\n\t\t\r\n\t\tPerson p1=new Person()",
"end": 328,
"score": 0.9998234510421753,
"start": 324,
"tag": "NAME",
"value": "Rewa"
},
{
"context": "erson();\r\n\t\tp1.setPersonNumber(2);\r\n\t\tp1.setName(\"Sana\");\r\n\t\tp1.setAge(25);\r\n\t\t\r\n\t\tpersons.put(10, p);\r\n",
"end": 425,
"score": 0.9998246431350708,
"start": 421,
"tag": "NAME",
"value": "Sana"
}
] | null | [] | package com.service;
import java.util.HashMap;
import org.springframework.stereotype.Service;
import com.model.Person;
@Service
public class PersonService {
HashMap<Integer,Person> persons=new HashMap<>();
public PersonService()
{
Person p=new Person();
p.setPersonNumber(1);
p.setName("Rewa");
p.setAge(20);
Person p1=new Person();
p1.setPersonNumber(2);
p1.setName("Sana");
p1.setAge(25);
persons.put(10, p);
persons.put(20, p1);
}
public Person getPerson(int pNumber) {
if(persons.containsKey(pNumber))
{
return persons.get(pNumber);
}
else {
return null;
}
}
public HashMap<Integer, Person> getAllPerson() {
return persons;
}
}
| 758 | 0.621372 | 0.601583 | 48 | 13.791667 | 14.149438 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.770833 | false | false | 3 |
00052f7e647146a4e85828833fb17ec87c90cb34 | 29,738,353,559,039 | 96e4074e16aa96b1a7240e62c9aebb133dd00bd0 | /04_Applets/src/Dessin.java | 06eb5fb6120521606314790c91db27b9abee5e8e | [] | no_license | arebii/Java_Projects | https://github.com/arebii/Java_Projects | fb9f2637c9aa95463e1cf2bdaa1aaf181137120e | cd6fc06d53cd3dae2762084a34d2c3b2b9f6fa8e | refs/heads/master | 2022-04-24T21:24:51.726000 | 2020-04-24T18:16:45 | 2020-04-24T18:16:45 | 256,570,702 | 0 | 1 | null | false | 2020-04-23T09:40:34 | 2020-04-17T17:41:29 | 2020-04-17T17:57:38 | 2020-04-23T09:40:33 | 62 | 0 | 1 | 0 | Java | false | false | import java.awt.*; // Graphique
import java.applet.*; // Applet
public class Dessin extends Applet {
public void init() {
setSize(400,400);
}
public void paint(Graphics g) {
//ciel
g.setColor(Color.blue);
g.fillRect(0,0,300,110);
//prairie
g.setColor(Color.green);
g.fillRect(0,110,300,90);
//soleil
g.setColor(Color.yellow);
g.fillOval(220,20,30,30);
//mur de la maison
g.setColor(Color.white);
g.fillRect(80,100,50,70);
g.setColor(Color.black);
g.drawRect(80,100,50,70);
//porte
g.drawRect(90,140,20,30);
g.drawLine(110,155,105,155);
//toit en triangle
int[] x={80,130,105};
int[] y={100,100,50};
g.setColor(Color.red);
g.fillPolygon(x,y,3);
g.setColor(Color.black);
g.drawPolygon(x,y,3);
}
}
| UTF-8 | Java | 783 | java | Dessin.java | Java | [] | null | [] | import java.awt.*; // Graphique
import java.applet.*; // Applet
public class Dessin extends Applet {
public void init() {
setSize(400,400);
}
public void paint(Graphics g) {
//ciel
g.setColor(Color.blue);
g.fillRect(0,0,300,110);
//prairie
g.setColor(Color.green);
g.fillRect(0,110,300,90);
//soleil
g.setColor(Color.yellow);
g.fillOval(220,20,30,30);
//mur de la maison
g.setColor(Color.white);
g.fillRect(80,100,50,70);
g.setColor(Color.black);
g.drawRect(80,100,50,70);
//porte
g.drawRect(90,140,20,30);
g.drawLine(110,155,105,155);
//toit en triangle
int[] x={80,130,105};
int[] y={100,100,50};
g.setColor(Color.red);
g.fillPolygon(x,y,3);
g.setColor(Color.black);
g.drawPolygon(x,y,3);
}
}
| 783 | 0.621967 | 0.508301 | 42 | 16.642857 | 11.474239 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.047619 | false | false | 3 |
e744861f16618631923cbd206e98c47587653eb0 | 9,019,431,384,863 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/6/6_22809a47fb141e504666d4f9e8848247f8fb4991/Transition/6_22809a47fb141e504666d4f9e8848247f8fb4991_Transition_t.java | 090b279d3f7a46f47ecce7de6221fa1248401428 | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | /*
* Copyright 2004-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.webflow.engine;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.style.ToStringCreator;
import org.springframework.util.Assert;
import org.springframework.webflow.core.AnnotatedObject;
import org.springframework.webflow.definition.TransitionDefinition;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.FlowExecutionException;
import org.springframework.webflow.execution.RequestContext;
/**
* A path from one {@link TransitionableState state} to another {@link State state}.
* <p>
* When executed a transition takes a flow execution from its current state, called the <i>source state</i>, to another
* state, called the </i>target state</i>. A transition may become eligible for execution on the occurrence of an
* {@link Event} from within a transitionable source state.
* <p>
* When an event occurs within this transition's source <code>TransitionableState</code> the determination of the
* eligibility of this transition is made by a <code>TransitionCriteria</code> object called the <i>matching criteria</i>.
* If the matching criteria returns <code>true</code> this transition is marked eligible for execution for that event.
* <p>
* Determination as to whether an eligible transition should be allowed to execute is made by a
* <code>TransitionCriteria</code> object called the <i>execution criteria</i>. If the execution criteria test fails
* this transition will <i>roll back</i> and reenter its source state. If the execution criteria test succeeds this
* transition will execute and take the flow to the transition's target state.
* <p>
* The target state of this transition is typically specified at configuration time in a static manner. If the target
* state of this transition needs to be calculated in a dynamic fashion at runtime configure a
* {@link TargetStateResolver} that supports such calculations.
*
* @see TransitionableState
* @see TransitionCriteria
* @see TargetStateResolver
*
* @author Keith Donald
* @author Erwin Vervaet
*/
public class Transition extends AnnotatedObject implements TransitionDefinition {
/**
* Logger, for use in subclasses.
*/
protected final Log logger = LogFactory.getLog(Transition.class);
/**
* The criteria that determine whether or not this transition matches as eligible for execution when an event occurs
* in the source state.
*/
private TransitionCriteria matchingCriteria;
/**
* The criteria that determine whether or not this transition, once matched, should complete execution or should
* <i>roll back</i>.
*/
private TransitionCriteria executionCriteria = WildcardTransitionCriteria.INSTANCE;
/**
* The resolver responsible for calculating the target state of this transition.
*/
private TargetStateResolver targetStateResolver;
/**
* Create a new transition that always matches and always executes, but its execution does nothing by default.
* @see #setMatchingCriteria(TransitionCriteria)
* @see #setExecutionCriteria(TransitionCriteria)
* @see #setTargetStateResolver(TargetStateResolver)
*/
public Transition() {
this(WildcardTransitionCriteria.INSTANCE, null);
}
/**
* Create a new transition that always matches and always executes, transitioning to the target state calculated by
* the provided targetStateResolver.
* @param targetStateResolver the resolver of the target state of this transition
* @see #setMatchingCriteria(TransitionCriteria)
* @see #setExecutionCriteria(TransitionCriteria)
*/
public Transition(TargetStateResolver targetStateResolver) {
this(WildcardTransitionCriteria.INSTANCE, targetStateResolver);
}
/**
* Create a new transition that matches on the specified criteria, transitioning to the target state calculated by
* the provided targetStateResolver.
* @param matchingCriteria the criteria for matching this transition
* @param targetStateResolver the resolver of the target state of this transition
* @see #setExecutionCriteria(TransitionCriteria)
*/
public Transition(TransitionCriteria matchingCriteria, TargetStateResolver targetStateResolver) {
setMatchingCriteria(matchingCriteria);
setTargetStateResolver(targetStateResolver);
}
// implementing transition definition
public String getId() {
return matchingCriteria.toString();
}
public String getTargetStateId() {
if (targetStateResolver != null) {
return targetStateResolver.toString();
} else {
return null;
}
}
/**
* Returns the criteria that determine whether or not this transition matches as eligible for execution.
* @return the transition matching criteria
*/
public TransitionCriteria getMatchingCriteria() {
return matchingCriteria;
}
/**
* Set the criteria that determine whether or not this transition matches as eligible for execution.
* @param matchingCriteria the transition matching criteria
*/
public void setMatchingCriteria(TransitionCriteria matchingCriteria) {
Assert.notNull(matchingCriteria, "The criteria for matching this transition is required");
this.matchingCriteria = matchingCriteria;
}
/**
* Returns the criteria that determine whether or not this transition, once matched, should complete execution or
* should <i>roll back</i>.
* @return the transition execution criteria
*/
public TransitionCriteria getExecutionCriteria() {
return executionCriteria;
}
/**
* Set the criteria that determine whether or not this transition, once matched, should complete execution or should
* <i>roll back</i>.
* @param executionCriteria the transition execution criteria
*/
public void setExecutionCriteria(TransitionCriteria executionCriteria) {
this.executionCriteria = executionCriteria;
}
/**
* Returns this transition's target state resolver.
*/
public TargetStateResolver getTargetStateResolver() {
return targetStateResolver;
}
/**
* Set this transition's target state resolver, to calculate what state to transition to when this transition is
* executed.
* @param targetStateResolver the target state resolver
*/
public void setTargetStateResolver(TargetStateResolver targetStateResolver) {
this.targetStateResolver = targetStateResolver;
}
/**
* Checks if this transition is eligible for execution given the state of the provided flow execution request
* context.
* @param context the flow execution request context
* @return true if this transition should execute, false otherwise
*/
public boolean matches(RequestContext context) {
return matchingCriteria.test(context);
}
/**
* Checks if this transition can complete its execution or should be rolled back, given the state of the flow
* execution request context.
* @param context the flow execution request context
* @return true if this transition can complete execution, false if it should roll back
*/
public boolean canExecute(RequestContext context) {
if (executionCriteria != null) {
return executionCriteria.test(context);
} else {
return false;
}
}
/**
* Execute this state transition. Should only be called if the {@link #matches(RequestContext)} method returns true
* for the given context.
* @param sourceState the source state to transition from, may be null if the current state is null
* @param context the flow execution control context
* @return a boolean indicating if executing this transition caused the current state to exit and a new state to
* enter
* @throws FlowExecutionException when transition execution fails
*/
public boolean execute(State sourceState, RequestControlContext context) throws FlowExecutionException {
if (canExecute(context)) {
if (logger.isDebugEnabled()) {
logger.debug("Executing " + this);
}
context.setCurrentTransition(this);
if (targetStateResolver != null) {
State targetState = targetStateResolver.resolveTargetState(this, sourceState, context);
if (targetState != null) {
if (sourceState != null) {
if (logger.isDebugEnabled()) {
logger.debug("Exiting state '" + sourceState.getId() + "'");
}
if (sourceState instanceof TransitionableState) {
((TransitionableState) sourceState).exit(context);
}
}
targetState.enter(context);
if (logger.isDebugEnabled()) {
if (context.getFlowExecutionContext().isActive()) {
logger.debug("Completed transition execution. As a result, the new state is '"
+ context.getCurrentState().getId() + "' in flow '"
+ context.getActiveFlow().getId() + "'");
} else {
logger.debug("Completed transition execution. As a result, the flow execution has ended");
}
}
return true;
}
}
}
return false;
}
public String toString() {
return new ToStringCreator(this).append("on", getMatchingCriteria()).append("to", getTargetStateResolver())
.toString();
}
}
| UTF-8 | Java | 10,061 | java | 6_22809a47fb141e504666d4f9e8848247f8fb4991_Transition_t.java | Java | [
{
"context": "a\r\n * @see TargetStateResolver\r\n * \r\n * @author Keith Donald\r\n * @author Erwin Vervaet\r\n */\r\n public class T",
"end": 2823,
"score": 0.9998713731765747,
"start": 2811,
"tag": "NAME",
"value": "Keith Donald"
},
{
"context": "olver\r\n * \r\n * @author Keith Donald\r\n * @author Erwin Vervaet\r\n */\r\n public class Transition extends Annotated",
"end": 2850,
"score": 0.9998828172683716,
"start": 2837,
"tag": "NAME",
"value": "Erwin Vervaet"
}
] | null | [] | /*
* Copyright 2004-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.webflow.engine;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.style.ToStringCreator;
import org.springframework.util.Assert;
import org.springframework.webflow.core.AnnotatedObject;
import org.springframework.webflow.definition.TransitionDefinition;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.FlowExecutionException;
import org.springframework.webflow.execution.RequestContext;
/**
* A path from one {@link TransitionableState state} to another {@link State state}.
* <p>
* When executed a transition takes a flow execution from its current state, called the <i>source state</i>, to another
* state, called the </i>target state</i>. A transition may become eligible for execution on the occurrence of an
* {@link Event} from within a transitionable source state.
* <p>
* When an event occurs within this transition's source <code>TransitionableState</code> the determination of the
* eligibility of this transition is made by a <code>TransitionCriteria</code> object called the <i>matching criteria</i>.
* If the matching criteria returns <code>true</code> this transition is marked eligible for execution for that event.
* <p>
* Determination as to whether an eligible transition should be allowed to execute is made by a
* <code>TransitionCriteria</code> object called the <i>execution criteria</i>. If the execution criteria test fails
* this transition will <i>roll back</i> and reenter its source state. If the execution criteria test succeeds this
* transition will execute and take the flow to the transition's target state.
* <p>
* The target state of this transition is typically specified at configuration time in a static manner. If the target
* state of this transition needs to be calculated in a dynamic fashion at runtime configure a
* {@link TargetStateResolver} that supports such calculations.
*
* @see TransitionableState
* @see TransitionCriteria
* @see TargetStateResolver
*
* @author <NAME>
* @author <NAME>
*/
public class Transition extends AnnotatedObject implements TransitionDefinition {
/**
* Logger, for use in subclasses.
*/
protected final Log logger = LogFactory.getLog(Transition.class);
/**
* The criteria that determine whether or not this transition matches as eligible for execution when an event occurs
* in the source state.
*/
private TransitionCriteria matchingCriteria;
/**
* The criteria that determine whether or not this transition, once matched, should complete execution or should
* <i>roll back</i>.
*/
private TransitionCriteria executionCriteria = WildcardTransitionCriteria.INSTANCE;
/**
* The resolver responsible for calculating the target state of this transition.
*/
private TargetStateResolver targetStateResolver;
/**
* Create a new transition that always matches and always executes, but its execution does nothing by default.
* @see #setMatchingCriteria(TransitionCriteria)
* @see #setExecutionCriteria(TransitionCriteria)
* @see #setTargetStateResolver(TargetStateResolver)
*/
public Transition() {
this(WildcardTransitionCriteria.INSTANCE, null);
}
/**
* Create a new transition that always matches and always executes, transitioning to the target state calculated by
* the provided targetStateResolver.
* @param targetStateResolver the resolver of the target state of this transition
* @see #setMatchingCriteria(TransitionCriteria)
* @see #setExecutionCriteria(TransitionCriteria)
*/
public Transition(TargetStateResolver targetStateResolver) {
this(WildcardTransitionCriteria.INSTANCE, targetStateResolver);
}
/**
* Create a new transition that matches on the specified criteria, transitioning to the target state calculated by
* the provided targetStateResolver.
* @param matchingCriteria the criteria for matching this transition
* @param targetStateResolver the resolver of the target state of this transition
* @see #setExecutionCriteria(TransitionCriteria)
*/
public Transition(TransitionCriteria matchingCriteria, TargetStateResolver targetStateResolver) {
setMatchingCriteria(matchingCriteria);
setTargetStateResolver(targetStateResolver);
}
// implementing transition definition
public String getId() {
return matchingCriteria.toString();
}
public String getTargetStateId() {
if (targetStateResolver != null) {
return targetStateResolver.toString();
} else {
return null;
}
}
/**
* Returns the criteria that determine whether or not this transition matches as eligible for execution.
* @return the transition matching criteria
*/
public TransitionCriteria getMatchingCriteria() {
return matchingCriteria;
}
/**
* Set the criteria that determine whether or not this transition matches as eligible for execution.
* @param matchingCriteria the transition matching criteria
*/
public void setMatchingCriteria(TransitionCriteria matchingCriteria) {
Assert.notNull(matchingCriteria, "The criteria for matching this transition is required");
this.matchingCriteria = matchingCriteria;
}
/**
* Returns the criteria that determine whether or not this transition, once matched, should complete execution or
* should <i>roll back</i>.
* @return the transition execution criteria
*/
public TransitionCriteria getExecutionCriteria() {
return executionCriteria;
}
/**
* Set the criteria that determine whether or not this transition, once matched, should complete execution or should
* <i>roll back</i>.
* @param executionCriteria the transition execution criteria
*/
public void setExecutionCriteria(TransitionCriteria executionCriteria) {
this.executionCriteria = executionCriteria;
}
/**
* Returns this transition's target state resolver.
*/
public TargetStateResolver getTargetStateResolver() {
return targetStateResolver;
}
/**
* Set this transition's target state resolver, to calculate what state to transition to when this transition is
* executed.
* @param targetStateResolver the target state resolver
*/
public void setTargetStateResolver(TargetStateResolver targetStateResolver) {
this.targetStateResolver = targetStateResolver;
}
/**
* Checks if this transition is eligible for execution given the state of the provided flow execution request
* context.
* @param context the flow execution request context
* @return true if this transition should execute, false otherwise
*/
public boolean matches(RequestContext context) {
return matchingCriteria.test(context);
}
/**
* Checks if this transition can complete its execution or should be rolled back, given the state of the flow
* execution request context.
* @param context the flow execution request context
* @return true if this transition can complete execution, false if it should roll back
*/
public boolean canExecute(RequestContext context) {
if (executionCriteria != null) {
return executionCriteria.test(context);
} else {
return false;
}
}
/**
* Execute this state transition. Should only be called if the {@link #matches(RequestContext)} method returns true
* for the given context.
* @param sourceState the source state to transition from, may be null if the current state is null
* @param context the flow execution control context
* @return a boolean indicating if executing this transition caused the current state to exit and a new state to
* enter
* @throws FlowExecutionException when transition execution fails
*/
public boolean execute(State sourceState, RequestControlContext context) throws FlowExecutionException {
if (canExecute(context)) {
if (logger.isDebugEnabled()) {
logger.debug("Executing " + this);
}
context.setCurrentTransition(this);
if (targetStateResolver != null) {
State targetState = targetStateResolver.resolveTargetState(this, sourceState, context);
if (targetState != null) {
if (sourceState != null) {
if (logger.isDebugEnabled()) {
logger.debug("Exiting state '" + sourceState.getId() + "'");
}
if (sourceState instanceof TransitionableState) {
((TransitionableState) sourceState).exit(context);
}
}
targetState.enter(context);
if (logger.isDebugEnabled()) {
if (context.getFlowExecutionContext().isActive()) {
logger.debug("Completed transition execution. As a result, the new state is '"
+ context.getCurrentState().getId() + "' in flow '"
+ context.getActiveFlow().getId() + "'");
} else {
logger.debug("Completed transition execution. As a result, the flow execution has ended");
}
}
return true;
}
}
}
return false;
}
public String toString() {
return new ToStringCreator(this).append("on", getMatchingCriteria()).append("to", getTargetStateResolver())
.toString();
}
}
| 10,048 | 0.716927 | 0.715734 | 248 | 38.56855 | 36.540237 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.625 | false | false | 3 |
d2e94a8d218eb97e14504a883e9e8f19caafb4d0 | 36,034,775,641,979 | 614ae2f706f38792d725f7f1b84747dc9c449409 | /src/main/java/pivotal/io/demo/customtoken/exception/OutOfServiceException.java | b340ce0cc95aeb6743bb26e136586825a682f137 | [] | no_license | pdeemea/custom-token-authentication | https://github.com/pdeemea/custom-token-authentication | 3796e5dd33786a84e5a885847a2b9d3e37cbf0a4 | 5ddcb297cae4d7642407bc2acaea2d3fc3c23ce2 | refs/heads/master | 2020-04-09T11:11:54.615000 | 2016-02-08T16:13:38 | 2016-02-08T16:13:38 | 50,960,179 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pivotal.io.demo.customtoken.exception;
@SuppressWarnings("serial")
public class OutOfServiceException extends RuntimeException {
public OutOfServiceException(String message) {
super(message);
}
public OutOfServiceException(Throwable cause) {
super(cause);
}
}
| UTF-8 | Java | 284 | java | OutOfServiceException.java | Java | [] | null | [] | package pivotal.io.demo.customtoken.exception;
@SuppressWarnings("serial")
public class OutOfServiceException extends RuntimeException {
public OutOfServiceException(String message) {
super(message);
}
public OutOfServiceException(Throwable cause) {
super(cause);
}
}
| 284 | 0.774648 | 0.774648 | 17 | 15.705882 | 20.877132 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false | 3 |
6ca028c149b9e4e63326a22f5d1b6326186d8a15 | 8,237,747,308,580 | 70721615f4d1174ab5c7da3956bb4186a054dfda | /src/fx/statistic/invoker/ProbablityCalculator.java | be727a05b967cf46978a53ab98887ad0af6235d8 | [] | no_license | desperado54/fx | https://github.com/desperado54/fx | be6281e4d5c1deeccf15d057d6d5ae74425f71b9 | 655ae5b52f06192a46d3cafe82fb42a695d3b625 | refs/heads/master | 2021-01-16T21:18:31.972000 | 2017-01-29T15:28:06 | 2017-01-29T15:28:06 | 33,834,326 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fx.statistic.invoker;
import fx.statistic.indicators.IIndicator;
import fx.statistic.indicators.RecentNIndicator;
import fx.statistic.probablity.NextDayContinuation;
public class ProbablityCalculator {
public static void main(String[] args) {
try
{
NextDayContinuation p = new NextDayContinuation("eurusd", "d1");
p.Calcuate();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
| UTF-8 | Java | 495 | java | ProbablityCalculator.java | Java | [] | null | [] | package fx.statistic.invoker;
import fx.statistic.indicators.IIndicator;
import fx.statistic.indicators.RecentNIndicator;
import fx.statistic.probablity.NextDayContinuation;
public class ProbablityCalculator {
public static void main(String[] args) {
try
{
NextDayContinuation p = new NextDayContinuation("eurusd", "d1");
p.Calcuate();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
| 495 | 0.616162 | 0.614141 | 22 | 21.5 | 20.468935 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 3 |
93c80586b07f5d937f1f5c0ac5fe63ece57f69c6 | 34,797,825,068,794 | a933c2903ae56f325da63cd36ac46576bfb37452 | /CucumberLiveView/src/main/java/com/surveillance/utilitiy/HtmlReportFile.java | e5209c113dc49c9aa7da182517e86164a24711ab | [] | no_license | chaitanya1327/cucumber-liveviewtech | https://github.com/chaitanya1327/cucumber-liveviewtech | aa4b11c50b553dbdc628c88c0c99c22f0fd94745 | 146b9515dd98c1199be99213e57333d1312400ef | refs/heads/master | 2023-04-03T15:42:40.389000 | 2021-03-23T08:16:32 | 2021-03-23T08:16:32 | 350,630,180 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.surveillance.utilitiy;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class HtmlReportFile {
static BufferedWriter bw;
static String color=""
;
public static void main(String[] args) throws Throwable
{
// File f1=new File("C:\\Users\\vgardula\\Desktop\\Reports\\Test1.html");
// f1.createNewFile();
int testCaseDeatisl[]={1,100,70,20,10};
int testCaseDeatisl2[]={2,100,100,0,0};
int testCaseDeatisl3[]={3,100,60,10,30};
String report="C:/Users/lenovo/Desktop/testReports/Index2.html";
createHtmlReport(report);
testDetails(report, "C:/Users/lenovo/Desktop/testReports", "CameraLiveUnit", testCaseDeatisl);
testDetails(report, "C:/Users/lenovo/Desktop/testReports", "Add New User", testCaseDeatisl2);
testDetails(report, "C:/Users/lenovo/Desktop/testReports", "Add New Cleint", testCaseDeatisl3);
}
/**
* Method Name : createHtmlReport
* purpose : creates a file and copies the mainContent and reportTemplate into it.
* parameters : fileName
* Example :
*/
public static void createHtmlReport(String fileName) throws Throwable
{
System.out.println("HTML report path :"+fileName);
File f1=new File(fileName);
f1.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(f1));
bw.write(MainContent()+reportTemplate());
bw.close();
}
//
/**
* Method Name : MainContent
* purpose : creates the Html report based on the testcases executed, time taken for execution, host name of the system where testcases are executed and so on...
* parameters : excelpath
* Example : <>, <>
*/
public static String MainContent()
{
color="#9933FF";
// String AppName=Mains.configfile.getCellData("Config", "Application Name ", 2);
String AppName="LiveView Technologies";
String content="<div class='header'><img src='"+"https://lvt.co/wp-content/uploads/2019/07/pasted-svg-303101x59.svg"+"' alt='Mountain View' overflow:'auto' float:'left' align='center'style='width:150px;height:150px;'><h1 style='color:blue' overflow:'auto' float:'left' align='center';><center></center>LVT - Automation Report</h1></div>"
//+"<h2 style='color:blue' align='center';><center>Automation Report</center></h2>"
+"<table height='10%' width='70%' border='1' bgcolor='"+color+"' style='font-family:tahoma; font-size:12'><font face='Verdana'>"
+"<tr bgcolor='"+color+"'><td height='1' width='20%'><font face='Verdana' size='2' color='white' weight='200'> Application Name </font></td><td align='center'><font id='appname' face='Verdana' size='2' color='white' weight='200'>"+AppName+"</font></td>"
// +"<td rowspan='11' align='center' bgcolor='"+color+"' width='10%'><div style='float: right;'><img src='data:image/png;base64,"+MainSuiteRunner.MasterPieChart+"' alt='Not coonnected to sharing path' align='middle'style='width:504px;height:500px;'></div></td>"
// +"<td rowspan='11' align='center' bgcolor='"+color+"' width='10%'><div style='float: right;'><img src='data:image/png;base64,"+MainSuiteRunner.tcsummaryPieChart+"' alt=Not coonnected to sharing path' align='middle'style='width:504px;height:500px;'></div></td>"
+"</tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Version </font></td><td align='center'><font id='Version' face='Verdana' size='2' color='white' weight='200'>"+"version"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Executed On </font></td><td align='center'><font id='ExecutedOn' face='Verdana' size='2' color='white' weight='200'>"+DateAndTimeFormate.dateFormate("dd/M/yyyy hh:mm:ss")+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Host Name </font></td><td align='center'><font id='HostName' face='Verdana' size='2' color='white' weight='200'>"+getHostName()+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Results Location </font></td><td align='center'><font id='ResultsLocation' face='Verdana' size='2' color='white' weight='200'>"+"MainSuiteRunner.RemotetResultsPath"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Docs </font></td><td align='center'><font id='TotalDocs' face='Verdana' size='2' color='white' weight='200'>"+"totalfiles"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Executed </font></td><td align='center'><font id='TotalExecuted' face='Verdana' size='2' color='white' weight='200'>"+"totalexecutedcount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Pass </font></td><td align='center'><font id='TotalPass' face='Verdana' size='2' color='white' weight='200'>"+"totalpasscount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Fail </font></td><td align='center'><font id='TotalFail'face='Verdana' size='2' color='white' weight='200'>"+"totalfailedcount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Skip </font></td><td align='center'><font id='TotalSkip'face='Verdana' size='2' color='white' weight='200'>"+"totalskippedcount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Elapsed Time </font></td><td align='center'><font class='special' id='TotalElapsedTime'face='Verdana' size='2' color='white' weight='200'>"+"totalelapced"+"</font></td></font></tr>"
+"</table>"
+"<br>";
return content;
}
/**
* Method Name : createxcelReport
* purpose : creates the html report based on the No. of test cases passed, failed and skiped.
* parameters : -
* Example : -
*/
public static String reportTemplate(){
// color="#9933FF";
color="#0000cc";
String template="<HTML><BODY>"
+ "<table height='2%' width='70%' style='font-family:Verdana; font-size:15'><tbody><tr bgcolor='"+color+"'>"
+"<th><font color='white'>S NO</font></th>"
+"<th><font color='white'>Test Name</font></th>"
+"<th><font color='white'>Total Executed</font></th>"
+"<th><font color='white'>Total Pass</font></th>"
+"<th><font color='white'>Total Fail</font></th>"
+"<th><font color='white'>Total Skip</font></th></tr>";
return template;
}
/**
* Method Name : testDetails
* purpose :
* parameters :
* Example :
*/
public static String testDetails(String fileName,String htmlReportpath,String htmlReportName,int results[]) throws Throwable
{
String withFail=null;
String bgclor="#80ffff";//#9933FF
if(results[3]>0){
withFail="<td bgcolor='"+bgclor+"' style='background-color:#FF0000'>"+results[3]+"</td>";
}
else
{
withFail="<td bgcolor='"+bgclor+"'>"+results[3]+"</td>";
}
String withskip=null;
if(results[4]>0){
withskip="<td bgcolor='#BEBEBE' style='background-color:#778899'>"+results[4]+"</td>";
}
else
{
withskip="<td bgcolor='"+bgclor+"'>"+results[4]+"</td>";
}
String data="<tr>"
+"<td bgcolor='"+bgclor+"'>"+results[0]+"</td>" //#A52A2A '#BEBEBE
+"<td bgcolor='#BEBEBE' style='background-color:"+bgclor+"'><a href='"+htmlReportpath+"'>"+htmlReportName+"</a>"
+"</td><td bgcolor='"+bgclor+"'>"+results[1]+"</td>"
+"<td bgcolor='#BEBEBE' style='background-color:#009b00'>"+results[2]+"</td>"// #A6D785 previous color #32CD32
+ withFail /*total fail column*/
// +"<td bgcolor='#BEBEBE' style='background-color:#778899'>"+results[4]+"</td>"//total skip column
+withskip
+"</tr>";
File f1=new File(fileName);
FileWriter write = new FileWriter(f1,true);
write.write(data);
write.close();
return data;
}
// public void endDetailReport(String report) throws IOException
// {
// FileWriter writer = new FileWriter(report,true);
// writer.write("</TABLE>");
// writer.close();
// writer = new FileWriter(Driver.reportFileNm,true);
// writer.write("</TABLE>");
// writer.close();
// }
/**
* Method Name : finalReportUpadte
* purpose : creates the final report of app version,Total No.of test cases and steps, No. of test cases passed, failed and skipped and time taken.
* parameters : filename, elapsedTime, resultDetails, testcasesDetails
* Example :
*/
public static void finalReportUpdate(String filene,String elapcedTime,int resultsDetaisl[],int TestCaseDetaisl[]) throws IOException
{
File f1=new File(filene);
FileWriter write = new FileWriter(f1,true);
/*String totalCasesAndSteps=TestCaseDetaisl[0]+" &"+resultsDetaisl[1];
String toatlPass=TestCaseDetaisl[1]+" &"+resultsDetaisl[2];
String totalFail=TestCaseDetaisl[2]+" &"+resultsDetaisl[3];
String totalSkips=TestCaseDetaisl[3]+" &"+resultsDetaisl[4];*/
String totalCasesAndSteps=TestCaseDetaisl[0]+"";
String toatlPass=TestCaseDetaisl[1]+"";
String totalFail=TestCaseDetaisl[2]+"";
String totalSkips=TestCaseDetaisl[3]+"";
String data="<script>document.getElementById('Version').innerHTML = "+1+";</script>"
+"<script>document.getElementById('TotalDocs').innerHTML = '"+resultsDetaisl[0]+"';</script>"
+"<script>document.getElementById('TotalExecuted').innerHTML = '"+totalCasesAndSteps+"';</script>"
+"<script>document.getElementById('TotalPass').innerHTML = ' "+toatlPass+"';</script>"
+"<script>document.getElementById('TotalFail').innerHTML = '"+totalFail+"';</script>"
+"<script>document.getElementById('TotalSkip').innerHTML = '"+totalSkips+"';</script>"
+"<script>document.getElementById('TotalElapsedTime').innerHTML =' "+elapcedTime+"';</script>"
;
write.write(data);
write.close();
}
/**
* Method Name : getHostName
* purpose : returns the hostname of the system where the testcases are executed.
* parameters : -
* Example : -
*/
public static String getHostName()
{
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
return hostname;
}
}
| UTF-8 | Java | 10,770 | java | HtmlReportFile.java | Java | [
{
"context": "ows Throwable\n\t{\n//\t\tFile f1=new File(\"C:\\\\Users\\\\vgardula\\\\Desktop\\\\Reports\\\\Test1.html\");\n//\t\tf1.createNew",
"end": 400,
"score": 0.9982629418373108,
"start": 392,
"tag": "USERNAME",
"value": "vgardula"
}
] | null | [] | package com.surveillance.utilitiy;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class HtmlReportFile {
static BufferedWriter bw;
static String color=""
;
public static void main(String[] args) throws Throwable
{
// File f1=new File("C:\\Users\\vgardula\\Desktop\\Reports\\Test1.html");
// f1.createNewFile();
int testCaseDeatisl[]={1,100,70,20,10};
int testCaseDeatisl2[]={2,100,100,0,0};
int testCaseDeatisl3[]={3,100,60,10,30};
String report="C:/Users/lenovo/Desktop/testReports/Index2.html";
createHtmlReport(report);
testDetails(report, "C:/Users/lenovo/Desktop/testReports", "CameraLiveUnit", testCaseDeatisl);
testDetails(report, "C:/Users/lenovo/Desktop/testReports", "Add New User", testCaseDeatisl2);
testDetails(report, "C:/Users/lenovo/Desktop/testReports", "Add New Cleint", testCaseDeatisl3);
}
/**
* Method Name : createHtmlReport
* purpose : creates a file and copies the mainContent and reportTemplate into it.
* parameters : fileName
* Example :
*/
public static void createHtmlReport(String fileName) throws Throwable
{
System.out.println("HTML report path :"+fileName);
File f1=new File(fileName);
f1.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(f1));
bw.write(MainContent()+reportTemplate());
bw.close();
}
//
/**
* Method Name : MainContent
* purpose : creates the Html report based on the testcases executed, time taken for execution, host name of the system where testcases are executed and so on...
* parameters : excelpath
* Example : <>, <>
*/
public static String MainContent()
{
color="#9933FF";
// String AppName=Mains.configfile.getCellData("Config", "Application Name ", 2);
String AppName="LiveView Technologies";
String content="<div class='header'><img src='"+"https://lvt.co/wp-content/uploads/2019/07/pasted-svg-303101x59.svg"+"' alt='Mountain View' overflow:'auto' float:'left' align='center'style='width:150px;height:150px;'><h1 style='color:blue' overflow:'auto' float:'left' align='center';><center></center>LVT - Automation Report</h1></div>"
//+"<h2 style='color:blue' align='center';><center>Automation Report</center></h2>"
+"<table height='10%' width='70%' border='1' bgcolor='"+color+"' style='font-family:tahoma; font-size:12'><font face='Verdana'>"
+"<tr bgcolor='"+color+"'><td height='1' width='20%'><font face='Verdana' size='2' color='white' weight='200'> Application Name </font></td><td align='center'><font id='appname' face='Verdana' size='2' color='white' weight='200'>"+AppName+"</font></td>"
// +"<td rowspan='11' align='center' bgcolor='"+color+"' width='10%'><div style='float: right;'><img src='data:image/png;base64,"+MainSuiteRunner.MasterPieChart+"' alt='Not coonnected to sharing path' align='middle'style='width:504px;height:500px;'></div></td>"
// +"<td rowspan='11' align='center' bgcolor='"+color+"' width='10%'><div style='float: right;'><img src='data:image/png;base64,"+MainSuiteRunner.tcsummaryPieChart+"' alt=Not coonnected to sharing path' align='middle'style='width:504px;height:500px;'></div></td>"
+"</tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Version </font></td><td align='center'><font id='Version' face='Verdana' size='2' color='white' weight='200'>"+"version"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Executed On </font></td><td align='center'><font id='ExecutedOn' face='Verdana' size='2' color='white' weight='200'>"+DateAndTimeFormate.dateFormate("dd/M/yyyy hh:mm:ss")+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Host Name </font></td><td align='center'><font id='HostName' face='Verdana' size='2' color='white' weight='200'>"+getHostName()+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Results Location </font></td><td align='center'><font id='ResultsLocation' face='Verdana' size='2' color='white' weight='200'>"+"MainSuiteRunner.RemotetResultsPath"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Docs </font></td><td align='center'><font id='TotalDocs' face='Verdana' size='2' color='white' weight='200'>"+"totalfiles"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Executed </font></td><td align='center'><font id='TotalExecuted' face='Verdana' size='2' color='white' weight='200'>"+"totalexecutedcount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Pass </font></td><td align='center'><font id='TotalPass' face='Verdana' size='2' color='white' weight='200'>"+"totalpasscount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Fail </font></td><td align='center'><font id='TotalFail'face='Verdana' size='2' color='white' weight='200'>"+"totalfailedcount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Testcases & Steps Skip </font></td><td align='center'><font id='TotalSkip'face='Verdana' size='2' color='white' weight='200'>"+"totalskippedcount"+"</font></td></tr>"
+"<tr bgcolor='"+color+"'><td height='1'><font face='Verdana' size='2' color='white' weight='200'> Total Elapsed Time </font></td><td align='center'><font class='special' id='TotalElapsedTime'face='Verdana' size='2' color='white' weight='200'>"+"totalelapced"+"</font></td></font></tr>"
+"</table>"
+"<br>";
return content;
}
/**
* Method Name : createxcelReport
* purpose : creates the html report based on the No. of test cases passed, failed and skiped.
* parameters : -
* Example : -
*/
public static String reportTemplate(){
// color="#9933FF";
color="#0000cc";
String template="<HTML><BODY>"
+ "<table height='2%' width='70%' style='font-family:Verdana; font-size:15'><tbody><tr bgcolor='"+color+"'>"
+"<th><font color='white'>S NO</font></th>"
+"<th><font color='white'>Test Name</font></th>"
+"<th><font color='white'>Total Executed</font></th>"
+"<th><font color='white'>Total Pass</font></th>"
+"<th><font color='white'>Total Fail</font></th>"
+"<th><font color='white'>Total Skip</font></th></tr>";
return template;
}
/**
* Method Name : testDetails
* purpose :
* parameters :
* Example :
*/
public static String testDetails(String fileName,String htmlReportpath,String htmlReportName,int results[]) throws Throwable
{
String withFail=null;
String bgclor="#80ffff";//#9933FF
if(results[3]>0){
withFail="<td bgcolor='"+bgclor+"' style='background-color:#FF0000'>"+results[3]+"</td>";
}
else
{
withFail="<td bgcolor='"+bgclor+"'>"+results[3]+"</td>";
}
String withskip=null;
if(results[4]>0){
withskip="<td bgcolor='#BEBEBE' style='background-color:#778899'>"+results[4]+"</td>";
}
else
{
withskip="<td bgcolor='"+bgclor+"'>"+results[4]+"</td>";
}
String data="<tr>"
+"<td bgcolor='"+bgclor+"'>"+results[0]+"</td>" //#A52A2A '#BEBEBE
+"<td bgcolor='#BEBEBE' style='background-color:"+bgclor+"'><a href='"+htmlReportpath+"'>"+htmlReportName+"</a>"
+"</td><td bgcolor='"+bgclor+"'>"+results[1]+"</td>"
+"<td bgcolor='#BEBEBE' style='background-color:#009b00'>"+results[2]+"</td>"// #A6D785 previous color #32CD32
+ withFail /*total fail column*/
// +"<td bgcolor='#BEBEBE' style='background-color:#778899'>"+results[4]+"</td>"//total skip column
+withskip
+"</tr>";
File f1=new File(fileName);
FileWriter write = new FileWriter(f1,true);
write.write(data);
write.close();
return data;
}
// public void endDetailReport(String report) throws IOException
// {
// FileWriter writer = new FileWriter(report,true);
// writer.write("</TABLE>");
// writer.close();
// writer = new FileWriter(Driver.reportFileNm,true);
// writer.write("</TABLE>");
// writer.close();
// }
/**
* Method Name : finalReportUpadte
* purpose : creates the final report of app version,Total No.of test cases and steps, No. of test cases passed, failed and skipped and time taken.
* parameters : filename, elapsedTime, resultDetails, testcasesDetails
* Example :
*/
public static void finalReportUpdate(String filene,String elapcedTime,int resultsDetaisl[],int TestCaseDetaisl[]) throws IOException
{
File f1=new File(filene);
FileWriter write = new FileWriter(f1,true);
/*String totalCasesAndSteps=TestCaseDetaisl[0]+" &"+resultsDetaisl[1];
String toatlPass=TestCaseDetaisl[1]+" &"+resultsDetaisl[2];
String totalFail=TestCaseDetaisl[2]+" &"+resultsDetaisl[3];
String totalSkips=TestCaseDetaisl[3]+" &"+resultsDetaisl[4];*/
String totalCasesAndSteps=TestCaseDetaisl[0]+"";
String toatlPass=TestCaseDetaisl[1]+"";
String totalFail=TestCaseDetaisl[2]+"";
String totalSkips=TestCaseDetaisl[3]+"";
String data="<script>document.getElementById('Version').innerHTML = "+1+";</script>"
+"<script>document.getElementById('TotalDocs').innerHTML = '"+resultsDetaisl[0]+"';</script>"
+"<script>document.getElementById('TotalExecuted').innerHTML = '"+totalCasesAndSteps+"';</script>"
+"<script>document.getElementById('TotalPass').innerHTML = ' "+toatlPass+"';</script>"
+"<script>document.getElementById('TotalFail').innerHTML = '"+totalFail+"';</script>"
+"<script>document.getElementById('TotalSkip').innerHTML = '"+totalSkips+"';</script>"
+"<script>document.getElementById('TotalElapsedTime').innerHTML =' "+elapcedTime+"';</script>"
;
write.write(data);
write.close();
}
/**
* Method Name : getHostName
* purpose : returns the hostname of the system where the testcases are executed.
* parameters : -
* Example : -
*/
public static String getHostName()
{
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
return hostname;
}
}
| 10,770 | 0.654775 | 0.628577 | 235 | 44.804256 | 66.663429 | 342 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.06383 | false | false | 3 |
70a60888911c02be09f11918b76e1cbca6a7d949 | 34,660,386,124,464 | 4934462180b9daadc6c610aa5f2666f851e329d1 | /Reservation/InterfaceListe.java | 548ef43d0d64721614ff7d8013ac86dd762a3bdc | [] | no_license | MelissaDaCosta/Gestion-Hotel-Java | https://github.com/MelissaDaCosta/Gestion-Hotel-Java | 08dab70634e6231ddde7282204bbf5f77d0f5246 | b54d02188b18aeeda84ce6fa91f1ba69d4305072 | refs/heads/master | 2021-05-15T09:09:57.301000 | 2017-10-23T16:15:47 | 2017-10-23T16:15:47 | 108,007,066 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.swing.*;
import java.awt.*;
public class InterfaceListe extends JPanel{
private JPanel panneau;
private CardLayout moncardlayout;
private ChambreModel chambremodel;
private Client monclient;
private int[] tabChambre;
public InterfaceListe(CardLayout card, JPanel pann, Client client, int[] tab, ChambreModel chambremod){
this.panneau= pann;
this.moncardlayout= card;
this.monclient=client;
this.chambremodel=chambremod;
this.tabChambre=tab;
this.afficherVue();
}
public void afficherVue(){
this.setLayout(new GridLayout(5, 1)); // met le layout en grid avec nos 3 éléments + les chambres dispo
Color couleur= new Color(200, 200, 255);
this.setBackground(couleur); // modifie couleur panneau
JLabel etiquette1= new JLabel("Liste des chambres");
etiquette1.setFont(new Font("", Font.BOLD, 35));
etiquette1.setHorizontalAlignment(JLabel.CENTER); // la positionne
JLabel etiquette2= new JLabel("Liste des chambres correspondant aux crit\u00e8res du client: "+monclient.getPrenom()+" "+monclient.getNom());
etiquette2.setHorizontalAlignment(JLabel.CENTER); // la positionne
this.add(etiquette1);
this.add(etiquette2);
JLabel etiquette3= new JLabel("Les crit\u00e8res du client: début r\u00e9servation: "+this.monclient.getDate()+" Nombre de nuit: "+this.monclient.getNuits());
etiquette3.setHorizontalAlignment(JLabel.CENTER); // la positionne
this.add(etiquette3);
ControleurRadioBouton controleurjr= new ControleurRadioBouton(this.moncardlayout, this.panneau, this.monclient, this.chambremodel);
ButtonGroup groupe = new ButtonGroup(); // cree ensemble de bouton
JPanel pann= new JPanel();
pann.setLayout(new GridLayout((this.tabChambre.length)/4, 0)); // creer gridlayout pour placer nos bouton radios
pann.setBackground(couleur);
for(int i=0; i<this.tabChambre.length; i++){
// creer bouton radios
JRadioButton jr = new JRadioButton(""+tabChambre[i]+"");
jr.setBackground(couleur);
groupe.add(jr);
pann.add(jr);
jr.addActionListener(controleurjr);
}
this.add(pann);
JPanel bouton= new JPanel();
bouton.setBackground(couleur);
JButton valider= new JButton("Valider");
JButton accueil= new JButton("Accueil");
bouton.add(valider);
bouton.add(accueil);
this.add(bouton);
ControleurBouton controleur= new ControleurBouton(this.moncardlayout, this.panneau, this.monclient);
accueil.addActionListener(controleur);
valider.addActionListener(controleurjr);
panneau.add(this, "Liste");
moncardlayout.show(panneau, "Liste");
}
} | UTF-8 | Java | 2,567 | java | InterfaceListe.java | Java | [] | null | [] | import javax.swing.*;
import java.awt.*;
public class InterfaceListe extends JPanel{
private JPanel panneau;
private CardLayout moncardlayout;
private ChambreModel chambremodel;
private Client monclient;
private int[] tabChambre;
public InterfaceListe(CardLayout card, JPanel pann, Client client, int[] tab, ChambreModel chambremod){
this.panneau= pann;
this.moncardlayout= card;
this.monclient=client;
this.chambremodel=chambremod;
this.tabChambre=tab;
this.afficherVue();
}
public void afficherVue(){
this.setLayout(new GridLayout(5, 1)); // met le layout en grid avec nos 3 éléments + les chambres dispo
Color couleur= new Color(200, 200, 255);
this.setBackground(couleur); // modifie couleur panneau
JLabel etiquette1= new JLabel("Liste des chambres");
etiquette1.setFont(new Font("", Font.BOLD, 35));
etiquette1.setHorizontalAlignment(JLabel.CENTER); // la positionne
JLabel etiquette2= new JLabel("Liste des chambres correspondant aux crit\u00e8res du client: "+monclient.getPrenom()+" "+monclient.getNom());
etiquette2.setHorizontalAlignment(JLabel.CENTER); // la positionne
this.add(etiquette1);
this.add(etiquette2);
JLabel etiquette3= new JLabel("Les crit\u00e8res du client: début r\u00e9servation: "+this.monclient.getDate()+" Nombre de nuit: "+this.monclient.getNuits());
etiquette3.setHorizontalAlignment(JLabel.CENTER); // la positionne
this.add(etiquette3);
ControleurRadioBouton controleurjr= new ControleurRadioBouton(this.moncardlayout, this.panneau, this.monclient, this.chambremodel);
ButtonGroup groupe = new ButtonGroup(); // cree ensemble de bouton
JPanel pann= new JPanel();
pann.setLayout(new GridLayout((this.tabChambre.length)/4, 0)); // creer gridlayout pour placer nos bouton radios
pann.setBackground(couleur);
for(int i=0; i<this.tabChambre.length; i++){
// creer bouton radios
JRadioButton jr = new JRadioButton(""+tabChambre[i]+"");
jr.setBackground(couleur);
groupe.add(jr);
pann.add(jr);
jr.addActionListener(controleurjr);
}
this.add(pann);
JPanel bouton= new JPanel();
bouton.setBackground(couleur);
JButton valider= new JButton("Valider");
JButton accueil= new JButton("Accueil");
bouton.add(valider);
bouton.add(accueil);
this.add(bouton);
ControleurBouton controleur= new ControleurBouton(this.moncardlayout, this.panneau, this.monclient);
accueil.addActionListener(controleur);
valider.addActionListener(controleurjr);
panneau.add(this, "Liste");
moncardlayout.show(panneau, "Liste");
}
} | 2,567 | 0.74454 | 0.730499 | 76 | 32.75 | 35.220779 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.315789 | false | false | 3 |
3694e1e52a4940307e5b4621b13594d08e199814 | 32,435,593,055,059 | b28cd15d937184ac1749110a04095cbb8a2906a9 | /Tutorial WitherSpawn/src/net/eduard/witherspawn/command/WitherCommand.java | b00e871e6028314afe2363c91e79c805c9577f22 | [] | no_license | ScoltBr/plugins | https://github.com/ScoltBr/plugins | 9a061ebe283390756d5ce58ebe134223e4120d15 | f3e7a589b1bfe059d87de64c757fd6c43382fe36 | refs/heads/master | 2020-04-21T18:33:10.505000 | 2019-01-25T23:47:09 | 2019-01-25T23:47:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.eduard.witherspawn.command;
import net.eduard.api.lib.manager.CommandManager;
public class WitherCommand extends CommandManager {
public WitherCommand() {
super("wither");
register(new Help());
register(new SetSpawn());
register(new Spawn());
}
}
| UTF-8 | Java | 275 | java | WitherCommand.java | Java | [] | null | [] |
package net.eduard.witherspawn.command;
import net.eduard.api.lib.manager.CommandManager;
public class WitherCommand extends CommandManager {
public WitherCommand() {
super("wither");
register(new Help());
register(new SetSpawn());
register(new Spawn());
}
}
| 275 | 0.730909 | 0.730909 | 14 | 18.571428 | 17.895388 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.214286 | false | false | 3 |
40c82651bf9e909d76fbaf72ec708570faec448b | 6,459,630,876,911 | c661e518f11551b4943fec9f9739b9039299c5e0 | /src/main/java/com/web/webstart/base/service/impl/BaseService.java | 1bc22f09dfdfaedbe9debf4eb53facfdf81eee14 | [] | no_license | SongJian0926/iread | https://github.com/SongJian0926/iread | 4972a9ce327bd204d13e99ee9710235d66f22ef6 | ec2328bc0a93d11a6bf94c78919d49a74a7b095e | refs/heads/master | 2021-01-21T15:45:17.386000 | 2017-05-20T01:12:49 | 2017-05-20T01:12:49 | 91,856,580 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.web.webstart.base.service.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @Title: BaseService.java
* @Package com.web.xxx.business.service.impl
* @Description: TODO
* @author eason.zt
* @date 2014年8月20日 下午6:55:24
* @version V1.0
*/
public abstract class BaseService<T> {
@Autowired
private EntityManagerFactory entityManagerFactory;
@SuppressWarnings("unchecked")
public List<T> query(String sql,String resultSetMapping){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql,resultSetMapping);
List<T> list = query.getResultList();
em.close();
return list;
}
public Integer insert(String sql){
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Query query= em.createNativeQuery(sql);
Integer r = query.executeUpdate();
em.getTransaction().commit();
em.close();
return r;
}
@SuppressWarnings("unchecked")
public List<Object[]> query(String sql,Integer begin,Integer count){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql);
if(begin != null && count != null){
query.setFirstResult(begin);
query.setMaxResults(count);
}
List<Object[]> list = query.getResultList();
em.close();
return list;
}
@SuppressWarnings("unchecked")
public List<String> queryString(String sql,Integer begin,Integer count){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql);
if(begin != null && count != null){
query.setFirstResult(begin);
query.setMaxResults(count);
}
List<String> list = query.getResultList();
em.close();
return list;
}
@SuppressWarnings("unchecked")
public List<Object[]> queryParams(String sql,Integer begin,Integer count,List<Object> params){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql);
for(int i=0;i<params.size();i++){
query.setParameter(i+1, params.get(i));
}
if(begin != null && count != null){
query.setFirstResult(begin);
query.setMaxResults(count);
}
List<Object[]> list = query.getResultList();
em.close();
return list;
}
public Integer delete(String sql,List<Object> params){
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Query query= em.createNativeQuery(sql);
for(int i=0;i<params.size();i++){
query.setParameter(i+1, params.get(i));
}
Integer r = query.executeUpdate();
em.getTransaction().commit();
em.close();
return r;
}
@SuppressWarnings("unchecked")
public List<Object[]> queryCall(String procString,List<Object> params){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(procString);
for(int i=0;i<params.size();i++){
query.setParameter(i+1, params.get(i));
}
List<Object[]> list = query.getResultList();
em.close();
return list;
}
}
| UTF-8 | Java | 3,165 | java | BaseService.java | Java | [
{
"context": "ness.service.impl\n * @Description: TODO\n * @author eason.zt\n * @date 2014年8月20日 下午6:55:24\n * @version V1.0\n *",
"end": 372,
"score": 0.999160885810852,
"start": 364,
"tag": "USERNAME",
"value": "eason.zt"
}
] | null | [] | package com.web.webstart.base.service.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @Title: BaseService.java
* @Package com.web.xxx.business.service.impl
* @Description: TODO
* @author eason.zt
* @date 2014年8月20日 下午6:55:24
* @version V1.0
*/
public abstract class BaseService<T> {
@Autowired
private EntityManagerFactory entityManagerFactory;
@SuppressWarnings("unchecked")
public List<T> query(String sql,String resultSetMapping){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql,resultSetMapping);
List<T> list = query.getResultList();
em.close();
return list;
}
public Integer insert(String sql){
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Query query= em.createNativeQuery(sql);
Integer r = query.executeUpdate();
em.getTransaction().commit();
em.close();
return r;
}
@SuppressWarnings("unchecked")
public List<Object[]> query(String sql,Integer begin,Integer count){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql);
if(begin != null && count != null){
query.setFirstResult(begin);
query.setMaxResults(count);
}
List<Object[]> list = query.getResultList();
em.close();
return list;
}
@SuppressWarnings("unchecked")
public List<String> queryString(String sql,Integer begin,Integer count){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql);
if(begin != null && count != null){
query.setFirstResult(begin);
query.setMaxResults(count);
}
List<String> list = query.getResultList();
em.close();
return list;
}
@SuppressWarnings("unchecked")
public List<Object[]> queryParams(String sql,Integer begin,Integer count,List<Object> params){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(sql);
for(int i=0;i<params.size();i++){
query.setParameter(i+1, params.get(i));
}
if(begin != null && count != null){
query.setFirstResult(begin);
query.setMaxResults(count);
}
List<Object[]> list = query.getResultList();
em.close();
return list;
}
public Integer delete(String sql,List<Object> params){
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Query query= em.createNativeQuery(sql);
for(int i=0;i<params.size();i++){
query.setParameter(i+1, params.get(i));
}
Integer r = query.executeUpdate();
em.getTransaction().commit();
em.close();
return r;
}
@SuppressWarnings("unchecked")
public List<Object[]> queryCall(String procString,List<Object> params){
EntityManager em = entityManagerFactory.createEntityManager();
Query query= em.createNativeQuery(procString);
for(int i=0;i<params.size();i++){
query.setParameter(i+1, params.get(i));
}
List<Object[]> list = query.getResultList();
em.close();
return list;
}
}
| 3,165 | 0.72393 | 0.717591 | 110 | 27.672728 | 21.784945 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.109091 | false | false | 3 |
38a5a2c97b9e71f4c9707f771348876e4eacac55 | 5,480,378,326,610 | 88e948112ec8f8e43bea36bd040ed5dc12cecf5c | /Ejericcio6ConcurrenciaSincronismo/src/edu/upc/eetac/dsa/exercises/java/lang/Principal.java | d0538cbddd91645ef0d8f8db207f45e2cdea5e3a | [] | no_license | marcelusDSA/Solucion-de-Ejercicios-Java | https://github.com/marcelusDSA/Solucion-de-Ejercicios-Java | d2cfa573e2b4e66d56a312c05dcf7eb9bbb3cc9c | edacbb9c4a2fa3d09ce63e306652b91e380ce38b | refs/heads/master | 2021-01-10T07:15:09.478000 | 2015-10-04T08:02:30 | 2015-10-04T08:02:30 | 43,538,913 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.upc.eetac.dsa.exercises.java.lang;
/**
* Created by marcelus on 29/09/15.
*/
public class Principal {
public static void main (String args[]){
String linea= "adarga antigua, rocín flaco y galgo corredor.\n";
ClaseBuffer claseBuffer = new ClaseBuffer();
Thread threadConsumidores = new Thread(new Consumidores(claseBuffer)," consumidor");
Thread threadProductores = new Thread(new Productores(claseBuffer, linea), "productores");
threadConsumidores.start();
threadProductores.start();
}
}
| UTF-8 | Java | 562 | java | Principal.java | Java | [
{
"context": ".eetac.dsa.exercises.java.lang;\n\n/**\n * Created by marcelus on 29/09/15.\n */\npublic class Principal {\n pu",
"end": 74,
"score": 0.929314374923706,
"start": 66,
"tag": "NAME",
"value": "marcelus"
}
] | null | [] | package edu.upc.eetac.dsa.exercises.java.lang;
/**
* Created by marcelus on 29/09/15.
*/
public class Principal {
public static void main (String args[]){
String linea= "adarga antigua, rocín flaco y galgo corredor.\n";
ClaseBuffer claseBuffer = new ClaseBuffer();
Thread threadConsumidores = new Thread(new Consumidores(claseBuffer)," consumidor");
Thread threadProductores = new Thread(new Productores(claseBuffer, linea), "productores");
threadConsumidores.start();
threadProductores.start();
}
}
| 562 | 0.686275 | 0.675579 | 15 | 36.400002 | 31.148676 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 3 |
3109db419256685727d8a76133e43f03316ef47e | 38,388,417,700,179 | f1589fba6262c9c29d8100d04053d3f43caf555f | /common-tara/src/main/java/com/sondertara/common/util/ErrorUtils.java | 8acb1a8f8c225fd37912d9c3565058ba970c7751 | [
"MIT"
] | permissive | sondertara/tara | https://github.com/sondertara/tara | 906c4b05ed3588213b0cf86fd0f25469a489b63f | 3ae3fcf9f27cb2c9e0dc8ece84850d07050cde15 | refs/heads/master | 2023-07-01T19:52:04.880000 | 2023-02-17T07:07:47 | 2023-02-17T07:07:47 | 220,164,988 | 9 | 3 | MIT | false | 2023-06-14T22:54:27 | 2019-11-07T06:15:48 | 2022-11-20T10:33:50 | 2023-06-14T22:54:26 | 3,215 | 8 | 3 | 2 | Java | false | false | package com.sondertara.common.util;
/**
* @author huangxiaohu
*/
public class ErrorUtils {
public static IllegalArgumentException illegalArgumentException(String message, Object... args) {
return new IllegalArgumentException(StringFormatter.format(message, args));
}
public static IllegalStateException illegalStateException(String message, Object... args) {
return new IllegalStateException(StringFormatter.format(message, args));
}
}
| UTF-8 | Java | 473 | java | ErrorUtils.java | Java | [
{
"context": "ackage com.sondertara.common.util;\n\n/**\n * @author huangxiaohu\n */\npublic class ErrorUtils {\n\n public static ",
"end": 63,
"score": 0.953116238117218,
"start": 52,
"tag": "USERNAME",
"value": "huangxiaohu"
}
] | null | [] | package com.sondertara.common.util;
/**
* @author huangxiaohu
*/
public class ErrorUtils {
public static IllegalArgumentException illegalArgumentException(String message, Object... args) {
return new IllegalArgumentException(StringFormatter.format(message, args));
}
public static IllegalStateException illegalStateException(String message, Object... args) {
return new IllegalStateException(StringFormatter.format(message, args));
}
}
| 473 | 0.750529 | 0.750529 | 15 | 30.533333 | 37.357491 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 3 |
76cb268fab533ab3aec57f227d07ae8bd13c7375 | 2,439,541,445,002 | c6688d29dc460952f23167ad7b8f45b3f69f5027 | /src/java/com/login/controlador/SitioController.java | 47b3a228b9db58801d92683a6bdb7a8e5cd10bea | [] | no_license | GnuWesc/panelAdmin | https://github.com/GnuWesc/panelAdmin | f2e9c53be45fd55508821505f42273a76f0383a9 | 8059ff706dfbdbc3d305481117c9b2087500773c | refs/heads/master | 2018-09-07T09:48:51.642000 | 2017-06-08T22:41:19 | 2017-06-08T22:41:19 | 93,552,993 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.login.controlador;
import com.login.ejb.UsuarioSitioUrbanoFacadeLocal;
import com.modelo.jpa.Categoria;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@ViewScoped
public class SitioController implements Serializable {
@EJB
private UsuarioSitioUrbanoFacadeLocal usuarioSitioUrbano;
private boolean mostrarSitioUrbano;
private boolean mostrarSitioRural;
private String radioOpcion;
private int idCategoria;
private String nombreSitio;
private String telefono;
private String sitioWeb;
private String direccion;
private String comentarios;
private double latitud;
private double longitud;
/**
* sitio buscado en editar
*/
private String sitioBuscar;
@PostConstruct
public void init() {
mostrarSitioUrbano = false;
mostrarSitioRural = false;
}
public String getSitioBuscar() {
return sitioBuscar;
}
public void setSitioBuscar(String sitioBuscar) {
this.sitioBuscar = sitioBuscar;
}
public String getRadioOpcion() {
return radioOpcion;
}
public void setRadioOpcion(String radioOpcion) {
this.radioOpcion = radioOpcion;
}
public boolean getMostrarSitioUrbano() {
return mostrarSitioUrbano;
}
public void setMostrarSitioUrbano(boolean mostrarSitioUrbano) {
this.mostrarSitioUrbano = mostrarSitioUrbano;
}
public boolean getMostrarSitioRural() {
return mostrarSitioRural;
}
public void setMostrarSitioRural(boolean mostrarSitioRural) {
this.mostrarSitioRural = mostrarSitioRural;
}
/**
* Lista de categorias
*/
public List<Categoria> listaCategorias() {
return usuarioSitioUrbano.listaCategorias();
}
/**
* Lista de sitios urbanos
*/
public List<String> listaSitiosUrb(String s) {
List<String> sitiosUrb = new ArrayList<>();
for (String data : usuarioSitioUrbano.listaSitiosUrb()) {
if (data.contains(s.toUpperCase())) {
sitiosUrb.add(data);
}
}
return sitiosUrb;
}
/**
* **
*/
public int getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(int idCategoria) {
this.idCategoria = idCategoria;
}
public String getNombreSitio() {
return nombreSitio;
}
public void setNombreSitio(String nombreSitio) {
this.nombreSitio = nombreSitio;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getSitioWeb() {
return sitioWeb;
}
public void setSitioWeb(String sitioWeb) {
this.sitioWeb = sitioWeb;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getComentarios() {
return comentarios;
}
public void setComentarios(String comentarios) {
this.comentarios = comentarios;
}
public double getLatitud() {
return latitud;
}
public void setLatitud(double latitud) {
this.latitud = latitud;
}
public double getLongitud() {
return longitud;
}
public void setLongitud(double longitud) {
this.longitud = longitud;
}
/**
* Metodos para crear, eliminar y actualizar sitios de interes
*/
public void almacenarSitio() {
if (usuarioSitioUrbano.almacenarSitio(idCategoria, nombreSitio, telefono, sitioWeb, direccion, comentarios, latitud, longitud)) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Sitio almacenado", null);
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Sitio no almacenado", null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}
| UTF-8 | Java | 4,629 | java | SitioController.java | Java | [] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.login.controlador;
import com.login.ejb.UsuarioSitioUrbanoFacadeLocal;
import com.modelo.jpa.Categoria;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@ViewScoped
public class SitioController implements Serializable {
@EJB
private UsuarioSitioUrbanoFacadeLocal usuarioSitioUrbano;
private boolean mostrarSitioUrbano;
private boolean mostrarSitioRural;
private String radioOpcion;
private int idCategoria;
private String nombreSitio;
private String telefono;
private String sitioWeb;
private String direccion;
private String comentarios;
private double latitud;
private double longitud;
/**
* sitio buscado en editar
*/
private String sitioBuscar;
@PostConstruct
public void init() {
mostrarSitioUrbano = false;
mostrarSitioRural = false;
}
public String getSitioBuscar() {
return sitioBuscar;
}
public void setSitioBuscar(String sitioBuscar) {
this.sitioBuscar = sitioBuscar;
}
public String getRadioOpcion() {
return radioOpcion;
}
public void setRadioOpcion(String radioOpcion) {
this.radioOpcion = radioOpcion;
}
public boolean getMostrarSitioUrbano() {
return mostrarSitioUrbano;
}
public void setMostrarSitioUrbano(boolean mostrarSitioUrbano) {
this.mostrarSitioUrbano = mostrarSitioUrbano;
}
public boolean getMostrarSitioRural() {
return mostrarSitioRural;
}
public void setMostrarSitioRural(boolean mostrarSitioRural) {
this.mostrarSitioRural = mostrarSitioRural;
}
/**
* Lista de categorias
*/
public List<Categoria> listaCategorias() {
return usuarioSitioUrbano.listaCategorias();
}
/**
* Lista de sitios urbanos
*/
public List<String> listaSitiosUrb(String s) {
List<String> sitiosUrb = new ArrayList<>();
for (String data : usuarioSitioUrbano.listaSitiosUrb()) {
if (data.contains(s.toUpperCase())) {
sitiosUrb.add(data);
}
}
return sitiosUrb;
}
/**
* **
*/
public int getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(int idCategoria) {
this.idCategoria = idCategoria;
}
public String getNombreSitio() {
return nombreSitio;
}
public void setNombreSitio(String nombreSitio) {
this.nombreSitio = nombreSitio;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getSitioWeb() {
return sitioWeb;
}
public void setSitioWeb(String sitioWeb) {
this.sitioWeb = sitioWeb;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getComentarios() {
return comentarios;
}
public void setComentarios(String comentarios) {
this.comentarios = comentarios;
}
public double getLatitud() {
return latitud;
}
public void setLatitud(double latitud) {
this.latitud = latitud;
}
public double getLongitud() {
return longitud;
}
public void setLongitud(double longitud) {
this.longitud = longitud;
}
/**
* Metodos para crear, eliminar y actualizar sitios de interes
*/
public void almacenarSitio() {
if (usuarioSitioUrbano.almacenarSitio(idCategoria, nombreSitio, telefono, sitioWeb, direccion, comentarios, latitud, longitud)) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Sitio almacenado", null);
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Sitio no almacenado", null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}
| 4,629 | 0.665154 | 0.665154 | 186 | 23.887096 | 23.056572 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424731 | false | false | 3 |
03faf77923ba7e63fe534798db8d7e9c07fe5897 | 6,133,213,317,516 | 72e174a9cf7da9cf13bfc5f15a12be60ca1b2301 | /src/main/java/io/localmotion/adminjob/commands/chatverification/ChatVerificationResult.java | 229ce4272dfb71667b682b9ba06af7f2d208fea3 | [
"Apache-2.0"
] | permissive | local-motion/smokefree-initiative-service | https://github.com/local-motion/smokefree-initiative-service | ec1ca522fa0a93233c3f38d804188162ec6bc7b4 | 11a01c68dd52b5ac456671a995a89ac2d8ca5d6b | refs/heads/master | 2023-08-17T14:53:08.336000 | 2019-10-22T11:20:58 | 2019-10-22T11:20:58 | 154,799,737 | 3 | 0 | Apache-2.0 | false | 2023-04-17T11:18:44 | 2018-10-26T08:08:30 | 2022-03-07T10:07:37 | 2023-04-17T11:18:42 | 513 | 1 | 0 | 39 | Java | false | false | package io.localmotion.adminjob.commands.chatverification;
import lombok.Value;
import java.util.List;
@Value
public class ChatVerificationResult {
private List<String> deviations;
}
| UTF-8 | Java | 190 | java | ChatVerificationResult.java | Java | [] | null | [] | package io.localmotion.adminjob.commands.chatverification;
import lombok.Value;
import java.util.List;
@Value
public class ChatVerificationResult {
private List<String> deviations;
}
| 190 | 0.8 | 0.8 | 10 | 18 | 19.26136 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
6919bdb94d50334e66a99d4abf09eaaabdf7c09a | 15,427,522,548,205 | 65ee2e90c169971eba5ca44ba132bc92ce6a7788 | /SuperSurvival/src/com/fooify/supersurvival/utils/UtilProj.java | 85e771a7815ebd01cd1e191e2fd1c316f0e8e2dd | [] | no_license | fooify/SuperSurvival | https://github.com/fooify/SuperSurvival | cf227295490c69b7ca21cc5105fd7e7648f72d70 | c6349b7474e67e4ba87aae561cc8aa9b2f9b9e07 | refs/heads/master | 2015-08-22T04:42:53.829000 | 2015-03-26T15:59:18 | 2015-03-26T15:59:18 | 32,935,401 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fooify.supersurvival.utils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Snowball;
import org.bukkit.util.BlockIterator;
import org.bukkit.util.Vector;
public class UtilProj {
// Gets the hit block of a projectile.
public static Block getHitBlock(Projectile p){
Block hit = null;
BlockIterator iterator = new BlockIterator(p.getLocation().getWorld(), p.getLocation().toVector(), p.getVelocity().normalize(), 0.0D, 4);
while(iterator.hasNext()){
hit = iterator.next();
if(hit.getType() != Material.AIR) break;
}
return hit;
}
// Launches a snowball from the player.
public static void throwSnowball(Player p, Vector v){
p.launchProjectile(Snowball.class).setVelocity(v);
}
// Fires an arrow from the player.
public static void shootArrow(Player p, Vector v){
p.launchProjectile(Arrow.class).setVelocity(v);
}
}
| UTF-8 | Java | 1,033 | java | UtilProj.java | Java | [] | null | [] | package com.fooify.supersurvival.utils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Snowball;
import org.bukkit.util.BlockIterator;
import org.bukkit.util.Vector;
public class UtilProj {
// Gets the hit block of a projectile.
public static Block getHitBlock(Projectile p){
Block hit = null;
BlockIterator iterator = new BlockIterator(p.getLocation().getWorld(), p.getLocation().toVector(), p.getVelocity().normalize(), 0.0D, 4);
while(iterator.hasNext()){
hit = iterator.next();
if(hit.getType() != Material.AIR) break;
}
return hit;
}
// Launches a snowball from the player.
public static void throwSnowball(Player p, Vector v){
p.launchProjectile(Snowball.class).setVelocity(v);
}
// Fires an arrow from the player.
public static void shootArrow(Player p, Vector v){
p.launchProjectile(Arrow.class).setVelocity(v);
}
}
| 1,033 | 0.719264 | 0.71636 | 34 | 28.382353 | 26.181509 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.558824 | false | false | 3 |
a5618e510c95375e8fcb58a0a183548c96cd678b | 3,178,275,830,261 | 775f717c65385e93ea947853bd26047b6e77b923 | /src/main/java/com/idealo/toyrobot/configuration/AppConfig.java | fe352ab63d31ee2790b8623432130f0b6946a377 | [] | no_license | fsoylemez/toyrobot | https://github.com/fsoylemez/toyrobot | 51d41c6720d638cbc07bca61f362bd306c45c30b | a7363d36f837e51cdcb9eb99284ac54184e1685a | refs/heads/master | 2020-03-31T15:15:57.515000 | 2018-10-17T07:23:57 | 2018-10-17T07:23:57 | 152,331,286 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.idealo.toyrobot.configuration;
import com.idealo.toyrobot.executor.PlaceCommandExecutor;
import com.idealo.toyrobot.model.Board;
import org.springframework.beans.factory.config.ServiceLocatorFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.ResourceBundleMessageSource;
@Configuration
@Profile(value = {"development"})
public class AppConfig {
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
source.setCacheSeconds(3600); // Refresh cache once per hour.
return source;
}
@Bean
ServiceLocatorFactoryBean commandExecutorFactory() {
ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
bean.setServiceLocatorInterface(CommandExecutorFactory.class);
return bean;
}
@Bean
@Scope(value = "singleton")
Board myBoard() {
return new Board();
}
@Bean
PlaceCommandExecutor placeCommandExecutor() {
return new PlaceCommandExecutor();
}
}
| UTF-8 | Java | 1,325 | java | AppConfig.java | Java | [] | null | [] | package com.idealo.toyrobot.configuration;
import com.idealo.toyrobot.executor.PlaceCommandExecutor;
import com.idealo.toyrobot.model.Board;
import org.springframework.beans.factory.config.ServiceLocatorFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.ResourceBundleMessageSource;
@Configuration
@Profile(value = {"development"})
public class AppConfig {
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
source.setCacheSeconds(3600); // Refresh cache once per hour.
return source;
}
@Bean
ServiceLocatorFactoryBean commandExecutorFactory() {
ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
bean.setServiceLocatorInterface(CommandExecutorFactory.class);
return bean;
}
@Bean
@Scope(value = "singleton")
Board myBoard() {
return new Board();
}
@Bean
PlaceCommandExecutor placeCommandExecutor() {
return new PlaceCommandExecutor();
}
}
| 1,325 | 0.752453 | 0.749434 | 43 | 29.813953 | 26.03241 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.418605 | false | false | 3 |
143b041e544d2f4e5e4ed6b8d8d5c6eb2d7a8581 | 25,907,242,748,627 | 88407296e0dff332d33d82b3e2f8a2aca19e2489 | /00_algorithm/algo_basic/src/rhtn_homework/PRO_L2_수식_최대화.java | 22e7c9940d3f908de757125eed48603d9ebe9e6e | [] | no_license | Kwon-Nam-Boo/algorithm | https://github.com/Kwon-Nam-Boo/algorithm | 1ee50de85084503bfea1d3f30ca2dac7094738f5 | 834ea72faf61b7b2f90ac1891bca2e8ef2e16f01 | refs/heads/master | 2023-05-08T14:07:10.009000 | 2021-06-05T07:25:32 | 2021-06-05T07:25:32 | 296,360,983 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class PRO_L2_수식_최대화 {
/*
* 상혁이 코드와 유사함 베끼려고 한건 아니고, 그냥 전체적으로 훑다가 머리에 박혀서 그만 ..
*
*/
private static StringBuilder sb = new StringBuilder();
private static char[] operator = {'*','+','-'};
private static char[] op;
private static boolean[] visited;
private static List<Long> numList;
private static List<Character> opList;
private static long ans;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String expression = "50*6-3*2";
System.out.println(solution(expression));
}
public static long solution(String expression) {
numList = new ArrayList<>();
opList = new ArrayList<>();
String num = "";
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
// 숫자면
if(c -'0' >= 0 && c -'0' <= 9 ) {
num+=c;
}else {
numList.add(Long.parseLong(num));
num = "";
opList.add(c);
}
}
numList.add(Long.parseLong(num));
visited = new boolean[3];
op = new char[3];
ans = 0;
dfs(0);
System.out.println(ans);
return ans;
}
private static void dfs(int i) {
if(i == 3) {
List<Long> numCopy = new ArrayList<>(numList);
List<Character> opCopy = new ArrayList<>(opList);
for (int j = 0; j < 3; j++) {
for (int k = 0; k < opCopy.size(); k++) {
// 현재 우선 순위에 대한 연산자이면
if(op[j] == opCopy.get(k)) {
// 해당 위치에 해당하는 숫자 두개를 계산한다
Long tmp = cal(numCopy.get(k), numCopy.get(k+1), op[j]);
// 계산후 제거
numCopy.remove(k);
numCopy.remove(k);
numCopy.add(k, tmp);
opCopy.remove(k);
k--;
}
}
}
ans = Math.max(ans, Math.abs(numCopy.get(0)));
return;
}
for (int j = 0; j < operator.length; j++) {
if(!visited[j]) {
visited[j] = true;
op[i] = operator[j];
dfs(i+1);
visited[j] = false;
}
}
}
private static long cal(long a, long b, char x) {
if(x =='+') return a+b;
else if(x =='-') return a-b;
else return a*b;
}
}
| UTF-8 | Java | 2,441 | java | PRO_L2_수식_최대화.java | Java | [] | null | [] | package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class PRO_L2_수식_최대화 {
/*
* 상혁이 코드와 유사함 베끼려고 한건 아니고, 그냥 전체적으로 훑다가 머리에 박혀서 그만 ..
*
*/
private static StringBuilder sb = new StringBuilder();
private static char[] operator = {'*','+','-'};
private static char[] op;
private static boolean[] visited;
private static List<Long> numList;
private static List<Character> opList;
private static long ans;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String expression = "50*6-3*2";
System.out.println(solution(expression));
}
public static long solution(String expression) {
numList = new ArrayList<>();
opList = new ArrayList<>();
String num = "";
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
// 숫자면
if(c -'0' >= 0 && c -'0' <= 9 ) {
num+=c;
}else {
numList.add(Long.parseLong(num));
num = "";
opList.add(c);
}
}
numList.add(Long.parseLong(num));
visited = new boolean[3];
op = new char[3];
ans = 0;
dfs(0);
System.out.println(ans);
return ans;
}
private static void dfs(int i) {
if(i == 3) {
List<Long> numCopy = new ArrayList<>(numList);
List<Character> opCopy = new ArrayList<>(opList);
for (int j = 0; j < 3; j++) {
for (int k = 0; k < opCopy.size(); k++) {
// 현재 우선 순위에 대한 연산자이면
if(op[j] == opCopy.get(k)) {
// 해당 위치에 해당하는 숫자 두개를 계산한다
Long tmp = cal(numCopy.get(k), numCopy.get(k+1), op[j]);
// 계산후 제거
numCopy.remove(k);
numCopy.remove(k);
numCopy.add(k, tmp);
opCopy.remove(k);
k--;
}
}
}
ans = Math.max(ans, Math.abs(numCopy.get(0)));
return;
}
for (int j = 0; j < operator.length; j++) {
if(!visited[j]) {
visited[j] = true;
op[i] = operator[j];
dfs(i+1);
visited[j] = false;
}
}
}
private static long cal(long a, long b, char x) {
if(x =='+') return a+b;
else if(x =='-') return a-b;
else return a*b;
}
}
| 2,441 | 0.597192 | 0.5871 | 97 | 22.494844 | 17.283043 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3 | false | false | 3 |
5435ec4b042fb9da39eb06811c37ae41cf9a4d9d | 33,423,435,517,663 | 1c5fd654b46d3fb018032dc11aa17552b64b191c | /spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/reactor/core/package-info.java | b9ee3655d0684f5902698ec4281b367e1b583f84 | [
"Apache-2.0"
] | permissive | yangfancoming/spring-boot-build | https://github.com/yangfancoming/spring-boot-build | 6ce9b97b105e401a4016ae4b75964ef93beeb9f1 | 3d4b8cbb8fea3e68617490609a68ded8f034bc67 | refs/heads/master | 2023-01-07T11:10:28.181000 | 2021-06-21T11:46:46 | 2021-06-21T11:46:46 | 193,871,877 | 0 | 0 | Apache-2.0 | false | 2022-12-27T14:52:46 | 2019-06-26T09:19:40 | 2021-06-21T11:46:55 | 2022-12-27T14:52:43 | 4,403 | 0 | 0 | 45 | Java | false | false |
/**
* Auto-configuration for Reactor Core.
*/
package org.springframework.boot.autoconfigure.reactor.core;
| UTF-8 | Java | 111 | java | package-info.java | Java | [] | null | [] |
/**
* Auto-configuration for Reactor Core.
*/
package org.springframework.boot.autoconfigure.reactor.core;
| 111 | 0.756757 | 0.756757 | 4 | 26.25 | 24.40671 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 3 |
4a910a3c25c7eb434ddeb3eff10cc599907deebc | 9,947,144,291,607 | de7e4fa19e4f4226e748dc958e057a198f445a0e | /netty/src/main/java/playground/netty/MyNettyUdpHandler.java | ee794e32aeb74c8641528520e097f7044a32844e | [] | no_license | bugjoe/dns-test | https://github.com/bugjoe/dns-test | 38cee76692fa0b9cc8d5966ada7b4bb6a41476f2 | 72275fd0c55b2da0f9f896caffb4ccd9fe66f871 | refs/heads/master | 2021-01-21T04:37:54.632000 | 2016-06-05T16:03:50 | 2016-06-05T16:03:50 | 35,031,893 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package playground.netty;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
/**
* @author josef.bauer@webants.com
*/
public class MyNettyUdpHandler extends MessageToMessageDecoder<DatagramPacket>
{
private static final AtomicLong COUNTER = new AtomicLong();
private final Random random = new Random(System.currentTimeMillis());
private final int sleep;
public MyNettyUdpHandler(int sleep)
{
this.sleep = sleep;
}
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket, List list) throws Exception
{
// new Thread(() -> {
// final long currentCount = COUNTER.incrementAndGet();
//
// try {
// Thread.sleep(random.nextInt(sleep));
// } catch (InterruptedException e) {
// System.out.println("ERROR while sleeping");
// }
//
// final ByteBuf buffer = Unpooled.buffer(64);
// buffer.writeBytes("Hey there".getBytes());
// channelHandlerContext.channel().writeAndFlush(new DatagramPacket(buffer, datagramPacket.sender()));
//
// if (currentCount % 1000 == 0) {
// System.out.println(Thread.currentThread().toString() + " / " + currentCount);
// }
// }).start();
final Channel channel = channelHandlerContext.channel();
channel.eventLoop().schedule(() -> {
final ByteBuf buffer = Unpooled.buffer(64);
buffer.writeBytes("Hey there".getBytes());
channel.writeAndFlush(new DatagramPacket(buffer, datagramPacket.sender()));
final long currentCount = COUNTER.incrementAndGet();
if (currentCount % 1000 == 0)
{
System.out.println(Thread.currentThread().toString() + " / " + currentCount);
}
}, random.nextInt(sleep), TimeUnit.MILLISECONDS);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
{
System.out.printf("ERROR: %s%n", cause.getMessage());
}
}
| UTF-8 | Java | 2,288 | java | MyNettyUdpHandler.java | Java | [
{
"context": "ler.codec.MessageToMessageDecoder;\n\n/**\n * @author josef.bauer@webants.com\n */\npublic class MyNettyUdpHandler extends Messag",
"end": 447,
"score": 0.9997773766517639,
"start": 424,
"tag": "EMAIL",
"value": "josef.bauer@webants.com"
}
] | null | [] | package playground.netty;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
/**
* @author <EMAIL>
*/
public class MyNettyUdpHandler extends MessageToMessageDecoder<DatagramPacket>
{
private static final AtomicLong COUNTER = new AtomicLong();
private final Random random = new Random(System.currentTimeMillis());
private final int sleep;
public MyNettyUdpHandler(int sleep)
{
this.sleep = sleep;
}
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket, List list) throws Exception
{
// new Thread(() -> {
// final long currentCount = COUNTER.incrementAndGet();
//
// try {
// Thread.sleep(random.nextInt(sleep));
// } catch (InterruptedException e) {
// System.out.println("ERROR while sleeping");
// }
//
// final ByteBuf buffer = Unpooled.buffer(64);
// buffer.writeBytes("Hey there".getBytes());
// channelHandlerContext.channel().writeAndFlush(new DatagramPacket(buffer, datagramPacket.sender()));
//
// if (currentCount % 1000 == 0) {
// System.out.println(Thread.currentThread().toString() + " / " + currentCount);
// }
// }).start();
final Channel channel = channelHandlerContext.channel();
channel.eventLoop().schedule(() -> {
final ByteBuf buffer = Unpooled.buffer(64);
buffer.writeBytes("Hey there".getBytes());
channel.writeAndFlush(new DatagramPacket(buffer, datagramPacket.sender()));
final long currentCount = COUNTER.incrementAndGet();
if (currentCount % 1000 == 0)
{
System.out.println(Thread.currentThread().toString() + " / " + currentCount);
}
}, random.nextInt(sleep), TimeUnit.MILLISECONDS);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
{
System.out.printf("ERROR: %s%n", cause.getMessage());
}
}
| 2,272 | 0.690122 | 0.684003 | 68 | 32.64706 | 30.157316 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.294118 | false | false | 3 |
e48407c234fe8aceba47dfc2987e19aa158909f9 | 15,925,738,766,265 | 33630bb72572f2e5cfaf5529faf178dedaa2aa0b | /dto/src/main/java/jp/chang/myclinic/dto/WqueueDTO.java | ac435c2f6a2eec0fcb2504fe522a280b369003b2 | [
"MIT"
] | permissive | hangilc/myclinic-spring | https://github.com/hangilc/myclinic-spring | 917472333853e3a2848cfb60ca5ade05098b700f | 69ac47ca1ae4383a423a8e097df3caea52ffcb41 | refs/heads/master | 2022-12-21T23:43:35.317000 | 2022-06-27T23:09:31 | 2022-06-27T23:09:31 | 135,880,487 | 0 | 0 | MIT | false | 2022-12-14T20:36:52 | 2018-06-03T06:43:15 | 2021-10-05T05:58:14 | 2022-12-14T20:36:48 | 10,124 | 0 | 0 | 43 | Java | false | false | package jp.chang.myclinic.dto;
import java.util.Objects;
public class WqueueDTO {
public int visitId;
public int waitState;
@Override
public String toString() {
return "WqueueDTO{" +
"visitId=" + visitId +
", waitState=" + waitState +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WqueueDTO wqueueDTO = (WqueueDTO) o;
return visitId == wqueueDTO.visitId &&
waitState == wqueueDTO.waitState;
}
@Override
public int hashCode() {
return Objects.hash(visitId, waitState);
}
} | UTF-8 | Java | 608 | java | WqueueDTO.java | Java | [] | null | [] | package jp.chang.myclinic.dto;
import java.util.Objects;
public class WqueueDTO {
public int visitId;
public int waitState;
@Override
public String toString() {
return "WqueueDTO{" +
"visitId=" + visitId +
", waitState=" + waitState +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WqueueDTO wqueueDTO = (WqueueDTO) o;
return visitId == wqueueDTO.visitId &&
waitState == wqueueDTO.waitState;
}
@Override
public int hashCode() {
return Objects.hash(visitId, waitState);
}
} | 608 | 0.662829 | 0.662829 | 31 | 18.645161 | 15.956692 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.709677 | false | false | 3 |
377e5e1883fd9187ef14d6e2cecd4ca4b72076f8 | 23,167,053,623,881 | fcde85c966e6deb647e4d679a474fbc364c4eabd | /src/main/java/tmw/me/com/betterfx/Console.java | dfb1c9d733ec8fb072c368a25e83c59b3b68ff23 | [] | no_license | Zev-G/SimpleCodingLanguage | https://github.com/Zev-G/SimpleCodingLanguage | ca0fdbcf01409569d651a721883b989d09ac8771 | 60d379b09206fc6c0106ee5965dc65a9f12e68bd | refs/heads/master | 2023-03-31T06:35:47.538000 | 2022-04-29T05:41:39 | 2022-04-29T05:41:39 | 294,510,981 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tmw.me.com.betterfx;
import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.SVGPath;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.util.Duration;
import tmw.me.com.Resources;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Console extends HBox {
private final VBox topBox = new VBox();
private final TextFlow consoleText = new TextFlow();
private final TextField consoleInput = new TextField();
private final SVGPath arrow = new SVGPath();
private final HBox inputBox = new HBox(arrow, consoleInput);
private final HBox wrapConsoleText = new HBox(consoleText);
private final ScrollPane consoleTextScrollPane = new ScrollPane(wrapConsoleText);
protected final ArrayList<ConsoleEvent> protectedOnUserInput = new ArrayList<>();
protected final ArrayList<ConsoleEvent> protectedOnPrint = new ArrayList<>();
protected final HashMap<PrintWriter, ConsoleEvent> printWriters = new HashMap<>();
private final ArrayList<ConsoleEvent> onUserInput = new ArrayList<>();
private final ArrayList<ConsoleEvent> onPrint = new ArrayList<>();
private Background mainBg = new Background(new BackgroundFill(Paint.valueOf("#333333"), CornerRadii.EMPTY, Insets.EMPTY));
private String textFill = "rgb(245, 245, 245)";
private Color defaultConsoleColor = Color.rgb(245, 245, 245);
private Font font = new Font("Terminal", 20);
private static final Font INPUT_FONT = new Font("Terminal", 24);
private final ArrayList<String> sent = new ArrayList<>();
private int currentText = 0;
private PrintStream printStream;
public Console() {
init();
}
public static Console generateForJava() {
Console console = new Console();
console.setOnUserInput();
System.setErr(console.generateNewPrintStream(Color.RED));
System.setOut(console.getStream());
try {
PipedInputStream inputStream = new PipedInputStream();
System.setIn(inputStream);
PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inputStream), true);
console.addPrintWriter(inWriter);
} catch (IOException e) {
e.printStackTrace();
}
return console;
}
private void init() {
topBox.getChildren().addAll(consoleTextScrollPane, inputBox);
consoleTextScrollPane.getStylesheets().add(Resources.getExternalForm(Resources.EDITOR_STYLES + "extras/scrollpane.css"));
VBox.setVgrow(consoleTextScrollPane, Priority.ALWAYS);
HBox.setHgrow(topBox, Priority.ALWAYS);
this.getChildren().addAll(topBox);
consoleTextScrollPane.setFitToWidth(true);
consoleTextScrollPane.setFitToHeight(true);
wrapConsoleText.setFillHeight(true);
wrapConsoleText.setPadding(new Insets(0, 5, 5, 5));
topBox.setFillWidth(true);
this.setFillHeight(true);
this.setBackground(mainBg);
inputBox.setFillHeight(true);
consoleText.heightProperty().addListener((observableValue, number, t1) -> Platform.runLater(() -> consoleTextScrollPane.setVvalue(1)));
arrow.setContent("M0 0l0 -34.3l19.6 17.15zM0 -9.8L0 -9.8M4.9 -14.7L4.9 -14.7L4.9 -19.6L0 -24.5L0 -9.8");
setArrowColor(Color.valueOf("#06c906"));
DropShadow shadow = new DropShadow(BlurType.THREE_PASS_BOX, Color.valueOf("#6b6b6b"), 10, 0.17, 0, 0);
setArrowEffect(shadow);
this.inputBox.setBorder(new Border(new BorderStroke(Color.valueOf("#292929"), BorderStrokeStyle.SOLID, new CornerRadii(0), new BorderWidths(5, 0, 0, 0), new Insets(-3))));
inputBox.setPadding(new Insets(0, 2, 2, 3));
consoleInput.setPadding(new Insets(0, 0, 13, 3));
inputBox.setBackground(mainBg);
consoleTextScrollPane.setBackground(mainBg);
consoleText.setBackground(mainBg);
consoleInput.setBackground(mainBg);
wrapConsoleText.setBackground(mainBg);
consoleInput.setFont(INPUT_FONT);
consoleInput.setStyle("-fx-text-fill: " + textFill);
setOnUserInput((input, source) -> {
DateTimeFormatter dft = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
addText(getDefaultText("[" + dft.format(now) + "]", Color.BLACK), true);
sendCurrentText(false);
if (input.equals("/help")) {
Text header = getDefaultText("---Help---");
header.setFill(Color.ROYALBLUE);
Text footer = getDefaultText("---Help---");
footer.setFill(Color.ROYALBLUE);
Text help = getDefaultText("/help > Displays This\nDeveloper note: This is the default onUserInput. Can be configured with setOnUserInput.");
help.setFill(Color.LIGHTSEAGREEN);
addText(header, true);
addText(help, true);
addText(footer, true);
} else {
Text secondText = getDefaultText("<- Invalid command, run /help for a list of valid commands.");
secondText.setFill(Color.RED);
addText(secondText, false);
}
});
consoleInput.setOnAction(actionEvent -> {
String consoleValue = consoleInput.getText();
for (ConsoleEvent event : protectedOnUserInput) {
event.onInput(consoleValue, this);
}
for (ConsoleEvent event : onUserInput) {
event.onInput(consoleValue, this);
}
});
consoleInput.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode() == KeyCode.DOWN) {
if (currentText - 1 > 0) {
currentText = currentText - 1;
consoleInput.setText(sent.get(sent.size() - currentText));
}
} else if (keyEvent.getCode() == KeyCode.UP) {
if (sent.size() > currentText) {
currentText++;
consoleInput.setText(sent.get(sent.size() - currentText));
}
}
});
inputBox.widthProperty().addListener((observableValue, number, t1) -> consoleInput.setPrefWidth(inputBox.getWidth() - 30));
}
public void setArrowColor(Color color) {
arrow.setFill(color);
}
public void setArrowEffect(Effect effect) {
arrow.setEffect(effect);
}
public ArrayList<ConsoleEvent> getOnUserInput() {
return onUserInput;
}
public void setOnUserInput() {
onUserInput.clear();
}
public void setOnUserInput(ConsoleEvent event) {
onUserInput.clear();
onUserInput.add(event);
}
public ArrayList<ConsoleEvent> getOnPrint() {
return onPrint;
}
public void setOnPrint(ConsoleEvent event) {
onPrint.clear();
onPrint.add(event);
}
public void addText(String string, boolean newLine) {
Text text = getDefaultText();
text.setText(string + " ");
addText(text, newLine);
for (ConsoleEvent event : protectedOnPrint) {
event.onInput(string, this);
}
for (ConsoleEvent event : onPrint) {
event.onInput(string, this);
}
}
public void addText(Text text, boolean newLine) {
if (newLine && !consoleText.getChildren().isEmpty()) text.setText("\n" + text.getText());
consoleText.getChildren().add(text);
}
public void addLines(Text... texts) {
addTexts(true, texts);
}
public void addTexts(Text... texts) {
addTexts(false, texts);
}
public void addTexts(boolean newLine, Text... texts) {
for (Text text : texts) {
addText(text, newLine);
}
}
public Text getDefaultText() {
return getDefaultText("", defaultConsoleColor);
}
public Text getDefaultText(String s) {
return getDefaultText(s, defaultConsoleColor);
}
public Text getDefaultText(Color color) {
return getDefaultText("", color);
}
public Text getDefaultText(String s, Color color) {
Text text = new Text(s);
text.setFont(font);
text.setFill(color);
return text;
}
public void sendCurrentText() {
sendCurrentText(defaultConsoleColor, true);
}
public void sendCurrentText(boolean newLine) {
sendCurrentText(defaultConsoleColor, newLine);
}
public void sendCurrentText(Color color) {
sendCurrentText(color, true);
}
public void sendCurrentText(Color color, boolean newLine) {
Text text = getDefaultText(consoleInput.getText());
text.setFill(color);
addText(text, newLine);
simulateMessageSend(consoleInput.getText());
consoleInput.setText("");
}
public void simulateMessageSend(String message) {
sent.add(message);
currentText = 0;
}
public TextField getConsoleInput() {
return consoleInput;
}
public TextFlow getConsoleText() {
return consoleText;
}
public void disableInput() {
this.topBox.getChildren().remove(inputBox);
}
public void enableInput() {
if (this.topBox.getChildren().contains(inputBox)) {
this.topBox.getChildren().add(inputBox);
}
}
public void toggleInput(boolean input) {
if (input) {
enableInput();
} else {
disableInput();
}
}
public void setMainBg(Paint paint) {
Background background = new Background(new BackgroundFill(paint, CornerRadii.EMPTY, Insets.EMPTY));
inputBox.setBackground(background);
consoleTextScrollPane.setBackground(background);
consoleTextScrollPane.setBorder(new Border(new BorderStroke(paint, BorderStrokeStyle.NONE, CornerRadii.EMPTY, BorderWidths.EMPTY)));
consoleText.setBackground(background);
consoleInput.setBackground(background);
wrapConsoleText.setBackground(background);
this.setBackground(background);
mainBg = background;
}
public void setTextColor(Color color) {
String style = toRgbString(color);
consoleInput.setStyle(style);
textFill = style;
for (Node text : consoleText.getChildren()) {
if (text.getClass() == Text.class) {
((Text) text).setFill(color);
}
}
defaultConsoleColor = color;
}
private String toRgbString(Color c) {
return "rgb("
+ to255Int(c.getRed())
+ "," + to255Int(c.getGreen())
+ "," + to255Int(c.getBlue())
+ ")";
}
private int to255Int(double d) {
return (int) (d * 255);
}
public PrintStream getStream() {
if (printStream == null) {
printStream = generateNewPrintStream(defaultConsoleColor);
}
return printStream;
}
public PrintStream generateNewPrintStream(Color streamColor) {
return new PrintStream(new OutputStream() {
private final StringBuilder builder = new StringBuilder();
@Override
public void write(int b) {
if (b == '\n') {
String s = builder.toString();
builder.setLength(0);
Text text = getDefaultText();
text.setText(s);
text.setFill(streamColor);
addText(text, true);
} else if (b != '\r') {
builder.append((char) b);
}
}
});
}
public void addPrintWriter(PrintWriter in) {
ConsoleEvent event = (inputtedString, eventConsole) -> in.println(inputtedString);
this.printWriters.put(in, event);
this.protectedOnUserInput.add(event);
}
public void removePrintWriter(PrintWriter writer) {
if (printWriters.containsKey(writer)) {
this.protectedOnUserInput.remove(this.printWriters.get(writer));
this.printWriters.remove(writer);
}
}
public Text[] genTexts(String... s) {
return genTexts(" ", '&', s);
}
public Text[] genTexts(char split, String... s) {
return genTexts(" ", split, s);
}
public Text[] genTexts(String inBetween, String... s) {
return genTexts(inBetween, '&', s);
}
public Text[] genTexts(String inBetween, char split, String... s) {
ArrayList<Text> texts = new ArrayList<>();
for (String string : s) {
texts.addAll(Arrays.asList(genText(string + inBetween, split)));
}
return texts.toArray(new Text[0]);
}
public Text[] genText(String s) {
return genText(s, '&');
}
public Text[] genText(String s, char split) {
if (!s.startsWith(String.valueOf(split))) s = split + "r" + s;
String[] colors = s.split(String.valueOf(split));
ArrayList<Text> texts = new ArrayList<>();
Text lastText = getDefaultText("");
for (String string : colors) {
if (!string.equals("")) {
Color color = TextModifier.colorFromChar(string.charAt(0));
Font font = TextModifier.fontFromChar(string.charAt(0), lastText.getFont());
boolean strikeThrough = TextModifier.strikethroughFromChar(string.charAt(0));
boolean underline = TextModifier.underlineFromChar(string.charAt(0));
Text newText = duplicateText(lastText);
newText.setText(string.substring(1));
if (color != null && !color.equals(lastText.getFill())) {
newText.setFill(color);
} else if (font != null && !font.equals(lastText.getFont())) {
newText.setFont(font);
} else if (underline != lastText.isUnderline()) {
newText.setUnderline(underline);
} else if (strikeThrough != lastText.isStrikethrough()) {
newText.setStrikethrough(strikeThrough);
}
lastText = newText;
texts.add(newText);
}
}
return texts.toArray(new Text[0]);
}
public Text genButton(String text) {
return genButton(text, defaultConsoleColor);
}
public Text genButton(String text, Color textFill) {
Text started = getDefaultText(text);
started.setFill(textFill);
started.setFont(Font.font(started.getFont().getFamily(), FontWeight.BOLD, started.getFont().getSize()));
started.setEffect(new Glow(0.4));
started.setCursor(Cursor.HAND);
started.setOpacity(0.8);
started.setOnMouseEntered(mouseEvent -> {
FadeTransition fadeTransition = new FadeTransition(new Duration(175), started);
fadeTransition.setToValue(1);
fadeTransition.play();
});
started.setOnMouseExited(mouseEvent -> {
FadeTransition fadeTransition = new FadeTransition(new Duration(175), started);
fadeTransition.setToValue(0.8);
fadeTransition.play();
});
return started;
}
public static Text duplicateText(Text text) {
Text newText = new Text(text.getText());
newText.setFont(text.getFont());
newText.setTextAlignment(text.getTextAlignment());
newText.setTabSize(text.getTabSize());
newText.setVisible(text.isVisible());
newText.setFill(text.getFill());
return newText;
}
public void setFont(Font font) {
this.font = font;
}
public Font getFont() {
return font;
}
}
| UTF-8 | Java | 16,441 | java | Console.java | Java | [] | null | [] | package tmw.me.com.betterfx;
import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.SVGPath;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.util.Duration;
import tmw.me.com.Resources;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Console extends HBox {
private final VBox topBox = new VBox();
private final TextFlow consoleText = new TextFlow();
private final TextField consoleInput = new TextField();
private final SVGPath arrow = new SVGPath();
private final HBox inputBox = new HBox(arrow, consoleInput);
private final HBox wrapConsoleText = new HBox(consoleText);
private final ScrollPane consoleTextScrollPane = new ScrollPane(wrapConsoleText);
protected final ArrayList<ConsoleEvent> protectedOnUserInput = new ArrayList<>();
protected final ArrayList<ConsoleEvent> protectedOnPrint = new ArrayList<>();
protected final HashMap<PrintWriter, ConsoleEvent> printWriters = new HashMap<>();
private final ArrayList<ConsoleEvent> onUserInput = new ArrayList<>();
private final ArrayList<ConsoleEvent> onPrint = new ArrayList<>();
private Background mainBg = new Background(new BackgroundFill(Paint.valueOf("#333333"), CornerRadii.EMPTY, Insets.EMPTY));
private String textFill = "rgb(245, 245, 245)";
private Color defaultConsoleColor = Color.rgb(245, 245, 245);
private Font font = new Font("Terminal", 20);
private static final Font INPUT_FONT = new Font("Terminal", 24);
private final ArrayList<String> sent = new ArrayList<>();
private int currentText = 0;
private PrintStream printStream;
public Console() {
init();
}
public static Console generateForJava() {
Console console = new Console();
console.setOnUserInput();
System.setErr(console.generateNewPrintStream(Color.RED));
System.setOut(console.getStream());
try {
PipedInputStream inputStream = new PipedInputStream();
System.setIn(inputStream);
PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inputStream), true);
console.addPrintWriter(inWriter);
} catch (IOException e) {
e.printStackTrace();
}
return console;
}
private void init() {
topBox.getChildren().addAll(consoleTextScrollPane, inputBox);
consoleTextScrollPane.getStylesheets().add(Resources.getExternalForm(Resources.EDITOR_STYLES + "extras/scrollpane.css"));
VBox.setVgrow(consoleTextScrollPane, Priority.ALWAYS);
HBox.setHgrow(topBox, Priority.ALWAYS);
this.getChildren().addAll(topBox);
consoleTextScrollPane.setFitToWidth(true);
consoleTextScrollPane.setFitToHeight(true);
wrapConsoleText.setFillHeight(true);
wrapConsoleText.setPadding(new Insets(0, 5, 5, 5));
topBox.setFillWidth(true);
this.setFillHeight(true);
this.setBackground(mainBg);
inputBox.setFillHeight(true);
consoleText.heightProperty().addListener((observableValue, number, t1) -> Platform.runLater(() -> consoleTextScrollPane.setVvalue(1)));
arrow.setContent("M0 0l0 -34.3l19.6 17.15zM0 -9.8L0 -9.8M4.9 -14.7L4.9 -14.7L4.9 -19.6L0 -24.5L0 -9.8");
setArrowColor(Color.valueOf("#06c906"));
DropShadow shadow = new DropShadow(BlurType.THREE_PASS_BOX, Color.valueOf("#6b6b6b"), 10, 0.17, 0, 0);
setArrowEffect(shadow);
this.inputBox.setBorder(new Border(new BorderStroke(Color.valueOf("#292929"), BorderStrokeStyle.SOLID, new CornerRadii(0), new BorderWidths(5, 0, 0, 0), new Insets(-3))));
inputBox.setPadding(new Insets(0, 2, 2, 3));
consoleInput.setPadding(new Insets(0, 0, 13, 3));
inputBox.setBackground(mainBg);
consoleTextScrollPane.setBackground(mainBg);
consoleText.setBackground(mainBg);
consoleInput.setBackground(mainBg);
wrapConsoleText.setBackground(mainBg);
consoleInput.setFont(INPUT_FONT);
consoleInput.setStyle("-fx-text-fill: " + textFill);
setOnUserInput((input, source) -> {
DateTimeFormatter dft = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
addText(getDefaultText("[" + dft.format(now) + "]", Color.BLACK), true);
sendCurrentText(false);
if (input.equals("/help")) {
Text header = getDefaultText("---Help---");
header.setFill(Color.ROYALBLUE);
Text footer = getDefaultText("---Help---");
footer.setFill(Color.ROYALBLUE);
Text help = getDefaultText("/help > Displays This\nDeveloper note: This is the default onUserInput. Can be configured with setOnUserInput.");
help.setFill(Color.LIGHTSEAGREEN);
addText(header, true);
addText(help, true);
addText(footer, true);
} else {
Text secondText = getDefaultText("<- Invalid command, run /help for a list of valid commands.");
secondText.setFill(Color.RED);
addText(secondText, false);
}
});
consoleInput.setOnAction(actionEvent -> {
String consoleValue = consoleInput.getText();
for (ConsoleEvent event : protectedOnUserInput) {
event.onInput(consoleValue, this);
}
for (ConsoleEvent event : onUserInput) {
event.onInput(consoleValue, this);
}
});
consoleInput.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode() == KeyCode.DOWN) {
if (currentText - 1 > 0) {
currentText = currentText - 1;
consoleInput.setText(sent.get(sent.size() - currentText));
}
} else if (keyEvent.getCode() == KeyCode.UP) {
if (sent.size() > currentText) {
currentText++;
consoleInput.setText(sent.get(sent.size() - currentText));
}
}
});
inputBox.widthProperty().addListener((observableValue, number, t1) -> consoleInput.setPrefWidth(inputBox.getWidth() - 30));
}
public void setArrowColor(Color color) {
arrow.setFill(color);
}
public void setArrowEffect(Effect effect) {
arrow.setEffect(effect);
}
public ArrayList<ConsoleEvent> getOnUserInput() {
return onUserInput;
}
public void setOnUserInput() {
onUserInput.clear();
}
public void setOnUserInput(ConsoleEvent event) {
onUserInput.clear();
onUserInput.add(event);
}
public ArrayList<ConsoleEvent> getOnPrint() {
return onPrint;
}
public void setOnPrint(ConsoleEvent event) {
onPrint.clear();
onPrint.add(event);
}
public void addText(String string, boolean newLine) {
Text text = getDefaultText();
text.setText(string + " ");
addText(text, newLine);
for (ConsoleEvent event : protectedOnPrint) {
event.onInput(string, this);
}
for (ConsoleEvent event : onPrint) {
event.onInput(string, this);
}
}
public void addText(Text text, boolean newLine) {
if (newLine && !consoleText.getChildren().isEmpty()) text.setText("\n" + text.getText());
consoleText.getChildren().add(text);
}
public void addLines(Text... texts) {
addTexts(true, texts);
}
public void addTexts(Text... texts) {
addTexts(false, texts);
}
public void addTexts(boolean newLine, Text... texts) {
for (Text text : texts) {
addText(text, newLine);
}
}
public Text getDefaultText() {
return getDefaultText("", defaultConsoleColor);
}
public Text getDefaultText(String s) {
return getDefaultText(s, defaultConsoleColor);
}
public Text getDefaultText(Color color) {
return getDefaultText("", color);
}
public Text getDefaultText(String s, Color color) {
Text text = new Text(s);
text.setFont(font);
text.setFill(color);
return text;
}
public void sendCurrentText() {
sendCurrentText(defaultConsoleColor, true);
}
public void sendCurrentText(boolean newLine) {
sendCurrentText(defaultConsoleColor, newLine);
}
public void sendCurrentText(Color color) {
sendCurrentText(color, true);
}
public void sendCurrentText(Color color, boolean newLine) {
Text text = getDefaultText(consoleInput.getText());
text.setFill(color);
addText(text, newLine);
simulateMessageSend(consoleInput.getText());
consoleInput.setText("");
}
public void simulateMessageSend(String message) {
sent.add(message);
currentText = 0;
}
public TextField getConsoleInput() {
return consoleInput;
}
public TextFlow getConsoleText() {
return consoleText;
}
public void disableInput() {
this.topBox.getChildren().remove(inputBox);
}
public void enableInput() {
if (this.topBox.getChildren().contains(inputBox)) {
this.topBox.getChildren().add(inputBox);
}
}
public void toggleInput(boolean input) {
if (input) {
enableInput();
} else {
disableInput();
}
}
public void setMainBg(Paint paint) {
Background background = new Background(new BackgroundFill(paint, CornerRadii.EMPTY, Insets.EMPTY));
inputBox.setBackground(background);
consoleTextScrollPane.setBackground(background);
consoleTextScrollPane.setBorder(new Border(new BorderStroke(paint, BorderStrokeStyle.NONE, CornerRadii.EMPTY, BorderWidths.EMPTY)));
consoleText.setBackground(background);
consoleInput.setBackground(background);
wrapConsoleText.setBackground(background);
this.setBackground(background);
mainBg = background;
}
public void setTextColor(Color color) {
String style = toRgbString(color);
consoleInput.setStyle(style);
textFill = style;
for (Node text : consoleText.getChildren()) {
if (text.getClass() == Text.class) {
((Text) text).setFill(color);
}
}
defaultConsoleColor = color;
}
private String toRgbString(Color c) {
return "rgb("
+ to255Int(c.getRed())
+ "," + to255Int(c.getGreen())
+ "," + to255Int(c.getBlue())
+ ")";
}
private int to255Int(double d) {
return (int) (d * 255);
}
public PrintStream getStream() {
if (printStream == null) {
printStream = generateNewPrintStream(defaultConsoleColor);
}
return printStream;
}
public PrintStream generateNewPrintStream(Color streamColor) {
return new PrintStream(new OutputStream() {
private final StringBuilder builder = new StringBuilder();
@Override
public void write(int b) {
if (b == '\n') {
String s = builder.toString();
builder.setLength(0);
Text text = getDefaultText();
text.setText(s);
text.setFill(streamColor);
addText(text, true);
} else if (b != '\r') {
builder.append((char) b);
}
}
});
}
public void addPrintWriter(PrintWriter in) {
ConsoleEvent event = (inputtedString, eventConsole) -> in.println(inputtedString);
this.printWriters.put(in, event);
this.protectedOnUserInput.add(event);
}
public void removePrintWriter(PrintWriter writer) {
if (printWriters.containsKey(writer)) {
this.protectedOnUserInput.remove(this.printWriters.get(writer));
this.printWriters.remove(writer);
}
}
public Text[] genTexts(String... s) {
return genTexts(" ", '&', s);
}
public Text[] genTexts(char split, String... s) {
return genTexts(" ", split, s);
}
public Text[] genTexts(String inBetween, String... s) {
return genTexts(inBetween, '&', s);
}
public Text[] genTexts(String inBetween, char split, String... s) {
ArrayList<Text> texts = new ArrayList<>();
for (String string : s) {
texts.addAll(Arrays.asList(genText(string + inBetween, split)));
}
return texts.toArray(new Text[0]);
}
public Text[] genText(String s) {
return genText(s, '&');
}
public Text[] genText(String s, char split) {
if (!s.startsWith(String.valueOf(split))) s = split + "r" + s;
String[] colors = s.split(String.valueOf(split));
ArrayList<Text> texts = new ArrayList<>();
Text lastText = getDefaultText("");
for (String string : colors) {
if (!string.equals("")) {
Color color = TextModifier.colorFromChar(string.charAt(0));
Font font = TextModifier.fontFromChar(string.charAt(0), lastText.getFont());
boolean strikeThrough = TextModifier.strikethroughFromChar(string.charAt(0));
boolean underline = TextModifier.underlineFromChar(string.charAt(0));
Text newText = duplicateText(lastText);
newText.setText(string.substring(1));
if (color != null && !color.equals(lastText.getFill())) {
newText.setFill(color);
} else if (font != null && !font.equals(lastText.getFont())) {
newText.setFont(font);
} else if (underline != lastText.isUnderline()) {
newText.setUnderline(underline);
} else if (strikeThrough != lastText.isStrikethrough()) {
newText.setStrikethrough(strikeThrough);
}
lastText = newText;
texts.add(newText);
}
}
return texts.toArray(new Text[0]);
}
public Text genButton(String text) {
return genButton(text, defaultConsoleColor);
}
public Text genButton(String text, Color textFill) {
Text started = getDefaultText(text);
started.setFill(textFill);
started.setFont(Font.font(started.getFont().getFamily(), FontWeight.BOLD, started.getFont().getSize()));
started.setEffect(new Glow(0.4));
started.setCursor(Cursor.HAND);
started.setOpacity(0.8);
started.setOnMouseEntered(mouseEvent -> {
FadeTransition fadeTransition = new FadeTransition(new Duration(175), started);
fadeTransition.setToValue(1);
fadeTransition.play();
});
started.setOnMouseExited(mouseEvent -> {
FadeTransition fadeTransition = new FadeTransition(new Duration(175), started);
fadeTransition.setToValue(0.8);
fadeTransition.play();
});
return started;
}
public static Text duplicateText(Text text) {
Text newText = new Text(text.getText());
newText.setFont(text.getFont());
newText.setTextAlignment(text.getTextAlignment());
newText.setTabSize(text.getTabSize());
newText.setVisible(text.isVisible());
newText.setFill(text.getFill());
return newText;
}
public void setFont(Font font) {
this.font = font;
}
public Font getFont() {
return font;
}
}
| 16,441 | 0.614014 | 0.604586 | 469 | 34.055439 | 27.931631 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 3 |
bbd4c4069abb1b08bbbe5a46a5f6660e47bf0fb9 | 26,749,056,351,387 | 7f07b3a1a762b76e83b6b73731e01c382e2654f7 | /app/src/main/java/com/omarmohamed/myvideogallery/ui/player/AbsVideoPlayer.java | 63f29e93bcad8769c9253b8cb92ca417d7e2270f | [] | no_license | OmarMohamedDev/MyVideoGallery | https://github.com/OmarMohamedDev/MyVideoGallery | 8f94d11fe1154dd1295f56a97100ed4e0aef1707 | 3fbd7b7ca9e7f9e145204663dc76c54b35cf9e6b | refs/heads/master | 2020-09-17T12:37:03.917000 | 2016-11-05T19:24:53 | 2016-11-05T19:24:53 | 67,189,409 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.omarmohamed.myvideogallery.ui.player;
/**
* This class handles underlying business to set up the exoplayer
*/
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.google.android.exoplayer.AspectRatioFrameLayout;
import com.google.android.exoplayer.ExoPlayer;
import com.google.android.exoplayer.MediaCodecVideoTrackRenderer;
import com.google.android.exoplayer.TrackRenderer;
import com.google.android.exoplayer.audio.AudioCapabilities;
import com.google.android.exoplayer.audio.AudioCapabilitiesReceiver;
import com.google.android.exoplayer.util.PlayerControl;
public abstract class AbsVideoPlayer extends AbsVideoPlayerImpl implements AudioCapabilitiesReceiver.Listener,
HlsRendererBuilder.Listener {
public static final int BUFFER_SEGMENT_SIZE = 64 * 1024;
public static final int BUFFER_SEGMENT_COUNT = 150;
public static final int ALLOWED_JOIN_TIME_MS = 5000;
public static final int MAX_DROPPED_FRAMES = 50;
// track renderer positions. could also include captions or metadata tracks
public static final int RENDERER_COUNT = 2;
public static final int VIDEO_RENDERER = 0;
public static final int AUDIO_RENDERER = 1;
private static final String TAG = AbsVideoPlayer.class.getSimpleName();
// custom vars for the exoplayer
// can be adjusted for different playback needs
private static final int MIN_BUFFER_MS = 1500;
private static final int MIN_REBUFFER_MS = 4000;
protected ExoPlayer mExoPlayer;
protected PlayerControl mPlayerController;
protected Handler mHandler;
private String mUri;
private SurfaceHolder mSurfaceHolder;
private HlsRendererBuilder mBuilder;
private AudioCapabilitiesReceiver mAudioCapabilitiesReceiver;
private MediaCodecVideoTrackRenderer mVideoRenderer;
private long mPreviousPosition;
public AbsVideoPlayer(Context context) {
this(context, null);
}
public AbsVideoPlayer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AbsVideoPlayer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
AspectRatioFrameLayout frame = new AspectRatioFrameLayout(this.getContext());
this.addView(frame);
SurfaceView surfaceView = new SurfaceView(this.getContext());
mSurfaceHolder = surfaceView.getHolder();
frame.addView(surfaceView);
mSurfaceHolder.addCallback(this);
mAudioCapabilitiesReceiver = new AudioCapabilitiesReceiver(getContext(), this);
mAudioCapabilitiesReceiver.register();
mHandler = new Handler();
mBuilder = new HlsRendererBuilder();
}
public void destroyPlayer() {
mAudioCapabilitiesReceiver.unregister();
releasePlayer();
}
public void setUri(String uri) {
mUri = uri;
}
public void releasePlayer() {
if (mExoPlayer != null) {
mPreviousPosition = mExoPlayer.getCurrentPosition();
mExoPlayer.release();
mExoPlayer = null;
mPlayerController = null;
mBuilder.cancel();
}
}
public void preparePlayer() {
if (mExoPlayer == null) {
mExoPlayer = ExoPlayer.Factory.newInstance(RENDERER_COUNT, MIN_BUFFER_MS, MIN_REBUFFER_MS);
mPlayerController = new PlayerControl(mExoPlayer);
mExoPlayer.setPlayWhenReady(true);
mExoPlayer.addListener(this);
mBuilder.build(getContext(), this, mUri);
}
}
public Handler getMainHandler() {
return mHandler;
}
@Override
public void onSuccess(TrackRenderer[] renderers) {
mVideoRenderer = (MediaCodecVideoTrackRenderer) renderers[VIDEO_RENDERER];
mExoPlayer.sendMessage(mVideoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, mSurfaceHolder.getSurface());
mExoPlayer.seekTo(mPreviousPosition);
mExoPlayer.prepare(renderers);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mVideoRenderer != null && mExoPlayer != null) {
mExoPlayer.sendMessage(mVideoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, mSurfaceHolder.getSurface());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mVideoRenderer != null && mExoPlayer != null) {
mExoPlayer.blockingSendMessage(mVideoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, mSurfaceHolder.getSurface());
}
}
}
| UTF-8 | Java | 4,729 | java | AbsVideoPlayer.java | Java | [
{
"context": "package com.omarmohamed.myvideogallery.ui.player;\n\n/**\n * This class hand",
"end": 23,
"score": 0.6998167037963867,
"start": 14,
"tag": "USERNAME",
"value": "armohamed"
}
] | null | [] | package com.omarmohamed.myvideogallery.ui.player;
/**
* This class handles underlying business to set up the exoplayer
*/
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.google.android.exoplayer.AspectRatioFrameLayout;
import com.google.android.exoplayer.ExoPlayer;
import com.google.android.exoplayer.MediaCodecVideoTrackRenderer;
import com.google.android.exoplayer.TrackRenderer;
import com.google.android.exoplayer.audio.AudioCapabilities;
import com.google.android.exoplayer.audio.AudioCapabilitiesReceiver;
import com.google.android.exoplayer.util.PlayerControl;
public abstract class AbsVideoPlayer extends AbsVideoPlayerImpl implements AudioCapabilitiesReceiver.Listener,
HlsRendererBuilder.Listener {
public static final int BUFFER_SEGMENT_SIZE = 64 * 1024;
public static final int BUFFER_SEGMENT_COUNT = 150;
public static final int ALLOWED_JOIN_TIME_MS = 5000;
public static final int MAX_DROPPED_FRAMES = 50;
// track renderer positions. could also include captions or metadata tracks
public static final int RENDERER_COUNT = 2;
public static final int VIDEO_RENDERER = 0;
public static final int AUDIO_RENDERER = 1;
private static final String TAG = AbsVideoPlayer.class.getSimpleName();
// custom vars for the exoplayer
// can be adjusted for different playback needs
private static final int MIN_BUFFER_MS = 1500;
private static final int MIN_REBUFFER_MS = 4000;
protected ExoPlayer mExoPlayer;
protected PlayerControl mPlayerController;
protected Handler mHandler;
private String mUri;
private SurfaceHolder mSurfaceHolder;
private HlsRendererBuilder mBuilder;
private AudioCapabilitiesReceiver mAudioCapabilitiesReceiver;
private MediaCodecVideoTrackRenderer mVideoRenderer;
private long mPreviousPosition;
public AbsVideoPlayer(Context context) {
this(context, null);
}
public AbsVideoPlayer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AbsVideoPlayer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
AspectRatioFrameLayout frame = new AspectRatioFrameLayout(this.getContext());
this.addView(frame);
SurfaceView surfaceView = new SurfaceView(this.getContext());
mSurfaceHolder = surfaceView.getHolder();
frame.addView(surfaceView);
mSurfaceHolder.addCallback(this);
mAudioCapabilitiesReceiver = new AudioCapabilitiesReceiver(getContext(), this);
mAudioCapabilitiesReceiver.register();
mHandler = new Handler();
mBuilder = new HlsRendererBuilder();
}
public void destroyPlayer() {
mAudioCapabilitiesReceiver.unregister();
releasePlayer();
}
public void setUri(String uri) {
mUri = uri;
}
public void releasePlayer() {
if (mExoPlayer != null) {
mPreviousPosition = mExoPlayer.getCurrentPosition();
mExoPlayer.release();
mExoPlayer = null;
mPlayerController = null;
mBuilder.cancel();
}
}
public void preparePlayer() {
if (mExoPlayer == null) {
mExoPlayer = ExoPlayer.Factory.newInstance(RENDERER_COUNT, MIN_BUFFER_MS, MIN_REBUFFER_MS);
mPlayerController = new PlayerControl(mExoPlayer);
mExoPlayer.setPlayWhenReady(true);
mExoPlayer.addListener(this);
mBuilder.build(getContext(), this, mUri);
}
}
public Handler getMainHandler() {
return mHandler;
}
@Override
public void onSuccess(TrackRenderer[] renderers) {
mVideoRenderer = (MediaCodecVideoTrackRenderer) renderers[VIDEO_RENDERER];
mExoPlayer.sendMessage(mVideoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, mSurfaceHolder.getSurface());
mExoPlayer.seekTo(mPreviousPosition);
mExoPlayer.prepare(renderers);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mVideoRenderer != null && mExoPlayer != null) {
mExoPlayer.sendMessage(mVideoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, mSurfaceHolder.getSurface());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mVideoRenderer != null && mExoPlayer != null) {
mExoPlayer.blockingSendMessage(mVideoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, mSurfaceHolder.getSurface());
}
}
}
| 4,729 | 0.709875 | 0.704166 | 131 | 35.099236 | 28.981661 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.664122 | false | false | 3 |
ebf4713f2c5bc3671227082741e477996f31bad2 | 26,276,609,944,843 | 7d9ca837241cac565a22129fa7e81af1c20077ac | /Job/src/controller/SearchController.java | 2d1ca50c43362c5a09268a388e54bf52052cf43b | [] | no_license | Xian83/job | https://github.com/Xian83/job | 34e4437bb2a5d3669e73820f652f0c502c2f23b8 | e2a5fad114a280f5c94f7c0797f68ca6bc4bd208 | refs/heads/master | 2020-05-24T05:05:17.226000 | 2017-04-03T05:46:35 | 2017-04-03T05:46:35 | 84,823,697 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import model.SearchDao;
@Controller
public class SearchController {
@Autowired
SearchDao sdao;
// Search Page main
@RequestMapping("/search")
public ModelAndView searchHandler(HttpServletRequest req,
@RequestParam(name = "CName", defaultValue = "") String CName) throws IOException {
int cnt = CName.equals("") ? 40231 : sdao.getTotal(req);
int size = cnt % 20 == 0 ? cnt / 20 : cnt / 20 + 1;
String pStr = req.getParameter("page") == null ? "1" : req.getParameter("page");
// int start = (Integer.parseInt(pStr) - 1) * 20 + 1;
// int end = Integer.parseInt(pStr) * 20;
// // 페이지 분할
// List<HashMap> list = sdao.pasing(start, end, CName);
// 커리어 캐치에서 기업명 List 가져오기
List list = sdao.getData(req);
System.out.println(list.size() + "개 기업 데이터 불러오는 중 ...");
// 기업명 기준으로 DB에서 데이터 가져오기
list = sdao.getDataByCName(list);
ModelAndView mav = new ModelAndView();
mav.setViewName("search");
mav.addObject("main", "search/list_form");
mav.addObject("cnt", cnt);
mav.addObject("size", size);
mav.addObject("page", pStr);
mav.addObject("list", list);
mav.addObject("CName", CName);
mav.addObject("key", sdao.getParam(req)); // paging 처리용
return mav;
}
// Detail Search Result Ajax
@RequestMapping("/search/detail")
public ModelAndView detailHandler(HttpServletRequest req) {
int cnt = sdao.getTotal(req); // 커리어 캐치에서 total data 개수 가져옴
int size = cnt % 20 == 0 ? cnt / 20 : cnt / 20 + 1; // 총 페이지 수
String pStr = req.getParameter("page") == null ? "1" : req.getParameter("page");
// 커리어 캐치에서 기업명 List 가져오기
List list = sdao.getData(req);
System.out.println(list.size() + "개 기업 데이터 불러오는 중 ...");
// 기업명 기준으로 DB에서 데이터 가져오기
list = sdao.getDataByCName(list);
// 상세 검색 목록 뷰
ModelAndView mav = new ModelAndView();
mav.setViewName("/search/searchAjax");
mav.addObject("list", list);
mav.addObject("page", pStr);
mav.addObject("cnt", cnt);
mav.addObject("size", size);
mav.addObject("key", sdao.getParam(req)); // paging 처리용
return mav;
}
} | UTF-8 | Java | 2,826 | java | SearchController.java | Java | [] | null | [] | package controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import model.SearchDao;
@Controller
public class SearchController {
@Autowired
SearchDao sdao;
// Search Page main
@RequestMapping("/search")
public ModelAndView searchHandler(HttpServletRequest req,
@RequestParam(name = "CName", defaultValue = "") String CName) throws IOException {
int cnt = CName.equals("") ? 40231 : sdao.getTotal(req);
int size = cnt % 20 == 0 ? cnt / 20 : cnt / 20 + 1;
String pStr = req.getParameter("page") == null ? "1" : req.getParameter("page");
// int start = (Integer.parseInt(pStr) - 1) * 20 + 1;
// int end = Integer.parseInt(pStr) * 20;
// // 페이지 분할
// List<HashMap> list = sdao.pasing(start, end, CName);
// 커리어 캐치에서 기업명 List 가져오기
List list = sdao.getData(req);
System.out.println(list.size() + "개 기업 데이터 불러오는 중 ...");
// 기업명 기준으로 DB에서 데이터 가져오기
list = sdao.getDataByCName(list);
ModelAndView mav = new ModelAndView();
mav.setViewName("search");
mav.addObject("main", "search/list_form");
mav.addObject("cnt", cnt);
mav.addObject("size", size);
mav.addObject("page", pStr);
mav.addObject("list", list);
mav.addObject("CName", CName);
mav.addObject("key", sdao.getParam(req)); // paging 처리용
return mav;
}
// Detail Search Result Ajax
@RequestMapping("/search/detail")
public ModelAndView detailHandler(HttpServletRequest req) {
int cnt = sdao.getTotal(req); // 커리어 캐치에서 total data 개수 가져옴
int size = cnt % 20 == 0 ? cnt / 20 : cnt / 20 + 1; // 총 페이지 수
String pStr = req.getParameter("page") == null ? "1" : req.getParameter("page");
// 커리어 캐치에서 기업명 List 가져오기
List list = sdao.getData(req);
System.out.println(list.size() + "개 기업 데이터 불러오는 중 ...");
// 기업명 기준으로 DB에서 데이터 가져오기
list = sdao.getDataByCName(list);
// 상세 검색 목록 뷰
ModelAndView mav = new ModelAndView();
mav.setViewName("/search/searchAjax");
mav.addObject("list", list);
mav.addObject("page", pStr);
mav.addObject("cnt", cnt);
mav.addObject("size", size);
mav.addObject("key", sdao.getParam(req)); // paging 처리용
return mav;
}
} | 2,826 | 0.669753 | 0.658565 | 86 | 28.16279 | 22.925999 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.813954 | false | false | 3 |
d7789efd67f9adb31b58dc7e969cf22376dbb476 | 5,540,507,831,357 | c8130567965fe4e1adc9794f70b20654d165f719 | /src/main/java/org/utn/frro/ds/reverseengineering/alquilervehiculos/service/ControladorAlquilarVehiculo.java | 3ec1664b2cd0b069aff7a18adbc80fa74a54eeb7 | [] | no_license | ignaciopaz/utn-frro-reverse-engineering | https://github.com/ignaciopaz/utn-frro-reverse-engineering | d0e84b547a5b10ab2e348eefb65b616eadc3b4aa | f209a645b4881e9361630347b1501f091fcd2a52 | refs/heads/master | 2021-01-21T07:08:17.106000 | 2017-05-17T17:09:43 | 2017-05-17T17:09:43 | 91,598,575 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.utn.frro.ds.reverseengineering.alquilervehiculos.service;
import java.util.*;
import org.utn.frro.ds.reverseengineering.alquilervehiculos.domain.*;
import org.utn.frro.ds.reverseengineering.alquilervehiculos.dao.*;
/** Esta clase Controla el CU Alquilar Vehículo.
* - Los alquileres mediante este CU comienzan hoy.
* - Los alquileres programados o reservados son manejados por otro CU.
* - Para simplificar el CU, se omiten conceptos de KM utilizados,
* consumo de combustible, roturas y estado del vehículo.
* - Para simplificar, no se tienen en cuenta hs de alquiler, se alquila por días completos. */
public class ControladorAlquilarVehiculo {
private CatalogoClientes cc;
private CatalogoTipoVehiculos ctv;
private CatalogoVehiculos cv;
private AlquilerRegistrador ca;
private Alquiler alquilerActual;
/** Método Constructor de la clase ControladorAlquilerVehiculos.
* Equivalente a método "create" de los DSD.
* El Controlador normalmente se crea desde la interfaz de usuario o una parte mas gral del Sistema */
public ControladorAlquilarVehiculo (CatalogoClientes cc,
CatalogoTipoVehiculos ctv,
CatalogoVehiculos cv, AlquilerRegistrador ca) {
this.cc=cc;
this.ctv=ctv;
this.cv=cv;
this.ca=ca;
}
public String identificarCliente(long codCliente) {
//Declara una variable local cliente de clase Cliente
Cliente cliente;
/* llama al método buscar del catálogo de clientes pasando el codCliente como parámetro.
Asigna el objeto cliente que retorna el método buscar a la variable cliente antes definida.*/
cliente = cc.buscar(codCliente);
if (cliente != null) {
//declara una variable local reazonSocial de la clase String
// y le asigna al valor de la razon social del cliente encontrado
String razonSocial = cliente.getRazonSocial();
// Crea una nuevo objeto de la clase Alquiler y asigna el objeto
// creado al atributo de instancia alquiler del controlador
alquilerActual = new Alquiler(cliente);
return razonSocial;
} else {//Si no se encuentra el cliente se devuelve una excepción (mensaje de error).
throw new RuntimeException("No existe un cliente con el código ingresado");
}
}
public Collection<String[]> seleccionarTipoVehiculo(long codTipoVehiculo, Date fechaHasta) {
//se asume que el alquiler comienza hoy. Se define una variable local fechaDesde del método.
Date fechaDesde = new Date();
alquilerActual.setPeriodo(fechaDesde, fechaHasta);
TipoVehiculo tipoVehiculo = ctv.buscar(codTipoVehiculo);
String descripcionTipo = tipoVehiculo.getDescripcionTipo();
Collection<Vehiculo> vechiculosDisp = cv.buscarDisponibles(tipoVehiculo,
fechaDesde, fechaHasta);
// Define una lista (Colección) de Array de Strings y le asigna una nueva instancia de ArrayList
//(Versión simplificada de devolución de datos al exterior. Aquí correspondería un objeto interfaz).
Collection<String[]> datosVehiculos = new ArrayList<String[]>();
//Para cada vehiculo en vehiculosDisp
for (Vehiculo vehiculo : vechiculosDisp) {
String patente = vehiculo.getPatente();
Modelo modelo = vehiculo.getModelo();
String codModelo = modelo.getCodModelo();
String codMarca = modelo.getMarca().getCodMarca();
//Se usa String.valueOf para convertir números a String.
String precioDia = String.valueOf(vehiculo.getPrecioDia());
//Define un array de objetos y le asigna los valores
String[] datosVehiculo = {patente, descripcionTipo, codMarca, codModelo, precioDia};
//agrega el array de strings con los datos del vehículo a
//la colleción de datosVehiculo
datosVehiculos.add(datosVehiculo);
}
return datosVehiculos;
}
public long seleccionarVehiculo(String patente) {
Vehiculo vehiculo = cv.buscar(patente);
if (vehiculo==null) {
throw new RuntimeException("No existe un vehiculo con la patente ingresada");
}
if (!vehiculo.estaDisponible(alquilerActual.getFechaInicio(), alquilerActual.getFechaFin())) {
throw new RuntimeException("El vehiculo seleccionado no está disponible en el periodo: " +
alquilerActual.getFechaInicio() + " - " +alquilerActual.getFechaFin());
}
alquilerActual.setVehiculo(vehiculo);
vehiculo.agregarAlquiler(alquilerActual);
ca.registrar(alquilerActual);
long nroAlquiler = alquilerActual.getNroAlquiler();
return nroAlquiler;
}
} | ISO-8859-1 | Java | 4,503 | java | ControladorAlquilarVehiculo.java | Java | [] | null | [] | package org.utn.frro.ds.reverseengineering.alquilervehiculos.service;
import java.util.*;
import org.utn.frro.ds.reverseengineering.alquilervehiculos.domain.*;
import org.utn.frro.ds.reverseengineering.alquilervehiculos.dao.*;
/** Esta clase Controla el CU Alquilar Vehículo.
* - Los alquileres mediante este CU comienzan hoy.
* - Los alquileres programados o reservados son manejados por otro CU.
* - Para simplificar el CU, se omiten conceptos de KM utilizados,
* consumo de combustible, roturas y estado del vehículo.
* - Para simplificar, no se tienen en cuenta hs de alquiler, se alquila por días completos. */
public class ControladorAlquilarVehiculo {
private CatalogoClientes cc;
private CatalogoTipoVehiculos ctv;
private CatalogoVehiculos cv;
private AlquilerRegistrador ca;
private Alquiler alquilerActual;
/** Método Constructor de la clase ControladorAlquilerVehiculos.
* Equivalente a método "create" de los DSD.
* El Controlador normalmente se crea desde la interfaz de usuario o una parte mas gral del Sistema */
public ControladorAlquilarVehiculo (CatalogoClientes cc,
CatalogoTipoVehiculos ctv,
CatalogoVehiculos cv, AlquilerRegistrador ca) {
this.cc=cc;
this.ctv=ctv;
this.cv=cv;
this.ca=ca;
}
public String identificarCliente(long codCliente) {
//Declara una variable local cliente de clase Cliente
Cliente cliente;
/* llama al método buscar del catálogo de clientes pasando el codCliente como parámetro.
Asigna el objeto cliente que retorna el método buscar a la variable cliente antes definida.*/
cliente = cc.buscar(codCliente);
if (cliente != null) {
//declara una variable local reazonSocial de la clase String
// y le asigna al valor de la razon social del cliente encontrado
String razonSocial = cliente.getRazonSocial();
// Crea una nuevo objeto de la clase Alquiler y asigna el objeto
// creado al atributo de instancia alquiler del controlador
alquilerActual = new Alquiler(cliente);
return razonSocial;
} else {//Si no se encuentra el cliente se devuelve una excepción (mensaje de error).
throw new RuntimeException("No existe un cliente con el código ingresado");
}
}
public Collection<String[]> seleccionarTipoVehiculo(long codTipoVehiculo, Date fechaHasta) {
//se asume que el alquiler comienza hoy. Se define una variable local fechaDesde del método.
Date fechaDesde = new Date();
alquilerActual.setPeriodo(fechaDesde, fechaHasta);
TipoVehiculo tipoVehiculo = ctv.buscar(codTipoVehiculo);
String descripcionTipo = tipoVehiculo.getDescripcionTipo();
Collection<Vehiculo> vechiculosDisp = cv.buscarDisponibles(tipoVehiculo,
fechaDesde, fechaHasta);
// Define una lista (Colección) de Array de Strings y le asigna una nueva instancia de ArrayList
//(Versión simplificada de devolución de datos al exterior. Aquí correspondería un objeto interfaz).
Collection<String[]> datosVehiculos = new ArrayList<String[]>();
//Para cada vehiculo en vehiculosDisp
for (Vehiculo vehiculo : vechiculosDisp) {
String patente = vehiculo.getPatente();
Modelo modelo = vehiculo.getModelo();
String codModelo = modelo.getCodModelo();
String codMarca = modelo.getMarca().getCodMarca();
//Se usa String.valueOf para convertir números a String.
String precioDia = String.valueOf(vehiculo.getPrecioDia());
//Define un array de objetos y le asigna los valores
String[] datosVehiculo = {patente, descripcionTipo, codMarca, codModelo, precioDia};
//agrega el array de strings con los datos del vehículo a
//la colleción de datosVehiculo
datosVehiculos.add(datosVehiculo);
}
return datosVehiculos;
}
public long seleccionarVehiculo(String patente) {
Vehiculo vehiculo = cv.buscar(patente);
if (vehiculo==null) {
throw new RuntimeException("No existe un vehiculo con la patente ingresada");
}
if (!vehiculo.estaDisponible(alquilerActual.getFechaInicio(), alquilerActual.getFechaFin())) {
throw new RuntimeException("El vehiculo seleccionado no está disponible en el periodo: " +
alquilerActual.getFechaInicio() + " - " +alquilerActual.getFechaFin());
}
alquilerActual.setVehiculo(vehiculo);
vehiculo.agregarAlquiler(alquilerActual);
ca.registrar(alquilerActual);
long nroAlquiler = alquilerActual.getNroAlquiler();
return nroAlquiler;
}
} | 4,503 | 0.73851 | 0.73851 | 96 | 44.708332 | 29.466406 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.864583 | false | false | 3 |
8c9364cfcb531cccafae039ef920f61874ae3b8a | 21,981,642,642,885 | 3b2e089c887b6031cd38ff20d477da7644e15105 | /src/uk/ac/kingston/ci5100/football/pair2/model/LeagueMatches.java | fa7effa6d66490e3ec0ef4d9271972042dfb3bde | [] | no_license | hassanazimi/Football | https://github.com/hassanazimi/Football | e13c0e9af27d17facd7c9c826513882fc538b0ab | e81c36660d10287bc57170be37b540e193135481 | refs/heads/master | 2021-01-25T07:40:07.348000 | 2015-11-07T18:36:56 | 2015-11-07T18:36:56 | 35,619,335 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.ac.kingston.ci5100.football.pair2.model;
import uk.ac.kingston.ci5100.football.pair2.utils.Convertors;
/**
*
* @author Hassan Azimi
*/
public final class LeagueMatches extends Matches {
private double ticketPrice;
private int awayFans;
/**
*
* @param csvString gets the file separated by comma and sets it to an array
*/
public LeagueMatches(String csvString) {
String[] attribute = Convertors.getStringAsArray(csvString, ",");
for (int i = 0; i < attribute.length; i++) {
String value = attribute[i];
switch (i) {
case 0:
this.setTeamname(value);
break;
case 1:
this.setResult(value);
break;
case 2:
this.setDate(value);
break;
case 3:
this.setOpponent(value);
break;
case 4:
this.setAttendance(Integer.parseInt(value));
break;
case 5:
this.setTicketPrice(Double.parseDouble(value));
break;
case 6:
this.setAwayFans(Integer.parseInt(value));
break;
}
}
}
/**
*
* @return the team name
*/
protected String getTeamname() {
return teamname;
}
/**
*
* @param teamname sets the team name
*/
protected void setTeamname(String teamname) {
this.teamname = teamname;
}
/**
* @return the result
*/
protected String getResult() {
return result;
}
/**
* @param result the result to set
*/
protected void setResult(String result) {
this.result = result;
}
/**
* @return the date
*/
protected String getDate() {
return date;
}
/**
* @param date the date to set
*/
protected void setDate(String date) {
this.date = date;
}
/**
* @return the opponent
*/
protected String getOpponent() {
return opponent;
}
/**
* @param opponent the opponent to set
*/
protected void setOpponent(String opponent) {
this.opponent = opponent;
}
/**
* @return the attendance
*/
protected int getAttendance() {
return attendance;
}
/**
* @param attendance the attendance to set
*/
protected void setAttendance(int attendance) {
this.attendance = attendance;
}
/**
* @return the ticketPrice
*/
protected double getTicketPrice() {
return ticketPrice;
}
/**
* @param ticketPrice the ticketPrice to set
*/
protected void setTicketPrice(double ticketPrice) {
this.ticketPrice = ticketPrice;
}
/**
* @return the awayFans
*/
protected int getAwayFans() {
return awayFans;
}
/**
* @param awayFans the awayFans to set
*/
protected void setAwayFans(int awayFans) {
this.awayFans = awayFans;
}
/**
* This method overrides the 'toString' method organizing the data in an easier read layout
*
* @return
*/
@Override
public String toString() {
return " " + teamname + " \t\t" + result + "\t" + date + "\t" + opponent + " \t" + attendance + "\t" + ticketPrice + "\t" + awayFans + "\n";
}
/**
* Compares team names without being case sensitive
*
* @param o LeagueMatches object to be compared
* @return a negative integer, 0 or a positive integer
*/
public int compareTo(LeagueMatches o) {
return this.getTeamname().compareToIgnoreCase(o.getTeamname());
}
}
| UTF-8 | Java | 3,863 | java | LeagueMatches.java | Java | [
{
"context": "ootball.pair2.utils.Convertors;\n\n/**\n *\n * @author Hassan Azimi\n */\npublic final class LeagueMatches extends Matc",
"end": 146,
"score": 0.9998394846916199,
"start": 134,
"tag": "NAME",
"value": "Hassan Azimi"
}
] | null | [] | package uk.ac.kingston.ci5100.football.pair2.model;
import uk.ac.kingston.ci5100.football.pair2.utils.Convertors;
/**
*
* @author <NAME>
*/
public final class LeagueMatches extends Matches {
private double ticketPrice;
private int awayFans;
/**
*
* @param csvString gets the file separated by comma and sets it to an array
*/
public LeagueMatches(String csvString) {
String[] attribute = Convertors.getStringAsArray(csvString, ",");
for (int i = 0; i < attribute.length; i++) {
String value = attribute[i];
switch (i) {
case 0:
this.setTeamname(value);
break;
case 1:
this.setResult(value);
break;
case 2:
this.setDate(value);
break;
case 3:
this.setOpponent(value);
break;
case 4:
this.setAttendance(Integer.parseInt(value));
break;
case 5:
this.setTicketPrice(Double.parseDouble(value));
break;
case 6:
this.setAwayFans(Integer.parseInt(value));
break;
}
}
}
/**
*
* @return the team name
*/
protected String getTeamname() {
return teamname;
}
/**
*
* @param teamname sets the team name
*/
protected void setTeamname(String teamname) {
this.teamname = teamname;
}
/**
* @return the result
*/
protected String getResult() {
return result;
}
/**
* @param result the result to set
*/
protected void setResult(String result) {
this.result = result;
}
/**
* @return the date
*/
protected String getDate() {
return date;
}
/**
* @param date the date to set
*/
protected void setDate(String date) {
this.date = date;
}
/**
* @return the opponent
*/
protected String getOpponent() {
return opponent;
}
/**
* @param opponent the opponent to set
*/
protected void setOpponent(String opponent) {
this.opponent = opponent;
}
/**
* @return the attendance
*/
protected int getAttendance() {
return attendance;
}
/**
* @param attendance the attendance to set
*/
protected void setAttendance(int attendance) {
this.attendance = attendance;
}
/**
* @return the ticketPrice
*/
protected double getTicketPrice() {
return ticketPrice;
}
/**
* @param ticketPrice the ticketPrice to set
*/
protected void setTicketPrice(double ticketPrice) {
this.ticketPrice = ticketPrice;
}
/**
* @return the awayFans
*/
protected int getAwayFans() {
return awayFans;
}
/**
* @param awayFans the awayFans to set
*/
protected void setAwayFans(int awayFans) {
this.awayFans = awayFans;
}
/**
* This method overrides the 'toString' method organizing the data in an easier read layout
*
* @return
*/
@Override
public String toString() {
return " " + teamname + " \t\t" + result + "\t" + date + "\t" + opponent + " \t" + attendance + "\t" + ticketPrice + "\t" + awayFans + "\n";
}
/**
* Compares team names without being case sensitive
*
* @param o LeagueMatches object to be compared
* @return a negative integer, 0 or a positive integer
*/
public int compareTo(LeagueMatches o) {
return this.getTeamname().compareToIgnoreCase(o.getTeamname());
}
}
| 3,857 | 0.521615 | 0.516697 | 167 | 22.131737 | 22.668545 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.245509 | false | false | 3 |
7711597d3169b547af71fd67e4e40732f2c23cf1 | 8,495,445,329,487 | e95553e433525f6199389703c9d376e13cc8c586 | /app/src/main/java/com/dev/emed/doctor/PatientHistoryFragment.java | 513d21dbfa0c120066f192c9a8eb115a4ed13f4a | [] | no_license | Jerinji2016/eMed | https://github.com/Jerinji2016/eMed | b6ebb96888f030ff92732680132f8c1133141ac1 | 8b99ba41fb1d87f7590e49261e40e38148d5b0e1 | refs/heads/master | 2021-01-03T18:01:00.478000 | 2020-07-11T14:20:14 | 2020-07-11T14:20:14 | 241,072,437 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dev.emed.doctor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.dev.emed.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class PatientHistoryFragment extends Fragment {
private static final String TAG = "PatientHistoryFragment";
private String userId;
private RecyclerView recyclerView;
private DatabaseReference mReff;
private ValueEventListener mListener;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.doc_fragment_patient_history, container, false);
if(getArguments() != null)
userId = getArguments().getString("userId");
recyclerView = view.findViewById(R.id.doc_prescription_history_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mReff = FirebaseDatabase.getInstance().getReference("Doctor").child(userId);
mListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
DataSnapshot ds = dataSnapshot.child("consultants");
recyclerView.setAdapter(new DoctorRecyclerViewAdapter(getActivity(), ds));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, "onCancelled: "+databaseError.getMessage());
}
};
mReff.addValueEventListener(mListener);
return view;
}
@Override
public void onPause() {
super.onPause();
if(mListener != null)
mReff.removeEventListener(mListener);
}
@Override
public void onResume() {
super.onResume();
if(mListener != null)
mReff.addValueEventListener(mListener);
}
@Override
public void onDestroy() {
super.onDestroy();
if(mListener != null)
mReff.removeEventListener(mListener);
}
}
| UTF-8 | Java | 2,682 | java | PatientHistoryFragment.java | Java | [] | null | [] | package com.dev.emed.doctor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.dev.emed.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class PatientHistoryFragment extends Fragment {
private static final String TAG = "PatientHistoryFragment";
private String userId;
private RecyclerView recyclerView;
private DatabaseReference mReff;
private ValueEventListener mListener;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.doc_fragment_patient_history, container, false);
if(getArguments() != null)
userId = getArguments().getString("userId");
recyclerView = view.findViewById(R.id.doc_prescription_history_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mReff = FirebaseDatabase.getInstance().getReference("Doctor").child(userId);
mListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
DataSnapshot ds = dataSnapshot.child("consultants");
recyclerView.setAdapter(new DoctorRecyclerViewAdapter(getActivity(), ds));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, "onCancelled: "+databaseError.getMessage());
}
};
mReff.addValueEventListener(mListener);
return view;
}
@Override
public void onPause() {
super.onPause();
if(mListener != null)
mReff.removeEventListener(mListener);
}
@Override
public void onResume() {
super.onResume();
if(mListener != null)
mReff.addValueEventListener(mListener);
}
@Override
public void onDestroy() {
super.onDestroy();
if(mListener != null)
mReff.removeEventListener(mListener);
}
}
| 2,682 | 0.693885 | 0.693885 | 81 | 31.82716 | 27.461214 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567901 | false | false | 3 |
d0280c0eb34bb5836ec000b241b558b3d6e550c5 | 32,023,276,162,890 | 17317f67b6691a21bd5db60c255ffe74ac8985f2 | /WEB20200723/src/main/java/com/scit/web9/service/MemberService.java | 75917eb6a7573bc269510fe0bb2aa12fbb914958 | [] | no_license | BaeJaeHyun7/SpringTest2 | https://github.com/BaeJaeHyun7/SpringTest2 | 8464a0881c946323c731378be745cf34f7dfd421 | 75fdc4fd8776793f530070b8578e41c0bc4d4d06 | refs/heads/master | 2022-12-28T14:04:52.859000 | 2020-09-26T02:40:17 | 2020-09-26T02:40:17 | 293,385,056 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scit.web9.service;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scit.web9.dao.MemberDao;
import com.scit.web9.dao.MemberMapper;
import com.scit.web9.vo.MemberVo;
@Service
public class MemberService {
@Autowired
private MemberDao dao;
public String memberJoin(MemberVo member) {
int cnt = dao.memberJoin(member);
String page = "";
if(cnt == 0) {
page = "redirect:/member/joinFail";
}else {
page = "redirect:/";
}
return page;
}
public ArrayList<MemberVo> joinList(){
ArrayList<MemberVo> list = dao.joinList();
return list;
}
public int memberDelete(String member_id) {
int cnt = dao.memberDelete(member_id);
return cnt;
}
}
| UTF-8 | Java | 801 | java | MemberService.java | Java | [] | null | [] | package com.scit.web9.service;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scit.web9.dao.MemberDao;
import com.scit.web9.dao.MemberMapper;
import com.scit.web9.vo.MemberVo;
@Service
public class MemberService {
@Autowired
private MemberDao dao;
public String memberJoin(MemberVo member) {
int cnt = dao.memberJoin(member);
String page = "";
if(cnt == 0) {
page = "redirect:/member/joinFail";
}else {
page = "redirect:/";
}
return page;
}
public ArrayList<MemberVo> joinList(){
ArrayList<MemberVo> list = dao.joinList();
return list;
}
public int memberDelete(String member_id) {
int cnt = dao.memberDelete(member_id);
return cnt;
}
}
| 801 | 0.706617 | 0.700375 | 49 | 15.346939 | 17.079109 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.22449 | false | false | 3 |
9539404d97c632ee7fba70d81f00601c259e5cac | 30,305,289,285,964 | b214f96566446763ce5679dd2121ea3d277a9406 | /modules/base/language-impl/src/main/java/consulo/language/impl/psi/SourceTreeToPsiMap.java | acadd04daf05e6e645708880ca0ad85677a8616d | [
"Apache-2.0",
"LicenseRef-scancode-jgraph"
] | permissive | consulo/consulo | https://github.com/consulo/consulo | aa340d719d05ac6cbadd3f7d1226cdb678e6c84f | d784f1ef5824b944c1ee3a24a8714edfc5e2b400 | refs/heads/master | 2023-09-06T06:55:04.987000 | 2023-09-01T06:42:16 | 2023-09-01T06:42:16 | 10,116,915 | 680 | 54 | Apache-2.0 | false | 2023-06-05T18:28:51 | 2013-05-17T05:48:18 | 2023-05-27T20:14:55 | 2023-06-05T18:28:50 | 978,666 | 673 | 48 | 69 | Java | false | false | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.language.impl.psi;
import consulo.language.ast.ASTNode;
import consulo.language.impl.ast.TreeElement;
import consulo.language.psi.PsiElement;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
public class SourceTreeToPsiMap {
private SourceTreeToPsiMap() { }
@Nullable
public static PsiElement treeElementToPsi(@Nullable final ASTNode element) {
return element == null ? null : element.getPsi();
}
@Nonnull
public static <T extends PsiElement> T treeToPsiNotNull(@Nonnull final ASTNode element) {
final PsiElement psi = element.getPsi();
assert psi != null : element;
//noinspection unchecked
return (T)psi;
}
@Nullable
public static ASTNode psiElementToTree(@Nullable final PsiElement psiElement) {
return psiElement == null ? null : psiElement.getNode();
}
@Nonnull
public static TreeElement psiToTreeNotNull(@Nonnull final PsiElement psiElement) {
final ASTNode node = psiElement.getNode();
assert node instanceof TreeElement : psiElement + ", " + node;
return (TreeElement)node;
}
public static boolean hasTreeElement(@Nullable final PsiElement psiElement) {
return psiElement instanceof TreeElement || psiElement instanceof ASTDelegatePsiElement || psiElement instanceof PsiFileImpl;
}
}
| UTF-8 | Java | 1,909 | java | SourceTreeToPsiMap.java | Java | [] | null | [] | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.language.impl.psi;
import consulo.language.ast.ASTNode;
import consulo.language.impl.ast.TreeElement;
import consulo.language.psi.PsiElement;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
public class SourceTreeToPsiMap {
private SourceTreeToPsiMap() { }
@Nullable
public static PsiElement treeElementToPsi(@Nullable final ASTNode element) {
return element == null ? null : element.getPsi();
}
@Nonnull
public static <T extends PsiElement> T treeToPsiNotNull(@Nonnull final ASTNode element) {
final PsiElement psi = element.getPsi();
assert psi != null : element;
//noinspection unchecked
return (T)psi;
}
@Nullable
public static ASTNode psiElementToTree(@Nullable final PsiElement psiElement) {
return psiElement == null ? null : psiElement.getNode();
}
@Nonnull
public static TreeElement psiToTreeNotNull(@Nonnull final PsiElement psiElement) {
final ASTNode node = psiElement.getNode();
assert node instanceof TreeElement : psiElement + ", " + node;
return (TreeElement)node;
}
public static boolean hasTreeElement(@Nullable final PsiElement psiElement) {
return psiElement instanceof TreeElement || psiElement instanceof ASTDelegatePsiElement || psiElement instanceof PsiFileImpl;
}
}
| 1,909 | 0.749607 | 0.743321 | 56 | 33.089287 | 31.005342 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446429 | false | false | 3 |
08fe679e7c6a37c06bfcecb35c0cde445c1c833b | 17,008,070,497,031 | 709e3ed6970c591bfe5c4492182d476cea018f49 | /au.id.cpd.eigenfaces/src/au/id/cpd/eigenfaces/data/SearchQuery.java | 91b80c028f2ddfb48ea44703228ed7cefa54e95a | [] | no_license | cxd/au.id.cpd.eigenfaces | https://github.com/cxd/au.id.cpd.eigenfaces | 6ed6941502e6661fafa5a2ff445698bcccf99024 | 05516a1144d8a74f0f396fe094c646bcf88233ae | refs/heads/master | 2021-01-10T21:31:19.599000 | 2015-05-10T08:58:14 | 2015-05-10T08:58:14 | 35,319,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package au.id.cpd.eigenfaces.data;
import java.util.*;
import au.id.cpd.algorithms.data.*;
/**
* The search result contains
* the resulting record that is associated with the query.
* @author cd
*
*/
public class SearchQuery {
/**
* An image file used to retrieve the query.
*/
private String imageFile;
/**
* Row vector of query data.
*/
private IMatrix<Double> query;
/**
* Row vector of closest match data
*/
private IMatrix<Double> result;
/**
* Distance from closest match.
*/
private double distance;
/**
* Index of the closest match.
*/
private int index;
/**
* Label corresponding to the closest match.
*/
private String label;
/**
* A set of distances corresponding to the image labels.
*/
private List<ITuple<String,Double>> distances;
/**
* default
*/
public SearchQuery() {
distances = new ArrayList<ITuple<String,Double>>();
}
/**
* Create with the query
* @param query
*/
public SearchQuery(IMatrix<Double> q) {
this();
query = q;
}
/**
* Load a query from the supplied image file.
* @param f - file name of image
* @param width - width of image
* @param height - height of image.
* @return true if successful false otherwise.
*/
public boolean loadQueryFromImageFile(String f, int width, int height) {
imageFile = f;
GrayscaleImageLoader loader = new GrayscaleImageLoader(width, height);
query = loader.loadRowMatrix(imageFile);
return (query != null);
}
/**
* @return the query
*/
public IMatrix<Double> getQuery() {
return query;
}
/**
* @param query the query to set
*/
public void setQuery(IMatrix<Double> query) {
this.query = query;
}
/**
* @return the result
*/
public IMatrix<Double> getResult() {
return result;
}
/**
* @param result the result to set
*/
public void setResult(IMatrix<Double> result) {
this.result = result;
}
/**
* @return the distance
*/
public double getDistance() {
return distance;
}
/**
* @param distance the distance to set
*/
public void setDistance(double distance) {
this.distance = distance;
}
/**
* @return the index
*/
public int getIndex() {
return index;
}
/**
* @param index the index to set
*/
public void setIndex(int index) {
this.index = index;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
/**
* @return the imageFile
*/
public String getImageFile() {
return imageFile;
}
/**
* @param imageFile the imageFile to set
*/
public void setImageFile(String imageFile) {
this.imageFile = imageFile;
}
/**
* @return the distances
*/
public List<ITuple<String, Double>> getDistances() {
return distances;
}
/**
* @param distances the distances to set
*/
public void setDistances(List<ITuple<String, Double>> distances) {
this.distances = distances;
}
}
| UTF-8 | Java | 3,003 | java | SearchQuery.java | Java | [
{
"context": "cord that is associated with the query.\n * @author cd\n *\n */\npublic class SearchQuery {\n\n\t/**\n\t * An im",
"end": 211,
"score": 0.9975014328956604,
"start": 209,
"tag": "USERNAME",
"value": "cd"
}
] | null | [] | /**
*
*/
package au.id.cpd.eigenfaces.data;
import java.util.*;
import au.id.cpd.algorithms.data.*;
/**
* The search result contains
* the resulting record that is associated with the query.
* @author cd
*
*/
public class SearchQuery {
/**
* An image file used to retrieve the query.
*/
private String imageFile;
/**
* Row vector of query data.
*/
private IMatrix<Double> query;
/**
* Row vector of closest match data
*/
private IMatrix<Double> result;
/**
* Distance from closest match.
*/
private double distance;
/**
* Index of the closest match.
*/
private int index;
/**
* Label corresponding to the closest match.
*/
private String label;
/**
* A set of distances corresponding to the image labels.
*/
private List<ITuple<String,Double>> distances;
/**
* default
*/
public SearchQuery() {
distances = new ArrayList<ITuple<String,Double>>();
}
/**
* Create with the query
* @param query
*/
public SearchQuery(IMatrix<Double> q) {
this();
query = q;
}
/**
* Load a query from the supplied image file.
* @param f - file name of image
* @param width - width of image
* @param height - height of image.
* @return true if successful false otherwise.
*/
public boolean loadQueryFromImageFile(String f, int width, int height) {
imageFile = f;
GrayscaleImageLoader loader = new GrayscaleImageLoader(width, height);
query = loader.loadRowMatrix(imageFile);
return (query != null);
}
/**
* @return the query
*/
public IMatrix<Double> getQuery() {
return query;
}
/**
* @param query the query to set
*/
public void setQuery(IMatrix<Double> query) {
this.query = query;
}
/**
* @return the result
*/
public IMatrix<Double> getResult() {
return result;
}
/**
* @param result the result to set
*/
public void setResult(IMatrix<Double> result) {
this.result = result;
}
/**
* @return the distance
*/
public double getDistance() {
return distance;
}
/**
* @param distance the distance to set
*/
public void setDistance(double distance) {
this.distance = distance;
}
/**
* @return the index
*/
public int getIndex() {
return index;
}
/**
* @param index the index to set
*/
public void setIndex(int index) {
this.index = index;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
/**
* @return the imageFile
*/
public String getImageFile() {
return imageFile;
}
/**
* @param imageFile the imageFile to set
*/
public void setImageFile(String imageFile) {
this.imageFile = imageFile;
}
/**
* @return the distances
*/
public List<ITuple<String, Double>> getDistances() {
return distances;
}
/**
* @param distances the distances to set
*/
public void setDistances(List<ITuple<String, Double>> distances) {
this.distances = distances;
}
}
| 3,003 | 0.64036 | 0.64036 | 182 | 15.5 | 17.081495 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.153846 | false | false | 3 |
84dd5904f4e50cd77a5e421d174765f1be8ac1e1 | 17,265,768,536,986 | a2cc4344c271b8c6b07792b26a92645cbe34c129 | /src/cz/muni/clusterix/entities/Result.java | 033b8a4bdd83a1544dee4fd3ac934f3a91c7c78d | [] | no_license | seziCZ/Clusterix | https://github.com/seziCZ/Clusterix | 32eb8bed0b12bbeaa2f4bc910422158a640fcda6 | dab4525781a4c89f38885ecfbcd5ff21dcac1410 | refs/heads/master | 2016-09-06T17:50:54.192000 | 2015-06-05T16:55:10 | 2015-06-05T16:55:10 | 36,623,405 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.muni.clusterix.entities;
import cz.muni.clusterix.businesstier.FieldMask;
import java.util.List;
/**
*
* Result of the probability search. Class contains stars, their probabilities,
* mask and restrictions proposed by the user and relevant cluster (OpenCluster)
* and field (ProperMotion) information.
*
* @author Tomas Sezima
*/
public class Result {
// cluster and field specification
private final OpenCluster cluster;
private final ProperMotion field;
// actual result
private final List<Star> stars;
private final int numOfMemebers;
// user given options
private final Restrictions rests;
private final FieldMask mask;
//constructor
/**
* Constructor.
*
* @param cluster Open cluster that has been evaluated
* @param field Proper motion of field stars
* @param stars Stars with assigned probabilities
* @param numOfMembers Expected number of cluster memebers
* @param rests Restrictions containing values used during memberhip
* probability computation
* @param mask FieldMask proposed by user
*/
public Result(OpenCluster cluster, ProperMotion field, List<Star> stars,
int numOfMembers, Restrictions rests, FieldMask mask) {
this.cluster = cluster;
this.field = field;
this.stars = stars;
this.numOfMemebers = numOfMembers;
this.rests = rests;
this.mask = mask;
}
//getters
public FieldMask getMask() {
return mask;
}
public Restrictions getRests() {
return rests;
}
public List<Star> getStars() {
return stars;
}
public OpenCluster getCluster() {
return cluster;
}
public ProperMotion getFieldProperMotion() {
return field;
}
public int getNumOfMembers() {
return numOfMemebers;
}
//equals and hashcode
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.cluster != null ? this.cluster.hashCode() : 0);
hash = 31 * hash + (this.field != null ? this.field.hashCode() : 0);
hash = 31 * hash + (this.stars != null ? this.stars.hashCode() : 0);
hash = 31 * hash + this.numOfMemebers;
hash = 31 * hash + (this.rests != null ? this.rests.hashCode() : 0);
hash = 31 * hash + (this.mask != null ? this.mask.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Result other = (Result) obj;
if (this.cluster != other.cluster && (this.cluster == null || !this.cluster.equals(other.cluster))) {
return false;
}
if (this.field != other.field && (this.field == null || !this.field.equals(other.field))) {
return false;
}
if (this.stars != other.stars && (this.stars == null || !this.stars.equals(other.stars))) {
return false;
}
if (this.numOfMemebers != other.numOfMemebers) {
return false;
}
if (this.rests != other.rests && (this.rests == null || !this.rests.equals(other.rests))) {
return false;
}
if (this.mask != other.mask && (this.mask == null || !this.mask.equals(other.mask))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Result{" + "cluster=" + cluster + ", field=" + field + ", stars="
+ stars + ", rests=" + rests + ", mask=" + mask + '}';
}
}
| UTF-8 | Java | 3,769 | java | Result.java | Java | [
{
"context": "nd field (ProperMotion) information.\n *\n * @author Tomas Sezima\n */\npublic class Result {\n\n // cluster and fie",
"end": 346,
"score": 0.9998422861099243,
"start": 334,
"tag": "NAME",
"value": "Tomas Sezima"
}
] | null | [] | package cz.muni.clusterix.entities;
import cz.muni.clusterix.businesstier.FieldMask;
import java.util.List;
/**
*
* Result of the probability search. Class contains stars, their probabilities,
* mask and restrictions proposed by the user and relevant cluster (OpenCluster)
* and field (ProperMotion) information.
*
* @author <NAME>
*/
public class Result {
// cluster and field specification
private final OpenCluster cluster;
private final ProperMotion field;
// actual result
private final List<Star> stars;
private final int numOfMemebers;
// user given options
private final Restrictions rests;
private final FieldMask mask;
//constructor
/**
* Constructor.
*
* @param cluster Open cluster that has been evaluated
* @param field Proper motion of field stars
* @param stars Stars with assigned probabilities
* @param numOfMembers Expected number of cluster memebers
* @param rests Restrictions containing values used during memberhip
* probability computation
* @param mask FieldMask proposed by user
*/
public Result(OpenCluster cluster, ProperMotion field, List<Star> stars,
int numOfMembers, Restrictions rests, FieldMask mask) {
this.cluster = cluster;
this.field = field;
this.stars = stars;
this.numOfMemebers = numOfMembers;
this.rests = rests;
this.mask = mask;
}
//getters
public FieldMask getMask() {
return mask;
}
public Restrictions getRests() {
return rests;
}
public List<Star> getStars() {
return stars;
}
public OpenCluster getCluster() {
return cluster;
}
public ProperMotion getFieldProperMotion() {
return field;
}
public int getNumOfMembers() {
return numOfMemebers;
}
//equals and hashcode
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.cluster != null ? this.cluster.hashCode() : 0);
hash = 31 * hash + (this.field != null ? this.field.hashCode() : 0);
hash = 31 * hash + (this.stars != null ? this.stars.hashCode() : 0);
hash = 31 * hash + this.numOfMemebers;
hash = 31 * hash + (this.rests != null ? this.rests.hashCode() : 0);
hash = 31 * hash + (this.mask != null ? this.mask.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Result other = (Result) obj;
if (this.cluster != other.cluster && (this.cluster == null || !this.cluster.equals(other.cluster))) {
return false;
}
if (this.field != other.field && (this.field == null || !this.field.equals(other.field))) {
return false;
}
if (this.stars != other.stars && (this.stars == null || !this.stars.equals(other.stars))) {
return false;
}
if (this.numOfMemebers != other.numOfMemebers) {
return false;
}
if (this.rests != other.rests && (this.rests == null || !this.rests.equals(other.rests))) {
return false;
}
if (this.mask != other.mask && (this.mask == null || !this.mask.equals(other.mask))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Result{" + "cluster=" + cluster + ", field=" + field + ", stars="
+ stars + ", rests=" + rests + ", mask=" + mask + '}';
}
}
| 3,763 | 0.573892 | 0.569116 | 131 | 27.770992 | 26.401644 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465649 | false | false | 3 |
973b23c78fb751e17b2c99418c93383ffc3e0821 | 29,746,943,499,699 | 4bf998e8a4dba825210e8a18498bcbf0781389eb | /projects/server/src/main/java/com/arqsoft/server/Infrastructure/AdapterPersistenceJDBC/Entity/Sandwich/Comment.java | f8e91129d2468f097423706fa08123a754a8c174 | [] | no_license | Sailor-Saturn/Hexagonal-Architecture-Spring-Boot-Postgres-JPA-JDBC-Monolith | https://github.com/Sailor-Saturn/Hexagonal-Architecture-Spring-Boot-Postgres-JPA-JDBC-Monolith | ef68b76bc680021b58773409679f9f92fca3ebef | 949b8f61392ca24f4a4a178ba69273e28f210950 | refs/heads/main | 2023-01-18T14:46:37.025000 | 2020-11-24T22:56:14 | 2020-11-24T22:56:14 | 315,771,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arqsoft.server.Infrastructure.AdapterPersistenceJDBC.Entity.Sandwich;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
@Table("comment")
public class Comment {
@Id
private Long id;
private String content;
private String title;
private long user_id;
public Long getId() {
return id;
}
public String getContent() {
return content;
}
public String getTitle() {
return title;
}
public long getUser_id() {
return user_id;
}
protected Comment() {}
public Comment(Long id, String content, String title, long user_id) {
this.id = id;
this.content = content;
this.title = title;
this.user_id = user_id;
}
public Comment(String content, String title, long user_id) {
this.content = content;
this.title = title;
this.user_id = user_id;
}
}
| UTF-8 | Java | 975 | java | Comment.java | Java | [] | null | [] | package com.arqsoft.server.Infrastructure.AdapterPersistenceJDBC.Entity.Sandwich;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
@Table("comment")
public class Comment {
@Id
private Long id;
private String content;
private String title;
private long user_id;
public Long getId() {
return id;
}
public String getContent() {
return content;
}
public String getTitle() {
return title;
}
public long getUser_id() {
return user_id;
}
protected Comment() {}
public Comment(Long id, String content, String title, long user_id) {
this.id = id;
this.content = content;
this.title = title;
this.user_id = user_id;
}
public Comment(String content, String title, long user_id) {
this.content = content;
this.title = title;
this.user_id = user_id;
}
}
| 975 | 0.622564 | 0.622564 | 48 | 19.3125 | 19.940701 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479167 | false | false | 3 |
e82f221f9c1edad8b2819b2d7e086170e12cf300 | 31,628,139,181,657 | c112183ba1a216e6ce3a75b460127ce1112e6414 | /src/main/java/com/technia/migration/KafkaConsumer/consumer/DataExecutorService.java | cb09b4f48e7dbb09d47449b567b14a968389b04b | [] | no_license | govipul/KafkaConsumer | https://github.com/govipul/KafkaConsumer | b61cae602749a92f68aa8a120d3a732ecf9c174b | 05a01fc9fcdae8fea63454ee0681f9cc77b1d603 | refs/heads/master | 2021-03-04T22:41:46.762000 | 2020-03-10T13:44:59 | 2020-03-10T13:44:59 | 246,072,282 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.technia.migration.KafkaConsumer.consumer;
import com.technia.migration.producer.model.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DataExecutorService implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(DataExecutorService.class);
private final Data data;
public DataExecutorService(Data data) {
this.data = data;
}
@Override
public void run() {
System.out.println(this.data);
LOGGER.info("This is the received message: {}",this.data);
}
}
| UTF-8 | Java | 571 | java | DataExecutorService.java | Java | [] | null | [] | package com.technia.migration.KafkaConsumer.consumer;
import com.technia.migration.producer.model.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DataExecutorService implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(DataExecutorService.class);
private final Data data;
public DataExecutorService(Data data) {
this.data = data;
}
@Override
public void run() {
System.out.println(this.data);
LOGGER.info("This is the received message: {}",this.data);
}
}
| 571 | 0.721541 | 0.718038 | 21 | 26.190475 | 25.382069 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 3 |
20429fc8b196927930825a6ad8e5d2889687f33e | 23,871,428,241,164 | 84673f3ab5d8d50e30ba2c945c9108dbd4243f52 | /dmall-service-api/dmall-service-api-order/src/main/java/com/dmall/oms/api/dto/demolitionorderpage/DemolitionOrderPageRequestDTO.java | 7879c64f8fc512e917500e8d541c629d7c731899 | [
"Apache-2.0"
] | permissive | yuhangtdm/dmall | https://github.com/yuhangtdm/dmall | 6d19395db0917d8dcfb09452ff34d82c03e5b774 | e77794a0dff75f56b6a70d9ffeb3d2482b2cfeb8 | refs/heads/master | 2022-12-09T00:02:47.231000 | 2020-06-13T14:20:20 | 2020-06-13T14:20:20 | 214,462,902 | 8 | 4 | Apache-2.0 | false | 2022-11-21T22:39:42 | 2019-10-11T14:55:13 | 2021-04-13T07:40:34 | 2022-11-21T22:39:39 | 8,326 | 7 | 4 | 5 | JavaScript | false | false | package com.dmall.oms.api.dto.demolitionorderpage;
import com.dmall.common.dto.PageRequestDTO;
import com.dmall.common.dto.validate.ValueInEnum;
import com.dmall.common.enums.SourceEnum;
import com.dmall.oms.api.enums.CancelTypeEnum;
import com.dmall.oms.api.enums.OrderStatusEnum;
import com.dmall.oms.api.enums.SplitEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* @description: PageOrderRequestDTO
* @author: created by hang.yu on 2020/4/4 16:16
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "PageOrderRequestDTO", description = "拆单分页请求实体")
public class DemolitionOrderPageRequestDTO extends PageRequestDTO {
@ApiModelProperty(value = "订单号", position = 1)
private Long orderId;
@ApiModelProperty(value = "订单来源", position = 2)
@ValueInEnum(SourceEnum.class)
private Integer source;
@ApiModelProperty(value = "会员id", position = 3)
private Long memberId;
@ApiModelProperty(value = "订单是否拆分: 1-未拆分;2-无需拆分;3-已拆分;", position = 4)
@ValueInEnum(SplitEnum.class)
private Integer isSplit;
@ApiModelProperty(value = "取消方式", position = 5)
@ValueInEnum(CancelTypeEnum.class)
private Integer cancelType;
@ApiModelProperty(value = "订单状态", position = 6)
@ValueInEnum(OrderStatusEnum.class)
private Integer orderStatus;
@ApiModelProperty(value = "订单创建时间,默认传当天", position = 7)
private Date createTime = new Date();
}
| UTF-8 | Java | 1,635 | java | DemolitionOrderPageRequestDTO.java | Java | [
{
"context": "iption: PageOrderRequestDTO\n * @author: created by hang.yu on 2020/4/4 16:16\n */\n@Data\n@EqualsAndHashCode(ca",
"end": 562,
"score": 0.9908959269523621,
"start": 555,
"tag": "USERNAME",
"value": "hang.yu"
}
] | null | [] | package com.dmall.oms.api.dto.demolitionorderpage;
import com.dmall.common.dto.PageRequestDTO;
import com.dmall.common.dto.validate.ValueInEnum;
import com.dmall.common.enums.SourceEnum;
import com.dmall.oms.api.enums.CancelTypeEnum;
import com.dmall.oms.api.enums.OrderStatusEnum;
import com.dmall.oms.api.enums.SplitEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* @description: PageOrderRequestDTO
* @author: created by hang.yu on 2020/4/4 16:16
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "PageOrderRequestDTO", description = "拆单分页请求实体")
public class DemolitionOrderPageRequestDTO extends PageRequestDTO {
@ApiModelProperty(value = "订单号", position = 1)
private Long orderId;
@ApiModelProperty(value = "订单来源", position = 2)
@ValueInEnum(SourceEnum.class)
private Integer source;
@ApiModelProperty(value = "会员id", position = 3)
private Long memberId;
@ApiModelProperty(value = "订单是否拆分: 1-未拆分;2-无需拆分;3-已拆分;", position = 4)
@ValueInEnum(SplitEnum.class)
private Integer isSplit;
@ApiModelProperty(value = "取消方式", position = 5)
@ValueInEnum(CancelTypeEnum.class)
private Integer cancelType;
@ApiModelProperty(value = "订单状态", position = 6)
@ValueInEnum(OrderStatusEnum.class)
private Integer orderStatus;
@ApiModelProperty(value = "订单创建时间,默认传当天", position = 7)
private Date createTime = new Date();
}
| 1,635 | 0.747224 | 0.734161 | 49 | 30.244898 | 21.451921 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632653 | false | false | 3 |
df97d35af5bab3d469249c9063be5137baebf7f5 | 17,351,667,930,761 | 8deaa118b7bdf6e2a3d2944db2112cf945dcfc64 | /src/main/java/no/kristianped/recipe/services/RecipeService.java | 7c4e49543fc6c6e4028a83dcbf437be5176b831e | [
"MIT"
] | permissive | Kristianped/recipe | https://github.com/Kristianped/recipe | 8330be1478b6b2b9e20e570281fb210fbcd19f1d | aa4c5679e3e7f44e39c0cc2ab70538e7644582ff | refs/heads/main | 2023-02-13T12:38:35.369000 | 2021-01-16T00:23:50 | 2021-01-16T00:23:50 | 327,102,651 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package no.kristianped.recipe.services;
import no.kristianped.recipe.commands.RecipeCommand;
import no.kristianped.recipe.domain.Recipe;
import java.util.Set;
public interface RecipeService {
Set<Recipe> getRecipes();
Recipe findById(long anyLong);
RecipeCommand saveRecipeCommand(RecipeCommand command);
RecipeCommand findByCommandById(Long id);
void deleteById(Long id);
}
| UTF-8 | Java | 403 | java | RecipeService.java | Java | [] | null | [] | package no.kristianped.recipe.services;
import no.kristianped.recipe.commands.RecipeCommand;
import no.kristianped.recipe.domain.Recipe;
import java.util.Set;
public interface RecipeService {
Set<Recipe> getRecipes();
Recipe findById(long anyLong);
RecipeCommand saveRecipeCommand(RecipeCommand command);
RecipeCommand findByCommandById(Long id);
void deleteById(Long id);
}
| 403 | 0.774194 | 0.774194 | 19 | 20.210526 | 20.67691 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 3 |
9285771067322424a5121f8e508e4fa8ada226ed | 20,117,626,822,494 | 98be0b0b5393349f2ea9338c8163b8fd82f07fcf | /BookLetter/src/com/lewisapp/bookletter/requestreview/RequestResult.java | db26e515a8f70a14cd25142bf64de1cf076aaa46 | [] | no_license | LewisLim579/BookLetter_EntireSource | https://github.com/LewisLim579/BookLetter_EntireSource | a925b885ebe81bb359d72af42c095cdfea448111 | 51f6cc042fc4d05c3d93b5161366b0fe2b22076f | refs/heads/master | 2022-08-27T18:12:19.546000 | 2022-07-31T04:45:28 | 2022-07-31T04:45:28 | 33,873,396 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lewisapp.bookletter.requestreview;
public class RequestResult {
String message;
}
| UTF-8 | Java | 99 | java | RequestResult.java | Java | [] | null | [] | package com.lewisapp.bookletter.requestreview;
public class RequestResult {
String message;
}
| 99 | 0.787879 | 0.787879 | 7 | 13.142858 | 16.685568 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 3 |
6f4aa920d26dbc8375b1eb8bd3f76b3da4aecafc | 22,462,679,021,097 | b2be5b45ba6dc2060bb79e38a5c355ff31d5560f | /src/main/java/com/citybank/adminapp/repository/charge/ChargeAccountTypeRepository.java | 781b213b6a36d0440f066c97ffb3ece2d7efd3de | [] | no_license | saifalam/reserveAdmin | https://github.com/saifalam/reserveAdmin | 6371625d22a7257fdc4b221328eda5dcd2096489 | bb54a32bdb670ed01845e0b55ec50015a56e94fc | refs/heads/master | 2020-03-29T12:15:08.218000 | 2015-07-09T19:49:24 | 2015-07-09T19:49:24 | 38,841,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.citybank.adminapp.repository.charge;
import com.citybank.adminapp.common.repository.BaseRepository;
import com.citybank.adminapp.model.entitymodel.charge.ChargeAccountTypeEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by BS23 on 6/18/14.
*/
@Repository
public class ChargeAccountTypeRepository extends BaseRepository<ChargeAccountTypeEntity> {
public List<ChargeAccountTypeEntity> getChargeAccountTypeEntityListByAccountType(int pageIndex,int itemAmount,int accountType) {
Session session = getSession();
int startPoint=(pageIndex-1)*itemAmount;
Query query= null;
if(accountType > 0 )
{
query =session.createQuery("From ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
}
else{
query =session.createQuery("From ChargeAccountTypeEntity WHERE IS_DELETE = 0");
}
query.setFirstResult(startPoint);
query.setMaxResults(itemAmount);
return query.list();
}
public List<ChargeAccountTypeEntity> getChargeAccountTypeEntityListByAccountType(int accountType) {
Session session = getSession();
Query query= null;
if(accountType > 0 )
{
query =session.createQuery("From ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
}
else{
query =session.createQuery("From ChargeAccountTypeEntity WHERE IS_DELETE = 0");
}
return query.list();
}
public List<ChargeAccountTypeEntity> getAllChargeAccountTypeEntity() {
Session session = getSession();
Query query =session.createQuery("From ChargeAccountTypeEntity WHERE IS_DELETE = 0");
return query.list();
}
public int getTotalChargeAccountType(int accountType) {
Session session = getSession();
Query query = null;
if(accountType > 0)
{
query=session.createQuery("SELECT COUNT(*) FROM ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
}
else{
query=session.createQuery("SELECT COUNT(*) FROM ChargeAccountTypeEntity WHERE IS_DELETE = 0");
}
int result=((Long)query.uniqueResult()).intValue();
return result;
}
public ChargeAccountTypeEntity getChargeAccountTypeEntityById(long id)
{
Session session = getSession();
Query query = session.createQuery("FROM ChargeAccountTypeEntity WHERE ID = :id AND IS_DELETE = 0");
query.setParameter("id",id);
return (ChargeAccountTypeEntity)query.uniqueResult();
}
public ChargeAccountTypeEntity getChargeAccountTypeEntityByAccountTypeAndSource(long accountType, String source) {
Session session = getSession();
Query query = session.createQuery("FROM ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND lower(SOURCE) = lower(:source) AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
query.setParameter("source",source);
return (ChargeAccountTypeEntity)query.uniqueResult();
}
}
| UTF-8 | Java | 3,404 | java | ChargeAccountTypeRepository.java | Java | [
{
"context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by BS23 on 6/18/14.\n */\n@Repository\npublic class ChargeAc",
"end": 347,
"score": 0.9993296265602112,
"start": 343,
"tag": "USERNAME",
"value": "BS23"
}
] | null | [] | package com.citybank.adminapp.repository.charge;
import com.citybank.adminapp.common.repository.BaseRepository;
import com.citybank.adminapp.model.entitymodel.charge.ChargeAccountTypeEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by BS23 on 6/18/14.
*/
@Repository
public class ChargeAccountTypeRepository extends BaseRepository<ChargeAccountTypeEntity> {
public List<ChargeAccountTypeEntity> getChargeAccountTypeEntityListByAccountType(int pageIndex,int itemAmount,int accountType) {
Session session = getSession();
int startPoint=(pageIndex-1)*itemAmount;
Query query= null;
if(accountType > 0 )
{
query =session.createQuery("From ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
}
else{
query =session.createQuery("From ChargeAccountTypeEntity WHERE IS_DELETE = 0");
}
query.setFirstResult(startPoint);
query.setMaxResults(itemAmount);
return query.list();
}
public List<ChargeAccountTypeEntity> getChargeAccountTypeEntityListByAccountType(int accountType) {
Session session = getSession();
Query query= null;
if(accountType > 0 )
{
query =session.createQuery("From ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
}
else{
query =session.createQuery("From ChargeAccountTypeEntity WHERE IS_DELETE = 0");
}
return query.list();
}
public List<ChargeAccountTypeEntity> getAllChargeAccountTypeEntity() {
Session session = getSession();
Query query =session.createQuery("From ChargeAccountTypeEntity WHERE IS_DELETE = 0");
return query.list();
}
public int getTotalChargeAccountType(int accountType) {
Session session = getSession();
Query query = null;
if(accountType > 0)
{
query=session.createQuery("SELECT COUNT(*) FROM ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
}
else{
query=session.createQuery("SELECT COUNT(*) FROM ChargeAccountTypeEntity WHERE IS_DELETE = 0");
}
int result=((Long)query.uniqueResult()).intValue();
return result;
}
public ChargeAccountTypeEntity getChargeAccountTypeEntityById(long id)
{
Session session = getSession();
Query query = session.createQuery("FROM ChargeAccountTypeEntity WHERE ID = :id AND IS_DELETE = 0");
query.setParameter("id",id);
return (ChargeAccountTypeEntity)query.uniqueResult();
}
public ChargeAccountTypeEntity getChargeAccountTypeEntityByAccountTypeAndSource(long accountType, String source) {
Session session = getSession();
Query query = session.createQuery("FROM ChargeAccountTypeEntity WHERE ACCOUNT_TYPE = :accountType AND lower(SOURCE) = lower(:source) AND IS_DELETE = 0");
query.setParameter("accountType",accountType);
query.setParameter("source",source);
return (ChargeAccountTypeEntity)query.uniqueResult();
}
}
| 3,404 | 0.68772 | 0.681845 | 83 | 40.012047 | 38.48877 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.60241 | false | false | 3 |
ba61882712ee913ed4cbe5b5317e2129314d1c08 | 33,182,917,377,819 | 69e90cc4032b3e51a35483418d2b53bf193dca4a | /src/java/compile/gen/java/StatementFormatter.java | 3c72a946089b0d215cabca2331c25c9ca4f079be | [
"MIT"
] | permissive | bhosmer/mesh | https://github.com/bhosmer/mesh | 6b0261940cfc2395a6a1fbf724302b180daddf16 | e8f7bca498a91d9fd447fa3ffe00f8d96fa01b1b | refs/heads/master | 2021-07-05T18:10:59.007000 | 2021-05-27T15:45:13 | 2021-05-27T15:45:13 | 9,678,847 | 7 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* ADOBE SYSTEMS INCORPORATED
* Copyright 2009-2013 Adobe Systems Incorporated
* All Rights Reserved.
* <p>
* NOTICE: Adobe permits you to use, modify, and distribute
* this file in accordance with the terms of the MIT license,
* a copy of which can be found in the LICENSE.txt file or at
* http://opensource.org/licenses/MIT.
*/
package compile.gen.java;
import compile.*;
import compile.Compiler;
import compile.gen.IntrinsicsResolver;
import compile.gen.Unit;
import compile.gen.UnitDictionary;
import compile.gen.java.inline.TermInliner;
import compile.module.Module;
import compile.module.Scope;
import compile.term.*;
import compile.term.visit.BindingVisitorBase;
import compile.type.*;
import compile.type.visit.TypeDumper;
import runtime.intrinsic._cond;
import runtime.rep.Record;
import runtime.rep.Tuple;
import runtime.rep.Lambda;
import runtime.intrinsic.IntrinsicLambda;
import runtime.rep.Variant;
import runtime.rep.list.ListValue;
import runtime.rep.list.PersistentList;
import runtime.rep.map.MapValue;
import runtime.rep.map.PersistentMap;
import java.util.*;
import static compile.parse.ApplyFlavor.StructAddr;
/**
* Formats terms into Java source expressions. Used for Javassist codegen.
* Note: what we're generating isn't quite legal Java--
* Javassist lets a few things past that javac doesn't like.
* (E.g. casts on top-level statements provoke "not a statement", and
* forward slashes are escaped in string literals.)
* So compiling source dumps almost works without edits but not quite.
* In the shell, $u dumps source to shell, $w dumps .java and .class files.
*/
public final class StatementFormatter extends BindingVisitorBase<String>
{
/**
* our compilation unit
*/
private final JavaUnit unit;
/**
* unit dictionary, used to resolve out-of-unit definitions
*/
private final UnitDictionary unitDictionary;
/**
* our current scope--our module if we're generating top-level code,
* or the current lambda. (we generate local functions out of line,
* so this is not a stack)
*/
private Scope currentScope;
/**
* 0 if we're generating top-level module code, 1 if we're in a lambda
* (see above comment)
*/
private int lambdaDepth;
/**
* current statement being generated
*/
private Statement currentStatement;
/**
* if true, we're currently generating expr code, even if
* {@link #currentStatement} is a non-result unbound term.
* Used by inliner to avoid generating mid-expr statement lists.
*/
private boolean inExpr;
/**
* map from symbol constants to generated field names
*/
private Map<SymbolLiteral, String> symbolConstants;
/**
* map from record types to generated keyset field names
*/
private Map<List<SimpleLiteralTerm>, String> keyListConstants;
/**
*
*/
private ArrayDeque<Class<?>> lvalueClassStack;
/**
*
*/
public StatementFormatter(
final JavaUnit unit,
final UnitDictionary unitDictionary)
{
this.unit = unit;
this.unitDictionary = unitDictionary;
this.currentScope = unit.getModule();
this.lambdaDepth = 0;
this.currentStatement = null;
this.inExpr = false;
this.symbolConstants = new HashMap<SymbolLiteral, String>();
this.keyListConstants = new HashMap<List<SimpleLiteralTerm>, String>();
this.lvalueClassStack = new ArrayDeque<Class<?>>();
}
/**
*
*/
public UnitDictionary getUnitDictionary()
{
return unitDictionary;
}
/**
* After generating constant bindings, {@link ModuleClassGenerator} installs
* them here. We don't generate these as bona fide bindings (and ref to them)
* earlier in the pipeline so that we're free to pick which constants to treat
* this way. E.g. when generating Java source we don't bother collecting
* number or string constants because we can just dump them into generated
* code.
*/
public void addSymbolConstant(final SymbolLiteral term, final String name)
{
symbolConstants.put(term, name);
}
public void addKeyListConstant(
final List<SimpleLiteralTerm> keySet,
final String name)
{
keyListConstants.put(keySet, name);
}
public boolean getInExpr()
{
return inExpr;
}
public Class<?> mapType(final Type type)
{
return TypeMapper.map(type);
}
public void setInExpr(final boolean inExpr)
{
this.inExpr = inExpr;
}
public Class<?> getLValueClass()
{
return lvalueClassStack.peek();
}
public void pushLValueClass(final Class<?> c)
{
lvalueClassStack.push(c);
}
public void popLValueClass()
{
lvalueClassStack.pop();
}
/**
* true if the current statement is an unbound value (i.e.,
* expr as statement) that is not providing the result of
* a lambda, and the given term is its value.
*/
public boolean isNonResultUnboundValue(final Term term)
{
if (!(currentStatement instanceof UnboundTerm))
return false;
if (term != ((UnboundTerm) currentStatement).getValue())
return false;
return currentScope instanceof Module ||
currentStatement != ((LambdaTerm) currentScope).getResultStatement();
}
/**
*
*/
public boolean statementsOkay(final ApplyTerm apply)
{
return !getInExpr() && isNonResultUnboundValue(apply);
}
// convenience
public String formatType(final Type type)
{
final Class<?> c = TypeMapper.map(type);
return formatClass(c);
}
private String formatClass(final Class<?> c)
{
final String name = c == Object[].class ? "Object[]" : c.getName();
return name.startsWith("java.lang.") ? c.getSimpleName() : name;
}
/**
* Generate Java code for statement.
* NOTE: assumes we're generating code for a lambda body, or some fragment that contains no
* bindings.
* Not suitable for top-level code containing bindings. For that use
* {@link #formatTopLevelStatement}.
*/
public String formatInLambdaStatement(final Statement statement)
{
final Statement save = currentStatement;
currentStatement = statement;
lambdaDepth++;
final String result =
statement.isBinding() ? visitBinding((Binding) statement) :
formatTermAs(((UnboundTerm) statement).getValue(), Object.class);
lambdaDepth--;
currentStatement = save;
return result;
}
/**
* Generate Java code for top-level term. Difference between top-level and lambda code is
* that value bindings are not declared inline, but are assumed to have been generated
* elsewhere.
* I.e. for var binding x = 5, it's the difference between lambda code
* <pre>
* class C { void f() { int x = 5; ... } }
* </pre>
* and top-level code
* <pre>
* class C { int x; C() { x = 5; } }
* </pre>
* For lambda code use {@link #formatInLambdaStatement}.
*/
public String formatTopLevelStatement(final Statement statement)
{
lambdaDepth = 0;
currentStatement = statement;
if (statement.isBinding())
{
return visitBinding((Binding) statement);
}
else if (statement instanceof UnboundTerm)
{
return formatTermAs(((UnboundTerm) statement).getValue(), Object.class);
}
else if (statement instanceof ImportStatement)
{
final ImportStatement importStatement = (ImportStatement) statement;
final Unit imported =
unitDictionary.getUnit(importStatement.getModuleName());
assert imported != null : "Imported unit not created";
if (!(imported instanceof JavaUnit))
{
Session.error(statement.getLoc(),
"import of non-Java unit not supported: {0}", statement.dump()
);
}
else
{
final ClassDef def = ((JavaUnit) imported).getModuleClassDef();
return def.getName() + "." + Constants.INSTANCE + ".run()";
}
}
return "";
}
/**
*
*/
public String fixup(final Loc loc, final String expr, final Type rtype)
{
return fixup(loc, expr, TypeMapper.map(rtype), getLValueClass());
}
/**
* reconcile incoming rvalue's type with lvalue context.
*/
public String fixup(
final Loc loc, final String expr, final Type rtype,
final Class<?> lclass)
{
return fixup(loc, expr, TypeMapper.map(rtype), lclass);
}
/**
*
*/
public String fixup(final Loc loc, final String expr, final Class<?> rclass)
{
return fixup(loc, expr, rclass, getLValueClass());
}
/**
*
*/
public String fixup(
final Loc loc, final String expr, final Class<?> rclass,
final Type ltype)
{
return fixup(loc, expr, rclass, TypeMapper.map(ltype));
}
/**
* reconcile incoming rvalue's rep class with lvalue context
*/
public String fixup(
final Loc loc, final String expr, final Class<?> rclass,
final Class<?> lclass)
{
if (lclass.isAssignableFrom(rclass))
{
// no cast needed
return expr;
}
final String result;
final String lclassName = formatClass(lclass);
final String rclassName = formatClass(rclass);
if (lclass.isPrimitive())
{
if (rclass.isPrimitive())
{
if (ClassUtils.canCastFromPrimToPrim(lclass, rclass))
{
result = "((" + formatClass(lclass) + ")" + expr + ")";
}
else
{
// any cross-primitive casting means typing went wrong upstream
Session.error(loc, "internal error: incompatible reps {0} := {1}",
lclassName, rclassName
);
result = expr;
}
}
else
{
// try unboxing rvalue to lclass
final Class<?> lbclass = ClassUtils.boxed(lclass);
if (lbclass.isAssignableFrom(rclass))
{
result = ClassUtils.unbox(expr, rclass);
}
else if (rclass.isAssignableFrom(lbclass))
{
final String castExpr =
"((" + formatClass(lbclass) + ")" + expr + ")";
result = ClassUtils.unbox(castExpr, lbclass);
}
else
{
Session.error(loc, "internal error: incompatible reps in {0} := {1}",
lclassName, rclassName
);
result = expr;
}
}
}
else if (rclass.isPrimitive())
{
// rtype must box to a subclass of ltype
if (!lclass.isAssignableFrom(ClassUtils.boxed(rclass)))
{
Session.error(loc, "internal error: incompatible reps {0} := {1}",
lclassName, rclassName
);
result = expr;
}
else
{
result = ClassUtils.box(expr, rclass);
}
}
else
{
// downcast if compatible
if (rclass.isAssignableFrom(lclass))
{
result = "((" + lclassName + ")" + expr + ")";
}
else
{
Session.error(loc, "internal error: incompatible reps {0} := {1}",
lclassName, rclassName
);
result = expr;
}
}
// if (Session.isDebug())
// Session.debug(loc,
// "fixup({0}, {1}) lclass = {2}, result = {3}",
// expr, rclassName, lclassName, result);
return result;
}
// TermVisitor
/**
*
*/
@Override
public String visitTerm(final Term term)
{
assert false;
return null;
}
/**
* format term, adding boxing and casting as necessary to make it
* compatible with the given representation class
*/
public String formatTermAs(final Term term, final Class<?> lclass)
{
pushLValueClass(lclass);
final String result = super.visitTerm(term);
popLValueClass();
return result;
}
/**
* format term, adding boxing and casting as necessary to make it
* compatible with the representation class for the given type.
*/
public String formatTermAs(final Term term, final Type ltype)
{
return formatTermAs(term, TypeMapper.map(ltype));
}
// BindingVisitor
/**
* ValueBindings produce different code depending on binding attributes
* and context.
* <ul>
* <li/>in lambda body code, all value bindings are handled inline.
* <li/>in top-level module code (which winds up in the constructor
* for the class that hosts the module state), all bindings have been
* declared as class fields, and constant bindings have been initialized.
* So in that case here we only generate updates to non-constant bindings.
* Note that this means (a) we may generate an empty statement, (b) final
* but non-constant top-level bindings can't be final fields in Java.
* </ul>
*/
@Override
public String visit(final LetBinding let)
{
final Type letType = let.getType();
final String lhs = lambdaDepth == 0 ? formatNameRef(let) :
// top-level, LHS assigns predeclared var
formatVarDeclLHS(let); // in lambda, LHS declares and assigns
final String rhs;
if (let.isIntrinsic())
{
if (Types.isFun(letType))
{
// Note: here we piggyback on the let initializer to install
// a prettyprint of an IntrinsicLambda's declared signature.
rhs = formatIntrinsicAsRHS(let) + ".setSigDump(\"" +
StringUtils.escapeJava(TypeDumper.dumpTypeParams(letType)) +
"\", \"" +
StringUtils.escapeJava(TypeDumper.dumpWithoutParams(letType)) +
"\")";
}
else
{
rhs = formatIntrinsicAsRHS(let);
}
}
else
{
// for non intrinsics, generate code for the RHS
rhs = formatTermAs(let.getValue(), TypeMapper.map(letType));
}
return lhs + " = " + rhs;
}
/**
* factored for external use
*/
public String formatVarDeclLHS(final LetBinding let)
{
return "final " + formatTypeName(let) + " " + formatNameRef(let);
}
/**
* when we have a lambda term available, we can use the lambda's java class
* as a type in generate generated code. Otherwise we go with generic type name.
*/
public String formatTypeName(final ValueBinding binding)
{
if (binding.isLet())
{
final Term rhs = binding.getValue();
if (rhs instanceof LambdaTerm)
return unit.ensureLambdaClassName((LambdaTerm) rhs, unitDictionary);
}
return formatType(binding.getType());
}
/**
*
*/
@Override
public String visit(final ParamBinding param)
{
return formatType(param.getType()) + " " + formatName(param.getName());
}
// TermVisitor
/**
* Format a name reference
*/
@Override
public String visit(final RefTerm ref)
{
// now we have a chance to constant-propagate refs to intrinsics
final ValueBinding binding = ref.getBinding();
if (binding.isLet())
{
final LetBinding let = (LetBinding) binding;
if (let.isIntrinsic())
return formatIntrinsicAsRHS(let);
}
return fixup(ref.getLoc(), formatNameRef(binding), ref.getType());
}
/**
* Helper - formats a binding name as a reference expression -
* qualifies globals defined outside the scope from which the
* reference is being made. (We only need to qualify globals--
* any out-of-scope lambdas will have been captured
* in a closure.)
* Note: package local, used by class generators.
*/
String formatNameRef(final ValueBinding binding)
{
final Scope bindingScope = binding.getScope();
if (bindingScope instanceof Module && bindingScope != currentScope)
{
// qualify top-level (i.e., module not lambda) bindings
// from outside refScope
final Module bindingModule = (Module) bindingScope;
// find the binding's unit.
// TODO should use a bidi map or something instead of lookup
final Unit bindingUnit = (bindingModule == unit.getModule()) ? unit :
Compiler.getUnitDictionary().getUnit(bindingModule.getName());
if (!(bindingUnit instanceof JavaUnit))
{
Session.error(
binding.getLoc(),
"references to non-Java bindings not supported: {0}",
binding.dump()
);
return formatName(binding.getName()); // error, unqualified
}
else
{
// Note: we have to actually use the class name if it's there,
// as it might be nonstandard for intrinsics.
final ClassDef moduleClassDef =
((JavaUnit) bindingUnit).getModuleClassDef();
// But it might not be there, e.g. if we're generating a lambda
// class before its defining module class.
final String moduleNameRef =
(moduleClassDef != null ? moduleClassDef.getName() :
ModuleClassGenerator.qualifiedModuleClassName(bindingModule)) +
"." + Constants.INSTANCE;
return moduleNameRef + "." + formatName(binding.getName());
}
}
else
{
// catch self-reference in lambda
if (binding.isLet())
{
final LetBinding let = (LetBinding) binding;
if (!let.isIntrinsic() && let.getValue() == currentScope)
{
// if we have no captured lambda bindings, we're in
// a static method and must use INSTANCE object.
// otherwise can just pass ourselves
return ((LambdaTerm) currentScope).hasCapturedLambdaBindings() ?
"this" : Constants.INSTANCE;
}
}
return formatName(binding.getName());
}
}
private IntrinsicLambda getIntrinsic(final LetBinding let)
{
final IntrinsicLambda intrinsic = IntrinsicsResolver.resolve(let);
assert intrinsic != null : "Intrinsic should have been previously resolved";
return intrinsic;
}
/**
* Here we access special knowledge about how to go from an intrinsic
* let binding in the current scope, to a compatible value in the
* underlying Java environment
*/
public String formatIntrinsicAsRHS(final LetBinding let)
{
final IntrinsicLambda intrinsic = getIntrinsic(let);
return intrinsic.getClass().getName() + "." + Constants.INSTANCE;
}
/**
* Because we're generating Java source, we have to stay away
* from Java keywords. A simple, fast but still relatively
* readable way to do this is just to tack on an underscore
* to every name. (Of course doing BC gen we won't need to do this,
* but then again we won't be able to read the generated code either.)
*/
public static String formatName(final String name)
{
return "_" + name;
}
/**
*
*/
public String visit(final ParamValue paramValue)
{
assert false : "undigested param value in codegen";
return null;
}
/**
* Generate Java source expression denoting a boolean literal.
*/
@Override
public String visit(final BoolLiteral boolLiteral)
{
final String expr = boolLiteral.getValue() ? "true" : "false";
return fixup(boolLiteral.getLoc(), expr, Types.BOOL);
}
/**
* Generate Java source expression denoting a natural number literal.
*/
@Override
public String visit(final IntLiteral intLiteral)
{
final String expr = "" + intLiteral.getValue();
return fixup(intLiteral.getLoc(), expr, Types.INT);
}
/**
* Generate Java source expression denoting a long number literal.
*/
public String visit(final LongLiteral longLiteral)
{
final String expr = "" + longLiteral.getValue() + "L";
return fixup(longLiteral.getLoc(), expr, Types.LONG);
}
/**
* Generate Java source expression denoting a floating point number literal.
*/
@Override
public String visit(final DoubleLiteral doubleLiteral)
{
final double value = doubleLiteral.getValue();
final String expr = Double.isNaN(value) ? "Double.NaN" : ("" + value);
return fixup(doubleLiteral.getLoc(), expr, Types.DOUBLE);
}
/**
* Generate Java source expression denoting a string literal.
*/
@Override
public String visit(final StringLiteral stringLiteral)
{
final String expr =
"\"" + StringUtils.escapeJava(stringLiteral.getValue()) + "\"";
return fixup(stringLiteral.getLoc(), expr, Types.STRING);
}
/**
* Generate Java source expression denoting a Symbol literal.
* We use pregenerated constants stashed in fields.
*/
@Override
public String visit(final SymbolLiteral symbolLiteral)
{
final String constant = symbolConstants.get(symbolLiteral);
final Loc loc = symbolLiteral.getLoc();
if (constant != null)
return fixup(loc, constant, Types.SYMBOL);
final String expr =
formatType(Types.SYMBOL) + ".get(\"" + symbolLiteral.getValue() + "\")";
return fixup(loc, expr, Types.SYMBOL);
}
/**
* Generate Java source expression to produce a List as specified by a literal term.
*/
@Override
public String visit(final ListTerm list)
{
final String listClassName = PersistentList.class.getName();
// format
final String expr;
final List<Term> items = list.getItems();
if (items.isEmpty())
{
expr = listClassName + ".EMPTY";
}
else
{
final StringBuilder buf = new StringBuilder(listClassName).
append(".alloc(").append(items.size()).append(")");
int i = 0;
for (final Term item : items)
{
final String itemExpr = formatTermAs(item, Object.class);
buf.append(".updateUnsafe").append("(").
append(i).append(", ").
append(itemExpr).append(")");
i++;
}
expr = buf.toString();
}
return fixup(list.getLoc(), expr, list.getType());
}
/**
* Generate Java source expression to produce a Map as specified by a literal term.
* Note that we produce an unversioned map.
*/
@Override
public String visit(final MapTerm map)
{
final StringBuilder buf;
final Iterator<Map.Entry<Term, Term>> iter =
map.getItems().entrySet().iterator();
if (!iter.hasNext())
{
buf = new StringBuilder(PersistentMap.class.getName()).append(".EMPTY");
}
else
{
Map.Entry<Term, Term> entry = iter.next();
final String fkey = formatTermAs(entry.getKey(), Object.class);
final String fval = formatTermAs(entry.getValue(), Object.class);
buf = new StringBuilder(PersistentMap.class.getName()).
append(".single(").append(fkey).append(", ").append(fval).append(")");
while (iter.hasNext())
{
entry = iter.next();
final String nkey = formatTermAs(entry.getKey(), Object.class);
final String nval = formatTermAs(entry.getValue(), Object.class);
buf.append(".assocUnsafe(").
append(nkey).append(", ").append(nval).append(")");
}
}
return fixup(map.getLoc(), buf.toString(), map.getType());
}
/**
* Generate Java source expression denoting a Tuple as specified by a literal term
*/
@Override
public String visit(final TupleTerm tuple)
{
final List<String> formatted = new ArrayList<String>();
final List<Term> items = tuple.getItems();
final String expr;
if (items.size() == 0)
{
expr = Tuple.class.getName() + ".UNIT";
}
else
{
for (final Term term : items)
formatted.add(formatTermAs(term, Object.class));
expr = Tuple.class.getName() + ".from(" +
formatObjectArrayLiteral(formatted) + ")";
}
return fixup(tuple.getLoc(), expr, Tuple.class);
}
/**
* Generate Java source expression denoting a Record as specified by a literal term
*/
@Override
public String visit(final RecordTerm record)
{
final List<SimpleLiteralTerm> keyList = record.getKeyList();
// get keyset field name
final String keyListField = keyListConstants.get(keyList);
if (keyListField == null)
assert false :
"missing key list field for " + DumpUtils.dumpList(keyList);
// generate value exprs
final List<String> valueExprs = new ArrayList<String>();
{
final Map<Term, Term> valueMap = record.getItems();
// important: since record types are permutation groups,
// must guarantee that terms are in symbol order.
for (final SimpleLiteralTerm key : keyList)
{
final Term value = valueMap.get(key);
valueExprs.add(formatTermAs(value, Object.class));
}
}
final String expr =
Record.class.getName() + ".from(" + keyListField + ", " +
formatObjectArrayLiteral(valueExprs) + ")";
return fixup(record.getLoc(), expr, record.getType());
}
/**
* Helper - generate Java source for an Object array constructor call.
* Complicated by a Javassist bug that rejects Object[]{}
*/
public String formatObjectArrayLiteral(
final Collection<String> formattedItems)
{
final StringBuilder buf = new StringBuilder().
append("new ").
append(Constants.OBJECT);
if (formattedItems.size() > 0)
{
buf.append("[]{").
append(StringUtils.join(formattedItems, ", ")).
append("}");
}
else
{
buf.append("[0]");
}
return buf.toString();
}
/**
* Generate Java source expression denoting a Variant as specified by a literal term
*/
@Override
public String visit(final VariantTerm var)
{
final String keyExpr = formatTermAs(var.getKey(), Object.class);
final String valExpr = formatTermAs(var.getValue(), Object.class);
final String expr =
"(new " + Variant.class.getName() + "(" + keyExpr + ", " + valExpr +
"))";
return fixup(var.getLoc(), expr, var.getType());
}
/**
* Generate Java source expression denoting a Variant as specified by a literal term
*/
@Override
public String visit(final CondTerm cond)
{
final String selExpr = formatTermAs(cond.getSel(), Variant.class);
final String casesExpr = formatTermAs(cond.getCases(), Record.class);
final String expr =
_cond.class.getName() + "." + Constants.INVOKE + "(" + selExpr + ", " +
casesExpr + ")";
return fixup(cond.getLoc(), expr, cond.getType());
}
/**
* Generate a Java expression constructing a lambda term.
*/
@Override
public String visit(final LambdaTerm lambda)
{
// we may be generating lambda class def here for the first time - push scope
final Scope prevScope = currentScope;
currentScope = lambda;
final ClassDef classDef = unit.ensureLambdaClassDef(lambda, this);
currentScope = prevScope;
// generate constructor call for lambda class -
// may need to pass captured variable initializers
final String expr;
if (lambda.hasCapturedLambdaBindings())
{
final Collection<ValueBinding> capturedBindings =
lambda.getCapturedLambdaBindings().values();
final List<String> ctorParams =
new ArrayList<String>(capturedBindings.size());
for (final ValueBinding binding : capturedBindings)
ctorParams.add(formatNameRef(binding));
expr = "new " + classDef.getName() + "(" +
StringUtils.join(ctorParams, ", ") + ")";
}
else
{
expr = classDef.getName() + "." + Constants.INSTANCE;
}
return fixup(lambda.getLoc(), expr, lambda.getType());
}
/**
* ApplyTerms include function invocations, collection lookups and structure member accesses.
*/
@Override
public String visit(final ApplyTerm apply)
{
final Term baseTerm = apply.getBase();
final Term argTerm = apply.getArg();
final Type baseType = baseTerm.getType().deref();
switch (apply.getFlav())
{
case FuncApp:
{
// calls to nominal type constructors are no-ops
final String instance = tryNominalCoerces(baseTerm, argTerm);
if (instance != null)
return instance;
// try to optimize based on a lambda dereference
final String invokeExpr = tryLambdaDeref(apply);
if (invokeExpr != null)
return invokeExpr;
return formatLambdaApplyTerm(baseTerm, argTerm);
}
case CollIndex:
{
if (Types.isList(baseType))
return formatListApplyTerm(apply);
if (Types.isMap(baseType))
return formatMapApplyTerm(apply);
Session.error(apply.getLoc(),
"internal error: invalid base term {0} : {1} in collection index expression " +
"{2}",
baseTerm.dump(), baseType.dump(), apply.dump()
);
break;
}
case StructAddr:
{
if (Types.isTup(baseType) || Types.isPolyTup(baseType))
return formatTupleApplyTerm(apply);
if (Types.isRec(baseType))
return formatRecordApplyTerm(apply);
if (Types.isPolyRec(baseType))
return formatPolyRecordApplyTerm(apply);
Session.error(apply.getLoc(),
"internal error: invalid base term {0} : {1} in structure address expression " +
"{2}",
baseTerm.dump(),
baseType.dump(),
apply.dump()
);
break;
}
default:
Session.error(
apply.getLoc(),
"internal error: unknown application flavor in expression {0}",
apply.dump()
);
break;
}
return null;
}
/**
* application on a list is positional lookup.
*/
private String formatListApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
final String expr = formatTermAs(base, ListValue.class) + ".get(" +
formatTermAs(arg, int.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* application on a map is key lookup.
*/
private String formatMapApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
final String expr = formatTermAs(base, MapValue.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* application on a tuple is positional member access.
*/
public String formatTupleApplyTerm(final ApplyTerm apply)
{
final Term arg = apply.getArg();
final Term base = apply.getBase();
assert arg.getType() == Types.INT;
{
final Term argDeref =
arg instanceof RefTerm ? ((RefTerm) arg).deref() : arg;
assert argDeref.isConstant();
}
final String expr = formatTermAs(base, Tuple.class) + ".get(" +
formatTermAs(arg, int.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* application on a record is keyed member access.
*/
private String formatRecordApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
{
final Term argDeref =
arg instanceof RefTerm ? ((RefTerm) arg).deref() : arg;
assert argDeref.isConstant();
}
final String expr;
final Type baseType = base.getType().deref();
if (Types.isRec(baseType))
{
final List<SimpleLiteralTerm> keyList = Types.recKeyList(baseType);
final int pos = keyList.indexOf(arg);
if (pos < keyList.size())
{
// positional lookup
expr = formatTermAs(base, Record.class) + ".getValue(" + pos + ")";
}
else
{
Session.error(apply.getLoc(),
"internal error: arg {0} not found in key list {1}", arg.dump(),
DumpUtils.dumpList(keyList)
);
// name lookup as error fallback
expr = formatTermAs(base, Record.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
}
}
else
{
// name lookup
expr = formatTermAs(base, Record.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
}
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* TODO move to ohori hidden params for poly rec access
*/
private String formatPolyRecordApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
final Type applyType = apply.getType();
if (Types.isVar(applyType))
Session.error(
apply.getLoc(),
"internal error: dynamic record access not currently supported"
);
{
final Term argDeref =
arg instanceof RefTerm ? ((RefTerm) arg).deref() : arg;
assert argDeref.isConstant();
}
// name lookup for now, see comment
final String expr = formatTermAs(base, Record.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* generate an application (tupled params), available for any lambda
*/
private String formatLambdaApplyTerm(final Term base, final Term arg)
{
final String expr =
formatTermAs(base, Lambda.class) + "." + Constants.APPLY + "(" +
formatTermAs(arg, Object.class) + ")";
return fixup(base.getLoc(), expr, Object.class);
}
/**
* Type constructors, destructors are no-ops. If we're applying
* one, just drill through to the underlying argument.
* TODO something less spidery for detecting these?
*/
private String tryNominalCoerces(final Term base, final Term arg)
{
if (!(base instanceof RefTerm))
return null;
final RefTerm baseRef = (RefTerm) base;
if (!baseRef.getBinding().isLet())
return null;
final LetBinding baseLet = (LetBinding) baseRef.getBinding();
if (baseLet.isIntrinsic() || !(baseLet.getValue() instanceof LambdaTerm))
return null;
final LambdaTerm lambda = (LambdaTerm) baseLet.getValue();
final Type lambdaType = lambda.getType();
final Type paramType = Types.funParam(lambdaType).deref();
final Type resultType = Types.funResult(lambdaType).deref();
if (paramType instanceof TypeDef)
{
// if param type is nominal, check for type dtor
final TypeDef paramDef = (TypeDef) paramType;
if (!paramDef.isNominal())
return null;
if (lambda != paramDef.getDtorLet().getValue())
return null;
return formatTermAs(arg, arg.getType());
}
else if (resultType instanceof TypeDef)
{
// if result type is nominal, check for type ctor
final TypeDef resultDef = (TypeDef) resultType;
if (!resultDef.isNominal())
return null;
if (lambda != resultDef.getCtorLet().getValue())
return null;
return formatTermAs(arg, arg.getType());
}
return null;
}
/**
* try things based on derefing the lambda:
* 0. inline some obvious stuff--direct conditionals, etc.
* 1. generate an invocation with scattered params if we can - which means
* when we have a specific Java signature for invoke(). Currently this
* is true when our base term resolves to a specific Java implementation
* class (so e.g. not a param ref), and that implementation has invoke()
* NOTE several early returns
*/
private String tryLambdaDeref(final ApplyTerm apply)
{
final Loc loc = apply.getLoc();
final Term base = apply.getBase();
final Type baseType = base.getType().eval();
assert Types.isFun(baseType);
final Term arg = apply.getArg();
final Type argType = arg.getType();
// note that we don't simply take the result type of the application.
// our generated code must deal with the unspecialized java type
// produced by the polymorphic function.
final Type resultType = Types.funResult(baseType);
final Type paramType = Types.funParam(baseType);
final InvokeInfo info = getInvokeInfo(base);
if (info == null)
return null;
// format base expr
final String invokeBase;
if (info.className != null)
{
// non-null class name means this is not a closure,
// so we have a static invoke()
// NOTE: early return if we inline successfully
final String inlined = TermInliner.tryInlining(apply, info, this);
if (inlined != null)
{
if (Session.isDebug())
Session.debug(loc, "inlined: {0} => {1}", apply.dump(), inlined);
return inlined;
}
// NOTE: visit base term even if we use class name directly,
// to trigger code gen
formatTermAs(base, baseType);
invokeBase = info.className + "." + Constants.INVOKE;
}
else
{
invokeBase = formatTermAs(base, baseType) + "." + Constants.INVOKE;
}
// format call
if (info.mode == InvokeInfo.InvokeMode.Scatter)
{
final String expr;
final List<Type> paramTypes =
((TypeList) Types.tupMembers(paramType).deref()).getItems();
final List<String> formatted = new ArrayList<String>();
if (arg instanceof TupleTerm)
{
// argument is a tuple literal - just pass individual members
final List<Term> args = ((TupleTerm) arg).getItems();
for (int i = 0; i < paramTypes.size(); i++)
formatted.add(formatTermAs(args.get(i), paramTypes.get(i)));
expr = invokeBase + "(" + StringUtils.join(formatted, ", ") + ")";
}
else if (arg instanceof RefTerm)
{
// if base is a simple ref term, call invoke with a scatter list
assert Types.isTup(argType);
final Type members = Types.tupMembers(argType);
assert members instanceof TypeList;
final Loc argLoc = arg.getLoc();
final List<Type> argTypes = ((TypeList) members).getItems();
for (int i = 0; i < paramTypes.size(); i++)
{
final ApplyTerm accessTerm =
new ApplyTerm(argLoc, arg, new IntLiteral(argLoc, i), StructAddr);
accessTerm.setType(argTypes.get(i));
formatted.add(formatTermAs(accessTerm, paramTypes.get(i)));
}
expr = invokeBase + "(" + StringUtils.join(formatted, ", ") + ")";
}
else
{
// NOTE: more elaborate strategies (temp assignments, etc.)
// don't seem to pay, so keeping things simple here.
return null;
}
// invoke result is strongly typed
return fixup(loc, expr, resultType);
}
else
{
final String expr = invokeBase + "(" + formatTermAs(arg, paramType) + ")";
return fixup(loc, expr, resultType);
}
}
/**
* Build an info packet to facilitate some simple optimizations, if the
* base term (of an application) can be dereferenced to a particular lambda,
* rather than a param.
* 1. In addition to the canonical apply(arg), Lambdas implement invoke(), which
* takes a scattered argument list. We want to call that if we can.
* 2. In non-closure Lambdas, the invoke() is static, so we can call with a
* direct reference to the Lambda's classname.
*/
public InvokeInfo getInvokeInfo(final Term base)
{
if (base instanceof LambdaTerm)
{
final LambdaTerm baseLambda = (LambdaTerm) base;
// this ensures a stable class name, but doesn't generate code
final String className =
unit.ensureLambdaClassName(baseLambda, unitDictionary);
// can scatter if num args != 1
final InvokeInfo.InvokeMode mode =
baseLambda.getParams().size() == 1 ? InvokeInfo.InvokeMode.NoScatter :
InvokeInfo.InvokeMode.Scatter;
// if no captured bindings, can call static invoke() directly
return new InvokeInfo(baseLambda, mode,
baseLambda.hasCapturedLambdaBindings() ? null : className
);
}
else if (base instanceof RefTerm)
{
// track down ref
final ValueBinding binding = ((RefTerm) base).getBinding();
if (binding.isLet())
{
// let binding, as opposed to a param binding
final LetBinding let = (LetBinding) binding;
if (let.isIntrinsic())
{
final IntrinsicLambda intrinsic = getIntrinsic(let);
final String lambdaClass = intrinsic.getClass().getName();
final Type baseType = base.getType().deref();
if (Types.isFun(baseType))
{
final Type paramType = Types.funParam(baseType);
if (Types.isTup(paramType) &&
Types.tupMembers(paramType) instanceof TypeList)
{
// scatter calls to non-variadic multi-arg functions
return new InvokeInfo(null, InvokeInfo.InvokeMode.Scatter,
lambdaClass
);
}
else
{
// otherwise, intrinsic takes a single argument
return new InvokeInfo(null, InvokeInfo.InvokeMode.NoScatter,
lambdaClass
);
}
}
// should be an assert? calling an intrinsic with non-function type?
return null;
}
else
{
// non-intrinsic, check RHS
return getInvokeInfo(let.getValue());
}
}
}
return null;
}
/**
*
*/
@Override
public String visit(final CoerceTerm coerce)
{
return formatTermAs(coerce.getTerm(), coerce.getType());
}
}
| UTF-8 | Java | 46,256 | java | StatementFormatter.java | Java | [] | null | [] | /**
* ADOBE SYSTEMS INCORPORATED
* Copyright 2009-2013 Adobe Systems Incorporated
* All Rights Reserved.
* <p>
* NOTICE: Adobe permits you to use, modify, and distribute
* this file in accordance with the terms of the MIT license,
* a copy of which can be found in the LICENSE.txt file or at
* http://opensource.org/licenses/MIT.
*/
package compile.gen.java;
import compile.*;
import compile.Compiler;
import compile.gen.IntrinsicsResolver;
import compile.gen.Unit;
import compile.gen.UnitDictionary;
import compile.gen.java.inline.TermInliner;
import compile.module.Module;
import compile.module.Scope;
import compile.term.*;
import compile.term.visit.BindingVisitorBase;
import compile.type.*;
import compile.type.visit.TypeDumper;
import runtime.intrinsic._cond;
import runtime.rep.Record;
import runtime.rep.Tuple;
import runtime.rep.Lambda;
import runtime.intrinsic.IntrinsicLambda;
import runtime.rep.Variant;
import runtime.rep.list.ListValue;
import runtime.rep.list.PersistentList;
import runtime.rep.map.MapValue;
import runtime.rep.map.PersistentMap;
import java.util.*;
import static compile.parse.ApplyFlavor.StructAddr;
/**
* Formats terms into Java source expressions. Used for Javassist codegen.
* Note: what we're generating isn't quite legal Java--
* Javassist lets a few things past that javac doesn't like.
* (E.g. casts on top-level statements provoke "not a statement", and
* forward slashes are escaped in string literals.)
* So compiling source dumps almost works without edits but not quite.
* In the shell, $u dumps source to shell, $w dumps .java and .class files.
*/
public final class StatementFormatter extends BindingVisitorBase<String>
{
/**
* our compilation unit
*/
private final JavaUnit unit;
/**
* unit dictionary, used to resolve out-of-unit definitions
*/
private final UnitDictionary unitDictionary;
/**
* our current scope--our module if we're generating top-level code,
* or the current lambda. (we generate local functions out of line,
* so this is not a stack)
*/
private Scope currentScope;
/**
* 0 if we're generating top-level module code, 1 if we're in a lambda
* (see above comment)
*/
private int lambdaDepth;
/**
* current statement being generated
*/
private Statement currentStatement;
/**
* if true, we're currently generating expr code, even if
* {@link #currentStatement} is a non-result unbound term.
* Used by inliner to avoid generating mid-expr statement lists.
*/
private boolean inExpr;
/**
* map from symbol constants to generated field names
*/
private Map<SymbolLiteral, String> symbolConstants;
/**
* map from record types to generated keyset field names
*/
private Map<List<SimpleLiteralTerm>, String> keyListConstants;
/**
*
*/
private ArrayDeque<Class<?>> lvalueClassStack;
/**
*
*/
public StatementFormatter(
final JavaUnit unit,
final UnitDictionary unitDictionary)
{
this.unit = unit;
this.unitDictionary = unitDictionary;
this.currentScope = unit.getModule();
this.lambdaDepth = 0;
this.currentStatement = null;
this.inExpr = false;
this.symbolConstants = new HashMap<SymbolLiteral, String>();
this.keyListConstants = new HashMap<List<SimpleLiteralTerm>, String>();
this.lvalueClassStack = new ArrayDeque<Class<?>>();
}
/**
*
*/
public UnitDictionary getUnitDictionary()
{
return unitDictionary;
}
/**
* After generating constant bindings, {@link ModuleClassGenerator} installs
* them here. We don't generate these as bona fide bindings (and ref to them)
* earlier in the pipeline so that we're free to pick which constants to treat
* this way. E.g. when generating Java source we don't bother collecting
* number or string constants because we can just dump them into generated
* code.
*/
public void addSymbolConstant(final SymbolLiteral term, final String name)
{
symbolConstants.put(term, name);
}
public void addKeyListConstant(
final List<SimpleLiteralTerm> keySet,
final String name)
{
keyListConstants.put(keySet, name);
}
public boolean getInExpr()
{
return inExpr;
}
public Class<?> mapType(final Type type)
{
return TypeMapper.map(type);
}
public void setInExpr(final boolean inExpr)
{
this.inExpr = inExpr;
}
public Class<?> getLValueClass()
{
return lvalueClassStack.peek();
}
public void pushLValueClass(final Class<?> c)
{
lvalueClassStack.push(c);
}
public void popLValueClass()
{
lvalueClassStack.pop();
}
/**
* true if the current statement is an unbound value (i.e.,
* expr as statement) that is not providing the result of
* a lambda, and the given term is its value.
*/
public boolean isNonResultUnboundValue(final Term term)
{
if (!(currentStatement instanceof UnboundTerm))
return false;
if (term != ((UnboundTerm) currentStatement).getValue())
return false;
return currentScope instanceof Module ||
currentStatement != ((LambdaTerm) currentScope).getResultStatement();
}
/**
*
*/
public boolean statementsOkay(final ApplyTerm apply)
{
return !getInExpr() && isNonResultUnboundValue(apply);
}
// convenience
public String formatType(final Type type)
{
final Class<?> c = TypeMapper.map(type);
return formatClass(c);
}
private String formatClass(final Class<?> c)
{
final String name = c == Object[].class ? "Object[]" : c.getName();
return name.startsWith("java.lang.") ? c.getSimpleName() : name;
}
/**
* Generate Java code for statement.
* NOTE: assumes we're generating code for a lambda body, or some fragment that contains no
* bindings.
* Not suitable for top-level code containing bindings. For that use
* {@link #formatTopLevelStatement}.
*/
public String formatInLambdaStatement(final Statement statement)
{
final Statement save = currentStatement;
currentStatement = statement;
lambdaDepth++;
final String result =
statement.isBinding() ? visitBinding((Binding) statement) :
formatTermAs(((UnboundTerm) statement).getValue(), Object.class);
lambdaDepth--;
currentStatement = save;
return result;
}
/**
* Generate Java code for top-level term. Difference between top-level and lambda code is
* that value bindings are not declared inline, but are assumed to have been generated
* elsewhere.
* I.e. for var binding x = 5, it's the difference between lambda code
* <pre>
* class C { void f() { int x = 5; ... } }
* </pre>
* and top-level code
* <pre>
* class C { int x; C() { x = 5; } }
* </pre>
* For lambda code use {@link #formatInLambdaStatement}.
*/
public String formatTopLevelStatement(final Statement statement)
{
lambdaDepth = 0;
currentStatement = statement;
if (statement.isBinding())
{
return visitBinding((Binding) statement);
}
else if (statement instanceof UnboundTerm)
{
return formatTermAs(((UnboundTerm) statement).getValue(), Object.class);
}
else if (statement instanceof ImportStatement)
{
final ImportStatement importStatement = (ImportStatement) statement;
final Unit imported =
unitDictionary.getUnit(importStatement.getModuleName());
assert imported != null : "Imported unit not created";
if (!(imported instanceof JavaUnit))
{
Session.error(statement.getLoc(),
"import of non-Java unit not supported: {0}", statement.dump()
);
}
else
{
final ClassDef def = ((JavaUnit) imported).getModuleClassDef();
return def.getName() + "." + Constants.INSTANCE + ".run()";
}
}
return "";
}
/**
*
*/
public String fixup(final Loc loc, final String expr, final Type rtype)
{
return fixup(loc, expr, TypeMapper.map(rtype), getLValueClass());
}
/**
* reconcile incoming rvalue's type with lvalue context.
*/
public String fixup(
final Loc loc, final String expr, final Type rtype,
final Class<?> lclass)
{
return fixup(loc, expr, TypeMapper.map(rtype), lclass);
}
/**
*
*/
public String fixup(final Loc loc, final String expr, final Class<?> rclass)
{
return fixup(loc, expr, rclass, getLValueClass());
}
/**
*
*/
public String fixup(
final Loc loc, final String expr, final Class<?> rclass,
final Type ltype)
{
return fixup(loc, expr, rclass, TypeMapper.map(ltype));
}
/**
* reconcile incoming rvalue's rep class with lvalue context
*/
public String fixup(
final Loc loc, final String expr, final Class<?> rclass,
final Class<?> lclass)
{
if (lclass.isAssignableFrom(rclass))
{
// no cast needed
return expr;
}
final String result;
final String lclassName = formatClass(lclass);
final String rclassName = formatClass(rclass);
if (lclass.isPrimitive())
{
if (rclass.isPrimitive())
{
if (ClassUtils.canCastFromPrimToPrim(lclass, rclass))
{
result = "((" + formatClass(lclass) + ")" + expr + ")";
}
else
{
// any cross-primitive casting means typing went wrong upstream
Session.error(loc, "internal error: incompatible reps {0} := {1}",
lclassName, rclassName
);
result = expr;
}
}
else
{
// try unboxing rvalue to lclass
final Class<?> lbclass = ClassUtils.boxed(lclass);
if (lbclass.isAssignableFrom(rclass))
{
result = ClassUtils.unbox(expr, rclass);
}
else if (rclass.isAssignableFrom(lbclass))
{
final String castExpr =
"((" + formatClass(lbclass) + ")" + expr + ")";
result = ClassUtils.unbox(castExpr, lbclass);
}
else
{
Session.error(loc, "internal error: incompatible reps in {0} := {1}",
lclassName, rclassName
);
result = expr;
}
}
}
else if (rclass.isPrimitive())
{
// rtype must box to a subclass of ltype
if (!lclass.isAssignableFrom(ClassUtils.boxed(rclass)))
{
Session.error(loc, "internal error: incompatible reps {0} := {1}",
lclassName, rclassName
);
result = expr;
}
else
{
result = ClassUtils.box(expr, rclass);
}
}
else
{
// downcast if compatible
if (rclass.isAssignableFrom(lclass))
{
result = "((" + lclassName + ")" + expr + ")";
}
else
{
Session.error(loc, "internal error: incompatible reps {0} := {1}",
lclassName, rclassName
);
result = expr;
}
}
// if (Session.isDebug())
// Session.debug(loc,
// "fixup({0}, {1}) lclass = {2}, result = {3}",
// expr, rclassName, lclassName, result);
return result;
}
// TermVisitor
/**
*
*/
@Override
public String visitTerm(final Term term)
{
assert false;
return null;
}
/**
* format term, adding boxing and casting as necessary to make it
* compatible with the given representation class
*/
public String formatTermAs(final Term term, final Class<?> lclass)
{
pushLValueClass(lclass);
final String result = super.visitTerm(term);
popLValueClass();
return result;
}
/**
* format term, adding boxing and casting as necessary to make it
* compatible with the representation class for the given type.
*/
public String formatTermAs(final Term term, final Type ltype)
{
return formatTermAs(term, TypeMapper.map(ltype));
}
// BindingVisitor
/**
* ValueBindings produce different code depending on binding attributes
* and context.
* <ul>
* <li/>in lambda body code, all value bindings are handled inline.
* <li/>in top-level module code (which winds up in the constructor
* for the class that hosts the module state), all bindings have been
* declared as class fields, and constant bindings have been initialized.
* So in that case here we only generate updates to non-constant bindings.
* Note that this means (a) we may generate an empty statement, (b) final
* but non-constant top-level bindings can't be final fields in Java.
* </ul>
*/
@Override
public String visit(final LetBinding let)
{
final Type letType = let.getType();
final String lhs = lambdaDepth == 0 ? formatNameRef(let) :
// top-level, LHS assigns predeclared var
formatVarDeclLHS(let); // in lambda, LHS declares and assigns
final String rhs;
if (let.isIntrinsic())
{
if (Types.isFun(letType))
{
// Note: here we piggyback on the let initializer to install
// a prettyprint of an IntrinsicLambda's declared signature.
rhs = formatIntrinsicAsRHS(let) + ".setSigDump(\"" +
StringUtils.escapeJava(TypeDumper.dumpTypeParams(letType)) +
"\", \"" +
StringUtils.escapeJava(TypeDumper.dumpWithoutParams(letType)) +
"\")";
}
else
{
rhs = formatIntrinsicAsRHS(let);
}
}
else
{
// for non intrinsics, generate code for the RHS
rhs = formatTermAs(let.getValue(), TypeMapper.map(letType));
}
return lhs + " = " + rhs;
}
/**
* factored for external use
*/
public String formatVarDeclLHS(final LetBinding let)
{
return "final " + formatTypeName(let) + " " + formatNameRef(let);
}
/**
* when we have a lambda term available, we can use the lambda's java class
* as a type in generate generated code. Otherwise we go with generic type name.
*/
public String formatTypeName(final ValueBinding binding)
{
if (binding.isLet())
{
final Term rhs = binding.getValue();
if (rhs instanceof LambdaTerm)
return unit.ensureLambdaClassName((LambdaTerm) rhs, unitDictionary);
}
return formatType(binding.getType());
}
/**
*
*/
@Override
public String visit(final ParamBinding param)
{
return formatType(param.getType()) + " " + formatName(param.getName());
}
// TermVisitor
/**
* Format a name reference
*/
@Override
public String visit(final RefTerm ref)
{
// now we have a chance to constant-propagate refs to intrinsics
final ValueBinding binding = ref.getBinding();
if (binding.isLet())
{
final LetBinding let = (LetBinding) binding;
if (let.isIntrinsic())
return formatIntrinsicAsRHS(let);
}
return fixup(ref.getLoc(), formatNameRef(binding), ref.getType());
}
/**
* Helper - formats a binding name as a reference expression -
* qualifies globals defined outside the scope from which the
* reference is being made. (We only need to qualify globals--
* any out-of-scope lambdas will have been captured
* in a closure.)
* Note: package local, used by class generators.
*/
String formatNameRef(final ValueBinding binding)
{
final Scope bindingScope = binding.getScope();
if (bindingScope instanceof Module && bindingScope != currentScope)
{
// qualify top-level (i.e., module not lambda) bindings
// from outside refScope
final Module bindingModule = (Module) bindingScope;
// find the binding's unit.
// TODO should use a bidi map or something instead of lookup
final Unit bindingUnit = (bindingModule == unit.getModule()) ? unit :
Compiler.getUnitDictionary().getUnit(bindingModule.getName());
if (!(bindingUnit instanceof JavaUnit))
{
Session.error(
binding.getLoc(),
"references to non-Java bindings not supported: {0}",
binding.dump()
);
return formatName(binding.getName()); // error, unqualified
}
else
{
// Note: we have to actually use the class name if it's there,
// as it might be nonstandard for intrinsics.
final ClassDef moduleClassDef =
((JavaUnit) bindingUnit).getModuleClassDef();
// But it might not be there, e.g. if we're generating a lambda
// class before its defining module class.
final String moduleNameRef =
(moduleClassDef != null ? moduleClassDef.getName() :
ModuleClassGenerator.qualifiedModuleClassName(bindingModule)) +
"." + Constants.INSTANCE;
return moduleNameRef + "." + formatName(binding.getName());
}
}
else
{
// catch self-reference in lambda
if (binding.isLet())
{
final LetBinding let = (LetBinding) binding;
if (!let.isIntrinsic() && let.getValue() == currentScope)
{
// if we have no captured lambda bindings, we're in
// a static method and must use INSTANCE object.
// otherwise can just pass ourselves
return ((LambdaTerm) currentScope).hasCapturedLambdaBindings() ?
"this" : Constants.INSTANCE;
}
}
return formatName(binding.getName());
}
}
private IntrinsicLambda getIntrinsic(final LetBinding let)
{
final IntrinsicLambda intrinsic = IntrinsicsResolver.resolve(let);
assert intrinsic != null : "Intrinsic should have been previously resolved";
return intrinsic;
}
/**
* Here we access special knowledge about how to go from an intrinsic
* let binding in the current scope, to a compatible value in the
* underlying Java environment
*/
public String formatIntrinsicAsRHS(final LetBinding let)
{
final IntrinsicLambda intrinsic = getIntrinsic(let);
return intrinsic.getClass().getName() + "." + Constants.INSTANCE;
}
/**
* Because we're generating Java source, we have to stay away
* from Java keywords. A simple, fast but still relatively
* readable way to do this is just to tack on an underscore
* to every name. (Of course doing BC gen we won't need to do this,
* but then again we won't be able to read the generated code either.)
*/
public static String formatName(final String name)
{
return "_" + name;
}
/**
*
*/
public String visit(final ParamValue paramValue)
{
assert false : "undigested param value in codegen";
return null;
}
/**
* Generate Java source expression denoting a boolean literal.
*/
@Override
public String visit(final BoolLiteral boolLiteral)
{
final String expr = boolLiteral.getValue() ? "true" : "false";
return fixup(boolLiteral.getLoc(), expr, Types.BOOL);
}
/**
* Generate Java source expression denoting a natural number literal.
*/
@Override
public String visit(final IntLiteral intLiteral)
{
final String expr = "" + intLiteral.getValue();
return fixup(intLiteral.getLoc(), expr, Types.INT);
}
/**
* Generate Java source expression denoting a long number literal.
*/
public String visit(final LongLiteral longLiteral)
{
final String expr = "" + longLiteral.getValue() + "L";
return fixup(longLiteral.getLoc(), expr, Types.LONG);
}
/**
* Generate Java source expression denoting a floating point number literal.
*/
@Override
public String visit(final DoubleLiteral doubleLiteral)
{
final double value = doubleLiteral.getValue();
final String expr = Double.isNaN(value) ? "Double.NaN" : ("" + value);
return fixup(doubleLiteral.getLoc(), expr, Types.DOUBLE);
}
/**
* Generate Java source expression denoting a string literal.
*/
@Override
public String visit(final StringLiteral stringLiteral)
{
final String expr =
"\"" + StringUtils.escapeJava(stringLiteral.getValue()) + "\"";
return fixup(stringLiteral.getLoc(), expr, Types.STRING);
}
/**
* Generate Java source expression denoting a Symbol literal.
* We use pregenerated constants stashed in fields.
*/
@Override
public String visit(final SymbolLiteral symbolLiteral)
{
final String constant = symbolConstants.get(symbolLiteral);
final Loc loc = symbolLiteral.getLoc();
if (constant != null)
return fixup(loc, constant, Types.SYMBOL);
final String expr =
formatType(Types.SYMBOL) + ".get(\"" + symbolLiteral.getValue() + "\")";
return fixup(loc, expr, Types.SYMBOL);
}
/**
* Generate Java source expression to produce a List as specified by a literal term.
*/
@Override
public String visit(final ListTerm list)
{
final String listClassName = PersistentList.class.getName();
// format
final String expr;
final List<Term> items = list.getItems();
if (items.isEmpty())
{
expr = listClassName + ".EMPTY";
}
else
{
final StringBuilder buf = new StringBuilder(listClassName).
append(".alloc(").append(items.size()).append(")");
int i = 0;
for (final Term item : items)
{
final String itemExpr = formatTermAs(item, Object.class);
buf.append(".updateUnsafe").append("(").
append(i).append(", ").
append(itemExpr).append(")");
i++;
}
expr = buf.toString();
}
return fixup(list.getLoc(), expr, list.getType());
}
/**
* Generate Java source expression to produce a Map as specified by a literal term.
* Note that we produce an unversioned map.
*/
@Override
public String visit(final MapTerm map)
{
final StringBuilder buf;
final Iterator<Map.Entry<Term, Term>> iter =
map.getItems().entrySet().iterator();
if (!iter.hasNext())
{
buf = new StringBuilder(PersistentMap.class.getName()).append(".EMPTY");
}
else
{
Map.Entry<Term, Term> entry = iter.next();
final String fkey = formatTermAs(entry.getKey(), Object.class);
final String fval = formatTermAs(entry.getValue(), Object.class);
buf = new StringBuilder(PersistentMap.class.getName()).
append(".single(").append(fkey).append(", ").append(fval).append(")");
while (iter.hasNext())
{
entry = iter.next();
final String nkey = formatTermAs(entry.getKey(), Object.class);
final String nval = formatTermAs(entry.getValue(), Object.class);
buf.append(".assocUnsafe(").
append(nkey).append(", ").append(nval).append(")");
}
}
return fixup(map.getLoc(), buf.toString(), map.getType());
}
/**
* Generate Java source expression denoting a Tuple as specified by a literal term
*/
@Override
public String visit(final TupleTerm tuple)
{
final List<String> formatted = new ArrayList<String>();
final List<Term> items = tuple.getItems();
final String expr;
if (items.size() == 0)
{
expr = Tuple.class.getName() + ".UNIT";
}
else
{
for (final Term term : items)
formatted.add(formatTermAs(term, Object.class));
expr = Tuple.class.getName() + ".from(" +
formatObjectArrayLiteral(formatted) + ")";
}
return fixup(tuple.getLoc(), expr, Tuple.class);
}
/**
* Generate Java source expression denoting a Record as specified by a literal term
*/
@Override
public String visit(final RecordTerm record)
{
final List<SimpleLiteralTerm> keyList = record.getKeyList();
// get keyset field name
final String keyListField = keyListConstants.get(keyList);
if (keyListField == null)
assert false :
"missing key list field for " + DumpUtils.dumpList(keyList);
// generate value exprs
final List<String> valueExprs = new ArrayList<String>();
{
final Map<Term, Term> valueMap = record.getItems();
// important: since record types are permutation groups,
// must guarantee that terms are in symbol order.
for (final SimpleLiteralTerm key : keyList)
{
final Term value = valueMap.get(key);
valueExprs.add(formatTermAs(value, Object.class));
}
}
final String expr =
Record.class.getName() + ".from(" + keyListField + ", " +
formatObjectArrayLiteral(valueExprs) + ")";
return fixup(record.getLoc(), expr, record.getType());
}
/**
* Helper - generate Java source for an Object array constructor call.
* Complicated by a Javassist bug that rejects Object[]{}
*/
public String formatObjectArrayLiteral(
final Collection<String> formattedItems)
{
final StringBuilder buf = new StringBuilder().
append("new ").
append(Constants.OBJECT);
if (formattedItems.size() > 0)
{
buf.append("[]{").
append(StringUtils.join(formattedItems, ", ")).
append("}");
}
else
{
buf.append("[0]");
}
return buf.toString();
}
/**
* Generate Java source expression denoting a Variant as specified by a literal term
*/
@Override
public String visit(final VariantTerm var)
{
final String keyExpr = formatTermAs(var.getKey(), Object.class);
final String valExpr = formatTermAs(var.getValue(), Object.class);
final String expr =
"(new " + Variant.class.getName() + "(" + keyExpr + ", " + valExpr +
"))";
return fixup(var.getLoc(), expr, var.getType());
}
/**
* Generate Java source expression denoting a Variant as specified by a literal term
*/
@Override
public String visit(final CondTerm cond)
{
final String selExpr = formatTermAs(cond.getSel(), Variant.class);
final String casesExpr = formatTermAs(cond.getCases(), Record.class);
final String expr =
_cond.class.getName() + "." + Constants.INVOKE + "(" + selExpr + ", " +
casesExpr + ")";
return fixup(cond.getLoc(), expr, cond.getType());
}
/**
* Generate a Java expression constructing a lambda term.
*/
@Override
public String visit(final LambdaTerm lambda)
{
// we may be generating lambda class def here for the first time - push scope
final Scope prevScope = currentScope;
currentScope = lambda;
final ClassDef classDef = unit.ensureLambdaClassDef(lambda, this);
currentScope = prevScope;
// generate constructor call for lambda class -
// may need to pass captured variable initializers
final String expr;
if (lambda.hasCapturedLambdaBindings())
{
final Collection<ValueBinding> capturedBindings =
lambda.getCapturedLambdaBindings().values();
final List<String> ctorParams =
new ArrayList<String>(capturedBindings.size());
for (final ValueBinding binding : capturedBindings)
ctorParams.add(formatNameRef(binding));
expr = "new " + classDef.getName() + "(" +
StringUtils.join(ctorParams, ", ") + ")";
}
else
{
expr = classDef.getName() + "." + Constants.INSTANCE;
}
return fixup(lambda.getLoc(), expr, lambda.getType());
}
/**
* ApplyTerms include function invocations, collection lookups and structure member accesses.
*/
@Override
public String visit(final ApplyTerm apply)
{
final Term baseTerm = apply.getBase();
final Term argTerm = apply.getArg();
final Type baseType = baseTerm.getType().deref();
switch (apply.getFlav())
{
case FuncApp:
{
// calls to nominal type constructors are no-ops
final String instance = tryNominalCoerces(baseTerm, argTerm);
if (instance != null)
return instance;
// try to optimize based on a lambda dereference
final String invokeExpr = tryLambdaDeref(apply);
if (invokeExpr != null)
return invokeExpr;
return formatLambdaApplyTerm(baseTerm, argTerm);
}
case CollIndex:
{
if (Types.isList(baseType))
return formatListApplyTerm(apply);
if (Types.isMap(baseType))
return formatMapApplyTerm(apply);
Session.error(apply.getLoc(),
"internal error: invalid base term {0} : {1} in collection index expression " +
"{2}",
baseTerm.dump(), baseType.dump(), apply.dump()
);
break;
}
case StructAddr:
{
if (Types.isTup(baseType) || Types.isPolyTup(baseType))
return formatTupleApplyTerm(apply);
if (Types.isRec(baseType))
return formatRecordApplyTerm(apply);
if (Types.isPolyRec(baseType))
return formatPolyRecordApplyTerm(apply);
Session.error(apply.getLoc(),
"internal error: invalid base term {0} : {1} in structure address expression " +
"{2}",
baseTerm.dump(),
baseType.dump(),
apply.dump()
);
break;
}
default:
Session.error(
apply.getLoc(),
"internal error: unknown application flavor in expression {0}",
apply.dump()
);
break;
}
return null;
}
/**
* application on a list is positional lookup.
*/
private String formatListApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
final String expr = formatTermAs(base, ListValue.class) + ".get(" +
formatTermAs(arg, int.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* application on a map is key lookup.
*/
private String formatMapApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
final String expr = formatTermAs(base, MapValue.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* application on a tuple is positional member access.
*/
public String formatTupleApplyTerm(final ApplyTerm apply)
{
final Term arg = apply.getArg();
final Term base = apply.getBase();
assert arg.getType() == Types.INT;
{
final Term argDeref =
arg instanceof RefTerm ? ((RefTerm) arg).deref() : arg;
assert argDeref.isConstant();
}
final String expr = formatTermAs(base, Tuple.class) + ".get(" +
formatTermAs(arg, int.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* application on a record is keyed member access.
*/
private String formatRecordApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
{
final Term argDeref =
arg instanceof RefTerm ? ((RefTerm) arg).deref() : arg;
assert argDeref.isConstant();
}
final String expr;
final Type baseType = base.getType().deref();
if (Types.isRec(baseType))
{
final List<SimpleLiteralTerm> keyList = Types.recKeyList(baseType);
final int pos = keyList.indexOf(arg);
if (pos < keyList.size())
{
// positional lookup
expr = formatTermAs(base, Record.class) + ".getValue(" + pos + ")";
}
else
{
Session.error(apply.getLoc(),
"internal error: arg {0} not found in key list {1}", arg.dump(),
DumpUtils.dumpList(keyList)
);
// name lookup as error fallback
expr = formatTermAs(base, Record.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
}
}
else
{
// name lookup
expr = formatTermAs(base, Record.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
}
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* TODO move to ohori hidden params for poly rec access
*/
private String formatPolyRecordApplyTerm(final ApplyTerm apply)
{
final Term base = apply.getBase();
final Term arg = apply.getArg();
final Type applyType = apply.getType();
if (Types.isVar(applyType))
Session.error(
apply.getLoc(),
"internal error: dynamic record access not currently supported"
);
{
final Term argDeref =
arg instanceof RefTerm ? ((RefTerm) arg).deref() : arg;
assert argDeref.isConstant();
}
// name lookup for now, see comment
final String expr = formatTermAs(base, Record.class) + ".get(" +
formatTermAs(arg, Object.class) + ")";
return fixup(apply.getLoc(), expr, Object.class);
}
/**
* generate an application (tupled params), available for any lambda
*/
private String formatLambdaApplyTerm(final Term base, final Term arg)
{
final String expr =
formatTermAs(base, Lambda.class) + "." + Constants.APPLY + "(" +
formatTermAs(arg, Object.class) + ")";
return fixup(base.getLoc(), expr, Object.class);
}
/**
* Type constructors, destructors are no-ops. If we're applying
* one, just drill through to the underlying argument.
* TODO something less spidery for detecting these?
*/
private String tryNominalCoerces(final Term base, final Term arg)
{
if (!(base instanceof RefTerm))
return null;
final RefTerm baseRef = (RefTerm) base;
if (!baseRef.getBinding().isLet())
return null;
final LetBinding baseLet = (LetBinding) baseRef.getBinding();
if (baseLet.isIntrinsic() || !(baseLet.getValue() instanceof LambdaTerm))
return null;
final LambdaTerm lambda = (LambdaTerm) baseLet.getValue();
final Type lambdaType = lambda.getType();
final Type paramType = Types.funParam(lambdaType).deref();
final Type resultType = Types.funResult(lambdaType).deref();
if (paramType instanceof TypeDef)
{
// if param type is nominal, check for type dtor
final TypeDef paramDef = (TypeDef) paramType;
if (!paramDef.isNominal())
return null;
if (lambda != paramDef.getDtorLet().getValue())
return null;
return formatTermAs(arg, arg.getType());
}
else if (resultType instanceof TypeDef)
{
// if result type is nominal, check for type ctor
final TypeDef resultDef = (TypeDef) resultType;
if (!resultDef.isNominal())
return null;
if (lambda != resultDef.getCtorLet().getValue())
return null;
return formatTermAs(arg, arg.getType());
}
return null;
}
/**
* try things based on derefing the lambda:
* 0. inline some obvious stuff--direct conditionals, etc.
* 1. generate an invocation with scattered params if we can - which means
* when we have a specific Java signature for invoke(). Currently this
* is true when our base term resolves to a specific Java implementation
* class (so e.g. not a param ref), and that implementation has invoke()
* NOTE several early returns
*/
private String tryLambdaDeref(final ApplyTerm apply)
{
final Loc loc = apply.getLoc();
final Term base = apply.getBase();
final Type baseType = base.getType().eval();
assert Types.isFun(baseType);
final Term arg = apply.getArg();
final Type argType = arg.getType();
// note that we don't simply take the result type of the application.
// our generated code must deal with the unspecialized java type
// produced by the polymorphic function.
final Type resultType = Types.funResult(baseType);
final Type paramType = Types.funParam(baseType);
final InvokeInfo info = getInvokeInfo(base);
if (info == null)
return null;
// format base expr
final String invokeBase;
if (info.className != null)
{
// non-null class name means this is not a closure,
// so we have a static invoke()
// NOTE: early return if we inline successfully
final String inlined = TermInliner.tryInlining(apply, info, this);
if (inlined != null)
{
if (Session.isDebug())
Session.debug(loc, "inlined: {0} => {1}", apply.dump(), inlined);
return inlined;
}
// NOTE: visit base term even if we use class name directly,
// to trigger code gen
formatTermAs(base, baseType);
invokeBase = info.className + "." + Constants.INVOKE;
}
else
{
invokeBase = formatTermAs(base, baseType) + "." + Constants.INVOKE;
}
// format call
if (info.mode == InvokeInfo.InvokeMode.Scatter)
{
final String expr;
final List<Type> paramTypes =
((TypeList) Types.tupMembers(paramType).deref()).getItems();
final List<String> formatted = new ArrayList<String>();
if (arg instanceof TupleTerm)
{
// argument is a tuple literal - just pass individual members
final List<Term> args = ((TupleTerm) arg).getItems();
for (int i = 0; i < paramTypes.size(); i++)
formatted.add(formatTermAs(args.get(i), paramTypes.get(i)));
expr = invokeBase + "(" + StringUtils.join(formatted, ", ") + ")";
}
else if (arg instanceof RefTerm)
{
// if base is a simple ref term, call invoke with a scatter list
assert Types.isTup(argType);
final Type members = Types.tupMembers(argType);
assert members instanceof TypeList;
final Loc argLoc = arg.getLoc();
final List<Type> argTypes = ((TypeList) members).getItems();
for (int i = 0; i < paramTypes.size(); i++)
{
final ApplyTerm accessTerm =
new ApplyTerm(argLoc, arg, new IntLiteral(argLoc, i), StructAddr);
accessTerm.setType(argTypes.get(i));
formatted.add(formatTermAs(accessTerm, paramTypes.get(i)));
}
expr = invokeBase + "(" + StringUtils.join(formatted, ", ") + ")";
}
else
{
// NOTE: more elaborate strategies (temp assignments, etc.)
// don't seem to pay, so keeping things simple here.
return null;
}
// invoke result is strongly typed
return fixup(loc, expr, resultType);
}
else
{
final String expr = invokeBase + "(" + formatTermAs(arg, paramType) + ")";
return fixup(loc, expr, resultType);
}
}
/**
* Build an info packet to facilitate some simple optimizations, if the
* base term (of an application) can be dereferenced to a particular lambda,
* rather than a param.
* 1. In addition to the canonical apply(arg), Lambdas implement invoke(), which
* takes a scattered argument list. We want to call that if we can.
* 2. In non-closure Lambdas, the invoke() is static, so we can call with a
* direct reference to the Lambda's classname.
*/
public InvokeInfo getInvokeInfo(final Term base)
{
if (base instanceof LambdaTerm)
{
final LambdaTerm baseLambda = (LambdaTerm) base;
// this ensures a stable class name, but doesn't generate code
final String className =
unit.ensureLambdaClassName(baseLambda, unitDictionary);
// can scatter if num args != 1
final InvokeInfo.InvokeMode mode =
baseLambda.getParams().size() == 1 ? InvokeInfo.InvokeMode.NoScatter :
InvokeInfo.InvokeMode.Scatter;
// if no captured bindings, can call static invoke() directly
return new InvokeInfo(baseLambda, mode,
baseLambda.hasCapturedLambdaBindings() ? null : className
);
}
else if (base instanceof RefTerm)
{
// track down ref
final ValueBinding binding = ((RefTerm) base).getBinding();
if (binding.isLet())
{
// let binding, as opposed to a param binding
final LetBinding let = (LetBinding) binding;
if (let.isIntrinsic())
{
final IntrinsicLambda intrinsic = getIntrinsic(let);
final String lambdaClass = intrinsic.getClass().getName();
final Type baseType = base.getType().deref();
if (Types.isFun(baseType))
{
final Type paramType = Types.funParam(baseType);
if (Types.isTup(paramType) &&
Types.tupMembers(paramType) instanceof TypeList)
{
// scatter calls to non-variadic multi-arg functions
return new InvokeInfo(null, InvokeInfo.InvokeMode.Scatter,
lambdaClass
);
}
else
{
// otherwise, intrinsic takes a single argument
return new InvokeInfo(null, InvokeInfo.InvokeMode.NoScatter,
lambdaClass
);
}
}
// should be an assert? calling an intrinsic with non-function type?
return null;
}
else
{
// non-intrinsic, check RHS
return getInvokeInfo(let.getValue());
}
}
}
return null;
}
/**
*
*/
@Override
public String visit(final CoerceTerm coerce)
{
return formatTermAs(coerce.getTerm(), coerce.getType());
}
}
| 46,256 | 0.556836 | 0.55569 | 1,489 | 30.065144 | 27.264626 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.422431 | false | false | 3 |
94fb70bf2e9dc31b8e1bbea85b08fef958d79e0e | 29,661,044,195,664 | 28d72003861f576be15afd7991c911558ae4344b | /src/main/java/com/app/repositories/ProductsRepository.java | f20fb1527c4f165a36ac3ae51026833e9d0d88b7 | [] | no_license | AndreiNicolae191/orderEatRepeat | https://github.com/AndreiNicolae191/orderEatRepeat | f6e1b71d3e64d37b03c78cfc2c62dc281bd9aece | ccb159ba4a7166483c3cfdc467343f6771249cd2 | refs/heads/master | 2023-06-22T14:22:28.080000 | 2021-07-24T11:30:09 | 2021-07-24T11:30:09 | 389,080,713 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.repositories;
import com.app.entities.Products;
import org.springframework.data.repository.CrudRepository;
public interface ProductsRepository extends CrudRepository<Products,Long> {
}
| UTF-8 | Java | 203 | java | ProductsRepository.java | Java | [] | null | [] | package com.app.repositories;
import com.app.entities.Products;
import org.springframework.data.repository.CrudRepository;
public interface ProductsRepository extends CrudRepository<Products,Long> {
}
| 203 | 0.842365 | 0.842365 | 7 | 28 | 27.856777 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 3 |
5b4a3ef67a70fa5e8decce34402730ed30cfc550 | 4,088,808,882,418 | f24f44fd4c659eddafdd0e44ad6d9086ae01515f | /pjCapitulo1_2/src/pFormularios/FrmVenta.java | a49afda972db227ba1e2c27567837531c8863318 | [] | no_license | nekixito/LibroDesaAplicJava8OONBE | https://github.com/nekixito/LibroDesaAplicJava8OONBE | 9632ecadc329099b53bb55b4b0662c5c6bde5789 | 95b762cd166574060a2f1cd21f2bce738570d24e | refs/heads/master | 2022-07-19T07:44:56.890000 | 2020-05-25T21:05:59 | 2020-05-25T21:05:59 | 259,188,776 | 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 pFormularios;
/**
*
* @author Multi
*/
public class FrmVenta extends javax.swing.JFrame {
/**
* Creates new form FrmVenta
*/
public FrmVenta() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblTituloGeneral = new javax.swing.JLabel();
lblTituloPrec = new javax.swing.JLabel();
txtTituloCant = new javax.swing.JLabel();
txtPrecio = new javax.swing.JTextField();
txtCantidad = new javax.swing.JTextField();
btnCalcular = new javax.swing.JButton();
txtLimpiar = new javax.swing.JButton();
lblTitSubt = new javax.swing.JLabel();
lblTitDesc = new javax.swing.JLabel();
lblSubtotal = new javax.swing.JLabel();
lblDescuento = new javax.swing.JLabel();
lblTitNet = new javax.swing.JLabel();
lblNeto = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblTituloGeneral.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblTituloGeneral.setText("VENTA DE PRODUCTOS - PROMOCIÓN");
lblTituloPrec.setText("PRECIO DEL PRODUCTO");
txtTituloCant.setText("CANTIDAD");
txtPrecio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPrecioActionPerformed(evt);
}
});
btnCalcular.setText("Calcular");
btnCalcular.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCalcularActionPerformed(evt);
}
});
txtLimpiar.setText("Limpiar");
txtLimpiar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtLimpiarActionPerformed(evt);
}
});
lblTitSubt.setText("SUBTOTAL:");
lblTitDesc.setText("DESCUENTO:");
lblSubtotal.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblSubtotal.setText("$0.00");
lblDescuento.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblDescuento.setText("$0.00");
lblTitNet.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitNet.setText("NETO A PAGAR");
lblNeto.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
lblNeto.setText("$0.00");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblTitSubt)
.addComponent(lblTitDesc))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblSubtotal)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblDescuento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNeto)
.addGap(97, 97, 97))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(lblTituloPrec)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtTituloCant))
.addComponent(lblTituloGeneral)
.addGroup(layout.createSequentialGroup()
.addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(txtCantidad)))
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblTitNet)
.addGroup(layout.createSequentialGroup()
.addComponent(btnCalcular)
.addGap(18, 18, 18)
.addComponent(txtLimpiar)))
.addContainerGap(30, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(lblTituloGeneral)
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTituloPrec)
.addComponent(txtTituloCant))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCalcular)
.addComponent(txtLimpiar))
.addGap(64, 64, 64)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTitSubt)
.addComponent(lblSubtotal)
.addComponent(lblTitNet))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTitDesc)
.addComponent(lblDescuento))
.addContainerGap(70, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNeto)
.addGap(68, 68, 68))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtPrecioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPrecioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPrecioActionPerformed
private void btnCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalcularActionPerformed
double precio = Double.parseDouble(txtPrecio.getText());
int cantidad = Integer.parseInt(txtCantidad.getText());
double subtotal = precio * cantidad;
double descuento = subtotal * 0.12;
double neto = subtotal - descuento;
lblSubtotal.setText("$"+String.format("%.2f", subtotal));
lblDescuento.setText("$"+String.format("%.2f", descuento));
lblNeto.setText("$"+String.format("%.2f",neto));
}//GEN-LAST:event_btnCalcularActionPerformed
private void txtLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtLimpiarActionPerformed
txtPrecio.setText("");
txtCantidad.setText("");
lblSubtotal.setText("0.00");
lblDescuento.setText("$0.00");
lblNeto.setText("$0.00");
}//GEN-LAST:event_txtLimpiarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmVenta().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCalcular;
private javax.swing.JLabel lblDescuento;
private javax.swing.JLabel lblNeto;
private javax.swing.JLabel lblSubtotal;
private javax.swing.JLabel lblTitDesc;
private javax.swing.JLabel lblTitNet;
private javax.swing.JLabel lblTitSubt;
private javax.swing.JLabel lblTituloGeneral;
private javax.swing.JLabel lblTituloPrec;
private javax.swing.JTextField txtCantidad;
private javax.swing.JButton txtLimpiar;
private javax.swing.JTextField txtPrecio;
private javax.swing.JLabel txtTituloCant;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 11,978 | java | FrmVenta.java | Java | [
{
"context": "itor.\n */\npackage pFormularios;\n\n/**\n *\n * @author Multi\n */\npublic class FrmVenta extends javax.swing.JFr",
"end": 231,
"score": 0.7800008654594421,
"start": 226,
"tag": "USERNAME",
"value": "Multi"
}
] | 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 pFormularios;
/**
*
* @author Multi
*/
public class FrmVenta extends javax.swing.JFrame {
/**
* Creates new form FrmVenta
*/
public FrmVenta() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblTituloGeneral = new javax.swing.JLabel();
lblTituloPrec = new javax.swing.JLabel();
txtTituloCant = new javax.swing.JLabel();
txtPrecio = new javax.swing.JTextField();
txtCantidad = new javax.swing.JTextField();
btnCalcular = new javax.swing.JButton();
txtLimpiar = new javax.swing.JButton();
lblTitSubt = new javax.swing.JLabel();
lblTitDesc = new javax.swing.JLabel();
lblSubtotal = new javax.swing.JLabel();
lblDescuento = new javax.swing.JLabel();
lblTitNet = new javax.swing.JLabel();
lblNeto = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblTituloGeneral.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblTituloGeneral.setText("VENTA DE PRODUCTOS - PROMOCIÓN");
lblTituloPrec.setText("PRECIO DEL PRODUCTO");
txtTituloCant.setText("CANTIDAD");
txtPrecio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPrecioActionPerformed(evt);
}
});
btnCalcular.setText("Calcular");
btnCalcular.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCalcularActionPerformed(evt);
}
});
txtLimpiar.setText("Limpiar");
txtLimpiar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtLimpiarActionPerformed(evt);
}
});
lblTitSubt.setText("SUBTOTAL:");
lblTitDesc.setText("DESCUENTO:");
lblSubtotal.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblSubtotal.setText("$0.00");
lblDescuento.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblDescuento.setText("$0.00");
lblTitNet.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitNet.setText("NETO A PAGAR");
lblNeto.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
lblNeto.setText("$0.00");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblTitSubt)
.addComponent(lblTitDesc))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblSubtotal)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblDescuento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNeto)
.addGap(97, 97, 97))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(lblTituloPrec)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtTituloCant))
.addComponent(lblTituloGeneral)
.addGroup(layout.createSequentialGroup()
.addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(txtCantidad)))
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblTitNet)
.addGroup(layout.createSequentialGroup()
.addComponent(btnCalcular)
.addGap(18, 18, 18)
.addComponent(txtLimpiar)))
.addContainerGap(30, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(lblTituloGeneral)
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTituloPrec)
.addComponent(txtTituloCant))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCalcular)
.addComponent(txtLimpiar))
.addGap(64, 64, 64)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTitSubt)
.addComponent(lblSubtotal)
.addComponent(lblTitNet))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTitDesc)
.addComponent(lblDescuento))
.addContainerGap(70, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNeto)
.addGap(68, 68, 68))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtPrecioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPrecioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPrecioActionPerformed
private void btnCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalcularActionPerformed
double precio = Double.parseDouble(txtPrecio.getText());
int cantidad = Integer.parseInt(txtCantidad.getText());
double subtotal = precio * cantidad;
double descuento = subtotal * 0.12;
double neto = subtotal - descuento;
lblSubtotal.setText("$"+String.format("%.2f", subtotal));
lblDescuento.setText("$"+String.format("%.2f", descuento));
lblNeto.setText("$"+String.format("%.2f",neto));
}//GEN-LAST:event_btnCalcularActionPerformed
private void txtLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtLimpiarActionPerformed
txtPrecio.setText("");
txtCantidad.setText("");
lblSubtotal.setText("0.00");
lblDescuento.setText("$0.00");
lblNeto.setText("$0.00");
}//GEN-LAST:event_txtLimpiarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmVenta().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCalcular;
private javax.swing.JLabel lblDescuento;
private javax.swing.JLabel lblNeto;
private javax.swing.JLabel lblSubtotal;
private javax.swing.JLabel lblTitDesc;
private javax.swing.JLabel lblTitNet;
private javax.swing.JLabel lblTitSubt;
private javax.swing.JLabel lblTituloGeneral;
private javax.swing.JLabel lblTituloPrec;
private javax.swing.JTextField txtCantidad;
private javax.swing.JButton txtLimpiar;
private javax.swing.JTextField txtPrecio;
private javax.swing.JLabel txtTituloCant;
// End of variables declaration//GEN-END:variables
}
| 11,978 | 0.609752 | 0.599983 | 243 | 48.288067 | 35.241077 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584362 | false | false | 3 |
d6d3d6187d412e9cac4200afe486b12a96fc9048 | 32,521,492,432,647 | 6e8d7e3a292b76138dadbe4e9b1d031045e038c7 | /app/src/main/java/com/wisdompark/minichoucreme/ui/SettingsGeneralActivity.java | 5f2715a23145e48d606104286ea8b63d68d52301 | [] | no_license | JoonghoLim/MiniChouCreme | https://github.com/JoonghoLim/MiniChouCreme | 8dd336ed3f44f3ead4a8ff115b3475a74eb81340 | 3fd3383225a666d16c0d6baafb42d0916a23385f | refs/heads/master | 2020-11-26T13:53:51.419000 | 2020-01-06T09:09:30 | 2020-01-06T09:09:30 | 229,035,094 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wisdompark.minichoucreme.ui;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import android.content.Intent;
import android.os.Bundle;
import com.wisdompark.minichoucreme.R;
public class SettingsGeneralActivity extends AppCompatActivity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_general);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsGeneralActivity.SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
intent = new Intent();
this.setResult(RESULT_OK, intent);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
protected void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
}
| UTF-8 | Java | 1,338 | java | SettingsGeneralActivity.java | Java | [] | null | [] | package com.wisdompark.minichoucreme.ui;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import android.content.Intent;
import android.os.Bundle;
import com.wisdompark.minichoucreme.R;
public class SettingsGeneralActivity extends AppCompatActivity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_general);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsGeneralActivity.SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
intent = new Intent();
this.setResult(RESULT_OK, intent);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
protected void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
}
| 1,338 | 0.692825 | 0.69133 | 43 | 30.11628 | 24.9196 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534884 | false | false | 3 |
dd942728023c04088cb18e0c3deb2cf271ef820b | 18,133,351,954,731 | 406e64a4255a3482b2432b925dd40a66d53d7378 | /application.java | 8a751f8c6e74b8678bcf092a09856a308a606046 | [] | no_license | ranjeet-sys1/practise | https://github.com/ranjeet-sys1/practise | 7fd732c6e35fdf9f9835f465f7fb003457c3c119 | 247a0a5183c478c914a36516531565cea1ec7468 | refs/heads/master | 2022-12-01T12:17:39.344000 | 2020-08-16T11:37:34 | 2020-08-16T11:37:34 | 279,587,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Application{
public static void main(String args[]){
System.out.println("************^^^^^####GITHUB Practice------************^^^^^####");
}
} | UTF-8 | Java | 164 | java | application.java | Java | [] | null | [] | public class Application{
public static void main(String args[]){
System.out.println("************^^^^^####GITHUB Practice------************^^^^^####");
}
} | 164 | 0.5 | 0.5 | 5 | 32 | 30.737598 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
0bf0dc290cabe87cdc073ae9a1b2c5f83b79c6cd | 678,604,878,498 | e2056d113f61ab39f7f0d8fcf014c2193b406e05 | /src/main/java/Graph/CycleInUndirectedGraph.java | dd231d223049b1938055f433f0c1aa007b14b941 | [] | no_license | RajshreeSoni/TryJava | https://github.com/RajshreeSoni/TryJava | bdaccdf3ce539aff5597c38ef9e224b71c171fc7 | d1ac948397a2d56f5e642b0a768bab4ff997f573 | refs/heads/master | 2021-03-03T12:13:34.331000 | 2020-03-09T06:27:55 | 2020-03-09T06:27:55 | 245,960,029 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Graph;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.util.Iterator;
public class CycleInUndirectedGraph {
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g1 = new Graph(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 1);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
if (isCyclic(4))
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
Graph g2 = new Graph(3);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
if (isCyclic(3))
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
}
static boolean isCyclic(int V) {
Boolean visited[] = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i =0;i<V;i++) {
if (!visited[i]) {
if (isCyclicUtil(i, visited, -1)) {
return true;
}
}
}
return false;
}
private static boolean isCyclicUtil(int v, Boolean[] visited, int parent) {
visited[v] = true;
Iterator<Integer> i = Graph.adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
if (isCyclicUtil(n, visited, v)) {
return true;
}
}
else if (n!=parent) {
return true;
}
}
return false;
}
}
| UTF-8 | Java | 1,434 | java | CycleInUndirectedGraph.java | Java | [] | null | [] | package Graph;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.util.Iterator;
public class CycleInUndirectedGraph {
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g1 = new Graph(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 1);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
if (isCyclic(4))
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
Graph g2 = new Graph(3);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
if (isCyclic(3))
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
}
static boolean isCyclic(int V) {
Boolean visited[] = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i =0;i<V;i++) {
if (!visited[i]) {
if (isCyclicUtil(i, visited, -1)) {
return true;
}
}
}
return false;
}
private static boolean isCyclicUtil(int v, Boolean[] visited, int parent) {
visited[v] = true;
Iterator<Integer> i = Graph.adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
if (isCyclicUtil(n, visited, v)) {
return true;
}
}
else if (n!=parent) {
return true;
}
}
return false;
}
}
| 1,434 | 0.566248 | 0.545328 | 63 | 21.761906 | 17.73143 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.68254 | false | false | 3 |
e1d3693e7eae0f219666f6f6b431fd81f0a2058b | 5,351,529,287,841 | db33f6e8d0847eab48669ad0e3b344f3d6fceef0 | /src/main/java/lesson4/task3/Dog.java | 3e980799766d3ba546dc441b55f0a06a72c67c7b | [] | no_license | bedon/aqa_tasks | https://github.com/bedon/aqa_tasks | e53df3277099e8568636da2ba3a30e0e22515197 | 15d14b826820ae224cdea726830fc98e6b1ff99a | refs/heads/master | 2022-07-06T23:56:07.577000 | 2019-07-29T16:10:18 | 2019-07-29T16:10:18 | 188,551,331 | 0 | 0 | null | false | 2019-05-26T17:45:58 | 2019-05-25T10:17:05 | 2019-05-26T16:27:44 | 2019-05-26T17:45:57 | 7 | 0 | 0 | 0 | Java | false | false | package lesson4.task3;
public class Dog {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
if (name.equals(""))
System.out.println("Name can't be empty");
else
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age <= 0)
System.out.println("Age should be > 0");
else
this.age = age;
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.setAge(0);
dog.setAge(-4);
dog.setAge(3);
dog.setName("");
dog.setName("Sirko");
}
}
| UTF-8 | Java | 736 | java | Dog.java | Java | [
{
"context": ");\n\n dog.setName(\"\");\n dog.setName(\"Sirko\");\n }\n}\n",
"end": 724,
"score": 0.9956743121147156,
"start": 719,
"tag": "NAME",
"value": "Sirko"
}
] | null | [] | package lesson4.task3;
public class Dog {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
if (name.equals(""))
System.out.println("Name can't be empty");
else
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age <= 0)
System.out.println("Age should be > 0");
else
this.age = age;
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.setAge(0);
dog.setAge(-4);
dog.setAge(3);
dog.setName("");
dog.setName("Sirko");
}
}
| 736 | 0.501359 | 0.491848 | 39 | 17.871796 | 14.615025 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 3 |
7ccbf32dff9968e1822df314c9f6f83ea1cae119 | 1,657,857,439,411 | b0e3b64f4277f4e6c02a1dad6df6cf9680c85f0f | /src/main/java/Service/ProductManager.java | eb3c666826deb7a9b3b8d06d4104d9685140bd41 | [] | no_license | HuyNH1998-CG/Module4-CRUDfake | https://github.com/HuyNH1998-CG/Module4-CRUDfake | db85f825e57dd6ab329bb6f176218bccf4d57338 | 6dc81233a98e584119343f2d253c32777fd367c3 | refs/heads/master | 2023-07-10T06:18:59.808000 | 2021-08-13T07:00:11 | 2021-08-13T07:00:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Service;
import Model.Category;
import Model.Product;
import java.util.ArrayList;
public class ProductManager {
public ArrayList<Product> list = new ArrayList<>();
public ArrayList<Category> categories = new ArrayList<>();
public ProductManager(){
categories.add(new Category("Fruit"));
categories.add(new Category("Fish"));
list.add(new Product("Apple",500, categories.get(0).getCategory()));
list.add(new Product("Water melon", 1000, categories.get(0).getCategory()));
list.add(new Product("Pineapple",750, categories.get(0).getCategory()));
list.add(new Product("Salmon",5000, categories.get(1).getCategory()));
list.add(new Product("Tuna",10000, categories.get(1).getCategory()));
list.add(new Product("Whale",100000, categories.get(1).getCategory()));
}
public void save(Product product){
list.add(product);
}
public void edit(Product product, int index){
list.set(index, product);
}
public void delete(int index){
list.remove(index);
}
}
| UTF-8 | Java | 1,084 | java | ProductManager.java | Java | [] | null | [] | package Service;
import Model.Category;
import Model.Product;
import java.util.ArrayList;
public class ProductManager {
public ArrayList<Product> list = new ArrayList<>();
public ArrayList<Category> categories = new ArrayList<>();
public ProductManager(){
categories.add(new Category("Fruit"));
categories.add(new Category("Fish"));
list.add(new Product("Apple",500, categories.get(0).getCategory()));
list.add(new Product("Water melon", 1000, categories.get(0).getCategory()));
list.add(new Product("Pineapple",750, categories.get(0).getCategory()));
list.add(new Product("Salmon",5000, categories.get(1).getCategory()));
list.add(new Product("Tuna",10000, categories.get(1).getCategory()));
list.add(new Product("Whale",100000, categories.get(1).getCategory()));
}
public void save(Product product){
list.add(product);
}
public void edit(Product product, int index){
list.set(index, product);
}
public void delete(int index){
list.remove(index);
}
}
| 1,084 | 0.655904 | 0.627306 | 30 | 35.099998 | 27.487391 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.033333 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.