hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
4c33fe9118b3151d7bc55a62f297b29ce07307e1 | 2,330 | package org.testcontainers.images.builder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.rnorth.visibleassertions.VisibleAssertions.assertTrue;
@RunWith(Parameterized.class)
public class DockerfileBuildTest {
private static final Path RESOURCE_PATH = Paths.get("src/test/resources/dockerfile-build-test");
public String expectedFileContent;
public ImageFromDockerfile image;
@Parameterized.Parameters
public static Object[][] parameters() {
return new Object[][]{
// Dockerfile build without explicit per-file inclusion
new Object[]{"test1234",
// docsShowRecursiveFileInclusion {
new ImageFromDockerfile()
.withFileFromPath(".", RESOURCE_PATH)
// }
},
// Dockerfile build using a non-standard Dockerfile
new Object[]{"test4567",
new ImageFromDockerfile()
.withFileFromPath(".", RESOURCE_PATH)
.withDockerfilePath("./Dockerfile-alt")
},
// Dockerfile build using build args
new Object[]{"test7890",
new ImageFromDockerfile()
.withFileFromPath(".", RESOURCE_PATH)
.withDockerfilePath("./Dockerfile-buildarg")
.withBuildArg("CUSTOM_ARG", "test7890")
},
};
}
public DockerfileBuildTest(String expectedFileContent, ImageFromDockerfile image) {
this.expectedFileContent = expectedFileContent;
this.image = image;
}
@Test
public void performTest() {
try (final GenericContainer container = new GenericContainer(image)
.withStartupCheckStrategy(new OneShotStartupCheckStrategy())
.withCommand("cat", "/test.txt")) {
container.start();
final String logs = container.getLogs();
assertTrue("expected file content indicates that dockerfile build steps have been run", logs.contains(expectedFileContent));
}
}
}
| 34.264706 | 136 | 0.639056 |
ba98a87feab637c63efdd1fb117950d1239c2bd8 | 7,859 | package com.alibaba.otter.canal.parse.driver.mysql.utils;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
/**
* mysql collation转换mapping关系表
*
* @author agapple 2018年11月5日 下午1:01:15
* @since 1.1.2
*/
public class CharsetUtil {
private static final String[] INDEX_TO_CHARSET = new String[2048];
private static final Map<String, Integer> CHARSET_TO_INDEX = new HashMap<String, Integer>();
static {
INDEX_TO_CHARSET[1] = "big5";
INDEX_TO_CHARSET[84] = "big5";
INDEX_TO_CHARSET[3] = "dec8";
INDEX_TO_CHARSET[69] = "dec8";
INDEX_TO_CHARSET[4] = "cp850";
INDEX_TO_CHARSET[80] = "cp850";
INDEX_TO_CHARSET[6] = "hp8";
INDEX_TO_CHARSET[72] = "hp8";
INDEX_TO_CHARSET[7] = "koi8r";
INDEX_TO_CHARSET[74] = "koi8r";
INDEX_TO_CHARSET[5] = "latin1";
INDEX_TO_CHARSET[8] = "latin1";
INDEX_TO_CHARSET[15] = "latin1";
INDEX_TO_CHARSET[31] = "latin1";
INDEX_TO_CHARSET[47] = "latin1";
INDEX_TO_CHARSET[48] = "latin1";
INDEX_TO_CHARSET[49] = "latin1";
INDEX_TO_CHARSET[94] = "latin1";
INDEX_TO_CHARSET[9] = "latin2";
INDEX_TO_CHARSET[21] = "latin2";
INDEX_TO_CHARSET[27] = "latin2";
INDEX_TO_CHARSET[77] = "latin2";
INDEX_TO_CHARSET[10] = "swe7";
INDEX_TO_CHARSET[82] = "swe7";
INDEX_TO_CHARSET[11] = "ascii";
INDEX_TO_CHARSET[65] = "ascii";
INDEX_TO_CHARSET[12] = "ujis";
INDEX_TO_CHARSET[91] = "ujis";
INDEX_TO_CHARSET[13] = "sjis";
INDEX_TO_CHARSET[88] = "sjis";
INDEX_TO_CHARSET[16] = "hebrew";
INDEX_TO_CHARSET[71] = "hebrew";
INDEX_TO_CHARSET[18] = "tis620";
INDEX_TO_CHARSET[69] = "tis620";
INDEX_TO_CHARSET[19] = "euckr";
INDEX_TO_CHARSET[85] = "euckr";
INDEX_TO_CHARSET[22] = "koi8u";
INDEX_TO_CHARSET[75] = "koi8u";
INDEX_TO_CHARSET[24] = "gb2312";
INDEX_TO_CHARSET[86] = "gb2312";
INDEX_TO_CHARSET[25] = "greek";
INDEX_TO_CHARSET[70] = "greek";
INDEX_TO_CHARSET[26] = "cp1250";
INDEX_TO_CHARSET[34] = "cp1250";
INDEX_TO_CHARSET[44] = "cp1250";
INDEX_TO_CHARSET[66] = "cp1250";
INDEX_TO_CHARSET[99] = "cp1250";
INDEX_TO_CHARSET[28] = "gbk";
INDEX_TO_CHARSET[87] = "gbk";
INDEX_TO_CHARSET[30] = "latin5";
INDEX_TO_CHARSET[78] = "latin5";
INDEX_TO_CHARSET[32] = "armscii8";
INDEX_TO_CHARSET[64] = "armscii8";
INDEX_TO_CHARSET[33] = "utf8";
INDEX_TO_CHARSET[83] = "utf8";
for (int i = 192; i <= 223; i++) {
INDEX_TO_CHARSET[i] = "utf8";
}
for (int i = 336; i <= 337; i++) {
INDEX_TO_CHARSET[i] = "utf8";
}
for (int i = 352; i <= 357; i++) {
INDEX_TO_CHARSET[i] = "utf8";
}
INDEX_TO_CHARSET[368] = "utf8";
INDEX_TO_CHARSET[2047] = "utf8";
INDEX_TO_CHARSET[35] = "ucs2";
INDEX_TO_CHARSET[90] = "ucs2";
for (int i = 128; i <= 151; i++) {
INDEX_TO_CHARSET[i] = "ucs2";
}
INDEX_TO_CHARSET[159] = "ucs2";
for (int i = 358; i <= 360; i++) {
INDEX_TO_CHARSET[i] = "ucs2";
}
INDEX_TO_CHARSET[36] = "cp866";
INDEX_TO_CHARSET[68] = "cp866";
INDEX_TO_CHARSET[37] = "keybcs2";
INDEX_TO_CHARSET[73] = "keybcs2";
INDEX_TO_CHARSET[38] = "macce";
INDEX_TO_CHARSET[43] = "macce";
INDEX_TO_CHARSET[39] = "macroman";
INDEX_TO_CHARSET[53] = "macroman";
INDEX_TO_CHARSET[40] = "cp852";
INDEX_TO_CHARSET[81] = "cp852";
INDEX_TO_CHARSET[20] = "latin7";
INDEX_TO_CHARSET[41] = "latin7";
INDEX_TO_CHARSET[42] = "latin7";
INDEX_TO_CHARSET[79] = "latin7";
INDEX_TO_CHARSET[45] = "utf8mb4";
INDEX_TO_CHARSET[46] = "utf8mb4";
for (int i = 224; i <= 247; i++) {
INDEX_TO_CHARSET[i] = "utf8mb4";
}
for (int i = 255; i <= 271; i++) {
INDEX_TO_CHARSET[i] = "utf8mb4";
}
for (int i = 273; i <= 275; i++) {
INDEX_TO_CHARSET[i] = "utf8mb4";
}
for (int i = 277; i <= 294; i++) {
INDEX_TO_CHARSET[i] = "utf8mb4";
}
for (int i = 296; i <= 298; i++) {
INDEX_TO_CHARSET[i] = "utf8mb4";
}
INDEX_TO_CHARSET[300] = "utf8mb4";
for (int i = 303; i <= 307; i++) {
INDEX_TO_CHARSET[i] = "utf8mb4";
}
INDEX_TO_CHARSET[326] = "utf8mb4";
INDEX_TO_CHARSET[328] = "utf8mb4";
INDEX_TO_CHARSET[14] = "cp1251";
INDEX_TO_CHARSET[23] = "cp1251";
INDEX_TO_CHARSET[50] = "cp1251";
INDEX_TO_CHARSET[51] = "cp1251";
INDEX_TO_CHARSET[52] = "cp1251";
INDEX_TO_CHARSET[54] = "utf16";
INDEX_TO_CHARSET[55] = "utf16";
for (int i = 101; i <= 124; i++) {
INDEX_TO_CHARSET[i] = "utf16";
}
INDEX_TO_CHARSET[327] = "utf16";
INDEX_TO_CHARSET[56] = "utf16le";
INDEX_TO_CHARSET[62] = "utf16le";
INDEX_TO_CHARSET[57] = "cp1256";
INDEX_TO_CHARSET[67] = "cp1256";
INDEX_TO_CHARSET[29] = "cp1257";
INDEX_TO_CHARSET[58] = "cp1257";
INDEX_TO_CHARSET[59] = "cp1257";
INDEX_TO_CHARSET[60] = "utf32";
INDEX_TO_CHARSET[61] = "utf32";
for (int i = 160; i <= 183; i++) {
INDEX_TO_CHARSET[i] = "utf32";
}
INDEX_TO_CHARSET[391] = "utf32";
INDEX_TO_CHARSET[63] = "binary";
INDEX_TO_CHARSET[92] = "geostd8";
INDEX_TO_CHARSET[93] = "geostd8";
INDEX_TO_CHARSET[95] = "cp932";
INDEX_TO_CHARSET[96] = "cp932";
INDEX_TO_CHARSET[97] = "eucjpms";
INDEX_TO_CHARSET[98] = "eucjpms";
for (int i = 248; i <= 250; i++) {
INDEX_TO_CHARSET[i] = "gb18030";
}
// charset --> index
for (int i = 0; i < 2048; i++) {
String charset = INDEX_TO_CHARSET[i];
if (charset != null && CHARSET_TO_INDEX.get(charset) == null) {
CHARSET_TO_INDEX.put(charset, i);
}
}
CHARSET_TO_INDEX.put("iso-8859-1", 14);
CHARSET_TO_INDEX.put("iso_8859_1", 14);
CHARSET_TO_INDEX.put("utf-8", 33);
CHARSET_TO_INDEX.put("utf8mb4", 45);
}
public static final String getCharset(int index) {
return INDEX_TO_CHARSET[index];
}
public static final int getIndex(String charset) {
if (charset == null || charset.length() == 0) {
return 0;
} else {
Integer i = CHARSET_TO_INDEX.get(charset.toLowerCase());
return (i == null) ? 0 : i.intValue();
}
}
/**
* 'utf8' COLLATE 'utf8_general_ci'
*
* @param charset
* @return
*/
public static final String collateCharset(String charset) {
String[] output = StringUtils.split(charset, "COLLATE");
return output[0].replace('\'', ' ').trim();
}
public static String getJavaCharset(String charset) {
if ("utf8".equals(charset)) {
return charset;
}
if (StringUtils.endsWithIgnoreCase(charset, "utf8mb4")) {
return "utf-8";
}
if (StringUtils.endsWithIgnoreCase(charset, "binary")) {
return "iso_8859_1";
}
return charset;
}
}
| 30.343629 | 97 | 0.525639 |
f27102b5e6386a79e294739295031c97af55a05a | 4,211 | package com.example.findmytag;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import com.example.findmytag.wifi.WiFiActivity;
public class LocationActivity extends AppCompatActivity {
Button btn_mappingfrag, btn_testingfrag, btn_listofwifi;
ImageButton btn_back;
FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Bundle bundle=getIntent().getExtras();
// String rssi=bundle.getString("rssi");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
btn_mappingfrag = findViewById(R.id.btn_mappingfrag);
btn_testingfrag = findViewById(R.id.btn_testingfrag);
btn_listofwifi = findViewById(R.id.listofwifi);
btn_back = findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
fragmentTransaction = getSupportFragmentManager().beginTransaction();
MappingFragment mappingFragment = new MappingFragment();
// bundle.putString("rssi", rssi);
// mappingFragment.setArguments(bundle);
fragmentTransaction.show(mappingFragment);
fragmentTransaction.replace(R.id.frag_container, mappingFragment);
fragmentTransaction.commit();
btn_listofwifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent x = new Intent(LocationActivity.this, WiFiActivity.class);
startActivity(x);
}
});
//MappingFragment mappingFragment = new MappingFragment();
btn_mappingfrag.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.performClick();
view.setPressed(true);
btn_testingfrag.setPressed(false);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frag_container, mappingFragment);
fragmentTransaction.commit();
return true;
}
});
// btn_mappingfrag.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
// fragmentTransaction = getSupportFragmentManager().beginTransaction();
// MappingFragment mappingFragment = new MappingFragment();
// fragmentTransaction.replace(R.id.frag_container, mappingFragment);
// fragmentTransaction.commit();
//
// }
// });
TestingFragment testingFragment = new TestingFragment();
btn_testingfrag.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.performClick();
view.setPressed(true);
btn_mappingfrag.setPressed(false);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
//TestingFragment testingFragment = new TestingFragment();
fragmentTransaction.replace(R.id.frag_container, testingFragment);
fragmentTransaction.commit();
return true;
}
});
// btn_testingfrag.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
// fragmentTransaction = getSupportFragmentManager().beginTransaction();
// TestingFragment testingFragment = new TestingFragment();
// fragmentTransaction.replace(R.id.frag_container, testingFragment);
// fragmentTransaction.commit();
//
// }
// });
}
} | 37.936937 | 87 | 0.638566 |
9620b4e0ef4f212b22bcdf9d012ee3b92e56ff69 | 5,942 | import java.util.Arrays;
import java.util.Scanner;
class Exam27 {
private Scanner sc= new Scanner(System.in);
final private String NUMBER;
public Exam27()
{
System.out.println("Check narcissisticNumber. Enter Integer: ");
this.NUMBER= sc.next();
}
private int narcissisticNumber()
{
String str= NUMBER;
char[] chrs= str.toCharArray();
final int CAHR_LEN= chrs.length;
int[] sums= new int[CAHR_LEN];
for (int i=0; i<CAHR_LEN; i++)
{
int num= Integer.parseInt(String.valueOf(chrs[i]));
int result= (int) Math.pow(num,CAHR_LEN);
sums[i]= result;
}
return Arrays.stream(sums).sum();
}
public void printCompareValue()
{
int input_number= Integer.parseInt(NUMBER);
int comparing_number= narcissisticNumber();
final String NARCISSISTIC= "NARCISSISTIC NOMBER!";
final String NOT= "NOT NARCISSISTIC NOMBER!";
if (input_number == comparing_number) System.out.println(NARCISSISTIC);
else System.out.println(NOT);
}
}
class Exam025_02 {
public void checkPrimeFactRangeInValue(int range)
{
int counter=0;
int[] prime = new int[500];
int ptr = 0;
prime[ptr++] = 2;
prime[ptr++] = 3;
for(int n=5; n<=range; n+=2) {
boolean flag = true;
for(int i=1; prime[i]*prime[i]<=n; i++) {
counter+=2;
if(n%prime[i]==0) {
flag = false;
break;
}
}
if(flag) {
counter++;
prime[ptr++] = n;
System.out.println(n);
}
}
//총 연산 횟수 : 3774
System.out.println("총 연산횟수 : " + counter);
}
}
class Exam025 {
private Scanner sc= new Scanner(System.in);
public int n;
final String INTRO= "소수 판별기, 정수를 입력하시오.";
public Exam025()
{
System.out.println(INTRO);
this.n= sc.nextInt();
}
private boolean checkPrimeFact()
{
int num= n;
if (num%2==0) return false;
for (int i=3; i<=num; i++)
{
int condition= num%i;
if (condition == 0 && num == i) return true;
if (condition == 0) return false;
}
return false;
}
public void print()
{
if (checkPrimeFact()) System.out.println("prime number");
else System.out.println("Not prime number");
}
}
class Exam023 {
private Scanner sc= new Scanner(System.in);
private int a,b;
final String INTRO01= "정수 부분을 입력하시오.";
final String INTRO02= "지수 부분을 입력하시오.";
public Exam023() {
System.out.println(INTRO01);
this.a= sc.nextInt();
System.out.println(INTRO02);
this.b= sc.nextInt();
}
private int init()
{
int num= a, sm= b, result=1;
for (int i=0; i<sm; i++) result*= num;
return result;
}
public void printResult()
{
System.out.printf("Result: %d", init());
}
}
class Exam022 {
private String str= new Exam021().intToString();
private String reverseString()
{
char[] c_arr= str.toCharArray();
final int MAX_LEN= c_arr.length;
char[] c_result= new char[MAX_LEN];
for (int i=0, j=MAX_LEN-1; i<MAX_LEN; i++,j--)
{
c_result[i]= c_arr[j];
}
return String.valueOf(c_result);
}
public void printString()
{
System.out.println(reverseString());
}
}
class Exam021 {
private int n;
final String INTRO= "Enter a Integer Number: ";
private Scanner sc= new Scanner(System.in);
public Exam021() {}
public void setData()
{
this.n= intToString().length();
}
public String intToString()
{
System.out.printf(INTRO);
int a= sc.nextInt();
return String.valueOf(a);
}
public void printPlaceValue()
{
setData();
System.out.printf("자리 수 출력: %d", n);
}
}
public class java16 {
private Scanner sc= new Scanner(System.in);
final String INTRO_01= "숫자를 입력하시오:";
final String INTRO_02= "연산자를 입력하시오:";
public double setNumber()
{
System.out.printf(INTRO_01);
return sc.nextDouble();
}
public char setOperator()
{
System.out.printf(INTRO_02);
return sc.next().charAt(0);
}
public double calculator(double a, double b, char x)
{
switch (x)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
default:
break;
}
return -1;
}
public static void main(String[] args) {
System.out.println("==========================");
java16 jv= new java16();
double a= jv.setNumber();
char x= jv.setOperator();
double b= jv.setNumber();
double result= jv.calculator(a,b,x);
System.out.println(result);
System.out.println("==========================");
Exam021 e21= new Exam021();
e21.printPlaceValue();
System.out.println("==========================");
Exam022 e22= new Exam022();
e22.printString();
System.out.println("==========================");
Exam023 e23= new Exam023();
e23.printResult();
System.out.println("==========================");
Exam025 e25= new Exam025();
e25.print();
System.out.println("==========================");
System.out.println("정수 범위를 입력하시오. 0 ~ ");
Exam025 e25_2= new Exam025();
new Exam025_02().checkPrimeFactRangeInValue(e25_2.n);
Exam27 e27= new Exam27();
e27.printCompareValue();
}
}
| 25.393162 | 79 | 0.510602 |
c27f44fe90917bee45c88c55eca4dbfe2d69c661 | 3,472 | package com.parking.rest;
import com.parking.rest.dto.AccountGroupDto;
import com.sun.jersey.api.client.WebResource;
import org.codehaus.jettison.json.JSONException;
import org.junit.Test;
import java.net.URISyntaxException;
public class AccountGroupTest extends ApplicationTest {
@Test
public void testCreateOneGroupSuccess() throws JSONException, URISyntaxException {
String authToken = getToken("admin", "admin");
AccountGroupDto accountgroup = new AccountGroupDto();
accountgroup.setDescription("test content");
accountgroup.setName("family");
WebResource webResource = client().resource("http://localhost:8080/parking");
String vehicle1 = webResource.path("/rest/accountGroups")
.header("X-Auth-Token", authToken)
.accept("application/json")
.type("application/json")
.post(String.class, gson.toJson(accountgroup));
System.out.println("JSON \n" + toPrettyFormat(vehicle1));
webResource = client().resource("http://localhost:8080/parking");
vehicle1 = webResource.path("/rest/accountGroups")
.header("X-Auth-Token", authToken)
.accept("application/json")
.type("application/json")
.get(String.class);
System.out.println("GET root = " + toPrettyFormat(vehicle1));
}
@Test
public void testCreateTwoGroupsSuccess() throws JSONException, URISyntaxException {
String authToken = getToken("admin", "admin");
AccountGroupDto accountgroup = new AccountGroupDto();
accountgroup.setDescription("test content");
accountgroup.setName("family");
WebResource webResource = client().resource("http://localhost:8080/parking");
String vehicle1 = webResource.path("/rest/accountGroups")
.header("X-Auth-Token", authToken)
.accept("application/json")
.type("application/json")
.post(String.class, gson.toJson(accountgroup));
System.out.println("JSON = \n" + toPrettyFormat(vehicle1));
accountgroup = new AccountGroupDto();
accountgroup.setName("family");
accountgroup.setDescription("test content");
webResource = client().resource("http://localhost:8080/parking");
vehicle1 = webResource.path("/rest/accountGroups")
.header("X-Auth-Token", authToken)
.accept("application/json")
.type("application/json")
.post(String.class, gson.toJson(accountgroup));
System.out.println("JSON = \n" + toPrettyFormat(vehicle1));
// GET 1
webResource = client().resource("http://localhost:8080/parking");
vehicle1 = webResource.path("/rest/accountGroups/3")
.header("X-Auth-Token", authToken)
.accept("application/json")
.type("application/json")
.get(String.class);
System.out.println("GET root = " + toPrettyFormat(vehicle1));
// GET ALL
webResource = client().resource("http://localhost:8080/parking");
vehicle1 = webResource.path("/rest/accountGroups")
.header("X-Auth-Token", authToken)
.accept("application/json")
.type("application/json")
.get(String.class);
System.out.println("JSON = \n" + toPrettyFormat(vehicle1));
}
}
| 37.333333 | 87 | 0.618088 |
430252c841503a2073d000ef9dd3f24b708e2777 | 607 | package net.ulno.libni.controller.gdx.desktop;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import net.ulno.libni.controller.gdx.Main;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "Libni Libgdx Controller";
config.width = 1280;
config.height = 900;
new LwjglApplication(new Main(), config);
}
}
| 33.722222 | 77 | 0.771005 |
83686d46903bb5a5c16e89097a5ef527ed022e55 | 1,922 | package simpkins.query;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class QueryContextController<T> implements QueryContext<T>, Iterator<T> {
private Iterator<T> iterator;
// we roll over to index=0 when the first object is fetched.
private int index = -1;
// stores the items we've already iterated through.
private List<T> cache;
protected QueryContextController(Iterator<T> iterator) {
this.iterator = iterator;
}
// don't create the cache unless we need to.
private List<T> getCache() {
if (cache == null)
cache = new ArrayList<>();
return cache;
}
// see if we've already cached the next item.
private boolean hasNextInCache() {
return cache != null && getCache().size() > index + 1;
}
// not in QueryContext interface because we only want the internal query tools to advance the index.
@Override
public T next() {
T next = getNext();
index++;
return next;
}
@Override
public int getIndex() {
return index;
}
@Override
public boolean isFirst() {
return index == 0;
}
@Override
public boolean hasPrevious() {
return !isFirst();
}
@Override
public T getPrevious() {
if (isFirst())
throw new NoSuchElementException();
return cache.get(index - 1);
}
@Override
public boolean isLast() {
return !hasNext();
}
@Override
public boolean hasNext() {
return iterator.hasNext() || hasNextInCache();
}
@Override
public T getNext() {
if (hasNextInCache()) {
return getCache().get(index + 1);
}
else {
T next = iterator.next();
getCache().add(next);
return next;
}
}
}
| 23.156627 | 104 | 0.584287 |
d2ec718592aea12f479e99b3f6cbcae9f5d3b3de | 3,379 | package al.jdi.dao.beans;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import al.jdi.dao.model.Agendamento;
import al.jdi.dao.model.Cliente;
import al.jdi.dao.model.CriacaoModificacao;
public class DefaultAgendamentoDaoTest {
private static final Long ID = 1l;
private static final String S = "S";
private DefaultAgendamentoDao defaultAgendamentoDao;
@Mock
private Session session;
@Mock
private Agendamento agendamento;
@Mock
private CriacaoModificacao criacaoModificacao;
@Mock
private Cliente cliente;
@Mock
private List<Agendamento> agendamentos;
@Mock
private Criteria criteria;
@Mock
private DefaultDao<Agendamento> dao;
@Before
public void setUp() throws Exception {
initMocks(this);
when(dao.getSession()).thenReturn(session);
when(session.createCriteria(Agendamento.class)).thenReturn(criteria);
when(criteria.add(Mockito.any(Criterion.class))).thenReturn(criteria);
when(criteria.uniqueResult()).thenReturn(agendamento);
when(agendamento.getCriacaoModificacao()).thenReturn(criacaoModificacao);
when(agendamento.getCliente()).thenReturn(cliente);
when(cliente.getAgendamento()).thenReturn(agendamentos);
when(cliente.getCriacaoModificacao()).thenReturn(criacaoModificacao);
defaultAgendamentoDao = new DefaultAgendamentoDao(dao);
}
@Test
public void adicionaShouldEmptyPreviousAgendamentos() throws Exception {
when(agendamentos.isEmpty()).thenReturn(false);
defaultAgendamentoDao.adiciona(agendamento);
verify(agendamentos).clear();
}
@Test
public void adicionaShouldAddAgendamento() throws Exception {
defaultAgendamentoDao.adiciona(agendamento);
verify(agendamentos).add(agendamento);
}
@Test
public void adicionaShouldUpdateCliente() throws Exception {
defaultAgendamentoDao.adiciona(agendamento);
verify(session).update(cliente);
}
@Test
public void procuraShouldLookForAgendamento() throws Exception {
assertThat(defaultAgendamentoDao.procura(cliente), is(sameInstance(agendamento)));
}
@Test
public void atualiza() throws Exception {
defaultAgendamentoDao.atualiza(agendamento);
verify(dao).atualiza(agendamento);
}
@Test
public void listaTudo() throws Exception {
when(dao.listaTudo()).thenReturn(agendamentos);
assertThat(defaultAgendamentoDao.listaTudo(), is(sameInstance(agendamentos)));
}
@Test
public void procuraId() throws Exception {
when(dao.procura(ID)).thenReturn(agendamento);
assertThat(defaultAgendamentoDao.procura(ID), is(sameInstance(agendamento)));
}
@Test
public void remove() throws Exception {
defaultAgendamentoDao.remove(agendamento);
verify(dao).remove(agendamento);
}
@Test
public void procuraString() throws Exception {
when(dao.procura(S)).thenReturn(agendamento);
assertThat(defaultAgendamentoDao.procura(S), is(sameInstance(agendamento)));
}
}
| 28.880342 | 86 | 0.765315 |
b36e1650e887166e1b3076e02ffcb923f161afa1 | 977 | /*
* ____ _ ____ _ _ _____ ___ _
* / ___| / \ | _ \| \ | |_ _\ \ / / \ | |
* | | / _ \ | |_) | \| || | \ \ / / _ \ | |
* | |___/ ___ \| _ <| |\ || | \ V / ___ \| |___
* \____/_/ \_\_| \_\_| \_|___| \_/_/ \_\_____|
*
* https://github.com/yingzhuo/carnival
*/
package com.github.yingzhuo.carnival.spring;
import lombok.val;
import org.springframework.core.convert.TypeDescriptor;
/**
* @author 应卓
*/
public final class ConversionUtils {
private ConversionUtils() {
super();
}
public static <T> T convert(Object source, Class<T> targetType) {
val service = SpringUtils.getConversionService();
return service.convert(source, targetType);
}
@Deprecated
public static Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
val service = SpringUtils.getConversionService();
return service.convert(source, sourceType, targetType);
}
}
| 27.138889 | 103 | 0.583419 |
bf2a3cd53d9aebfc69a3ea3063f340db841fa424 | 369 | package shakeanapple.backtracker.parser.ltlformula.old.rule;
import shakeanapple.backtracker.parser.ltlformula.old.State;
import shakeanapple.backtracker.parser.ltlformula.old.Parser;
import shakeanapple.backtracker.parser.ltlformula.old.tree.Node;
public abstract class Rule {
private String name;
public abstract Node apply(State state, Parser parser);
}
| 28.384615 | 64 | 0.815718 |
310fe99da48a247248d28f28bfb4bb573392fe75 | 4,222 | package RozetkaTest;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.util.List;
public class RozetkaVerificationOfFilters {
String baseUrl = "https://rozetka.com.ua/";
WebDriver driver;
WebDriverWait wait;
@BeforeSuite
public void driverSetUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
wait = new WebDriverWait(driver, 20);
driver.manage().window().maximize();
driver.get(baseUrl);
}
@AfterSuite
public void quiteBrowser() {
driver.quit();
}
@Test
public void addToFiltersAcerAndAsus() throws Exception {
driver.findElement(By.name("search")).sendKeys("samsung" + Keys.ENTER);
WebElement tablet = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Планшеты")));
tablet.click();
WebElement acerFilter = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a label[for=Acer]")));
acerFilter.click();
driver.findElement(By.cssSelector("a label[for=Asus]")).click();
List<WebElement> result = driver.findElements(By.cssSelector("span[class=goods-tile__title]"));
for (int i = 0; i < result.size(); i++) {
if (!(result.get(i).getText().toLowerCase().contains("samsung") || result.get(i).getText().toLowerCase().contains("acer") || result.get(i).getText().toLowerCase().contains("asus"))) {
throw new Exception(result.get(i).getText().toLowerCase() + " no samsung or acer or asus");
}
}
}
@Test
public void priceFilter() throws Exception {
driver.findElement(By.name("search")).sendKeys("samsung" + Keys.ENTER);
WebElement tablet = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Планшеты")));
tablet.click();
WebElement priceMin = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[formcontrolname=min]")));
priceMin.click();
priceMin.clear();
priceMin.sendKeys("5000");
WebElement priceMax = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[formcontrolname=max]")));
priceMax.click();
priceMax.clear();
priceMax.sendKeys("15000");
driver.findElement(By.cssSelector("fieldset > div > button")).click();
List<WebElement> searchResults = driver.findElements(By.cssSelector("p span[class=goods-tile__price-value]"));
for (int i = 0; i < searchResults.size(); i++) {
int temp = Integer.parseInt(searchResults.get(i).getText().replaceAll(" ", ""));
if (temp < 5000 || temp > 15000) {
throw new Exception(searchResults.get(i).getText() + " <5000 || >15000");
}
}
}
@Test
public void addToFilterGalaxyA10() throws Exception {
driver.findElement(By.name("search")).sendKeys("samsung" + Keys.ENTER);
WebElement tablet = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Планшеты")));
tablet.click();
WebElement GalaxyA10Filter = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a label[for='Galaxy Tab A 10.1']")));
GalaxyA10Filter.click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span[class=goods-tile__title]")));
List<WebElement> result = driver.findElements(By.cssSelector("span[class=goods-tile__title]"));
for (int i = 0; i < result.size(); i++) {
if (!(result.get(i).getText().toLowerCase().contains("galaxy tab a 10.1"))) {
throw new Exception(result.get(i).getText().toLowerCase() + " no Galaxy Tab A 10.1");
}
}
}
}
| 45.397849 | 195 | 0.670062 |
bf80d62e7813f1c74332dc3c318ad0ef1c327cde | 5,576 | package wzp.com.texturemusic.bean;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
/**
* Created by Wang on 2017/6/28.
* 评论实体类
*/
public class CommentBean implements Parcelable {
private String commentId;
private String commnetCreaterName;
private Long commentCreaterId;
private String commentCreaterImgUrl;
private String description;
private String createTime;
private Integer likeCount;
private Integer shareCount;
private Integer commentCount;
private String val;
private UserBean userBean;
private List<String> imgUrls;
private MusicBean musicBean;
private List<CommentBean> replayList;
private List<CommentBean> hotComment;//精彩评论
public String getCommentId() {
return commentId;
}
public void setCommentId(String commentId) {
this.commentId = commentId;
}
public String getCommnetCreaterName() {
return commnetCreaterName;
}
public void setCommnetCreaterName(String commnetCreaterName) {
this.commnetCreaterName = commnetCreaterName;
}
public Long getCommentCreaterId() {
return commentCreaterId;
}
public void setCommentCreaterId(Long commentCreaterId) {
this.commentCreaterId = commentCreaterId;
}
public String getCommentCreaterImgUrl() {
return commentCreaterImgUrl;
}
public void setCommentCreaterImgUrl(String commentCreaterImgUrl) {
this.commentCreaterImgUrl = commentCreaterImgUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getLikeCount() {
return likeCount;
}
public void setLikeCount(Integer likeCount) {
this.likeCount = likeCount;
}
public Integer getShareCount() {
return shareCount;
}
public void setShareCount(Integer shareCount) {
this.shareCount = shareCount;
}
public Integer getCommentCount() {
return commentCount;
}
public void setCommentCount(Integer commentCount) {
this.commentCount = commentCount;
}
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
public List<String> getImgUrls() {
return imgUrls;
}
public void setImgUrls(List<String> imgUrls) {
this.imgUrls = imgUrls;
}
public MusicBean getMusicBean() {
return musicBean;
}
public void setMusicBean(MusicBean musicBean) {
this.musicBean = musicBean;
}
public List<CommentBean> getReplayList() {
return replayList;
}
public void setReplayList(List<CommentBean> replayList) {
this.replayList = replayList;
}
public List<CommentBean> getHotComment() {
return hotComment;
}
public void setHotComment(List<CommentBean> hotComment) {
this.hotComment = hotComment;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.commentId);
dest.writeString(this.commnetCreaterName);
dest.writeValue(this.commentCreaterId);
dest.writeString(this.commentCreaterImgUrl);
dest.writeString(this.description);
dest.writeString(this.createTime);
dest.writeValue(this.likeCount);
dest.writeValue(this.shareCount);
dest.writeValue(this.commentCount);
dest.writeString(this.val);
dest.writeParcelable(this.userBean, flags);
dest.writeStringList(this.imgUrls);
dest.writeParcelable(this.musicBean, flags);
dest.writeTypedList(this.replayList);
dest.writeTypedList(this.hotComment);
}
public CommentBean() {
}
protected CommentBean(Parcel in) {
this.commentId = in.readString();
this.commnetCreaterName = in.readString();
this.commentCreaterId = (Long) in.readValue(Long.class.getClassLoader());
this.commentCreaterImgUrl = in.readString();
this.description = in.readString();
this.createTime = in.readString();
this.likeCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.shareCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.commentCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.val = in.readString();
this.userBean = in.readParcelable(UserBean.class.getClassLoader());
this.imgUrls = in.createStringArrayList();
this.musicBean = in.readParcelable(MusicBean.class.getClassLoader());
this.replayList = in.createTypedArrayList(CommentBean.CREATOR);
this.hotComment = in.createTypedArrayList(CommentBean.CREATOR);
}
public static final Creator<CommentBean> CREATOR = new Creator<CommentBean>() {
@Override
public CommentBean createFromParcel(Parcel source) {
return new CommentBean(source);
}
@Override
public CommentBean[] newArray(int size) {
return new CommentBean[size];
}
};
}
| 26.937198 | 83 | 0.664275 |
7ccacaf9f4a60c16aefc1684ec6eb16b18b6a5a1 | 287 | package io.github.pikaq;
/**
* 异步回调,发送异步请求时使用
*
* @author pleuvoir
*
*/
public interface InvokeCallback {
/**
* 接收到响应时触发
*/
void onReceiveResponse(final RemotingFuture remotingFuture);
/**
* 发送异常时触发
*/
void onRequestException(final RemotingFuture remotingFuture);
}
| 13.666667 | 62 | 0.696864 |
0aab08198ec3871e58a04f393987a07df8b6c55d | 473 | package com.sx4.bot.handlers;
import com.mongodb.event.ClusterClosedEvent;
import com.mongodb.event.ClusterListener;
import com.mongodb.event.ClusterOpeningEvent;
public class MongoDatabaseHandler implements ClusterListener {
public void clusterOpening(ClusterOpeningEvent event) {
System.out.println("Connected to the MongoDB server");
}
public void clusterClosed(ClusterClosedEvent event) {
System.err.println("Disconnected from the MongoDB server");
}
}
| 26.277778 | 62 | 0.803383 |
9356482a76eadd035a6f03671f8add54f8b5cb83 | 1,517 | package com.venky.swf.plugins.collab.db.model.user;
import com.venky.core.util.ObjectUtil;
import com.venky.swf.db.model.Model;
import com.venky.swf.db.table.ModelImpl;
import com.venky.swf.plugins.collab.util.MailUtil;
public class EmailImpl<T extends Model & com.venky.swf.plugins.collab.db.model.user.Email> extends ModelImpl<T> {
public EmailImpl(){
super();
}
public EmailImpl(T email) {
super(email);
}
public void resendOtp(){
sendOtp(false);
}
public void sendOtp(){
sendOtp(true);
}
public void sendOtp(boolean generateFresh) {
T email = getProxy();
if (generateFresh || ObjectUtil.isVoid(email.getLastOtp())){
email.setLastOtp(OtpEnabled.generateOTP());
}
email.setValidated(false);
email.save();
MailUtil.getInstance().sendMail(email.getEmail(),"Your verification code.", "Your verification code is : " + email.getLastOtp());
}
public void validateOtp(String otp) {
T email = getProxy();
if (!ObjectUtil.equals(email.getLastOtp(), otp)) {
email.setValidated(false);
} else {
email.setValidated(true);
email.setLastOtp(null);
}
email.save();
}
public void validateOtp(){
validateOtp(getProxy().getOtp());
}
private String otp = null;
public String getOtp(){
return this.otp;
}
public void setOtp(String otp){
this.otp = otp;
}
}
| 25.711864 | 137 | 0.610415 |
878a08dc7e785cde3a6bdbc8c72fb7b1aef970a7 | 4,546 | /*
* Copyright (C) 2017 grandcentrix GmbH
* 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 net.grandcentrix.thirtyinch.internal;
import net.grandcentrix.thirtyinch.TiPresenter;
import net.grandcentrix.thirtyinch.TiView;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.concurrent.Executor;
import static org.mockito.Mockito.mock;
public class TiActivityDelegateBuilder {
private boolean mIsChangingConfigurations = false;
private boolean mIsDontKeepActivitiesEnabled = false;
private boolean mIsFinishing = false;
private TiPresenter<TiView> mPresenter;
private TiPresenterProvider<TiPresenter<TiView>> mPresenterProvider;
private TiPresenterProvider<TiPresenter<TiView>> mRetainedPresenterProvider;
private TiPresenterSavior mSavior = new MockSavior();
public TiActivityDelegate<TiPresenter<TiView>, TiView> build() {
TiPresenterProvider<TiPresenter<TiView>> presenterProvider = mPresenterProvider;
if (presenterProvider == null) {
presenterProvider = new TiPresenterProvider<TiPresenter<TiView>>() {
@NonNull
@Override
public TiPresenter<TiView> providePresenter() {
return mPresenter;
}
};
}
return new TiActivityDelegate<>(new DelegatedTiActivity<TiPresenter<TiView>>() {
@Nullable
@Override
public TiPresenter<TiView> getRetainedPresenter() {
if (mRetainedPresenterProvider == null) {
return null;
}
return mRetainedPresenterProvider.providePresenter();
}
@Override
public Executor getUiThreadExecutor() {
return new Executor() {
@Override
public void execute(@NonNull final Runnable action) {
action.run();
}
};
}
@Override
public boolean isActivityChangingConfigurations() {
return mIsChangingConfigurations;
}
@Override
public boolean isActivityFinishing() {
return mIsFinishing;
}
@Override
public boolean isDontKeepActivitiesEnabled() {
return mIsDontKeepActivitiesEnabled;
}
}, new TiViewProvider<TiView>() {
@NonNull
@Override
public TiView provideView() {
return mock(TiView.class);
}
}, presenterProvider, new TiLoggingTagProvider() {
@Override
public String getLoggingTag() {
return "TestLogTag";
}
}, mSavior);
}
public TiActivityDelegateBuilder setDontKeepActivitiesEnabled(final boolean enabled) {
mIsDontKeepActivitiesEnabled = enabled;
return this;
}
public TiActivityDelegateBuilder setIsChangingConfigurations(final boolean changing) {
mIsChangingConfigurations = changing;
return this;
}
public TiActivityDelegateBuilder setIsFinishing(final boolean finishing) {
mIsFinishing = finishing;
return this;
}
public TiActivityDelegateBuilder setPresenter(TiPresenter<TiView> presenter) {
mPresenter = presenter;
return this;
}
public TiActivityDelegateBuilder setPresenterProvider(
TiPresenterProvider<TiPresenter<TiView>> provider) {
mPresenterProvider = provider;
return this;
}
public TiActivityDelegateBuilder setRetainedPresenterProvider(
TiPresenterProvider<TiPresenter<TiView>> retainedPresenterProvider) {
mRetainedPresenterProvider = retainedPresenterProvider;
return this;
}
public TiActivityDelegateBuilder setSavior(final TiPresenterSavior savior) {
mSavior = savior;
return this;
}
}
| 32.014085 | 90 | 0.642323 |
3d6fe4e239b3305aba622a32716cfd4064338e4e | 6,087 | package de.mathema.sas.memorygame.rules;
import de.mathema.sas.memorygame.cards.Card;
import de.mathema.sas.memorygame.player.Player;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class GameTest {
Game game;
@Mock
GameView gameView;
@Mock
Player firstPlayer;
@Mock
Player secondPlayer;
@Mock
Card firstSelectedCard;
@Mock
Card secondSelectedCard;
@Before
public void init() {
game = Mockito.spy(new Game(gameView, firstPlayer, secondPlayer));
when(gameView.selectCard(any(), any()))
.thenReturn(firstSelectedCard)
.thenReturn(secondSelectedCard);
}
@Test
public void testStartRound_CardsMatch() {
// stops the game after one round
doReturn(true).when(game).noMoreCards(any());
when(firstSelectedCard.matches(secondSelectedCard)).thenReturn(true);
game.start();
verify(firstPlayer).scorePoint();
verify(secondPlayer, times(0)).scorePoint();
verify(firstSelectedCard).turnFaceUp();
verify(firstSelectedCard).freezeFaceUp();
verify(secondSelectedCard).turnFaceUp();
verify(secondSelectedCard).freezeFaceUp();
}
@Test
public void testStartRound_CardsDontMatch() {
// stops the game after one round
doReturn(true).when(game).noMoreCards(any());
when(firstSelectedCard.matches(secondSelectedCard)).thenReturn(false);
game.start();
verify(firstPlayer, times(0)).scorePoint();
verify(secondPlayer, times(0)).scorePoint();
verify(firstSelectedCard).turnFaceUp();
verify(firstSelectedCard).turnFaceDown();
verify(secondSelectedCard).turnFaceUp();
verify(secondSelectedCard).turnFaceDown();
}
@Test
public void testStartRound_ChangePlayersEachRound() {
// stops the game after two rounds
doReturn(false).
doReturn(true)
.when(game).noMoreCards(any());
when(firstSelectedCard.matches(secondSelectedCard)).thenReturn(false);
game.start();
verify(game, times(1)).startRound(firstPlayer);
verify(game, times(1)).startRound(secondPlayer);
}
@Test
public void testNextPlayer_CardsMatch_SamePlayerPlaysOn() {
when(firstSelectedCard.matches(secondSelectedCard)).thenReturn(true);
Player nextPlayer = game.nextPlayer(firstPlayer, firstSelectedCard, secondSelectedCard);
assertEquals(firstPlayer, nextPlayer);
nextPlayer = game.nextPlayer(secondPlayer, firstSelectedCard, secondSelectedCard);
assertEquals(secondPlayer, nextPlayer);
}
@Test
public void testNextPlayer_CardsDontMatch_TheOtherPlayerIsOn() {
when(firstSelectedCard.matches(secondSelectedCard)).thenReturn(false);
Player nextPlayer = game.nextPlayer(firstPlayer, firstSelectedCard, secondSelectedCard);
assertEquals(secondPlayer, nextPlayer);
nextPlayer = game.nextPlayer(secondPlayer, firstSelectedCard, secondSelectedCard);
assertEquals(firstPlayer, nextPlayer);
}
@Test
public void testTurnCardsFaceDown() {
Card firstCard = Mockito.mock(Card.class);
Card secondCard = Mockito.mock(Card.class);
game.turnCardsFaceDown(firstCard, secondCard);
verify(firstCard).turnFaceDown();
verify(secondCard).turnFaceDown();
verify(gameView).update(any(), any());
}
@Test
public void testTurnCardsFaceUp() {
Card firstCard = Mockito.mock(Card.class);
Card secondCard = Mockito.mock(Card.class);
game.turnCardsFaceUp(firstCard, secondCard);
verify(firstCard).turnFaceUp();
verify(secondCard).turnFaceUp();
verify(gameView).update(any(), any());
}
@Test
public void testFreezeCards() {
Card firstCard = Mockito.mock(Card.class);
Card secondCard = Mockito.mock(Card.class);
game.freezeCards(firstCard, secondCard);
verify(firstCard).freezeFaceUp();
verify(secondCard).freezeFaceUp();
verify(gameView).update(any(), any());
}
@Test
public void finishGame_PlayerOneWins() {
when(firstPlayer.outscores(secondPlayer)).thenReturn(true);
game.finishGame();
verify(firstPlayer).increaseRating();
verify(secondPlayer).reduceRating();
verify(gameView).winner(firstPlayer);
}
@Test
public void finishGame_PlayerOneLooses() {
when(firstPlayer.outscores(secondPlayer)).thenReturn(false);
game.finishGame();
verify(firstPlayer).reduceRating();
verify(secondPlayer).increaseRating();
verify(gameView).winner(secondPlayer);
}
@Test
public void createDuplicateCards() {
ArgumentCaptor<List<Card>> captureCards = ArgumentCaptor.forClass(List.class);
game.updateBoard();
verify(gameView).update(captureCards.capture(), any());
List<Card> cards = captureCards.getValue();
Set<Card> uniqueCards = new HashSet<>(cards);
assertEquals(uniqueCards.size(), cards.size() / 2);
}
@Test
public void noCardsInPlay_GameFinished() {
when(firstSelectedCard.isInPlay()).thenReturn(false);
when(secondSelectedCard.isInPlay()).thenReturn(false);
assertEquals(true, game.noMoreCards(List.of(firstSelectedCard, secondSelectedCard)));
}
@Test
public void cardsStillInPlay_GameNotFinished() {
when(firstSelectedCard.isInPlay()).thenReturn(true);
assertEquals(false, game.noMoreCards(List.of(firstSelectedCard, secondSelectedCard)));
}
}
| 31.056122 | 96 | 0.679317 |
10d740e65339d6b446b432f424990a1873624a8a | 6,093 | package com.eminent.usb.a3d;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
/**
* Created by kentlee on 2017/10/11.
*/
public class A3DController {
private static int s_interval = 135;
private static int s_integration_max_reg_value = 161;
private UsbDevice m_usb_device;
private UsbDeviceConnection m_usb_connection;
public A3DController( UsbDevice device, UsbDeviceConnection connection ) {
m_usb_device = device;
m_usb_connection = connection;
}
public void initDevice() {
UsbInterface intf = m_usb_device.getInterface( 0 );
m_usb_connection.claimInterface( intf, true );
}
public boolean resetSettings() {
boolean result = true;
result &= cameraWrite( (byte) 0x95, (byte) 0x20 ); // 0x40 = 60/4, 0x20 = 60/2, 0x00 = 60 FPS
result &= cameraWrite( (byte) 0x10, (byte) 0x0f ); // 0x0- = 400mA, 0x1- = 200mA, 0x2- = 100mA, 0x3- = 50mA
result &= cameraWrite( (byte) 0x14, (byte) 0x02 );
result &= cameraWrite( (byte) 0x08, (byte) 0x04 );
result &= cameraWrite( (byte) 0x00, (byte) 0xa1 ); // integration time = 0x1a ~ 0xa1
return result;
}
public boolean initCamera() {
initDevice();
return resetSettings();
}
public boolean setIntegrationTime( float value ) {
value = Math.min( 1.f, Math.max( 0.f, value ) );
int set_value = (int) ( value * (float) s_interval ) + ( s_integration_max_reg_value - s_interval );
set_value = Math.min( s_integration_max_reg_value, Math.max( 0, set_value ) );
return set_integration_time( set_value );
}
public boolean setIntegrationTimeWithRegisterValue( int value ) {
value = Math.min( s_integration_max_reg_value, Math.max( 0, value ) );
return set_integration_time( value );
}
public boolean setFrameRate( int fps ) {
// 0x30 = 15, 0x20 = 30, 0x10 = 60 FPS
if ( fps == 25 ) {
set_n_table( (byte) 183 );
set_m_table( (byte) 8 );
return set_frame_rate( 0x20 );
}
set_n_table( (byte) 117 );
set_m_table( (byte) 10 );
byte b = 0x20;
if ( fps == 60 ) {
b = 0x10;
} else if ( fps == 30 ) {
b = 0x20;
} else if ( fps == 15 ) {
b = 0x30;
}
return set_frame_rate( b );
}
public boolean setCurrentPower( int miniAmp ) {
// 0x0- = 400mA, 0x1- = 200mA, 0x2- = 100mA, 0x3- = 50mA
byte b = 0x00;
if ( miniAmp == 200 )
b = 0x10;
else if ( miniAmp == 100 )
b = 0x20;
else if ( miniAmp == 50 )
b = 0x30;
return set_current_power( b );
}
public boolean setPowerOn( boolean on ) {
return on ? set_power_on() : set_power_off();
}
public boolean turnOn() {
return setPowerOn( true );
}
public boolean turnOff() {
return setPowerOn( false );
}
public boolean cameraRead( byte addr, byte[] read_buffer ) {
if ( read_buffer.length < 2 )
return false;
final int[] result = new int[2];
{
byte[] buffer = new byte[] { addr, 0x00 };
result[0] = control_transfer( 0x21, 0x01, 0x0400, 0x0400, buffer );
}
{
byte[] buffer = read_buffer;
result[1] = control_transfer( 0xa1, 0x81, 0x0500, 0x0400, buffer );
}
// Log.i( "USBCameraController", "cameraRead result = " + result[0] + ", " + result[1] );
return ( result[0] == 2 && result[1] == 2 );
}
public boolean cameraWrite( byte addr, byte data ) {
final int[] result = new int[2];
{
byte[] buffer = new byte[] { addr, 0x00 };
result[0] = control_transfer( 0x21, 0x01, 0x0400, 0x0400, buffer );
}
{
byte[] buffer = new byte[] { data, 0x00 };
result[1] = control_transfer( 0x21, 0x01, 0x0500, 0x0400, buffer );
}
// Log.i( "USBCameraController", "cameraWrite result = " + result[0] + ", " + result[1] );
return ( result[0] == 2 && result[1] == 2 );
}
// =============================================================================== //
protected int control_transfer( int requestType, int request, int value, int index, byte[] buffer ) {
return m_usb_connection.controlTransfer( requestType, request, value, index, buffer, buffer.length, 2000 );
}
protected boolean set_integration_time( int reg_value ) {
byte b = (byte) ( reg_value & 0xFF );
return cameraWrite( (byte) 0x00, b );
}
protected boolean read_integration_time( byte[] read_buffer ) {
return cameraRead( (byte) 0x00, read_buffer );
}
protected boolean set_m_table( int reg_value ) {
return cameraWrite( (byte) 0x07, (byte) ( reg_value & 0xFF ) );
}
protected boolean set_n_table( int reg_value ) {
return cameraWrite( (byte) 0x06, (byte) ( reg_value & 0xFF ) );
}
protected boolean set_frame_rate( int reg_value ) {
return cameraWrite( (byte) 0x95, (byte) ( reg_value & 0xFF ) );
}
protected boolean read_frame_rate( byte[] read_buffer ) {
return cameraRead( (byte) 0x95, read_buffer );
}
protected boolean set_current_power( int reg_value ) {
byte b = ( (byte) ( reg_value & 0xF0 ) );
return cameraWrite( (byte) 0x10, (byte) ( b | 0x0f ) );
}
protected boolean read_current_power( byte[] read_buffer ) {
return cameraRead( (byte) 0x10, read_buffer );
}
protected boolean set_power_off() {
boolean result = cameraWrite( (byte) 0x10, (byte) 0x07 );
return result & cameraWrite( (byte) 0x8d, (byte) 0xa1 );
}
protected boolean set_power_on() {
boolean result = cameraWrite( (byte) 0x10, (byte) 0x0f );
return result & cameraWrite( (byte) 0x8d, (byte) 0x00 );
}
}
| 29.434783 | 115 | 0.569178 |
fb5bf7fc67a8261dd70bfab64b9dd84965bd2096 | 2,821 | package com.mickey305.util.file.zip;
import com.mickey305.util.file.AbsCompressManager;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.*;
/**
* Created by K.Misaki on 2017/04/02.
*
*/
public class ZipCompressor extends AbsCompressManager<BufferedInputStream, ZipOutputStream> {
private static final int DEFAULT_COMPRESS_LEVEL = 5;
private static final int DEFAULT_BUFFER_POOL_SIZE = 2^10;
private static final String DEFAULT_ENCODING = "UTF-8";
private String encoding;
private ZipCompressor() {}
public static ZipCompressor getInstance() {
return ZipCompressorHolder.INSTANCE;
}
private static class ZipCompressorHolder {
private static final ZipCompressor INSTANCE = new ZipCompressor();
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* 圧縮する(コアタスク)
* @param bis オープン済み入力ストリーム(オートクローズ:{@link java.lang.AutoCloseable})
* @param inRelativeFileName 圧縮対象のファイルパス名(入力フォルダをルートフォルダとした場合の相対的なファイル名)
* @param zos オープン済み出力ストリーム(オートクローズ:{@link java.lang.AutoCloseable})
* @return オープン済み出力ストリーム(後続処理返却用)
* @throws IOException 入出力例外
*/
@Override
protected ZipOutputStream compress(BufferedInputStream bis, String inRelativeFileName, ZipOutputStream zos) throws IOException {
zos.setLevel(DEFAULT_COMPRESS_LEVEL);
zos.setEncoding((getEncoding() == null)
? DEFAULT_ENCODING
: getEncoding());
zos.putNextEntry(new ZipEntry(inRelativeFileName));
int readSize;
byte buffer[] = new byte[DEFAULT_BUFFER_POOL_SIZE];
while ((readSize = bis.read(buffer, 0, buffer.length)) != -1) {
zos.write(buffer, 0, readSize);
}
zos.closeEntry();
return zos;
}
/**
* 入力ストリームを生成する
* @param inFile 入力ストリームにバインドするファイル
* @return 入力ストリーム
* @throws FileNotFoundException ファイル存在例外
*/
@Nonnull
@Override
public BufferedInputStream createInputStream(@Nullable File inFile) throws FileNotFoundException {
assert inFile != null;
FileInputStream fis = new FileInputStream(inFile);
return new BufferedInputStream(fis);
}
/**
* 出力ストリームを生成する
* @param outFile 出力ストリームにバインドするファイル
* @return 出力ストリーム
* @throws FileNotFoundException ファイル存在例外
*/
@Nonnull
@Override
public ZipOutputStream createOutputStream(@Nullable File outFile) throws FileNotFoundException {
assert outFile != null;
FileOutputStream fos = new FileOutputStream(outFile);
return new ZipOutputStream(fos);
}
}
| 30.663043 | 132 | 0.683446 |
727e17776f270d72496fc3d4de26b9eb5c3f0df9 | 379 | package com.example.libo.myapplication.Activity;
import android.os.Bundle;
import android.app.Activity;
import com.example.libo.myapplication.R;
public class UserSearchActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_search);
}
}
| 22.294118 | 56 | 0.765172 |
32b016298efd01b5c4ad51df4ff0c17e56d27c47 | 435 | package com.example.githubclient;
public interface APIConfiguration {
static final String COMPANY_DOMAIN = "xpandit-fa07db";
static final String API_BASE_URL_PD = "https://" + COMPANY_DOMAIN + ".pipedrive.com/";
static final String API_BASE_URL_GH = "https://api.github.com/";
static final String API_VERSION_SPEC_GH = "application/vnd.github.v3+json";
static final String JSON_CONTENT_TYPE = "application/json";
} | 48.333333 | 90 | 0.751724 |
4c127569dce1c378c26da4a8acf0da5487682c97 | 872 | package com.ruan.hncc.dms.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import com.ruan.hncc.dms.entity.CaseModelCatalog;
import com.ruan.hncc.dms.service.CaseModelCatalogService;
/**
* 病例模版目录表
*
* @author ruanteng
* Date 2021-02-27 00:56:42
* Copyright (C) hlhs
*/
@RestController
@RequestMapping("dms/casemodelcatalog")
public class CaseModelCatalogController {
@Resource
private CaseModelCatalogService caseModelCatalogService;
}
| 26.424242 | 62 | 0.81422 |
89148a9fac79718b7d290ba69f8d10f2a93f3857 | 1,619 | /**
*copyright(C)2012
*Ods信息技术软件有限公司 & Service Corporation All rights reserved
*/
package com.ods.base.action.system.bulletin;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSessions;
/**
*<b>系统名称:</b><b>
*武警遵义支队按纲建队系统
*</b>
* <br>
*
*
*<b>文件名:</b><br>
*
*DwrMessageSend.java<br>
* <br>
*
*<b>类名:</b><br>
*
*
*DwrMessageSend类.<br>
* <br>
*
*<br>
*<b>概要说明</b><br>
*
*
*
*DwrMessageSend类的概要说明<br>
** * * * * * *
*
*dwr消息发送实现类<br>
*
*<b>***History*** </b/><br>
*更新年月日, 更改原因, 姓名, 更新内容<br>
*2012-1-17, cause, 10325431@qq.com, 新建<br>
*
*@author :10325431@qq.com
*@since :2012-1-17
*@version:1.0
*/
public class DwrMessageSend {
/**
*属性名:SEND_JS_METHOD、类型:String、作成日:2009-10-17.<br>
*含义:页面js方法
*/
private static final String SEND_JS_METHOD = "showMessageJustInTime";
public static void sendMsg(final String messageInfoJson) {
Browser.withAllSessions(new Runnable() {
public void run() {
System.out.println("┣▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇═—");
System.out.println("开始进行消息发送="+messageInfoJson);
System.out.println("∝╬══→∝╬══→∝╬══→∝╬══→∝╬══→∝╬══→∝╬══→");
ScriptSessions.addFunctionCall(SEND_JS_METHOD,messageInfoJson);
}
});
}
}
| 24.907692 | 81 | 0.555281 |
64c7afc53a8c7ac0a4214f725edeb3aa245dbf14 | 1,121 | package foo;
import static androidx.lifecycle.Lifecycle.Event.ON_START;
import static androidx.lifecycle.Lifecycle.Event.ON_STOP;
import androidx.lifecycle.Lifecycle.Event;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
public class Bar implements LifecycleObserver {
@OnLifecycleEvent(ON_START)
public void doOnStart() {
}
@OnLifecycleEvent(ON_STOP)
public void doOnStop1Arg(LifecycleOwner provider) {
}
@OnLifecycleEvent(ON_STOP)
public void doOnStop2Args(LifecycleOwner provider) {
}
public static class Inner1 implements LifecycleObserver {
@OnLifecycleEvent(ON_START)
public void doOnStart() {
}
public static class Inner2 implements LifecycleObserver {
@OnLifecycleEvent(ON_START)
public void doOnStart() {
}
public static class Inner3 implements LifecycleObserver {
@OnLifecycleEvent(ON_START)
public void doOnStart() {
}
}
}
}
}
| 26.690476 | 69 | 0.67975 |
81a0020ed70aa0fcd46bbfee01f37b3f950b7bb8 | 252 | package com.github.extermania.leetcode;
public class $0596_Classes_More_Than_5_Students_24_88 {
// select class from(
// select count(1) as cnt, class from (select distinct student, class from courses) group by class
// )where cnt>=5
}
| 31.5 | 101 | 0.72619 |
bf35c02acf608dcc45f46bfdf4238d3b84bd8010 | 7,181 | /*
* The FUJABA ToolSuite RE project:
*
* FUJABA is the acronym for 'From Uml to Java And Back Again'
* and originally aims to provide an environment for round-trip
* engineering using UML as visual programming language. During
* the last years, the environment has become a base for several
* research activities, e.g. distributed software, database
* systems, modelling mechanical and electrical systems and
* their simulation. Thus, the environment has become a project,
* where this source code is part of. Further details are avail-
* able via http://www.fujaba.de
*
* Copyright (C) Fujaba Development Group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA or download the license under
* http://www.gnu.org/copyleft/lesser.html
*
* WARRANTY:
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* Contact address:
*
* Fujaba Management Board
* Software Engineering Group
* University of Paderborn
* Warburgerstr. 100
* D-33098 Paderborn
* Germany
*
* URL : http://www.fujaba.de
* email: info@fujaba.de
*
*/
package org.reclipse.behavior.inference.input;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.reclipse.behavior.inference.StructuralAnnotation;
/**
* @author lowende
* @author Last editor: $Author: lowende $
* @version $Revision: 3736 $ $Date: 2007-09-04 21:16:47 +0200 (Di, 04 Sep 2007) $
*/
public class StructuralAnnotationsWriter
{
private final Set<StructuralAnnotation> annotations;
/**
* @param annotations the annotations to be saved.
*/
public StructuralAnnotationsWriter(
final Set<StructuralAnnotation> annotations)
{
this.annotations = annotations;
}
/**
* @param file The file to save the document in.
* @return true, if file has been written
*/
public boolean save(String fileName, final boolean zipped)
{
try
{
Writer writer;
ZipOutputStream zipOutputStream = null;
if (zipped)
{
if (!fileName
.endsWith(IStructuralAnnotationsConstants.ZIP_FILE_SUFFIX))
{
fileName += IStructuralAnnotationsConstants.ZIP_FILE_SUFFIX;
}
final File file = new File(fileName);
final FileOutputStream fileOutputStream = new FileOutputStream(file);
zipOutputStream = new ZipOutputStream(fileOutputStream);
final ZipEntry zipEntry = new ZipEntry(
IStructuralAnnotationsConstants.FILE_NAME);
zipOutputStream.putNextEntry(zipEntry);
final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
zipOutputStream);
writer = new BufferedWriter(outputStreamWriter);
}
else
{
if (!fileName
.endsWith(IStructuralAnnotationsConstants.XML_FILE_SUFFIX))
{
fileName += IStructuralAnnotationsConstants.XML_FILE_SUFFIX;
}
final FileWriter fileWriter = new FileWriter(fileName);
writer = new BufferedWriter(fileWriter);
}
generateXMLDocument(writer);
writer.flush();
writer.close();
if (zipOutputStream != null)
{
zipOutputStream.close();
}
}
catch (final IOException e)
{
return false;
}
return true;
}
public void generateXMLDocument(final Writer writer) throws IOException
{
writer.write("<?xml version=\"1.0\" standalone=\"no\"?>\n\n");
writer.write("<!DOCTYPE ");
writer.write(IStructuralAnnotationsConstants.STRUCTURAL_ANNOTATIONS_TAG);
writer.write(" SYSTEM \"");
writer.write(IStructuralAnnotationsConstants.SYSTEM_ID);
writer.write("\">\n\n");
generateXMLTagForGFRN(writer);
}
private void generateXMLTagForGFRN(final Writer writer) throws IOException
{
writer.write("<");
writer.write(IStructuralAnnotationsConstants.STRUCTURAL_ANNOTATIONS_TAG);
writer.write(" ");
writer.write(IStructuralAnnotationsConstants.SIZE_ATTRIBUTE);
writer.write("=\"");
writer.write(Integer.toString(this.annotations.size()));
writer.write("\">\n\n");
for (final StructuralAnnotation annotation : this.annotations)
{
generateXMLTagForGFRNAnnotation(writer, annotation);
}
writer.write("</");
writer.write(IStructuralAnnotationsConstants.STRUCTURAL_ANNOTATIONS_TAG);
writer.write(">\n");
}
private void generateXMLTagForGFRNAnnotation(final Writer writer,
final StructuralAnnotation annotation) throws IOException
{
writer.write(" <");
writer.write(IStructuralAnnotationsConstants.STRUCTURAL_ANNOTATION_TAG);
writer.write(" ");
writer.write(IStructuralAnnotationsConstants.NAME_ATTRIBUTE);
writer.write("=\"");
writer.write(annotation.getType());
writer.write("\" ");
writer.write(IStructuralAnnotationsConstants.FUZZY_BELIEF_ATTRIBUTE);
writer.write("=\"");
writer.write(Double.toString(annotation.getFuzzyBelief()));
writer.write("\">\n");
for (final String key : annotation.keysOfNodes())
{
generateXMLTagForBinding(writer, key, annotation.getFromNodes(key));
}
writer.write(" </");
writer.write(IStructuralAnnotationsConstants.STRUCTURAL_ANNOTATION_TAG);
writer.write(">\n\n");
}
private void generateXMLTagForBinding(final Writer writer, final String key,
final String value) throws IOException
{
writer.write(" <");
writer.write(IStructuralAnnotationsConstants.BOUND_OBJECT_TAG);
writer.write(" ");
writer.write(IStructuralAnnotationsConstants.KEY_ATTRIBUTE);
writer.write("=\"");
writer.write(key);
writer.write("\" ");
writer.write(IStructuralAnnotationsConstants.NAME_ATTRIBUTE);
writer.write("=\"");
writer.write(value);
writer.write("\"/>\n");
}
}
| 32.789954 | 83 | 0.645732 |
3fbdf810f656747613d1476f4dc6445349fe98f6 | 1,686 | package com.algaworks.algafood.api.exceptionhandler;
import java.time.OffsetDateTime;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Getter;
@ApiModel("Problema")
@JsonInclude(Include.NON_NULL)
@Getter
@Builder
public class Problem {
@ApiModelProperty(example = "400", position = 1)
private Integer status;
@ApiModelProperty(example = "https://algafood.com.br/erro-de-sistema", position = 5)
private String type;
@ApiModelProperty(example = "Erro de sistema", position = 10)
private String title;
@ApiModelProperty(example = "Ocorreu um erro interno inesperado no sistema. Tente novamente e se o problema persistir, entre em contato com o administrador do sistema.", position = 15)
private String detail;
@ApiModelProperty(example = "Ocorreu um erro interno inesperado no sistema. Tente novamente e se o problema persistir, entre em contato com o administrador do sistema.", position = 20)
private String userMessage;
@ApiModelProperty(example = "2021-05-23T20:16:47.2931276Z", position = 25)
private OffsetDateTime timestamp;
@ApiModelProperty(value = "Campos que geraram o(s) erro(s)", position = 30)
private List<Error> errors;
@ApiModel("ObjetoProblema")
@Getter
@Builder
public static class Error {
@ApiModelProperty(example = "preco")
private String name;
@ApiModelProperty(example = "O preço é obrigatório")
private String userMessage;
}
}
| 30.654545 | 188 | 0.736655 |
dd2ee4e2f088d066f074d626ebd1e669e814d278 | 504 | package com.review.socket.TCPTest04;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author 小白
* @create 2021/4/14
*/
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket =new ServerSocket(999);
while(true){
Socket socket=serverSocket.accept();
ServerHandler handler =new ServerHandler(socket);
Thread thread =new Thread(handler);
thread.start();
}
}
}
| 24 | 61 | 0.634921 |
b922b98a0532ce59f9d627c926c200b3d7da873b | 4,900 | package org.apache.lucene.demo;
import org.apache.lucene.search.similarities.*;
import org.apache.lucene.index.FieldInvertState;
import org.apache.lucene.search.CollectionStatistics;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.TermStatistics;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.SmallFloat;
public class CMPT456Similarity extends TFIDFSimilarity {
/** Cache of decoded bytes. */
private static final float[] NORM_TABLE = new float[256];
static {
for (int i = 0; i < 256; i++) {
NORM_TABLE[i] = SmallFloat.byte315ToFloat((byte)i);
}
}
/** Sole constructor: parameter-free */
public CMPT456Similarity() {}
/** Implemented as <code>overlap / maxOverlap</code>. */
@Override
public float coord(int overlap, int maxOverlap) {
return overlap / (float)maxOverlap;
}
/** Implemented as <code>1/sqrt(sumOfSquaredWeights)</code>. */
@Override
public float queryNorm(float sumOfSquaredWeights) {
return (float)(1.0 / Math.sqrt(sumOfSquaredWeights));
}
/**
* Encodes a normalization factor for storage in an index.
* <p>
* The encoding uses a three-bit mantissa, a five-bit exponent, and the
* zero-exponent point at 15, thus representing values from around 7x10^9 to
* 2x10^-9 with about one significant decimal digit of accuracy. Zero is also
* represented. Negative numbers are rounded up to zero. Values too large to
* represent are rounded down to the largest representable value. Positive
* values too small to represent are rounded up to the smallest positive
* representable value.
*
* @see org.apache.lucene.document.Field#setBoost(float)
* @see org.apache.lucene.util.SmallFloat
*/
@Override
public final long encodeNormValue(float f) {
return SmallFloat.floatToByte315(f);
}
/**
* Decodes the norm value, assuming it is a single byte.
*
* @see #encodeNormValue(float)
*/
@Override
public final float decodeNormValue(long norm) {
return NORM_TABLE[(int) (norm & 0xFF)]; // & 0xFF maps negative bytes to positive above 127
}
/** Implemented as
* <code>state.getBoost()*lengthNorm(numTerms)</code>, where
* <code>numTerms</code> is {@link FieldInvertState#getLength()} if {@link
* #setDiscountOverlaps} is false, else it's {@link
* FieldInvertState#getLength()} - {@link
* FieldInvertState#getNumOverlap()}.
*
* @lucene.experimental */
@Override
public float lengthNorm(FieldInvertState state) {
final int numTerms;
if (discountOverlaps)
numTerms = state.getLength() - state.getNumOverlap();
else
numTerms = state.getLength();
return state.getBoost() * ((float) (1.0 / Math.sqrt(numTerms)));
}
/** Implemented as <code>sqrt(freq)</code>. */
@Override
public float tf(float freq) {
return (float)Math.sqrt(1+freq);
}
/** Implemented as <code>1 / (distance + 1)</code>. */
@Override
public float sloppyFreq(int distance) {
return 1.0f / (distance + 1);
}
/** The default implementation returns <code>1</code> */
@Override
public float scorePayload(int doc, int start, int end, BytesRef payload) {
return 1;
}
@Override
public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics termStats) {
final long df = termStats.docFreq();
final long docCount = collectionStats.docCount() == -1 ? collectionStats.maxDoc() : collectionStats.docCount();
final float idf = idf(df, docCount);
return Explanation.match(idf, "idf, computed as log((docCount+2)/(docFreq+2)) + 1 from:",
Explanation.match(df, "docFreq"),
Explanation.match(docCount, "docCount"));
}
/** Implemented as <code>log((docCount+1)/(docFreq+1)) + 1</code>. */
@Override
public float idf(long docFreq, long docCount) {
return (float)(Math.log((docCount+2)/(double)(docFreq+2)) + 1.0);
}
/**
* True if overlap tokens (tokens with a position of increment of zero) are
* discounted from the document's length.
*/
protected boolean discountOverlaps = true;
/** Determines whether overlap tokens (Tokens with
* 0 position increment) are ignored when computing
* norm. By default this is true, meaning overlap
* tokens do not count when computing norms.
*
* @lucene.experimental
*
* @see #computeNorm
*/
public void setDiscountOverlaps(boolean v) {
discountOverlaps = v;
}
/**
* Returns true if overlap tokens are discounted from the document's length.
* @see #setDiscountOverlaps
*/
public boolean getDiscountOverlaps() {
return discountOverlaps;
}
@Override
public String toString() {
return "CMPT456Similarity";
}
}
| 32.450331 | 116 | 0.664082 |
8922b1470575bbb8ddc0a499e5b90f0e395167c7 | 826 | package homework.cardealer.domain.dto.seed;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement(name = "suppliers")
@XmlAccessorType(XmlAccessType.FIELD)
public class SupplierSeedRootDto implements Serializable {
@XmlElement(name = "supplier")
private List<SupplierSeedDto> supplierDto;
public SupplierSeedRootDto() {
this.supplierDto = new ArrayList<>();
}
public List<SupplierSeedDto> getSupplierDto() {
return supplierDto;
}
public void setSupplierDto(List<SupplierSeedDto> supplierDto) {
this.supplierDto = supplierDto;
}
}
| 27.533333 | 67 | 0.756659 |
c608b038ce79c6be9f74929813a7c0ef310b1942 | 1,093 | package com.shejiaomao.weibo.widget;
import com.cattong.entity.Status;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.style.ClickableSpan;
import android.view.View;
import com.shejiaomao.weibo.activity.MicroBlogActivity;
public class CommentClickableSpan extends ClickableSpan {
private Status status;
public CommentClickableSpan(Status status) {
this.status = status;
}
@Override
public void onClick(View widget) {
if (status == null) {
return;
}
Context context = widget.getContext();
Intent intent = new Intent();
Bundle bundle = new Bundle();
//
// bundle.putInt("TYPE", Constants.EDIT_TYPE_COMMENT);
// bundle.putSerializable("STATUS", status);
// intent.putExtras(bundle);
//
// intent.setClass(context, EditCommentActivity.class);
bundle.putSerializable("STATUS", status);
intent.putExtras(bundle);
intent.setClass(context, MicroBlogActivity.class);
((Activity)context).startActivity(intent);
}
}
| 26.02381 | 58 | 0.716377 |
697da2a34fa894d0eb0b5c0e1e4c06aa53a68f0f | 856 | class Main {
public static int binarySearch(int[] array, int target) {
int high = array.length - 1;
int low = 0;
while (high >= low) {
int middle = (low + high) / 2;
if (array[middle] == target) {
return middle;
} else if (array[middle] > target) {
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] array = new int[] { 0, 1, 21, 33, 45, 45, 61, 71, 72, 73 };
int index = binarySearch(array, 33);
int index2 = binarySearch(array, 133);
assert index == 3 : "Wrong Answer";
assert index2 == -1 : "Wrong Answer";
System.out.println("Correct Answer");
}
} | 28.533333 | 74 | 0.453271 |
62295802309378cf9b205d14cec4e31119bf78c7 | 5,885 | /*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gukize;
/*
* Created by Hippo on 8/22/2016.
*/
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.conaco.Conaco;
import com.hippo.conaco.ValueHelper;
import com.hippo.image.BitmapDecoder;
import com.hippo.image.Image;
import com.hippo.image.ImageData;
import com.hippo.image.ImageInfo;
import com.hippo.image.ImageRenderer;
import com.hippo.streampipe.InputStreamPipe;
import java.io.IOException;
public class Gukize {
private Gukize() {}
private static Conaco<IBData> sConaco;
public static void init(Builder builder) {
if (sConaco != null) {
throw new IllegalStateException("Can't init Gukize twice");
}
builder.isValid();
IBDrawable.init(builder.coreAnimatedThreadCount);
sConaco = builder.build();
}
public static Conaco<IBData> getConaco() {
if (sConaco == null) {
throw new IllegalStateException("Please call Gukize.init(build)");
}
return sConaco;
}
private static class ImageDataHelper implements ValueHelper<IBData> {
private static final String LOG_TAG = ImageDataHelper.class.getSimpleName();
@Nullable
@Override
public IBData decode(@NonNull InputStreamPipe isPipe) {
try {
isPipe.obtain();
// Get image info
final ImageInfo info = new ImageInfo();
if (!BitmapDecoder.decode(isPipe.open(), info)) {
Log.w(LOG_TAG, "This InputSteam is not a Image.");
return null;
}
isPipe.close();
if (info.frameCount == 1) {
// It is a static image, use Bitmap
final Bitmap bitmap = BitmapDecoder.decode(isPipe.open());
if (bitmap != null) {
return new BData(bitmap);
} else {
return null;
}
} else {
// It may be a animated image
final ImageData imageData = Image.decode(isPipe.open());
if (imageData != null) {
if (imageData.getFrameCount() == 1) {
// It is a static image, draw image to Bitmap
final Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(imageData.getWidth(), imageData.getHeight(),
imageData.isOpaque() ? Bitmap.Config.RGB_565 : Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError e) {
Log.d(LOG_TAG, "Can't create Bitmap, out of memory.");
imageData.recycle();
return null;
}
final ImageRenderer imageRenderer = imageData.createImageRenderer();
imageRenderer.render(bitmap, 0, 0, 0, 0, imageData.getWidth(), imageData.getHeight(), 1, false, 0);
imageRenderer.recycle();
imageData.recycle();
return new BData(bitmap);
} else {
// It is a animated
// Fix odd delay
imageData.setBrowserCompat(true);
return new IData(imageData);
}
} else {
return null;
}
}
} catch (IOException e) {
return null;
} finally {
isPipe.close();
isPipe.release();
}
}
@Override
public int sizeOf(@NonNull String key, @NonNull IBData value) {
return value.getByteCount();
}
@Override
public void onAddToMemoryCache(@NonNull String key, @NonNull IBData value) {
value.addReference();
}
@Override
public void onRemoveFromMemoryCache(@NonNull String key, @NonNull IBData value) {
value.removeReference();
}
@Override
public boolean useMemoryCache(@NonNull String key, @Nullable IBData value) {
return true;
}
}
public static class Builder extends Conaco.Builder<IBData> {
/**
* The core thread count for animated image.
* 0 ~ 3 is fine. More animated image for large number.
*/
public int coreAnimatedThreadCount = 0;
public Builder() {
valueHelper = new ImageDataHelper();
}
@Override
public void isValid() throws IllegalStateException {
super.isValid();
if (!hasMemoryCache) {
throw new IllegalStateException("Gukize must support memory cache");
}
if (!(valueHelper instanceof ImageDataHelper)) {
throw new IllegalStateException("Don't assign objectHelper");
}
}
}
}
| 34.415205 | 127 | 0.535599 |
f7cd7b987ac3abfad1be9fc125d40e2926624ee1 | 2,978 |
import java.time.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.io.*;
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//this is the new nurse window
public class newNurse extends FinalProjectApp {
//Nurse to be returned later
Nurse aNurse = new Nurse();
//FinalProjectApp ref = new FinalProjectApp();
//Nurse map
//HashMap<Integer, Nurse> NurseCatalog = new HashMap<Integer, Nurse>();
//provide methods to add values
public void addNurse(int akey, Nurse aNurse){
super.NurseCatalogGet().put(akey, aNurse);
}
public void creation() {
//main new nurse window
JFrame frame4 = new JFrame("add Nurse window");
frame4.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame4.setLayout(new BoxLayout(frame4.getContentPane(), BoxLayout.PAGE_AXIS));
//JButton
JButton button = new JButton("create");
//initial texts
JLabel title = new JLabel("****************CREATOR*****************");
//ID
JLabel textLabelID = new JLabel("type ID");
JTextField nameFieldID = new JTextField( 20);
//name
JLabel textLabelName = new JLabel("type Name");
JTextField nameFieldName = new JTextField( 20);
//gender
JLabel textLabelGender = new JLabel("type gender");
JTextField nameFieldGender = new JTextField( 20);
//DOB
JLabel textLabelDOB = new JLabel("type date of birth");
JTextField nameFieldDOB = new JTextField( 20);
//Occupation
JLabel textLabelOccupation = new JLabel("type occupation");
JTextField nameFieldOccupation = new JTextField( 20);
//the action happens here
//first we convert ID to int
//int recordedID = Integer.parseInt(nameFieldID.getText());
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.out.print("clicked");
//Create the new Nurse
Nurse aNurse = new Nurse(Integer.parseInt(nameFieldID.getText()), nameFieldName.getText(), nameFieldDOB.getText(), nameFieldGender.getText(), nameFieldOccupation.getText());
System.out.print("gate i");
addNurse(aNurse.getID(), aNurse);
System.out.print("gate ii");
//close after
frame4.dispose();
}
//} catch (IOException e) {
//System.out.println(e.getMessage());
});
//add element to frame
frame4.add(title);
frame4.add(textLabelID);
frame4.add(nameFieldID);
frame4.add(textLabelName);
frame4.add(nameFieldName /*BorderLayout.EAST*/);
frame4.add(textLabelGender);
frame4.add(nameFieldGender /*BorderLayout.EAST*/);
frame4.add(textLabelDOB);
frame4.add(nameFieldDOB /*BorderLayout.EAST*/);
frame4.add(textLabelOccupation);
frame4.add(nameFieldOccupation /*BorderLayout.EAST*/);
frame4.add(button, BorderLayout.SOUTH);
frame4.setLocationRelativeTo(null);
frame4.pack();
frame4.setVisible(true);
//return aNurse;
//debug
//System.out.println(super.NurseCatalog);
}
} | 21.737226 | 177 | 0.692747 |
af7edc27651dcb0cf7c6ebac423043d0cfb0c2dd | 5,080 | /*
* Copyright (c) 2020 Squaredesk GmbH and Oliver Dotzauer.
*
* This program is distributed under the squaredesk open source license. See the LICENSE file distributed with this
* work for additional information regarding copyright ownership. You may also obtain a copy of the license at
*
* https://squaredesk.ch/license/oss/LICENSE
*/
package ch.squaredesk.nova.autoconfigure.comm.http;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("nova.http.client")
public class HttpClientConfigurationProperties {
/** Defines, whether HTTP client mode should be enabled */
private boolean enable = true;
/** Default amount of seconds to wait for a reponse before a timeout is triggered */
private int defaultRequestTimeoutInSeconds;
/** Should zipping of transmitted data be enforced? */
private boolean compressionEnforced;
/** Amount of seconds to wait for a connection before a timeout is triggered */
private int connectionTimeoutInSeconds;
/** Amount of seconds to wait for a websocket connection before a timeout is triggered */
private int webSocketTimeoutInSeconds;
/** DANGER! If set to true, no HTTPS certificate validation is performed. Only use in DEV mode and at your own risk! */
private boolean acceptAnyCertificate;
private String userAgent;
/** (Optional) SSL certificate. If this is set, the attribute sslCertificatePathIsIgnored */
private String sslCertificateContent;
/** (Optional) path to an SSL certificate */
private String sslCertificatePath;
/** (Optional) path to an SSL key store */
private String sslKeyStorePath;
/** (Optional) password of the SSL key store, defined in the attribute sslKeystorePath */
private String sslKeyStorePass;
public int getDefaultRequestTimeoutInSeconds() {
return defaultRequestTimeoutInSeconds;
}
public void setDefaultRequestTimeoutInSeconds(int defaultRequestTimeoutInSeconds) {
this.defaultRequestTimeoutInSeconds = defaultRequestTimeoutInSeconds;
}
public boolean isCompressionEnforced() {
return compressionEnforced;
}
public void setCompressionEnforced(boolean compressionEnforced) {
this.compressionEnforced = compressionEnforced;
}
public int getConnectionTimeoutInSeconds() {
return connectionTimeoutInSeconds;
}
public void setConnectionTimeoutInSeconds(int connectionTimeoutInSeconds) {
this.connectionTimeoutInSeconds = connectionTimeoutInSeconds;
}
public int getWebSocketTimeoutInSeconds() {
return webSocketTimeoutInSeconds;
}
public void setWebSocketTimeoutInSeconds(int webSocketTimeoutInSeconds) {
this.webSocketTimeoutInSeconds = webSocketTimeoutInSeconds;
}
public boolean isAcceptAnyCertificate() {
return acceptAnyCertificate;
}
public void setAcceptAnyCertificate(boolean acceptAnyCertificate) {
this.acceptAnyCertificate = acceptAnyCertificate;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public String getSslCertificateContent() {
return sslCertificateContent;
}
public void setSslCertificateContent(String sslCertificateContent) {
this.sslCertificateContent = sslCertificateContent;
}
public String getSslKeyStorePath() {
return sslKeyStorePath;
}
public void setSslKeyStorePath(String sslKeyStorePath) {
this.sslKeyStorePath = sslKeyStorePath;
}
public String getSslKeyStorePass() {
return sslKeyStorePass;
}
public void setSslKeyStorePass(String sslKeyStorePass) {
this.sslKeyStorePass = sslKeyStorePass;
}
@Override
public String toString() {
return "HttpClientSettings{" +
", enabled='" + enable + '\'' +
", sslKeyStorePath='" + sslKeyStorePath + '\'' +
", sslKeyStorePass is " + (sslKeyStorePass == null ? "provided" : "null") +
", sslCertificateContent is " + (sslCertificateContent == null ? "provided" : "null") +
", defaultRequestTimeoutInSeconds='" + defaultRequestTimeoutInSeconds + '\'' +
", compressionEnforced='" + compressionEnforced + '\'' +
", connectionTimeoutInSeconds='" + connectionTimeoutInSeconds + '\'' +
", webSocketTimeoutInSeconds='" + webSocketTimeoutInSeconds + '\'' +
", sslAcceptAnyCertificate='" + acceptAnyCertificate + '\'' +
", userAgent='" + userAgent + '\'' +
'}';
}
public String getSslCertificatePath() {
return sslCertificatePath;
}
public void setSslCertificatePath(String sslCertificatePath) {
this.sslCertificatePath = sslCertificatePath;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
}
| 35.524476 | 123 | 0.692913 |
d5b750601ae6b82e0cffd4f21d01043c8860fd38 | 539 | package com.liwy.study.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
//@EnableAutoConfiguration
@SpringBootApplication
@ServletComponentScan // 扫描Servlet
//@MapperScan("com.liwy.study.springboot.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
} | 33.6875 | 68 | 0.808905 |
e534f006f381b08c8406bcdf4cab64a6b4c59ab6 | 1,381 | package tk.snapz;
import com.ericrabil.yamlconfiguration.configuration.InvalidConfigurationException;
import tk.snapz.server.SnapzServerApplication;
import tk.snapz.server.minecraft.spigot.SpigotServer;
import tk.snapz.server.minecraft.spigot.SpigotServers;
import tk.snapz.usermanager.Users;
import tk.snapz.web.SpringApplication;
import java.io.File;
import java.io.IOException;
public class Starter {
public static void main(String[] args) {
DefaultDataStructure.checkAndCreate(new File(""));
new Thread(() -> {
while (true) {
//Debug Thread!
for (SpigotServer server : SpigotServers.servers) {
System.out.println(server.serverName + " | isOnline=" + server.isOnline());
}
try {
Thread.sleep(3000);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
}
}).start();
try {
Users.init();
} catch (IOException | InvalidConfigurationException ioException) {
ioException.printStackTrace();
}
Thread t = new Thread(() -> SnapzServerApplication.start(args));
t.start();
Thread s = new Thread(() -> SpringApplication.start(args));
s.start();
}
}
| 32.880952 | 95 | 0.606083 |
1334199cd2ec91a64a801f5283e0256ec16629df | 3,252 | /*
* 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 objects2;
/**
*
* @author swade
*/
public class Car {
//public member variables: we don't need to implement logic
//to change these values
public int year;
public String makeModel;
//private member variables because we want to control
//their values: outside classes access these through methods
private boolean isEngineRunning;
private double speed;
private int gear;
/**
* simulates starting this car instance's engine
*/
public void startEngine() {
isEngineRunning = true;
System.out.println("...crank...crank...vroom!");
}
/**
* simulates stopping this car instance's engine
*/
public void stopEngine() {
isEngineRunning = false;
speed = 0;
gear = 0;
System.out.println("...grblllll....shldunk");
}
/**
* Allows access to our private engine status boolean member variable called
* isEngineRunning
*
* @return the status of the engine: true means on, false means off
*/
public boolean checkEngineStatus() {
return isEngineRunning;
}
/**
* Allows access to our private speed variable
* @return the car object's current speed
*/
public double getCurrentSpeed() {
return speed;
}
/**
* Allows access to our private gear variable
* @return the car object's current gear
*/
public int getCurrentGear() {
return gear;
}
/**
* Controls the car's increases in speed
*
* @param mphIncrease
* @return the current speed of the car after the acceleration has been
* taken into account
*/
public double accelerate(int mphIncrease) {
double os = speed;
speed = speed + mphIncrease;
if(speed<5){
gear = 1;
}else if(speed<15){
gear = 2;
}else if(speed<30){
gear = 3;
}else if(speed<40){
gear = 4;
}else{
gear = 5;
}
return speed;
}//close accelerate
/**
* Controls the car's decreases in speed
*
* @param mphDecrease
* @return the current speed of the car after the deceleration
*/
public double decelerate(int mphDecrease) {
if (mphDecrease < speed) {
speed = speed - mphDecrease;
if(speed > 39){
gear = 5;
}else if(speed > 29){
gear = 4;
}else if(speed > 14){
gear = 3;
}else if(speed > 4){
gear = 2;
}else{
gear = 1;
}
return speed;
} else {
System.out.println("Your car is not going fast enough to decelerate that much.");
return speed;
}
}//close decelerate
private void upShift(double oldSpeed, double mphIncrease){
System.out.println("Something");
}
}//close Car
| 26.016 | 94 | 0.544588 |
43ac08d60b46f9fa1628aeb93899e72efb8930fb | 1,095 | package com.github.catalin.cretu.verspaetung.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalTime;
@Repository
public interface LineJpaRepository extends JpaRepository<LineEntity, Long> {
@Modifying(flushAutomatically = true, clearAutomatically = true)
@Query(nativeQuery = true,
value = "insert into times values (null, :line_id, :stop_id, :time)")
void saveStopTimeEntity(
@Param("line_id") final Long lineId,
@Param("stop_id") final Long stopId,
@Param("time") final String time);
@Query("select stopTime from StopTimeEntity stopTime " +
"where stopTime.stop.id = :stopId " +
"and stopTime.time = :time")
StopTimeEntity findStopTimeEntity(
@Param("stopId") final Long id,
@Param("time") final LocalTime time);
} | 37.758621 | 81 | 0.706849 |
ea8bd7729b9c1eff462a318c7bff79e8665c2f5b | 1,065 | package frc.robot.commands;
import edu.wpi.first.wpilibj.GenericHID.Hand;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.Drive_Subsystem;
public class TeleDriveCommand extends CommandBase {
private final XboxController driver_Controller;
private final Drive_Subsystem drive_Subsystem;
public TeleDriveCommand(XboxController driver_Controller, Drive_Subsystem drive_Subsystem) {
this.driver_Controller = driver_Controller;
this.drive_Subsystem = drive_Subsystem;
addRequirements(drive_Subsystem);
}
@Override
public void execute() {
drive_Subsystem.arcadeDrive(getSpeed(), getRotation(),true);
}
private double getSpeed() {
double speed =-driver_Controller.getY(Hand.kLeft);
return speed;
}
private double getRotation() {
double rotation = driver_Controller.getRawAxis(2);
return rotation;
}
@Override
public boolean isFinished() {
return false;
}
@Override
public void end(boolean interrupted) {
}
}
| 22.1875 | 94 | 0.75493 |
ac121d5a5f7ca62a8717f9359d55c469d51f0888 | 1,908 | /**
* Copyright (c) 2000-2020 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 com.liferay.portletmvc4spring.thin;
import java.io.IOException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.liferay.portletmvc4spring.context.XmlPortletApplicationContext;
/**
* @author Raymond Augé
*/
public class OSGiPortletApplicationContext extends XmlPortletApplicationContext {
@Override
protected ResourcePatternResolver getResourcePatternResolver() {
return new OSGiPathMatchingResourcePatternResolver(this);
}
private class OSGiPathMatchingResourcePatternResolver extends PathMatchingResourcePatternResolver {
public OSGiPathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
super(resourceLoader);
}
@Override
protected Resource resolveRootDirResource(Resource original) throws IOException {
URL url = original.getURL();
String protocol = url.getProtocol();
if (protocol.startsWith("bundle")) {
return new UrlResource(FileLocator.resolve(url));
}
return original;
}
}
}
| 29.8125 | 100 | 0.787212 |
8b3ccae14bafd3cef97772b709ffc34a6552cf4f | 291 | package localhost.abec2304.kurokohi;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public interface Info {
void init(DataInputStream dis) throws IOException;
void write(DataOutputStream dos) throws IOException;
}
| 20.785714 | 57 | 0.745704 |
8b8ed1efb8a024eed4328d28a3eb20cec5998e0c | 2,565 | package com.boot.basics.coding.netty.echo;
import com.boot.basics.coding.netty.echo.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import javax.net.ssl.SSLException;
import java.security.cert.CertificateException;
/**
* @Author cherrishccl
* @Date 2020/8/11 9:28
* @Version 1.0
* @Description
*/
public class EchoServer {
static final boolean SSL = System.getProperty("ssl") != null;
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
public static void main(String[] args) throws CertificateException, SSLException {
final SslContext sslCtx;
if(SSL){
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
}else {
sslCtx = null;
}
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
final EchoServerHandler serverHandler = new EchoServerHandler();
ServerBootstrap b = new ServerBootstrap();
try {
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if(null != sslCtx){
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(serverHandler);
}
});
ChannelFuture f = b.bind(PORT).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
| 38.863636 | 94 | 0.623002 |
066ec9c0d4252b93be7fb8ceb16b102e5497fac0 | 7,616 | /*******************************************************************************
* Copyright (c) 2011 Earth System Grid Federation
* ALL RIGHTS RESERVED.
* U.S. Government sponsorship acknowledged.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package esg.security.policy.service.impl;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import esg.security.policy.service.api.PolicyAttribute;
import esg.security.policy.service.api.PolicyService;
import esg.security.policy.service.api.PolicyStatement;
import esg.security.registry.service.api.ReloadableFileSetObserver;
import esg.security.registry.service.impl.ReloadableFileSet;
import esg.security.utils.xml.Parser;
/**
* Implementation of {@link esg.security.policy.service.api.PolicyService} backed up by one or more local XML configuration files.
* The XML files contain regular expressions matching the resource identifiers, and this service implementation will return
* the policy statements for the first match found, for the given action. The local policy files are automatically reloaded if changed.
*
* Note that this implementation disregards the case of the "action" parameter (i.e. "Read" and "read" are considered identical).
*
* @author luca.cinquini
*
*/
public class PolicyServiceLocalXmlImpl implements PolicyService, ReloadableFileSetObserver {
LinkedHashMap<Pattern, List<PolicyStatement>> policies = new LinkedHashMap<Pattern, List<PolicyStatement>>();
// Utility class that watches the set of local XML configuration files for changes.
private ReloadableFileSet watcher;
private final Log LOG = LogFactory.getLog(this.getClass());
private final static Namespace NS = Namespace.getNamespace("http://www.esgf.org/security");
/**
* Constructor accepts a comma-separated list of one or more files.
* Files can be specified with an absolute path (if starting with '/') or with a relative classpath (if not starting with '/').
*
* @param xmlFilePaths
* @throws Exception
*/
public PolicyServiceLocalXmlImpl(final String xmlFilePaths) throws Exception {
// instantiate files watcher
watcher = new ReloadableFileSet(xmlFilePaths);
watcher.setObserver(this);
// trigger first loading of configuration files
watcher.reload();
}
/** Method to update the local policy map by re-parsing the configured XML files.
* This method disregards parsing errors from any single file, and moves on to parsing the next file.
*/
public void parse(final List<File> policyFiles) {
// temporary storage for policy statements
final LinkedHashMap<Pattern, List<PolicyStatement>> _policies = new LinkedHashMap<Pattern, List<PolicyStatement>>();
// loop over policy files
for (final File policyFile : policyFiles) {
try {
parseXml(policyFile, _policies);
if (LOG.isInfoEnabled()) LOG.info("Loaded information from policy file="+policyFile.getAbsolutePath());
} catch(Exception e) {
LOG.warn("Error pasring XML policy file: "+policyFile.getAbsolutePath()+": "+e.getMessage());
}
}
// update local data storage
synchronized (policies) {
policies = _policies;
}
print();
}
@Override
public List<PolicyAttribute> getRequiredAttributes(String resource, String action) {
// reload policies if needed
watcher.reload();
final List<PolicyAttribute> attributes = new ArrayList<PolicyAttribute>();
for (final Pattern pattern : policies.keySet()) {
Matcher matcher = pattern.matcher(resource);
if (matcher.matches()) {
for (final PolicyStatement pstmt : policies.get(pattern)) {
if (pstmt.getAction().toString().equalsIgnoreCase(action)) {
attributes.add(pstmt.getAttribute());
}
}
}
}
return attributes;
}
/**
* Method to parse a single XML file containing policy statements into the given policy map.
*
* @param file
* @param _policies
* @throws MalformedURLException
* @throws IOException
* @throws JDOMException
*/
void parseXml(final File file, final LinkedHashMap<Pattern, List<PolicyStatement>> _policies) throws MalformedURLException, IOException, JDOMException {
final Document doc = Parser.toJDOM(file.getAbsolutePath(), false);
final Element root = doc.getRootElement();
// must store additional map because Pattern does not re-implement hashCode()
final Map<String, Pattern> patterns = new HashMap<String, Pattern>();
for (final Object pol : root.getChildren("policy", NS)) {
final Element policy = (Element)pol;
final String resource = policy.getAttributeValue("resource");
final Pattern pattern = Pattern.compile(resource);
if (patterns.get(resource)==null) {
patterns.put(resource, pattern);
_policies.put(pattern, new ArrayList<PolicyStatement>());
}
_policies.get(patterns.get(resource)).add(
new PolicyStatementImpl(policy.getAttributeValue("resource"),
policy.getAttributeValue("attribute_type"),
policy.getAttributeValue("attribute_value"),
policy.getAttributeValue("action"))
);
}
}
// debug method
public void print() {
for (final Pattern p : policies.keySet()) {
System.out.println("Resource Pattern="+p.toString());
for (final PolicyStatement pstmt : policies.get(p)) {
System.out.println("\t"+pstmt);
}
}
}
}
| 41.617486 | 244 | 0.694459 |
3e356713c8338b7533c92f52701722869a63de8a | 251 | package com.shj.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AutowiredBean {
public void say() {
System.out.println("autowired bean");
}
}
| 19.307692 | 62 | 0.741036 |
490b66901a8e73aee853c2d6814174bae0f03f91 | 14,869 | package cn.ichi.android.presentation;
import android.app.Presentation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.VideoView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by mozj on 2018/5/9.
*/
public class DifferentDisplay extends Presentation {
private ImageView imageView;
private VideoView videoView;
private ListView listProducts;
private ListView listCoupons;
private TextView txtTotal;
private MyBaseAdapter myProductAdapter;
private MyBaseAdapter myCouponAdapter;
private LinearLayout viewLayout;
private LinearLayout orderLayout;
private int showType = 1;
private boolean isCreated = false;
private int imageDisplayTime = 5000;
private Context outerContext;
private Handler handler;
private int meesageType;
private MyList<String> mediaFiles = new MyList<String>();
private MyList<String> menuFiles = new MyList<String>();
private static final int CANCEL = -1;
private static final int INIT_ICHI = 0;
private static final int ORDER = 1;
private static final int MEDIA_FILES = 2;
private static final int ADVERTISEMENT = 3;
private static final int MENUS = 4;
private static final int DOWNLOADING = 99;
private List<String> imgExtensions = new ArrayList<String>();
private List<String> videoExtensions = new ArrayList<String>();
public DifferentDisplay(Context outerContext, Display display) {
super(outerContext,display);
//TODOAuto-generated constructor stub
this.outerContext = outerContext;
this.handler = new MyHandler();
imgExtensions.add("bmp");
imgExtensions.add("jpg");
imgExtensions.add("png");
videoExtensions.add("mp4");
videoExtensions.add("3gp");
videoExtensions.add("mov");
videoExtensions.add("avi");
videoExtensions.add("flv");
videoExtensions.add("wmv");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diffrentdisplay_basket);
imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ichi_logo);
videoView = (VideoView)findViewById(R.id.video_player_view);
videoView.setMediaController(null);
videoView.setVisibility(View.GONE);
viewLayout = (LinearLayout)findViewById(R.id.layout_view);
orderLayout = (LinearLayout)findViewById(R.id.layout_order);
listProducts = (ListView)findViewById(R.id.listProduct);
if (null == myProductAdapter) {
myProductAdapter = new MyBaseAdapter(outerContext, null);
}
listProducts.setAdapter(myProductAdapter);
listCoupons = (ListView)findViewById(R.id.listCoupon);
if (null == myCouponAdapter) {
myCouponAdapter = new MyBaseAdapter(outerContext, null);
}
listCoupons.setAdapter(myCouponAdapter);
txtTotal = (TextView)findViewById(R.id.txtTotal);
isCreated = true;
initHeader();
setShowType(showType);
}
@Override
protected void onStop() {
if (videoView.isPlaying()) {
videoView.stopPlayback();
}
meesageType = CANCEL;
}
private void setHeaderText(View headerView, int id, String title){
TextView textView2 = (TextView) headerView.findViewById(id);
if (title == null || title.isEmpty()) {
textView2.setVisibility(View.GONE);
} else {
textView2.setVisibility(View.VISIBLE);
textView2.setText(title);
textView2.setTextSize(22.0f);
textView2.setGravity(Gravity.CENTER);
textView2.setBackgroundColor(Color.parseColor("#3399FF"));
}
}
private void initHeader() {
// 商品
View productTitle = findViewById(R.id.productTitle);
setHeaderText(productTitle, R.id.textView2, "商品");
setHeaderText(productTitle, R.id.textView3, "数量");
setHeaderText(productTitle, R.id.textView4, "金额");
// 优惠
View couponTitle = findViewById(R.id.couponTitle);
setHeaderText(couponTitle, R.id.textView2, "优惠名称");
setHeaderText(couponTitle, R.id.textView3, "");
setHeaderText(couponTitle, R.id.textView4, "优惠金额");
}
public boolean isUsing(String file) {
for(int i = 0; i < mediaFiles.size(); i++)
{
if (mediaFiles.get(i).equals(file)){
return true;
}
}
for(int i = 0; i < menuFiles.size(); i++)
{
if (menuFiles.get(i).equals(file)){
return true;
}
}
return false;
}
public void setShowType(int showType) {
this.showType = showType;
if (!isCreated) {
return;
}
switch (showType) {
case 0:
if (videoView.isPlaying()) {
videoView.stopPlayback();
}
viewLayout.setVisibility(View.GONE);
orderLayout.setVisibility(View.GONE);
break;
case 1:
viewLayout.setVisibility(View.VISIBLE);
orderLayout.setVisibility(View.GONE);
break;
case 2:
viewLayout.setVisibility(View.VISIBLE);
orderLayout.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
public void setImageDisplayTime(int imageDisplayTime) {
this.imageDisplayTime = imageDisplayTime;
}
public void ShowMenu() {
if (menuFiles.size() > 0) {
if (meesageType != MENUS) {
meesageType = MENUS;
sendHandleMessage(0, meesageType);
}
} else {
ShowInitLogo();
}
}
public void ShowMedia() {
if (mediaFiles.size() > 0) {
if (meesageType != MEDIA_FILES) {
meesageType = MEDIA_FILES;
sendHandleMessage(0, meesageType);
}
} else {
ShowInitLogo();
}
}
public void ShowInitLogo() {
meesageType = INIT_ICHI;
sendHandleMessage(0, meesageType);
}
public void ShowWaiting() {
meesageType = DOWNLOADING;
sendHandleMessage(0, meesageType);
}
public void ShowAdvertisement() {
if (meesageType != ADVERTISEMENT) {
meesageType = ADVERTISEMENT;
sendHandleMessage(0, meesageType);
}
}
public void setOrder(Order order) {
Message message = new Message();
message.obj = order;
message.what = ORDER;
this.handler.sendMessage(message);
}
public void clearAllFiles(){
mediaFiles.clear();
menuFiles.clear();
}
public void clearMediaFiles() {
mediaFiles.clear();
}
public void clearMenuFiles() {
menuFiles.clear();
}
public boolean addMediaFile(String path) {
String prefix = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
if (imgExtensions.indexOf(prefix) >= 0 || videoExtensions.indexOf(prefix) >= 0) {
synchronized(mediaFiles) {
return mediaFiles.add(path);
}
}
return false;
}
public boolean addMenuFile(String path) {
String prefix = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
if (imgExtensions.indexOf(prefix) >= 0) {
synchronized(menuFiles) {
return menuFiles.add(path);
}
}
return false;
}
public void setMediaFile(String path, int mediaType) {
synchronized(mediaFiles) {
mediaFiles.clear();
String prefix = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
if ((mediaType & 1) == 1 && imgExtensions.indexOf(prefix) >= 0) {
mediaFiles.add(path);
}
if ((mediaType & 2) == 2 && videoExtensions.indexOf(prefix) >= 0) {
mediaFiles.add(path);
}
if (mediaFiles.size() > 0) {
meesageType = MEDIA_FILES;
sendHandleMessage(0, meesageType);
}
}
}
public void setMediaDir(String path, int mediaType) {
File file = new File(path);
File[] fs = file.listFiles();
synchronized(mediaFiles) {
mediaFiles.clear();
for (File f : fs) {
String fileName = f.getPath();
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if ((mediaType & 1) == 1 && imgExtensions.indexOf(prefix) >= 0) {
mediaFiles.add(fileName);
}
if ((mediaType & 2) == 2 && videoExtensions.indexOf(prefix) >= 0) {
mediaFiles.add(fileName);
}
}
if (mediaFiles.size() > 0) {
meesageType = MEDIA_FILES;
sendHandleMessage(0, meesageType);
}
}
}
private void sendHandleMessage(int index, int handleType) {
if (index < 0) {
return;
}
Message message = new Message();
message.obj = index;
message.what = handleType;
this.handler.sendMessage(message);
}
private void ShowMediaFile(String fileName, int nextIndex) {
if (fileName == null) {
return;
}
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (imgExtensions.indexOf(prefix) >= 0)
{
ShowImageFile(fileName, nextIndex, MEDIA_FILES);
}
else if (videoExtensions.indexOf(prefix) >= 0)
{
ShowVideoFile(fileName, nextIndex);
}
}
private void ShowImageFile(final String imgFile, final int nextIndex, final int meesageType) {
if (imgFile == null){
return;
}
Bitmap bitmap = Utils.readImage(imgFile);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
imageView.setVisibility(View.VISIBLE);
videoView.setVisibility(View.GONE);
videoView.setOnCompletionListener(null);
if (videoView.isPlaying()) {
videoView.stopPlayback();
}
if (nextIndex >= 0) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(imageDisplayTime);
sendHandleMessage(nextIndex, meesageType);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
private void ShowVideoFile(final String videoFile, final int nextIndex) {
if (videoFile == null){
return;
}
if (videoView.isPlaying()) {
videoView.stopPlayback();
}
videoView.setVideoPath(videoFile);
videoView.start();
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (nextIndex >= 0) {
sendHandleMessage(nextIndex, MEDIA_FILES);
}
}
});
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
videoView.stopPlayback(); //播放异常,则停止播放,防止弹窗使界面阻塞
if (nextIndex >= 0) {
sendHandleMessage(nextIndex, MEDIA_FILES);
}
return true;
}
});
imageView.setVisibility(View.GONE);
videoView.setVisibility(View.VISIBLE);
}
private class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (!isCreated) {
return;
}
final int type = msg.what;
if (type == ORDER) {
Order order = (Order)msg.obj;
myProductAdapter.setOrderItems(order.items);
myCouponAdapter.setOrderItems(order.coupons);
String finalFee = String.format("%-6.2f", order.finalFee == null ? 0.0 : order.finalFee);
txtTotal.setText("总金额: " + finalFee + "元");
return;
}
if (type != meesageType) {
return;
}
Integer index = (Integer)msg.obj;
String fileName = null;
int nextIndex = -1;
switch (type) {
case MEDIA_FILES:
synchronized(mediaFiles) {
if (index < mediaFiles.size()) {
fileName = mediaFiles.get(index);
nextIndex = (index + 1) % mediaFiles.size();
}
}
ShowMediaFile(fileName, nextIndex);
break;
case ADVERTISEMENT:
break;
case MENUS:
synchronized(menuFiles) {
if (index < menuFiles.size()) {
fileName = menuFiles.get(index);
nextIndex = (index + 1) % menuFiles.size();
}
}
ShowImageFile(fileName, nextIndex, MENUS);
break;
case DOWNLOADING:
imageView.setImageResource(R.drawable.ichi_downloading);
imageView.setVisibility(View.VISIBLE);
videoView.setVisibility(View.GONE);
break;
case INIT_ICHI:
imageView.setImageResource(R.drawable.ichi_logo);
imageView.setVisibility(View.VISIBLE);
videoView.setVisibility(View.GONE);
break;
default:
break;
}
}
}
}
| 28.539347 | 105 | 0.550541 |
802431369c45af6e84a4cb3c6ddc4028658449ad | 1,998 | package us.ihmc.acsell.hardware.command;
import us.ihmc.robotics.dataStructures.registry.YoVariableRegistry;
import us.ihmc.robotics.dataStructures.variable.DoubleYoVariable;
import us.ihmc.sensorProcessing.sensors.RawJointSensorDataHolder;
public class AcsellJointCommand
{
private final YoVariableRegistry registry;
private final DoubleYoVariable tauDesired;
private final DoubleYoVariable damping;
private final int numberOfActuators;
private final double[] motorAngles;
private double q, qd, qdd_d;
public AcsellJointCommand(String name, int numberOfActuators, YoVariableRegistry parentRegistry)
{
this.registry = new YoVariableRegistry(name);
this.tauDesired = new DoubleYoVariable(name + "TauDesired", registry);
this.damping = new DoubleYoVariable(name + "Damping", registry);
this.numberOfActuators = numberOfActuators;
this.motorAngles = new double[numberOfActuators];
parentRegistry.addChild(registry);
}
public void setTauDesired(double tau_d, double qdd_d, RawJointSensorDataHolder rawSensorData)
{
this.tauDesired.set(tau_d);
this.q = rawSensorData.getQ_raw();
this.qd = rawSensorData.getQd_raw();
this.qdd_d = qdd_d;
for(int i = 0; i < numberOfActuators; i++)
{
motorAngles[i] = rawSensorData.getMotorAngle(i);
}
}
public double getQ()
{
return q;
}
public double getQd()
{
return qd;
}
public double getQdd_d()
{
return qdd_d;
}
public double getTauDesired()
{
return tauDesired.getDoubleValue();
}
public int getNumberOfActuators()
{
return numberOfActuators;
}
public double getMotorAngle(int actuator)
{
return motorAngles[actuator];
}
public double getDamping()
{
return damping.getDoubleValue();
}
public void setDamping(double value)
{
damping.set(value);
}
}
| 23.785714 | 99 | 0.675175 |
58d14c37ea2f8d4c2131fd1f3a65571b2b3f45b0 | 661 | package binarytrees;
/**
* For each node in a binary search tree, create a new duplicate node, and
* insert the duplicate as the left child of the original node. The resulting
* tree should still be a binary search tree.
*
* Signature of expected method:
*
* public static <T> void doubleTree(TreeNode<T> root) {...}
*/
public class BstDoubleTree {
public static <T> void doubleTree(TreeNode<T> root) {
if (root == null) {
return;
}
doubleTree(root.getLeft());
doubleTree(root.getRight());
TreeNode<T> duplicate = new TreeNode<T>(root.getValue());
duplicate.setLeft(root.getLeft());
root.setLeft(duplicate);
return;
}
}
| 23.607143 | 77 | 0.683812 |
7ad266b9da2bad7cc513db86d6db0d8537ff74ec | 2,223 | /*
* Copyright 2010 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 com.hs.mail.imap.server.codec;
import java.util.LinkedList;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import com.hs.mail.imap.parser.Token;
/**
* An IMAP message.
*
* @author Won Chul Doh
* @since Jan 22, 2010
*
*/
public interface ImapMessage {
public String getCommand();
LinkedList<Token> getTokens();
void setTokens(LinkedList<Token> tokens);
/**
* Returns the content of this message. If there is no content, an
* {@link ChannelBuffers#EMPTY_BUFFER} is returned.
*/
ChannelBuffer getLiteral();
/**
* Sets the content of this message. If {@code null} is specified, the
* content of this message will be set to
* {@link ChannelBuffers#EMPTY_BUFFER}.
*/
void setLiteral(ChannelBuffer literal);
/**
* Returns the length of the content. Please note that this value is
* not retrieved from {@link #getContent()} but from the
* {@code "Content-Length"} header, and thus they are independent from each
* other.
*
* @return the content length or {@code 0} if this message does not have
* the {@code "Content-Length"} header
*/
long getLiteralLength();
void setLiteralLength(long literalLength);
/**
* Returns {@code true} if and only if we need to send command continuation
* request before reading literal data.
*/
boolean isNeedContinuationRequest();
void setNeedContinuationRequest(boolean needContinuationRequest);
boolean isNeedParsing();
}
| 28.87013 | 80 | 0.681511 |
793fdc9c36702fad7fb80393eebb65dcaa15ed37 | 678 | // Copyright (c) 2015 Elements of Programming Interviews. All rights reserved.
package com.epi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IntersectSortedArrays2 {
// @include
public static List<Integer> intersectTwoSortedArrays(List<Integer> A,
List<Integer> B) {
List<Integer> intersectionAB = new ArrayList<>();
for (int i = 0; i < A.size(); ++i) {
if ((i == 0 || A.get(i) != A.get(i - 1))
&& Collections.binarySearch(B, A.get(i)) >= 0) {
intersectionAB.add(A.get(i));
}
}
return intersectionAB;
}
// @exclude
}
| 28.25 | 78 | 0.587021 |
65f9fcf4dc16045cd7a2b40804d3b06f78c8d180 | 8,620 | /*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.cryostat.rules;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.function.Function;
import io.cryostat.configuration.CredentialsManager;
import io.cryostat.core.log.Logger;
import io.cryostat.core.net.Credentials;
import io.cryostat.platform.ServiceRef;
import io.cryostat.util.HttpStatusCodeIdentifier;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.client.utils.URLEncodedUtils;
class PeriodicArchiver implements Runnable {
private final ServiceRef serviceRef;
private final CredentialsManager credentialsManager;
private final Rule rule;
private final WebClient webClient;
private final Function<Credentials, MultiMap> headersFactory;
private final Function<Pair<ServiceRef, Rule>, Void> failureNotifier;
private final Logger logger;
private final Queue<String> previousRecordings;
PeriodicArchiver(
ServiceRef serviceRef,
CredentialsManager credentialsManager,
Rule rule,
WebClient webClient,
Function<Credentials, MultiMap> headersFactory,
Function<Pair<ServiceRef, Rule>, Void> failureNotifier,
Logger logger) {
this.webClient = webClient;
this.serviceRef = serviceRef;
this.credentialsManager = credentialsManager;
this.rule = rule;
this.headersFactory = headersFactory;
this.failureNotifier = failureNotifier;
this.logger = logger;
// FIXME this needs to be populated at startup by scanning the existing archived recordings,
// in case we have been restarted and already previously processed archival for this rule
this.previousRecordings = new ArrayDeque<>(this.rule.getPreservedArchives());
}
@Override
public void run() {
logger.trace("PeriodicArchiver for {} running", rule.getRecordingName());
try {
while (this.previousRecordings.size() > this.rule.getPreservedArchives() - 1) {
pruneArchive(this.previousRecordings.remove()).get();
}
performArchival();
} catch (InterruptedException | ExecutionException e) {
logger.error(e);
failureNotifier.apply(Pair.of(serviceRef, rule));
}
}
void performArchival() throws InterruptedException, ExecutionException {
// FIXME using an HTTP request to localhost here works well enough, but is needlessly
// complex. The API handler targeted here should be refactored to extract the logic that
// creates the recording from the logic that simply figures out the recording parameters
// from the POST form, path param, and headers. Then the handler should consume the API
// exposed by this refactored chunk, and this refactored chunk can also be consumed here
// rather than firing HTTP requests to ourselves
String path =
URI.create(
String.format(
"/api/v1/targets/%s/recordings/%s",
URLEncodedUtils.formatSegments(
serviceRef.getServiceUri().toString()),
URLEncodedUtils.formatSegments(rule.getRecordingName())))
.normalize()
.toString();
this.logger.trace("PATCH \"save\" {}", path);
CompletableFuture<String> future = new CompletableFuture<>();
this.webClient
.patch(path)
.putHeaders(headersFactory.apply(credentialsManager.getCredentials(serviceRef)))
.sendBuffer(
Buffer.buffer("save"),
ar -> {
if (ar.failed()) {
this.logger.error(
new IOException("Periodic archival failed", ar.cause()));
future.completeExceptionally(ar.cause());
return;
}
HttpResponse<Buffer> resp = ar.result();
if (!HttpStatusCodeIdentifier.isSuccessCode(resp.statusCode())) {
this.logger.error(resp.bodyAsString());
future.completeExceptionally(new IOException(resp.bodyAsString()));
return;
}
future.complete(resp.bodyAsString());
});
this.previousRecordings.add(future.get());
}
Future<Boolean> pruneArchive(String recordingName) {
logger.trace("Pruning {}", recordingName);
String path =
URI.create(
String.format(
"/api/v1/recordings/%s",
URLEncodedUtils.formatSegments(recordingName)))
.normalize()
.toString();
this.logger.trace("DELETE {}", path);
CompletableFuture<Boolean> future = new CompletableFuture<>();
this.webClient
.delete(path)
.putHeaders(headersFactory.apply(credentialsManager.getCredentials(serviceRef)))
.send(
ar -> {
if (ar.failed()) {
this.logger.error(
new IOException("Archival prune failed", ar.cause()));
future.completeExceptionally(ar.cause());
return;
}
HttpResponse<Buffer> resp = ar.result();
if (!HttpStatusCodeIdentifier.isSuccessCode(resp.statusCode())) {
this.logger.error(resp.bodyAsString());
future.completeExceptionally(new IOException(resp.bodyAsString()));
return;
}
previousRecordings.remove(recordingName);
future.complete(true);
});
return future;
}
}
| 45.851064 | 100 | 0.604408 |
ff1e4797647839add1f03ee23bf65998aca99073 | 2,308 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.tools;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
/**
* Abstract class that implements {@see CommonCrawlFormat} interface.
*
*/
public abstract class AbstractCommonCrawlFormat implements CommonCrawlFormat {
protected String url;
protected byte[] content;
protected Metadata metadata;
protected Configuration conf;
public AbstractCommonCrawlFormat(String url, byte[] content, Metadata metadata, Configuration conf) {
this.url = url;
this.content = content;
this.metadata = metadata;
this.conf = conf;
}
@Override
public String getJsonData(boolean mapAll) throws IOException {
if (mapAll) {
return getJsonDataAll();
}
else {
return getJsonDataSet();
}
}
protected abstract String getJsonDataSet() throws IOException;
protected abstract String getJsonDataAll() throws IOException;
protected String ifNullString(String value) {
return (value != null) ? value : "";
}
protected static String getHostName() {
String hostName = "";
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
}
return hostName;
}
protected static String getHostAddress() {
String hostAddress = "";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException uhe) {
}
return hostAddress;
}
}
| 27.152941 | 102 | 0.739601 |
e65f95850f41d3399fa0f17eadd9c564db55e04f | 2,017 | package packets.data.enums;
/*
* A class representation of the `useItemType` packet variable with helper functions.
*/
public enum UseItemType {
INVALID(-1, "Invalid"),
/**
* Sent for consumables and single-use abilities such as spells and tomes.
*/
DEFAULT(0, "Default"),
/**
* Sent to start using an ability such as a Ninja's shuriken.
*/
START(1, "StartUse"),
/**
* Sent to end using an ability.
*/
END(2, "EndUse");
private final int useType;
private final String useName;
UseItemType(byte useType, String useName) {
this.useType = useType;
this.useName = useName;
}
UseItemType(int useType, String useName) {
this.useType = (byte) useType & 0xff;
this.useName = useName;
}
/**
* Return an ItemUseType object from a given ID.
*
* @param useType The integer ID of the usage type code.
* @return A UseItemType object or null if not found.
*/
public static UseItemType fromCode(int useType) {
// TODO: make this more efficient by not looping
for (UseItemType index : UseItemType.values()) {
if (index.useType == useType) return index;
}
return null;
}
/**
* Return an ItemUseType object from a given ID.
*
* @param useType The byte ID of the usage type code.
* @return A UseItemType object or null if not found.
*/
public static UseItemType fromCode(byte useType) {
return fromCode((int) useType);
}
/**
* Return an ItemUseType object from a given name.
*
* @param useName The name of the usage type.
* @return A UseItemType object or null if not found.
*/
public static UseItemType fromName(String useName) {
for (UseItemType index : UseItemType.values()) {
if (index.useName.equals(useName)) return index;
}
return null;
}
public String toString() {
return this.useName;
}
} | 26.893333 | 85 | 0.607338 |
036ea358f43b3aa98c282cb2e0ee29b4fdd6aa5c | 1,972 | package com.emc.thye;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "userstore.db";
private static final int SCHEMA = 1;
static String TABLE = "Notes";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_TEXT = "text";
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE " + TABLE + "(" + COLUMN_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME
+ " TEXT, " + COLUMN_DATE + " TEXT, " + COLUMN_TEXT + " TEXT);");
}
catch (SQLiteException e){
if (e.getMessage().contains("no such table")){
Log.e("SQLExc", "Creating table " + TABLE + "because it doesn't exist!" );
// create table
// re-run query, etc.
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE);
onCreate(db);
}
public void addNote(SQLiteDatabase db, String title, String time){
db.execSQL("INSERT INTO "+ TABLE +" (" + COLUMN_NAME
+ ", " + COLUMN_DATE + ", " + COLUMN_TEXT + ")" +
"VALUES ('" + title + "', '" + time + "', '');");
}
public void cleanTable(SQLiteDatabase db){
db.execSQL("DELETE FROM " + TABLE);
}
}
| 34 | 90 | 0.61359 |
e9d95347c6d4c8d32eed6af4c85585cf35aa56a9 | 524 | package org.jpromise.functions;
import org.jpromise.patterns.Pattern3;
public abstract class OnFulfilled3<V1, V2, V3> implements OnFulfilled<Pattern3<V1, V2, V3>> {
@Override
public final void fulfilled(Pattern3<V1, V2, V3> result) throws Throwable {
if (result == null) {
fulfilled(null, null, null);
}
else {
fulfilled(result.item1, result.item2, result.item3);
}
}
public abstract void fulfilled(V1 item1, V2 item2, V3 item3) throws Throwable;
}
| 29.111111 | 93 | 0.650763 |
128b1b10e5f5739daadaac7581038311117e873b | 12,030 | import com.github.hlvx.dao.database.sql.DAO;
import com.github.hlvx.dao.database.sql.DaoManager;
import com.github.hlvx.dao.database.sql.SQLSession;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.UpdateResult;
public class Example {
public static void main(String[] args) throws NoSuchMethodException {
test();
}
public static void test() throws NoSuchMethodException {
Vertx vertx = Vertx.vertx();
JsonObject config = new JsonObject()
.put("url", "jdbc:hsqldb:mem:test?shutdown=true")
.put("driver_class", "org.hsqldb.jdbcDriver")
.put("max_pool_size", 30);
JDBCClient client = JDBCClient.createShared(vertx, config);
// Creates a new manager for this JDBC configuration
DaoManager manager = new DaoManager(client);
// Register our DAOs.
// This step is optional but will increase the speed of the first instantiation of each DAO
manager.registerDao(MyDaoClass.class);
manager.registerDao(MyDaoClass2.class);
// Simple query example
manager.createDao(MyDaoClass.class, daoResult -> {
if (daoResult.succeeded()) {
daoResult.result().exampleQuery(resultSet -> {
if (resultSet.succeeded()) {
ResultSet rs = resultSet.result();
// Do what you want to do with your result set here
daoResult.result().close();
} else {
// Handle error
throw new RuntimeException(resultSet.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
} else {
// Handle error
throw new RuntimeException(daoResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
// Single DAO Transaction example
manager.createDao(MyDaoClass.class, daoResult -> {
if (daoResult.succeeded()) {
MyDaoClass dao = daoResult.result();
dao.startTransaction(sessionResult -> {
if (sessionResult.succeeded()) {
dao.exampleInsert(resultSetResult -> {
if (resultSetResult.succeeded()) {
dao.deleteUser(deletionResult -> {
if (deletionResult.succeeded()) {
dao.commit(result -> {
if (result.failed()) {
dao.rollback(result2 -> {
if (result2.failed()) {
// Handle error
throw new RuntimeException(result2.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
// Handle error
throw new RuntimeException(result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
} else dao.close();
});
} else {
dao.rollback(result -> {
if (result.failed()) {
// Handle error
throw new RuntimeException(result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
// Handle error
throw new RuntimeException(deletionResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
}, "username");
} else {
dao.rollback(result -> {
if (result.failed()) {
// Handle error
throw new RuntimeException(result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
// Handle error
throw new RuntimeException(resultSetResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
}, "username", "email");
} else {
// Handle error
throw new RuntimeException(sessionResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
} else {
// Handle error
throw new RuntimeException(daoResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
// Multiple DAO Transaction example
SQLSession.createSession(client, sessionResult -> {
if (sessionResult.succeeded()) {
SQLSession session = sessionResult.result();
manager.createDao(session, MyDaoClass.class, dao1Result -> {
if (dao1Result.succeeded()) {
MyDaoClass dao1 = dao1Result.result();
manager.createDao(session, MyDaoClass2.class, dao2Result -> {
MyDaoClass2 dao2 = dao2Result.result();
if (dao2Result.succeeded()) {
session.startTransaction(result -> {
if (result.succeeded()) {
dao1.exampleInsert(resultSet1Result -> {
if (resultSet1Result.succeeded()) {
dao2.exampleUpdate(resultSet2Result -> {
if (resultSet2Result.succeeded()) {
session.commit(commitResult -> {
if (commitResult.failed()) {
// Handle error
throw new RuntimeException(sessionResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
session.close();
dao1.close();
dao2.close();
} else {
session.rollback(rollbackResult -> {
if (rollbackResult.failed()) {
// Handle error
throw new RuntimeException(sessionResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
// Handle error
throw new RuntimeException(resultSet2Result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
}, "username", "newUsername");
} else {
session.rollback(rollbackResult -> {
if (rollbackResult.failed()) {
// Handle error
throw new RuntimeException(rollbackResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
// Handle error
throw new RuntimeException(resultSet1Result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
}, "username", "email");
} else {
// Handle error
throw new RuntimeException(result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
} else {
// Handle error
throw new RuntimeException(dao2Result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
} else {
// Handle error
throw new RuntimeException(dao1Result.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
} else {
// Handle error
throw new RuntimeException(sessionResult.cause()); // This will ensure that the DAO and the session are closed. You can also use dao.close(); manually
}
});
}
private static class MyDaoClass extends DAO {
public void exampleQuery(Handler<AsyncResult<ResultSet>> handler) {
executeQuery(handler, "SELECT * FROM users");
}
public void exampleInsert(Handler<AsyncResult<UpdateResult>> handler, String username, String email) {
executeInsert(handler, "INSERT INTO users (username, email) VALUES (?, ?)", username, email);
}
public void deleteUser(Handler<AsyncResult<UpdateResult>> handler, String username) {
executeUpdate(handler, "DELETE FROM users WHERE username = ?", username);
}
}
private static class MyDaoClass2 extends DAO {
public void exampleUpdate(Handler<AsyncResult<UpdateResult>> handler, String username, String newUsername) {
executeUpdate(handler, "UPDATE users SET username = ? WHERE username = ?", newUsername, username);
}
}
}
| 61.377551 | 214 | 0.438071 |
a3c327e1cc89dc1e756ef71086e53182c661323b | 971 | package io.qameta.allure.junitplatform.features;
import io.qameta.allure.Epic;
import io.qameta.allure.Feature;
import io.qameta.allure.Owner;
import io.qameta.allure.Stories;
import io.qameta.allure.Story;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import java.util.stream.Stream;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
/**
* @author charlie (Dmitry Baev).
*/
@Epic("epic4")
@Feature("feature4")
@Story("story4")
public class DynamicTests {
@Epic("epic1")
@Epic("epic2")
@Epic("epic3")
@Feature("feature1")
@Feature("feature2")
@Feature("feature3")
@Story("story1")
@Stories({
@Story("story2"),
@Story("story3")
})
@Owner("some-owner")
@TestFactory
Stream<DynamicTest> dynamicTestsFromStream() {
return Stream.of("A", "B", "C").map(
str -> dynamicTest("test" + str, () -> {
}));
}
}
| 22.581395 | 60 | 0.634398 |
c3665a4e73b62c2083d5e640b0e79629a2eef213 | 3,849 | /* RMIHashes.java --
Copyright (c) 1996, 1997, 1998, 1999, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.rmi.server;
import gnu.java.lang.CPStringBuilder;
import gnu.java.lang.reflect.TypeSignature;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.lang.reflect.Method;
import java.security.MessageDigest;
public class RMIHashes
{
//There're other places using DigestOutputStream to generate hash in classpath, but I think the way I used
//here is more efficient, anyway, you can switch to DigestOutputStream by doing like "//or:" comments say.
//or:add this statement: private static final NullOutputStream nullOutputStream = new NullOutputStream ();
public static long getMethodHash(Method meth)
{
//Object Serialization Spec 8.3
try
{
MessageDigest md = MessageDigest.getInstance ("SHA");
//or:remove this statement: DigestOutputStream digest_out = new DigestOutputStream (nullOutputStream, md);
ByteArrayOutputStream digest_out = new ByteArrayOutputStream();
DataOutputStream data_out = new DataOutputStream (digest_out);
CPStringBuilder sbuf = new CPStringBuilder();
sbuf.append(meth.getName());
sbuf.append('(');
Class params[] = meth.getParameterTypes();
for(int i = 0; i < params.length; i++)
sbuf.append(TypeSignature.getEncodingOfClass(params[i]));
sbuf.append(')');
Class rcls = meth.getReturnType();
if(rcls != Void.TYPE)
sbuf.append(TypeSignature.getEncodingOfClass(rcls));
else
sbuf.append('V');
data_out.writeUTF (sbuf.toString());
data_out.flush();
data_out.close ();
md.update(digest_out.toByteArray()); //or:remove this statement
byte[] sha = md.digest ();
long result = 0;
int len = sha.length < 8 ? sha.length : 8;
for (int i=0; i < len; i++)
result += (long)(sha[i] & 0xFF) << (8 * i);
return result;
}catch(Exception _){
return -1L;
}
}
public static long getInterfaceHash(Class clazz)
{
return clazz.hashCode ();
}
}
| 38.108911 | 114 | 0.714471 |
093725164eef034e5c26dbd8923ac564a5da9efc | 185 | package com.r00ta.ffm.core.models;
public enum ManagedEntityStatus {
ACCEPTED,
PREPARING,
PROVISIONING,
READY,
DEPROVISION,
DELETING,
DELETED,
FAILED
}
| 14.230769 | 34 | 0.664865 |
690bcfff0184586f5eb0afd131e378c35d6bfa8f | 489 | package au.com.turingg.microlibs.mimak;
import java.io.IOException;
/**
* Root class for all Mimak exceptions.
*
* @author Behrang Saeedzadeh
*/
public class MimakException extends IOException {
public MimakException() {
}
public MimakException(String message) {
super(message);
}
public MimakException(String message, Throwable cause) {
super(message, cause);
}
public MimakException(Throwable cause) {
super(cause);
}
}
| 17.464286 | 60 | 0.664622 |
5e3eef0169373073d25b99d6c0cbf6aa39bc0a6e | 2,604 | /* */ package classes.lrg.insider.plugins.core.properties.hismo.functions;
/* */
/* */ import lrg.common.abstractions.entities.AbstractEntityInterface;
/* */ import lrg.common.abstractions.entities.ResultEntity;
/* */ import lrg.insider.plugins.core.properties.hismo.HismoDetail;
/* */ import lrg.insider.plugins.core.properties.hismo.functions.Detail;
/* */ import lrg.memoria.core.Function;
/* */ import lrg.memoria.hismo.core.FunctionHistory;
/* */ import lrg.memoria.hismo.core.GlobalFunctionHistory;
/* */ import lrg.memoria.hismo.core.MethodHistory;
/* */
/* */ public class Detail extends HismoDetail {
/* 13 */ public Detail() { super("Detail", "Constructs a detailed HTML String to be shown in the browser.", new String[] { "method history", "global function history" }, "string"); }
/* */
/* */
/* */ public ResultEntity compute(AbstractEntityInterface anEntity) {
/* 17 */ if (!(anEntity instanceof FunctionHistory)) return null;
/* */
/* 19 */ FunctionHistory aFunctionHistory = (FunctionHistory)anEntity;
/* */
/* 21 */ if (aFunctionHistory instanceof MethodHistory) {
/* 22 */ text = "<h1>Method History Detail: ";
/* */ } else {
/* 24 */ text = "<h1>Global Function History Detail: ";
/* 25 */ } String text = String.valueOf(text) + linkTo(aFunctionHistory) + "</h1><hr><br>";
/* 26 */ if (aFunctionHistory instanceof MethodHistory) {
/* 27 */ text = String.valueOf(text) + "Belongs to Class History:" + linkTo(((MethodHistory)aFunctionHistory).getClassHistory()) + "<br>";
/* */ } else {
/* 29 */ text = String.valueOf(text) + "Belongs to Namespace History:" + linkTo(((GlobalFunctionHistory)aFunctionHistory).getNamespaceHistory()) + "<br>";
/* 30 */ } text = String.valueOf(text) + "Number of parameters in first version: " + ((Function)aFunctionHistory.getFirstVersion()).getParameterList().size() + "<br>";
/* 31 */ text = String.valueOf(text) + "Number of parameters in last version: " + ((Function)aFunctionHistory.getLastVersion()).getParameterList().size() + "<br>";
/* 32 */ computeHismoDetail(aFunctionHistory);
/* 33 */ text = String.valueOf(text) + computeLocationDetail(aFunctionHistory);
/* 34 */ return new ResultEntity(text);
/* */ }
/* */ }
/* Location: C:\Users\emill\Dropbox\slimmerWorden\2018-2019-Semester2\THESIS\iPlasma6\tools\iPlasma\classes.zip!\classes\lrg\insider\plugins\core\properties\hismo\functions\Detail.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 1.0.7
*/ | 62 | 198 | 0.65745 |
8de5121229bb08405bbffbc75bf414b38260cf44 | 264 | package com.kr.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingTest {
private static final Logger log = LoggerFactory.getLogger(LoggingTest.class);
public static void main(String[] args) {
log.info("Logging Test");
}
}
| 18.857143 | 78 | 0.75 |
8ba2628147db5304fe08097d35c21116870528d6 | 3,155 | /*
* WPCleaner: A tool to help on Wikipedia maintenance tasks.
* Copyright (C) 2017 Nicolas Vervelle
*
* See README.txt file for licensing information.
*/
package org.wikipediacleaner.api.data;
import org.wikipediacleaner.api.configuration.WikiConfiguration;
/**
* Information about Linter categories.
*/
public class LinterCategory implements Comparable<LinterCategory> {
/** Level of the category */
private final String level;
/** Name of the category */
private final String category;
public final static String LEVEL_HIGH = "high";
public final static String LEVEL_MEDIUM = "medium";
public final static String LEVEL_LOW = "low";
/**
* @param level Level of the category.
* @param category Name of the category.
*/
public LinterCategory(String level, String category) {
this.level = level;
this.category = category;
}
/**
* @return Level of the category.
*/
public String getLevel() {
return level;
}
/**
* @param config Wiki configuration.
* @return Localized name of the level.
*/
public String getLevelName(WikiConfiguration config) {
if (config != null) {
String result = config.getMessageByName("linter-heading-" + level + "-priority");
if (result != null) {
return result;
}
}
return level;
}
/**
* @return Name of the category.
*/
public String getCategory() {
return category;
}
/**
* @param config Wiki configuration.
* @return Localized name of the category.
*/
public String getCategoryName(WikiConfiguration config) {
if (config != null) {
String result = config.getMessageByName("linter-category-" + category);
if (result != null) {
return result;
}
}
return category;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public int compareTo(LinterCategory lc) {
int compare;
// Level
compare = level.compareTo(lc.level);
if (compare != 0) {
if (level.equals(LEVEL_HIGH)) {
return -1;
} else if (lc.level.equals(LEVEL_HIGH)) {
return 1;
}
if (level.equals(LEVEL_MEDIUM)) {
return -1;
} else if (lc.level.equals(LEVEL_MEDIUM)) {
return 1;
}
return compare;
}
// Name
compare = category.compareTo(lc.category);
if (compare != 0) {
return compare;
}
return compare;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (o.getClass() != getClass())) {
return false;
}
LinterCategory lc = (LinterCategory) o;
boolean equals = true;
equals &= level.equals(lc.level);
equals &= category.equals(lc.category);
return equals;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return category.hashCode();
}
}
| 22.862319 | 88 | 0.591759 |
d5a598f79c1aa43c140529e3e65a0f42332baf60 | 1,739 | package com.github.sawied.jweb.api;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.github.sawied.jweb.api.bean.PersonInfo;
import com.github.sawied.jweb.entity.UserEntity;
import com.github.sawied.jweb.service.UserService;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody UserEntity save(@Valid @RequestBody PersonInfo personInfo) {
UserEntity user=new UserEntity();
user.setName(personInfo.getName());
return userService.saveUser(user);
}
@RequestMapping(method=RequestMethod.GET)
public Page<UserEntity> getAll(){
return userService.list();
}
@RequestMapping(path="/{id}",method=RequestMethod.GET)
public @ResponseBody UserEntity getOne(@PathVariable("id") Long id) {
return userService.findUser(id);
}
@RequestMapping("/portrait")
public void uploadImage(MultipartFile file,HttpServletResponse response) throws IOException {
IOUtils.copy(file.getInputStream(), response.getOutputStream());
}
}
| 30.508772 | 94 | 0.807936 |
31dcc9003a274beeaa0298d499b387636cf218f6 | 10,849 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.spatial.bbox;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.spatial.ShapeValuesSource;
import org.locationtech.spatial4j.shape.Rectangle;
/**
* The algorithm is implemented as envelope on envelope (rect on rect) overlays rather than complex
* polygon on complex polygon overlays.
*
* <p>Spatial relevance scoring algorithm:
*
* <dl>
* <dt>queryArea
* <dd>the area of the input query envelope
* <dt>targetArea
* <dd>the area of the target envelope (per Lucene document)
* <dt>intersectionArea
* <dd>the area of the intersection between the query and target envelopes
* <dt>queryTargetProportion
* <dd>A 0-1 factor that divides the score proportion between query and target. 0.5 is evenly.
* <dt>queryRatio
* <dd>intersectionArea / queryArea; (see note)
* <dt>targetRatio
* <dd>intersectionArea / targetArea; (see note)
* <dt>queryFactor
* <dd>queryRatio * queryTargetProportion;
* <dt>targetFactor
* <dd>targetRatio * (1 - queryTargetProportion);
* <dt>score
* <dd>queryFactor + targetFactor;
* </dl>
*
* Additionally, note that an optional minimum side length {@code minSideLength} may be used
* whenever an area is calculated (queryArea, targetArea, intersectionArea). This allows for points
* or horizontal/vertical lines to be used as the query shape and in such case the descending order
* should have smallest boxes up front. Without this, a point or line query shape typically scores
* everything with the same value since there is 0 area.
*
* <p>Note: The actual computation of queryRatio and targetRatio is more complicated so that it
* considers points and lines. Lines have the ratio of overlap, and points are either 1.0 or 0.0
* depending on whether it intersects or not.
*
* <p>Originally based on Geoportal's <a
* href="http://geoportal.svn.sourceforge.net/svnroot/geoportal/Geoportal/trunk/src/com/esri/gpt/catalog/lucene/SpatialRankingValueSource.java">
* SpatialRankingValueSource</a> but modified quite a bit. GeoPortal's algorithm will yield a score
* of 0 if either a line or point is compared, and it doesn't output a 0-1 normalized score (it
* multiplies the factors), and it doesn't support minSideLength, and it had dateline bugs.
*
* @lucene.experimental
*/
public class BBoxOverlapRatioValueSource extends BBoxSimilarityValueSource {
// -180/+180 degrees (not part of identity; attached to parent strategy/field)
private final boolean isGeo;
private final Rectangle queryExtent;
private final double queryArea; // not part of identity
private final double minSideLength;
private final double queryTargetProportion;
// TODO option to compute geodetic area
/**
* @param rectValueSource mandatory; source of rectangles
* @param isGeo True if ctx.isGeo() and thus dateline issues should be attended to
* @param queryExtent mandatory; the query rectangle
* @param queryTargetProportion see class javadocs. Between 0 and 1.
* @param minSideLength see class javadocs. 0.0 will effectively disable.
*/
public BBoxOverlapRatioValueSource(
ShapeValuesSource rectValueSource,
boolean isGeo,
Rectangle queryExtent,
double queryTargetProportion,
double minSideLength) {
super(rectValueSource);
this.isGeo = isGeo;
this.minSideLength = minSideLength;
this.queryExtent = queryExtent;
this.queryArea = calcArea(queryExtent.getWidth(), queryExtent.getHeight());
assert queryArea >= 0;
this.queryTargetProportion = queryTargetProportion;
if (queryTargetProportion < 0 || queryTargetProportion > 1.0)
throw new IllegalArgumentException("queryTargetProportion must be >= 0 and <= 1");
}
/**
* Construct with 75% weighting towards target (roughly GeoPortal's default), geo degrees assumed,
* no minimum side length.
*/
public BBoxOverlapRatioValueSource(ShapeValuesSource rectValueSource, Rectangle queryExtent) {
this(rectValueSource, true, queryExtent, 0.25, 0.0);
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) return false;
BBoxOverlapRatioValueSource that = (BBoxOverlapRatioValueSource) o;
if (Double.compare(that.minSideLength, minSideLength) != 0) return false;
if (Double.compare(that.queryTargetProportion, queryTargetProportion) != 0) return false;
if (!queryExtent.equals(that.queryExtent)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
long temp;
result = 31 * result + queryExtent.hashCode();
temp = Double.doubleToLongBits(minSideLength);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(queryTargetProportion);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
protected String similarityDescription() {
return queryExtent.toString() + "," + queryTargetProportion;
}
@Override
protected double score(Rectangle target, AtomicReference<Explanation> exp) {
// calculate "height": the intersection height between two boxes.
double top = Math.min(queryExtent.getMaxY(), target.getMaxY());
double bottom = Math.max(queryExtent.getMinY(), target.getMinY());
double height = top - bottom;
if (height < 0) {
if (exp != null) {
exp.set(Explanation.noMatch("No intersection"));
}
return 0; // no intersection
}
// calculate "width": the intersection width between two boxes.
double width = 0;
{
Rectangle a = queryExtent;
Rectangle b = target;
if (a.getCrossesDateLine() == b.getCrossesDateLine()) {
// both either cross or don't
double left = Math.max(a.getMinX(), b.getMinX());
double right = Math.min(a.getMaxX(), b.getMaxX());
if (!a.getCrossesDateLine()) { // both don't
if (left <= right) {
width = right - left;
} else if (isGeo
&& (Math.abs(a.getMinX()) == 180 || Math.abs(a.getMaxX()) == 180)
&& (Math.abs(b.getMinX()) == 180 || Math.abs(b.getMaxX()) == 180)) {
width = 0; // both adjacent to dateline
} else {
if (exp != null) {
exp.set(Explanation.noMatch("No intersection"));
}
return 0; // no intersection
}
} else { // both cross
width = right - left + 360;
}
} else {
if (!a.getCrossesDateLine()) { // then flip
a = target;
b = queryExtent;
}
// a crosses, b doesn't
double qryWestLeft = Math.max(a.getMinX(), b.getMinX());
double qryWestRight = b.getMaxX();
if (qryWestLeft < qryWestRight) width += qryWestRight - qryWestLeft;
double qryEastLeft = b.getMinX();
double qryEastRight = Math.min(a.getMaxX(), b.getMaxX());
if (qryEastLeft < qryEastRight) width += qryEastRight - qryEastLeft;
if (qryWestLeft > qryWestRight && qryEastLeft > qryEastRight) {
if (exp != null) {
exp.set(Explanation.noMatch("No intersection"));
}
return 0; // no intersection
}
}
}
// calculate queryRatio and targetRatio
double intersectionArea = calcArea(width, height);
double queryRatio;
if (queryArea > 0) {
queryRatio = intersectionArea / queryArea;
} else if (queryExtent.getHeight() > 0) { // vert line
queryRatio = height / queryExtent.getHeight();
} else if (queryExtent.getWidth() > 0) { // horiz line
queryRatio = width / queryExtent.getWidth();
} else {
queryRatio = queryExtent.relate(target).intersects() ? 1 : 0; // could be optimized
}
double targetArea = calcArea(target.getWidth(), target.getHeight());
assert targetArea >= 0;
double targetRatio;
if (targetArea > 0) {
targetRatio = intersectionArea / targetArea;
} else if (target.getHeight() > 0) { // vert line
targetRatio = height / target.getHeight();
} else if (target.getWidth() > 0) { // horiz line
targetRatio = width / target.getWidth();
} else {
targetRatio = target.relate(queryExtent).intersects() ? 1 : 0; // could be optimized
}
assert queryRatio >= 0 && queryRatio <= 1 : queryRatio;
assert targetRatio >= 0 && targetRatio <= 1 : targetRatio;
// combine ratios into a score
double queryFactor = queryRatio * queryTargetProportion;
double targetFactor = targetRatio * (1.0 - queryTargetProportion);
double score = queryFactor + targetFactor;
if (exp != null) {
String minSideDesc = minSideLength > 0.0 ? " (minSide=" + minSideLength + ")" : "";
exp.set(
Explanation.match(
(float) score,
this.getClass().getSimpleName() + ": queryFactor + targetFactor",
Explanation.match(
(float) intersectionArea,
"IntersectionArea" + minSideDesc,
Explanation.match((float) width, "width"),
Explanation.match((float) height, "height"),
Explanation.match((float) queryTargetProportion, "queryTargetProportion")),
Explanation.match(
(float) queryFactor,
"queryFactor",
Explanation.match((float) targetRatio, "ratio"),
Explanation.match((float) queryArea, "area of " + queryExtent + minSideDesc)),
Explanation.match(
(float) targetFactor,
"targetFactor",
Explanation.match((float) targetRatio, "ratio"),
Explanation.match((float) targetArea, "area of " + target + minSideDesc))));
}
return score;
}
/** Calculates the area while applying the minimum side length. */
private double calcArea(double width, double height) {
return Math.max(minSideLength, width) * Math.max(minSideLength, height);
}
}
| 39.886029 | 144 | 0.66301 |
f8e494f794d8448c0d1f06021c8ece839b613b64 | 7,595 | package com.xiaomaigou.code.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
/**
* 字段属性
*
* @author xiaomaiyun
* @version 1.2.3
* @date 2020/5/30 12:47
*/
@ApiModel(description = "字段属性")
public class Column implements Serializable {
private static final Long serialVersionUID = 1L;
/**
* 表的名称
*/
@ApiModelProperty(value = "表的名称", name = "tableName")
private String tableName;
/**
* 字段名称
*/
@ApiModelProperty(value = "字段名称", name = "columnName")
private String columnName;
/**
* 字段类型
*/
@ApiModelProperty(value = "字段类型", name = "dataType")
private String dataType;
/**
* 字段备注
*/
@ApiModelProperty(value = "字段备注", name = "columnComment")
private String columnComment;
/**
* 是否允许为空(允许为空:YES,不能为空:NO;注意:该字段为String类型,如果需要判断该字段是否允许为null请使用notNull字段代替)
*/
@ApiModelProperty(value = "是否允许为空(允许为空:YES,不能为空:NO;注意:该字段为String类型,如果需要判断该字段是否允许为null请使用notNull字段代替)", name = "isNullable")
private String isNullable;
/**
* 主键(主键:PRI;注意:该字段为String类型,如果需要判断该字段是否为主键请使用isPrimaryKey字段代替)
*/
@ApiModelProperty(value = "主键(主键:PRI;注意:该字段为String类型,如果需要判断该字段是否为主键请使用isPrimaryKey字段代替)", name = "columnKey")
private String columnKey;
/**
* 是否为自增(自增:auto_increment;注意:该字段为String类型,如果需要判断该字段是否为自增请使用isAutoIncrement字段代替)
*/
@ApiModelProperty(value = "是否为自增(自增:auto_increment;注意:该字段为String类型,如果需要判断该字段是否为自增请使用isAutoIncrement字段代替)", name = "extra")
private String extra;
/**
* 字段名称(第一个字母大写),如:user_name => UserName
*/
@ApiModelProperty(value = "字段名称(第一个字母大写),如:user_name => UserName", name = "attrName")
private String attrName;
/**
* 属性名称(第一个字母小写),如:user_name => userName
*/
@ApiModelProperty(value = "属性名称(第一个字母小写),如:user_name => userName", name = "attrname")
private String attrname;
/**
* 属性类型
*/
@ApiModelProperty(value = "属性类型", name = "attrType")
private String attrType;
/**
* 是否自增
*/
@ApiModelProperty(value = "是否为自增(自增:true)", name = "isAutoIncrement")
private Boolean isAutoIncrement;
/**
* 是否主键
*/
@ApiModelProperty(value = "主键(主键:true)", name = "primaryKey")
private Boolean primaryKey;
/**
* 不能为空
*/
@ApiModelProperty(value = "不能为空(不能为空:true)", name = "notNull")
private Boolean notNull;
/**
* 是否作为搜索字段(作为搜索字段:true)
*/
@ApiModelProperty(value = "是否作为搜索字段(作为搜索字段:true)", name = "search")
private Boolean search;
public Column() {
}
public Column(String tableName, String columnName, String dataType, String columnComment, String isNullable, String columnKey, String extra, String attrName, String attrname, String attrType, Boolean isAutoIncrement, Boolean primaryKey, Boolean notNull, Boolean search) {
this.tableName = tableName;
this.columnName = columnName;
this.dataType = dataType;
this.columnComment = columnComment;
this.isNullable = isNullable;
this.columnKey = columnKey;
this.extra = extra;
this.attrName = attrName;
this.attrname = attrname;
this.attrType = attrType;
this.isAutoIncrement = isAutoIncrement;
this.primaryKey = primaryKey;
this.notNull = notNull;
this.search = search;
}
public Boolean getAutoIncrement() {
if (isAutoIncrement == null) {
isAutoIncrement = StringUtils.equalsIgnoreCase(this.getExtra(), "auto_increment");
}
return isAutoIncrement;
}
public Boolean getNotNull() {
if (notNull == null) {
notNull = StringUtils.equalsIgnoreCase(this.getIsNullable(), "NO");
}
return notNull;
}
public Boolean getPrimaryKey() {
if (primaryKey == null) {
primaryKey = StringUtils.equalsAnyIgnoreCase(this.getColumnKey(), "PRI");
}
return primaryKey;
}
public Boolean getSearch() {
if (search == null) {
search = !this.getPrimaryKey();
}
return search;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getColumnComment() {
// 总是返回空字符串
columnComment = StringUtils.defaultString(columnComment, StringUtils.EMPTY);
// 去掉换行符
columnComment = StringUtils.replace(columnComment, StringUtils.LF, StringUtils.EMPTY);
columnComment = StringUtils.replace(columnComment, StringUtils.CR, StringUtils.EMPTY);
return columnComment;
}
public void setColumnComment(String columnComment) {
this.columnComment = columnComment;
}
public String getIsNullable() {
return isNullable;
}
public void setIsNullable(String isNullable) {
this.isNullable = isNullable;
}
public String getColumnKey() {
return columnKey;
}
public void setColumnKey(String columnKey) {
this.columnKey = columnKey;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public String getAttrName() {
return attrName;
}
public void setAttrName(String attrName) {
this.attrName = attrName;
}
public String getAttrname() {
return attrname;
}
public void setAttrname(String attrname) {
this.attrname = attrname;
}
public String getAttrType() {
return attrType;
}
public void setAttrType(String attrType) {
this.attrType = attrType;
}
// public Boolean getAutoIncrement() {
// return isAutoIncrement;
// }
public void setAutoIncrement(Boolean autoIncrement) {
isAutoIncrement = autoIncrement;
}
// public Boolean getPrimaryKey() {
// return primaryKey;
// }
public void setPrimaryKey(Boolean primaryKey) {
this.primaryKey = primaryKey;
}
// public Boolean getNotNull() {
// return notNull;
// }
public void setNotNull(Boolean notNull) {
this.notNull = notNull;
}
// public Boolean getSearch() {
// return search;
// }
public void setSearch(Boolean search) {
this.search = search;
}
@Override
public String toString() {
return "Column{" +
"tableName='" + tableName + '\'' +
", columnName='" + columnName + '\'' +
", dataType='" + dataType + '\'' +
", columnComment='" + columnComment + '\'' +
", isNullable='" + isNullable + '\'' +
", columnKey='" + columnKey + '\'' +
", extra='" + extra + '\'' +
", attrName='" + attrName + '\'' +
", attrname='" + attrname + '\'' +
", attrType='" + attrType + '\'' +
", isAutoIncrement=" + isAutoIncrement +
", primaryKey=" + primaryKey +
", notNull=" + notNull +
", search=" + search +
'}';
}
}
| 26.649123 | 275 | 0.602107 |
809c66dfdd937d21d5e3fc1b7edd5fd1630564d4 | 389 | package io.pivotal.cla.service;
import java.util.List;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class MigratePullRequestStatusRequest {
/**
* Repository ids in the format of spring-projects/spring-security
*/
final List<String> repositoryIds;
final String commitStatusUrl;
final String accessToken;
final String faqUrl;
final String baseSyncUrl;
} | 16.208333 | 67 | 0.773779 |
1a59fa0a45bbca1f702c5b8e172af7753e1f9bba | 1,764 | /*
* Copyright 2017 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.cucumber.platform.smartmetering.support.ws.smartmetering.adhoc;
import java.util.Map;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.adhoc.SynchronizeTimeAsyncRequest;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.adhoc.SynchronizeTimeRequest;
import org.opensmartgridplatform.cucumber.platform.smartmetering.PlatformSmartmeteringKeys;
import org.opensmartgridplatform.cucumber.platform.smartmetering.support.ws.smartmetering.RequestFactoryHelper;
public class SynchronizeTimeRequestFactory {
private SynchronizeTimeRequestFactory() {
// Private constructor for utility class
}
public static SynchronizeTimeRequest fromParameterMap(final Map<String, String> parameters) {
final SynchronizeTimeRequest request = new SynchronizeTimeRequest();
request.setDeviceIdentification(
parameters.get(PlatformSmartmeteringKeys.DEVICE_IDENTIFICATION));
request.setSynchronizeTimeRequestData(
SynchronizeTimeRequestDataFactory.fromParameterMap(parameters));
return request;
}
public static SynchronizeTimeAsyncRequest fromScenarioContext() {
final SynchronizeTimeAsyncRequest asyncRequest = new SynchronizeTimeAsyncRequest();
asyncRequest.setCorrelationUid(RequestFactoryHelper.getCorrelationUidFromScenarioContext());
asyncRequest.setDeviceIdentification(
RequestFactoryHelper.getDeviceIdentificationFromScenarioContext());
return asyncRequest;
}
}
| 44.1 | 111 | 0.816327 |
e9d879358c653ae90e7c3ff4758f9e5cf7f279f1 | 435 | package frc.robot.simulator.hal;
import edu.wpi.first.hal.JNIWrapper;
/**
* Sim JNI classes must be structured EXACTLY like their counterpart non-sim JNI classes. If a single field or method is added or removed, the ByteBuddy redefine will fail
*/
public class SimConstantsJNI extends JNIWrapper {
public static int getSystemClockTicksPerMicrosecond() {
// from ConstantsInternal.h in wpilib
return 40;
}
}
| 31.071429 | 171 | 0.744828 |
6e5683fc7acf8b877f0a7fa831e328165a1ae4a2 | 2,042 | package com.googlecode.yatspec.plugin.sequencediagram;
import com.googlecode.totallylazy.Sequence;
import com.googlecode.yatspec.state.givenwhenthen.CapturedInputAndOutputs;
import org.junit.Test;
import static com.googlecode.totallylazy.Sequences.sequence;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class ByNamingConventionMessageProducerTest {
@Test
public void ignoresValuesWithoutNamingConvention() {
CapturedInputAndOutputs inputAndOutputs = new CapturedInputAndOutputs().add("Shopping Basket", new Object());
Sequence<SequenceDiagramMessage> messages = sequence(new ByNamingConventionMessageProducer().messages(inputAndOutputs));
assertThat(messages.isEmpty(), is(true));
}
@Test
public void convertsValuesWithNamingConventionToSequenceDiagramMessages() {
CapturedInputAndOutputs inputAndOutputs = new CapturedInputAndOutputs().add("Kiss from Boy to Girl", new Object()).add("Slap from Girl to Boy", new Object());
Sequence<SequenceDiagramMessage> messages = sequence(new ByNamingConventionMessageProducer().messages(inputAndOutputs));
assertThat(messages.size(), is(equalTo(2)));
assertThat(messages.first(), is(equalTo(new SequenceDiagramMessage("Boy", "Girl", "Kiss", "Kiss_from_Boy_to_Girl"))));
assertThat(messages.second(), is(equalTo(new SequenceDiagramMessage("Girl", "Boy", "Slap", "Slap_from_Girl_to_Boy"))));
}
@Test
public void dealsWithGroups() {
CapturedInputAndOutputs inputAndOutputs = new CapturedInputAndOutputs().add("(grouped) Kiss from Boy to Girl", new Object());
Sequence<SequenceDiagramMessage> messages = sequence(new ByNamingConventionMessageProducer().messages(inputAndOutputs));
assertThat(messages.size(), is(equalTo(1)));
assertThat(messages.first(), is(equalTo(new SequenceDiagramMessage("Boy", "Girl", "(grouped) Kiss", "_grouped__Kiss_from_Boy_to_Girl"))));
}
}
| 53.736842 | 166 | 0.75808 |
8ca9ea10763eb42d7749dcb4626280c9cb7d67e5 | 556 | package com.neo.qiaoqiaochat.web.model.vo;
import lombok.Data;
/**
* 好友返回参数
* @author linyi
* @date 2020/7/28 9:00
*/
@Data
public class FriendVO {
/**
* 账号
*/
private String account;
/**
* 昵称
*/
private String nickName;
/**
* 好友备注
*/
private String remarkName;
/**
* 头像地址
*/
private String headImageIndex;
/**
* 好友关系 0好友 1拉黑
*/
private Integer relationIndex;
/**
* 消息接收策略 0接收并提示 1接收但不提示 2拒收
*/
private Integer msgReceiveSetting;
}
| 11.829787 | 42 | 0.535971 |
8d311d9787079be65a4ee843b08efa42536edfbf | 384 | package com.mmnaseri.utils.spring.data.sample.mocks;
import com.mmnaseri.utils.spring.data.domain.impl.matchers.AbstractUnaryMatcher;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/12/16, 7:01 PM)
*/
public class NotMatchingUnaryMatcher extends AbstractUnaryMatcher {
@Override
protected boolean matches(Object value) {
return false;
}
}
| 22.588235 | 80 | 0.723958 |
43bc9a7eda4d388aeb92ba0630df645447fb0e52 | 12,631 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|jaxrs
operator|.
name|model
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|Consumes
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|Produces
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|core
operator|.
name|MediaType
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|endpoint
operator|.
name|Endpoint
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|message
operator|.
name|Exchange
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|message
operator|.
name|ExchangeImpl
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|message
operator|.
name|Message
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|message
operator|.
name|MessageImpl
import|;
end_import
begin_import
import|import
name|org
operator|.
name|easymock
operator|.
name|EasyMock
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_class
specifier|public
class|class
name|OperationResourceInfoTest
block|{
annotation|@
name|Produces
argument_list|(
literal|"text/xml"
argument_list|)
annotation|@
name|Consumes
argument_list|(
literal|"application/xml"
argument_list|)
specifier|static
class|class
name|TestClass
block|{
annotation|@
name|Produces
argument_list|(
literal|"text/plain"
argument_list|)
specifier|public
name|void
name|doIt
parameter_list|()
block|{
comment|// empty
block|}
empty_stmt|;
annotation|@
name|Consumes
argument_list|(
literal|"application/atom+xml"
argument_list|)
specifier|public
name|void
name|doThat
parameter_list|()
block|{
comment|// empty
block|}
empty_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testConsumeTypes
parameter_list|()
throws|throws
name|Exception
block|{
name|OperationResourceInfo
name|ori1
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doIt"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|List
argument_list|<
name|MediaType
argument_list|>
name|ctypes
init|=
name|ori1
operator|.
name|getConsumeTypes
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|"Single media type expected"
argument_list|,
literal|1
argument_list|,
name|ctypes
operator|.
name|size
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"Class resource consume type should be used"
argument_list|,
literal|"application/xml"
argument_list|,
name|ctypes
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
name|OperationResourceInfo
name|ori2
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doThat"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|ctypes
operator|=
name|ori2
operator|.
name|getConsumeTypes
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
literal|"Single media type expected"
argument_list|,
literal|1
argument_list|,
name|ctypes
operator|.
name|size
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"Method consume type should be used"
argument_list|,
literal|"application/atom+xml"
argument_list|,
name|ctypes
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testProduceTypes
parameter_list|()
throws|throws
name|Exception
block|{
name|OperationResourceInfo
name|ori1
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doIt"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|List
argument_list|<
name|MediaType
argument_list|>
name|ctypes
init|=
name|ori1
operator|.
name|getProduceTypes
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|"Single media type expected"
argument_list|,
literal|1
argument_list|,
name|ctypes
operator|.
name|size
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"Method produce type should be used"
argument_list|,
literal|"text/plain"
argument_list|,
name|ctypes
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
name|OperationResourceInfo
name|ori2
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doThat"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|ctypes
operator|=
name|ori2
operator|.
name|getProduceTypes
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
literal|"Single media type expected"
argument_list|,
literal|1
argument_list|,
name|ctypes
operator|.
name|size
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"Class resource produce type should be used"
argument_list|,
literal|"text/xml"
argument_list|,
name|ctypes
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testComparator1
parameter_list|()
throws|throws
name|Exception
block|{
name|OperationResourceInfo
name|ori1
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doIt"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|ori1
operator|.
name|setURITemplate
argument_list|(
operator|new
name|URITemplate
argument_list|(
literal|"/"
argument_list|)
argument_list|)
expr_stmt|;
name|OperationResourceInfo
name|ori2
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doThat"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|ori2
operator|.
name|setURITemplate
argument_list|(
operator|new
name|URITemplate
argument_list|(
literal|"/"
argument_list|)
argument_list|)
expr_stmt|;
name|OperationResourceInfoComparator
name|cmp
init|=
operator|new
name|OperationResourceInfoComparator
argument_list|(
literal|null
argument_list|,
literal|null
argument_list|)
decl_stmt|;
name|int
name|result
init|=
name|cmp
operator|.
name|compare
argument_list|(
name|ori1
argument_list|,
name|ori2
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|0
argument_list|,
name|result
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testComparator2
parameter_list|()
throws|throws
name|Exception
block|{
name|Message
name|m
init|=
name|createMessage
argument_list|()
decl_stmt|;
name|OperationResourceInfo
name|ori1
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doIt"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|ori1
operator|.
name|setURITemplate
argument_list|(
operator|new
name|URITemplate
argument_list|(
literal|"/"
argument_list|)
argument_list|)
expr_stmt|;
name|OperationResourceInfo
name|ori2
init|=
operator|new
name|OperationResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
operator|.
name|getMethod
argument_list|(
literal|"doThat"
argument_list|,
operator|new
name|Class
index|[]
block|{}
argument_list|)
argument_list|,
operator|new
name|ClassResourceInfo
argument_list|(
name|TestClass
operator|.
name|class
argument_list|)
argument_list|)
decl_stmt|;
name|ori2
operator|.
name|setURITemplate
argument_list|(
operator|new
name|URITemplate
argument_list|(
literal|"/"
argument_list|)
argument_list|)
expr_stmt|;
name|OperationResourceInfoComparator
name|cmp
init|=
operator|new
name|OperationResourceInfoComparator
argument_list|(
name|m
argument_list|,
literal|"POST"
argument_list|,
literal|false
argument_list|,
name|MediaType
operator|.
name|WILDCARD_TYPE
argument_list|,
name|Collections
operator|.
name|singletonList
argument_list|(
name|MediaType
operator|.
name|WILDCARD_TYPE
argument_list|)
argument_list|)
decl_stmt|;
name|int
name|result
init|=
name|cmp
operator|.
name|compare
argument_list|(
name|ori1
argument_list|,
name|ori2
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|0
argument_list|,
name|result
argument_list|)
expr_stmt|;
block|}
specifier|private
specifier|static
name|Message
name|createMessage
parameter_list|()
block|{
name|Message
name|m
init|=
operator|new
name|MessageImpl
argument_list|()
decl_stmt|;
name|Exchange
name|e
init|=
operator|new
name|ExchangeImpl
argument_list|()
decl_stmt|;
name|m
operator|.
name|setExchange
argument_list|(
name|e
argument_list|)
expr_stmt|;
name|e
operator|.
name|setInMessage
argument_list|(
name|m
argument_list|)
expr_stmt|;
name|Endpoint
name|endpoint
init|=
name|EasyMock
operator|.
name|createMock
argument_list|(
name|Endpoint
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|endpoint
operator|.
name|get
argument_list|(
literal|"org.apache.cxf.jaxrs.comparator"
argument_list|)
argument_list|)
operator|.
name|andReturn
argument_list|(
literal|null
argument_list|)
expr_stmt|;
name|EasyMock
operator|.
name|replay
argument_list|(
name|endpoint
argument_list|)
expr_stmt|;
name|e
operator|.
name|put
argument_list|(
name|Endpoint
operator|.
name|class
argument_list|,
name|endpoint
argument_list|)
expr_stmt|;
return|return
name|m
return|;
block|}
block|}
end_class
end_unit
| 14.602312 | 810 | 0.805558 |
e51c150163b5daacb08b372e9bd257aeae6f8093 | 1,013 | package com.ma.home;
import java.util.Deque;
import java.util.LinkedList;
public class TrainComposition {
private final Deque<Integer> wagons = new LinkedList<>();
public void attachWagonFromLeft(int wagonId) {
wagons.addFirst(wagonId);
}
public void attachWagonFromRight(int wagonId) {
wagons.addLast(wagonId);
}
public int detachWagonFromLeft() {
int index = 0;
if (!wagons.isEmpty()) {
index = wagons.removeFirst();
}
return index;
}
public int detachWagonFromRight() {
int index = 0;
if (!wagons.isEmpty()) {
index = wagons.removeLast();
}
return index;
}
public static void main(String[] args) {
TrainComposition tree = new TrainComposition();
tree.attachWagonFromLeft(7);
tree.attachWagonFromLeft(13);
System.out.println(tree.detachWagonFromRight()); // 7
System.out.println(tree.detachWagonFromLeft()); // 13
}
} | 25.974359 | 61 | 0.611056 |
c583c4086e28c9e3be97765f9ae7dae8b86c25a9 | 875 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013-2014 sagyf Yang. The Four Group.
*/
package goja.lucene.analyzer;
import org.junit.Test;
import org.wltea.analyzer.core.Lexeme;
import java.util.List;
public class AnalyzerTest {
@Test
public void testAnalyzer() throws Exception {
List<Lexeme> words = Analyzer.getInstance().analyzer("字典内的是否能够自动匹配呢,还是买入05建元1s这个,这个也可以放心的00定向国债2把唉,那就买入10000万,收益率:8%,评级为AAA");
for (Lexeme word : words) {
System.out.println(word);
}
}
@Test
public void testDisableSmart() throws Exception {
List<Lexeme> words = Analyzer.getInstance().disableSmart()
.analyzer("字典内的是否能够自动匹配呢,还是买入05建元1s这个,这个也可以放心的00定向国债2把唉,那就买入10000万,收益率:8%");
for (Lexeme word : words) {
System.out.println(word);
}
}
} | 26.515152 | 134 | 0.659429 |
81c21b81b41e118d4f16e5ad4defa8c4d19036b0 | 6,138 | /*
* Copyright 2016 Claymore Minds Limited and Niche Solutions (UK) Limited
*
* 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.viewserver.operators.table;
import io.viewserver.catalog.ICatalog;
import io.viewserver.core.ExecutionContext;
import io.viewserver.schema.ITableStorage;
import io.viewserver.schema.Schema;
import io.viewserver.schema.column.ColumnHolder;
import io.viewserver.util.ViewServerException;
import gnu.trove.map.hash.TObjectIntHashMap;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nickc on 23/09/2014.
*/
public class KeyedTable extends Table {
protected TableKeyDefinition tableKeyDefinition;
private TObjectIntHashMap<Object> keys = new TObjectIntHashMap<>(8, 0.75f, -1);
public KeyedTable(String name, ExecutionContext executionContext, ICatalog catalog, Schema schema, ITableStorage storage, TableKeyDefinition tableKeyDefinition) {
super(name, executionContext, catalog, schema, storage);
if (tableKeyDefinition == null) {
throw new RuntimeException(String.format("Unable to create a keyed table \"%s\" with a null table key definition", name));
}
this.tableKeyDefinition = tableKeyDefinition;
}
@Override
public void initialise(int capacity) {
if (initialised) {
throw new RuntimeException("Table already initialised");
}
for (String keyColumn : tableKeyDefinition.getKeys()) {
ColumnHolder keyHolder = this.getOutput().getSchema().getColumnHolder(keyColumn);
// add the key column for the caller if it wasn't declared explicitly in the schema
if (keyHolder == null) {
throw new RuntimeException(String.format("The key column %s was not defined in the schema, it should be defined", keyColumn));
}
}
super.initialise(capacity);
}
@Override
public int addRow(ITableRowUpdater updater) {
return super.addRow(new DelegatingTableRowUpdater(updater) {
@Override
public void setValues(ITableRow row) {
super.setValues(row);
TableKey tableKey = getTableKey(row);
storeKeyForRow(tableKey, row.getRowId());
}
});
}
// TODO: set key column values in here
public int addRow(TableKey tableKey, ITableRowUpdater updater) {
int rowId = getRow(tableKey);
if (rowId != -1) {
throw new ViewServerException("A row already exists with that key");
}
rowId = super.addRow(updater);
storeKeyForRow(tableKey, rowId);
return rowId;
}
@Override
public void updateRow(int row, ITableRowUpdater updater) {
super.updateRow(row, new DelegatingTableRowUpdater(updater) {
@Override
public void setValues(ITableRow tableRow) {
TableKey oldKey = KeyedTable.this.getTableKey(tableRow);
super.setValues(tableRow);
TableKey newKey = KeyedTable.this.getTableKey(tableRow);
if (!newKey.equals(oldKey)) {
KeyedTable.this.removeKey(oldKey);
KeyedTable.this.storeKeyForRow(newKey, row);
}
}
});
}
public void updateRow(TableKey tableKey, ITableRowUpdater updater) {
Object keyValue = tableKeyDefinition.getValue(tableKey);
int rowId = keys.get(keyValue);
super.updateRow(rowId, updater);
}
public void updateRow(ITableRowUpdater updater) {
updateRow(getTableKey(updater), updater);
}
public void addOrUpdateRow(ITableRowUpdater updater) {
TableKey tableKey = getTableKey(updater);
int rowId = getRow(tableKey);
if (rowId != -1) {
updateRow(tableKey, updater);
} else {
addRow(updater);
}
}
private TableKey getTableKey(ITableRowUpdater updater) {
List<String> keys = tableKeyDefinition.getKeys();
int count = keys.size();
Object[] keyValues = new Object[count];
for (int i = 0; i < count; i++) {
keyValues[i] = updater.getValue(keys.get(i));
}
return new TableKey(keyValues);
}
@Override
public void removeRow(int rowId) {
tableRow.setRowId(rowId);
TableKey tableKey = getTableKey(tableRow);
removeRow(tableKey);
}
public void removeRow(TableKey tableKey) {
int rowId = removeKey(tableKey);
super.removeRow(rowId);
}
public int getRow(TableKey tableKey){
Object keyValue = tableKeyDefinition.getValue(tableKey);
return keys.get(keyValue);
}
protected TableKey getTableKey(ITableRow row) {
List<Object> keyValues = new ArrayList<>();
List<String> keys = tableKeyDefinition.getKeys();
int count = keys.size();
for (int i = 0; i < count; i++) {
keyValues.add(row.getValue(keys.get(i)));
}
return new TableKey(keyValues.toArray());
}
private void storeKeyForRow(TableKey tableKey, int rowId) {
Object keyValue = tableKeyDefinition.getValue(tableKey);
if(tableKey.size() != tableKeyDefinition.size()){
throw new RuntimeException(String.format("There must be exactly %d values in the table key \"%s\"", tableKeyDefinition.size(),tableKey));
}
keys.put(keyValue, rowId);
}
private int removeKey(TableKey tableKey) {
Object keyValue = tableKeyDefinition.getValue(tableKey);
return keys.remove(keyValue);
}
}
| 33.911602 | 166 | 0.64679 |
bd47ddf3fa977cc8ce2885ad68d89fb7e60dd0b4 | 10,065 | /*
*
* Copyright (c) 2013 - 2020 Lijun Liao
*
* 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.xipki.security;
import com.alibaba.fastjson.JSON;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xipki.password.PasswordResolver;
import org.xipki.password.Passwords;
import org.xipki.password.Passwords.PasswordConf;
import org.xipki.security.pkcs11.*;
import org.xipki.security.pkcs11.iaik.IaikP11ModuleFactory;
import org.xipki.security.pkcs12.P12SignerFactory;
import org.xipki.util.*;
import java.io.Closeable;
import java.io.IOException;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Utility class to initialize {@link SecurityFactory} and {@link P11CryptServiceFactory}.
*
* @author Lijun Liao
*/
public class Securities implements Closeable {
public static class KeystoreConf extends ValidatableConf {
private String type;
private FileOrBinary keystore;
private String password;
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public FileOrBinary getKeystore() {
return keystore;
}
public void setKeystore(FileOrBinary value) {
this.keystore = value;
}
public String getPassword() {
return password;
}
public void setPassword(String value) {
this.password = value;
}
@Override
public void validate()
throws InvalidConfException {
notBlank(type, "type");
validate(keystore);
}
} // class KeystoreConf
public static class SecurityConf extends ValidatableConf {
private boolean keyStrongrandomEnabled;
private boolean signStrongrandomEnabled;
private int defaultSignerParallelism = 32;
private FileOrValue pkcs11Conf;
private PasswordConf password;
/**
* list of classes that implement org.xipki.security.SignerFactory
*/
private List<String> signerFactories;
public static final SecurityConf DEFAULT;
static {
DEFAULT = new SecurityConf();
}
public boolean isKeyStrongrandomEnabled() {
return keyStrongrandomEnabled;
}
public void setKeyStrongrandomEnabled(boolean keyStrongrandomEnabled) {
this.keyStrongrandomEnabled = keyStrongrandomEnabled;
}
public boolean isSignStrongrandomEnabled() {
return signStrongrandomEnabled;
}
public void setSignStrongrandomEnabled(boolean signStrongrandomEnabled) {
this.signStrongrandomEnabled = signStrongrandomEnabled;
}
public int getDefaultSignerParallelism() {
return defaultSignerParallelism;
}
public void setDefaultSignerParallelism(int defaultSignerParallelism) {
this.defaultSignerParallelism = defaultSignerParallelism;
}
public FileOrValue getPkcs11Conf() {
return pkcs11Conf;
}
public void setPkcs11Conf(FileOrValue pkcs11Conf) {
this.pkcs11Conf = pkcs11Conf;
}
public PasswordConf getPassword() {
return password == null ? PasswordConf.DEFAULT : password;
}
public void setPassword(PasswordConf password) {
this.password = password;
}
public List<String> getSignerFactories() {
return signerFactories;
}
public void setSignerFactories(List<String> signerFactories) {
this.signerFactories = signerFactories;
}
@Override
public void validate()
throws InvalidConfException {
validate(password);
}
} // class SecurityConf
private static final Logger LOG = LoggerFactory.getLogger(Securities.class);
private P11ModuleFactoryRegisterImpl p11ModuleFactoryRegister;
private P11CryptServiceFactoryImpl p11CryptServiceFactory;
private SecurityFactoryImpl securityFactory;
private final List<P11ModuleFactory> p11ModuleFactories;
public Securities() {
this(createDefaultFactories());
}
public Securities(List<P11ModuleFactory> p11ModuleFactories) {
this.p11ModuleFactories = p11ModuleFactories != null
? new ArrayList<>(p11ModuleFactories) : Collections.emptyList();
}
private static List<P11ModuleFactory> createDefaultFactories() {
List<P11ModuleFactory> factories = new ArrayList<>(3);
factories.add(new IaikP11ModuleFactory());
String[] classNames = {
"org.xipki.security.pkcs11.emulator.EmulatorP11ModuleFactory",
"org.xipki.security.pkcs11.proxy.ProxyP11ModuleFactory"
};
ClassLoader cl = Securities.class.getClassLoader();
for (String className : classNames) {
Class<?> clazz;
try {
clazz = cl.loadClass(className);
} catch (ClassNotFoundException ex) {
LOG.info("{} not in the classpath, ignore it", className);
continue;
}
try {
factories.add((P11ModuleFactory) clazz.newInstance());
} catch (InstantiationException | IllegalAccessException ex) {
LogUtil.error(LOG, ex, "could not create new instance of " + className);
}
}
return factories;
}
public SecurityFactory getSecurityFactory() {
return securityFactory;
}
public P11CryptServiceFactory getP11CryptServiceFactory() {
return p11CryptServiceFactory;
}
public void init()
throws IOException, InvalidConfException {
init(null);
}
public void init(SecurityConf conf)
throws IOException, InvalidConfException {
if (Security.getProvider("BC") == null) {
LOG.info("add BouncyCastleProvider");
Security.addProvider(new BouncyCastleProvider());
} else {
LOG.info("BouncyCastleProvider already added");
}
if (conf == null) {
conf = SecurityConf.DEFAULT;
}
initSecurityFactory(conf);
}
@Override
public void close() {
if (p11ModuleFactoryRegister != null) {
try {
p11ModuleFactoryRegister.close();
} catch (Throwable th) {
LOG.error("error while closing P11ModuleFactoryRegister", th);
}
p11ModuleFactoryRegister = null;
}
if (p11CryptServiceFactory != null) {
try {
p11CryptServiceFactory.close();
} catch (Throwable th) {
LOG.error("error while closing P11CryptServiceFactory", th);
}
this.p11CryptServiceFactory = null;
}
} // method close
private void initSecurityFactory(SecurityConf conf)
throws IOException, InvalidConfException {
Passwords passwords = new Passwords();
passwords.init(conf.getPassword());
securityFactory = new SecurityFactoryImpl();
securityFactory.setStrongRandom4SignEnabled(conf.isSignStrongrandomEnabled());
securityFactory.setStrongRandom4KeyEnabled(conf.isKeyStrongrandomEnabled());
securityFactory.setDefaultSignerParallelism(conf.getDefaultSignerParallelism());
SignerFactoryRegisterImpl signerFactoryRegister = new SignerFactoryRegisterImpl();
securityFactory.setSignerFactoryRegister(signerFactoryRegister);
securityFactory.setPasswordResolver(passwords.getPasswordResolver());
// PKCS#12
initSecurityPkcs12(signerFactoryRegister);
// PKCS#11
if (conf.getPkcs11Conf() != null) {
initSecurityPkcs11(conf.getPkcs11Conf(), signerFactoryRegister,
passwords.getPasswordResolver());
}
// register additional SignerFactories
if (CollectionUtil.isNotEmpty(conf.getSignerFactories())) {
for (String className : conf.getSignerFactories()) {
try {
Class<?> clazz = Class.forName(className);
SignerFactory factory = (SignerFactory) clazz.newInstance();
signerFactoryRegister.registFactory(factory);
} catch (ClassCastException | ClassNotFoundException | IllegalAccessException
| InstantiationException ex) {
throw new InvalidConfException("error caught while initializing SignerFactory "
+ className + ": " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
}
}
}
} // method initSecurityFactory
private void initSecurityPkcs12(SignerFactoryRegisterImpl signerFactoryRegister) {
P12SignerFactory p12SignerFactory = new P12SignerFactory();
p12SignerFactory.setSecurityFactory(securityFactory);
signerFactoryRegister.registFactory(p12SignerFactory);
} // method initSecurityPkcs12
private void initSecurityPkcs11(FileOrValue pkcs11Conf,
SignerFactoryRegisterImpl signerFactoryRegister, PasswordResolver passwordResolver)
throws InvalidConfException {
p11ModuleFactoryRegister = new P11ModuleFactoryRegisterImpl();
for (P11ModuleFactory m : p11ModuleFactories) {
p11ModuleFactoryRegister.registFactory(m);
}
p11CryptServiceFactory = new P11CryptServiceFactoryImpl();
p11CryptServiceFactory.setP11ModuleFactoryRegister(p11ModuleFactoryRegister);
p11CryptServiceFactory.setPasswordResolver(passwordResolver);
Pkcs11conf pkcs11ConfObj;
try {
pkcs11ConfObj = JSON.parseObject(pkcs11Conf.readContent(), Pkcs11conf.class);
} catch (IOException ex) {
throw new InvalidConfException("could not create P11Conf: " + ex.getMessage(), ex);
}
p11CryptServiceFactory.setPkcs11Conf(pkcs11ConfObj);
p11CryptServiceFactory.init();
P11SignerFactory p11SignerFactory = new P11SignerFactory();
p11SignerFactory.setSecurityFactory(securityFactory);
p11SignerFactory.setP11CryptServiceFactory(p11CryptServiceFactory);
signerFactoryRegister.registFactory(p11SignerFactory);
} // method initSecurityPkcs11
}
| 29.429825 | 90 | 0.72002 |
23f05857e05706bb06962f1dc4aec202b940768a | 2,449 | package application;
import com.interactivemesh.jfx.importer.obj.ObjModelImporter;
import javafx.application.Application;
import javafx.scene.AmbientLight;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.shape.MeshView;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import java.net.URL;
/**
* @author MING
* @author Liu BaoYang
* @author Wang YiYan
* @author Robert Chen
*/
public class Show3DModelStage extends Application {
private static Stage showModelStage = null;
public static Stage getShowModelStage() {
if (showModelStage == null) { showModelStage = new Stage(); }
return showModelStage;
}
// 创建包含 3D 模型的场景
private Scene createScene() {
// 设置 3D 模型的照相机、创建 3D 模型的信息组与漫反射灯,使 3D 模型的每个角度都能看到颜色
Group model = load3dModel(getClass().getResource("../resource/beamModel/bridge1.obj"));
PerspectiveCamera camera = new PerspectiveCamera(true);
AmbientLight ambientLight = new AmbientLight(Color.WHITE);
// 调整照相机角度
camera.setTranslateX(-25);
camera.setTranslateY(0);
camera.setTranslateZ(-93);
// 调整模型角度、添加灯光效果
model.getTransforms().add(new Rotate(10, Rotate.X_AXIS));
model.getTransforms().add(new Rotate(60, Rotate.Y_AXIS));
model.getTransforms().add(new Rotate(-90, Rotate.Z_AXIS));
model.getChildren().add(ambientLight);
Scene scene = new Scene(model, 1000, 660, true);
scene.setCamera(camera);
return scene;
}
// 导入 3D 模型数据
private Group load3dModel(URL url) {
Group modelRoot = new Group();
ObjModelImporter importer = new ObjModelImporter();
importer.read(url);
for (MeshView view : importer.getImport()) { modelRoot.getChildren().add(view); }
return modelRoot;
}
@Override
public void start(Stage stage) {
URL iconUrl = getClass().getResource("../resource/image/icon/prebeams.png");
Image icon = new Image(iconUrl.toExternalForm());
stage.getIcons().add(icon);
stage.setTitle("桥梁 3D模型 展示界面");
stage.setScene(createScene());
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) { launch(args); }
public void showStage() { start(getShowModelStage()); }
}
| 32.223684 | 95 | 0.672111 |
bd5047361920d50163a7b4997a96005f593f30e7 | 4,540 | package com.wallet.crypto.trustapp.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.support.design.widget.TextInputLayout;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListenerAdapter;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.EditText;
import android.widget.TextView;
import com.wallet.crypto.trustapp.R;
/**
* TextInputLayout temporary workaround for helper text showing
* https://gist.github.com/drstranges/1a86965f582f610244d6
*/
public class HelperTextInputLayout extends TextInputLayout {
static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator();
private CharSequence mHelperText;
private ColorStateList mHelperTextColor;
private boolean mHelperTextEnabled = false;
private boolean mErrorEnabled = false;
private TextView mHelperView;
private int mHelperTextAppearance = R.style.HelperTextAppearance;
public HelperTextInputLayout(Context _context) {
super(_context);
}
public HelperTextInputLayout(Context _context, AttributeSet _attrs) {
super(_context, _attrs);
final TypedArray a = getContext().obtainStyledAttributes(
_attrs,
R.styleable.HelperTextInputLayout,0,0);
try {
mHelperTextColor = a.getColorStateList(R.styleable.HelperTextInputLayout_helperTextColor);
mHelperText = a.getText(R.styleable.HelperTextInputLayout_helperText);
} finally {
a.recycle();
}
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
if (child instanceof EditText) {
if (!TextUtils.isEmpty(mHelperText)) {
setHelperText(mHelperText);
}
}
}
public int getHelperTextAppearance() {
return mHelperTextAppearance;
}
public void setHelperTextAppearance(int _helperTextAppearanceResId) {
mHelperTextAppearance = _helperTextAppearanceResId;
}
public void setHelperTextColor(ColorStateList _helperTextColor) {
mHelperTextColor = _helperTextColor;
}
public void setHelperTextEnabled(boolean _enabled) {
if (mHelperTextEnabled == _enabled) return;
if (_enabled && mErrorEnabled) {
setErrorEnabled(false);
}
if (this.mHelperTextEnabled != _enabled) {
if (_enabled) {
this.mHelperView = new TextView(this.getContext());
this.mHelperView.setTextAppearance(this.getContext(), this.mHelperTextAppearance);
if (mHelperTextColor != null){
this.mHelperView.setTextColor(mHelperTextColor);
}
this.mHelperView.setVisibility(INVISIBLE);
this.addView(this.mHelperView);
if (this.mHelperView != null) {
ViewCompat.setPaddingRelative(
this.mHelperView,
ViewCompat.getPaddingStart(getEditText()),
0, ViewCompat.getPaddingEnd(getEditText()),
getEditText().getPaddingBottom());
}
} else {
this.removeView(this.mHelperView);
this.mHelperView = null;
}
this.mHelperTextEnabled = _enabled;
}
}
public void setHelperText(CharSequence _helperText) {
mHelperText = _helperText;
if (!this.mHelperTextEnabled) {
if (TextUtils.isEmpty(mHelperText)) {
return;
}
this.setHelperTextEnabled(true);
}
if (!TextUtils.isEmpty(mHelperText)) {
this.mHelperView.setText(mHelperText);
this.mHelperView.setVisibility(VISIBLE);
ViewCompat.setAlpha(this.mHelperView, 0.0F);
ViewCompat.animate(this.mHelperView)
.alpha(1.0F).setDuration(200L)
.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
.setListener(null).start();
} else if (this.mHelperView.getVisibility() == VISIBLE) {
ViewCompat.animate(this.mHelperView)
.alpha(0.0F).setDuration(200L)
.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
.setListener(new ViewPropertyAnimatorListenerAdapter() {
public void onAnimationEnd(View view) {
mHelperView.setText(null);
mHelperView.setVisibility(INVISIBLE);
}
}).start();
}
this.sendAccessibilityEvent(2048);
}
@Override
public void setErrorEnabled(boolean _enabled) {
if (mErrorEnabled == _enabled) return;
mErrorEnabled = _enabled;
if (_enabled && mHelperTextEnabled) {
setHelperTextEnabled(false);
}
super.setErrorEnabled(_enabled);
if (!(_enabled || TextUtils.isEmpty(mHelperText))) {
setHelperText(mHelperText);
}
}
} | 30.066225 | 93 | 0.756608 |
9cdd15c745d88b43d58143b697d3a3538c9919b5 | 4,841 | /*
* MIT License
*
* Copyright (c) 2018 Isaac Ellingson (Falkreon) and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.elytradev.marsenal.client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Nullable;
import com.elytradev.marsenal.MagicArsenal;
import com.elytradev.marsenal.client.star.LegacyLineSegmentStar;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
/**
* Notes to implementors:
* <li> Emitters MUST have a zero-arg constructor, and be registered with Emitter.
*/
public abstract class Emitter {
private static HashMap<String, Class<? extends Emitter>> registry = new HashMap<>();
private static HashMap<String, Class<? extends WorldEmitter>> worldEmitterRegistry = new HashMap<>();
public static void register(String key, Class<? extends Emitter> impl) { registry.put(key, impl); }
public static void registerWorldEmitter(String key, Class<? extends WorldEmitter> impl) { worldEmitterRegistry.put(key, impl); }
@Nullable
public static Emitter create(String key) {
Class<? extends Emitter> clazz = registry.get(key);
try {
if (clazz!=null) {
return clazz.getDeclaredConstructor().newInstance();
}
} catch (Throwable t) {
MagicArsenal.LOG.warn("Unable to create emitter for class {}. Thrown: {}", clazz, t);
}
return null;
}
@Nullable
public static WorldEmitter createWorldEmitter(String key, NBTTagCompound tag) {
Class<? extends WorldEmitter> clazz = worldEmitterRegistry.get(key);
try {
if (clazz!=null) {
return clazz.getDeclaredConstructor().newInstance();
}
} catch (Throwable t) {
MagicArsenal.LOG.warn("Unable to create emitter for class {}. Thrown: {}", clazz, t);
}
return null;
}
public World world;
public float x = 0;
public float y = 0;
public float z = 0;
public Entity source = null;
public Entity entity = null;
private boolean dead = false;
public void init(World world, float x, float y, float z, Entity source, Entity target) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.source = source;
this.entity = target;
}
public void kill() {
dead = true;
}
/** Called once every world tick, so that new particles can be spawned or old particles can have their trajectories adjusted */
public abstract void tick();
/** Called once every frame, in case the emitter needs to draw an effect directly to the screen in worldspace. */
public abstract void draw(float partialFrameTime, double dx, double dy, double dz);
/** If this returns true at any time, the emitter will be removed from the scheduler and cease to be. */
public boolean isDead() {
return dead;
}
public static void drawStars(double dx, double dy, double dz, Collection<LegacyLineSegmentStar> stars) {
drawStars(0, dx, dy, dz, stars, false);
}
private static List<LegacyLineSegmentStar> deadStars = new ArrayList<>();
public static void drawStars(float partialFrameTime, double dx, double dy, double dz, Collection<LegacyLineSegmentStar> stars, boolean doPhysics) {
GlStateManager.disableLighting();
GlStateManager.disableTexture2D();
GlStateManager.enableBlend();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
for(LegacyLineSegmentStar star : stars) {
star.paint(dx, dy, dz);
if (doPhysics) {
star.tick(partialFrameTime);
if (star.lifetime<=0) deadStars.add(star);
}
}
if (doPhysics) {
stars.removeAll(deadStars);
deadStars.clear();
}
GlStateManager.disableBlend();
GlStateManager.enableLighting();
GlStateManager.enableTexture2D();
}
}
| 34.827338 | 148 | 0.737658 |
2e775d51b92b07608f64c99e6ba838b7f29c523a | 713 | package com.sai.javafx.calendar.cell;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
/**
* AbstractCell
* @author Sai.Dandem
*
*/
public abstract class AbstractCell extends StackPane {
protected Text txt;
public AbstractCell(){
super();
}
public abstract void setCellId(String id);
public abstract void setCellWidth(double width);
public abstract void setCellHeight(double height);
public abstract void setCellStyle(String styleClass);
/**
* @return the txt
*/
public Text getTxt() {
return txt;
}
/**
* @param txt the txt to set
*/
public void setTxt(Text txt) {
this.txt = txt;
}
}
| 18.763158 | 57 | 0.638149 |
17207757ff080f72bd847ab33d2e14ba98bae6c3 | 202 | package net.zelaznog.library.model;
/**
* Created by Decaedro on 30/01/2016.
*/
public class App {
public String title;
public String pkg;
public String url;
public String version;
}
| 16.833333 | 37 | 0.678218 |
e6584f029263b9fc89590cf463f38ccfdba8347f | 6,036 | import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.swing.*;
public class Client {
public static void main(String[] args) {
setupGUI();
}
private static void setupGUI() {
// Main window
JFrame frame = new JFrame();
frame.setBounds(100, 100, 455, 165); // set position and dimension
frame.setResizable(false); // lock window size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // fully terminate application when user clicks close button
frame.setTitle("UDP Calculator"); // set window title
frame.getContentPane().setLayout(null); // set layout to correctly draw components
// First number label
JLabel firstNumberLabel = new JLabel("First Number"); // create label component
firstNumberLabel.setBounds(20, 20, 200, 20); // set position relative to top left corner of window and set dimensions
frame.getContentPane().add(firstNumberLabel); // add component to layout
// Second number label
JLabel secondNumberLabel = new JLabel("Second Number");
secondNumberLabel.setBounds(20, 45, 200, 20);
frame.getContentPane().add(secondNumberLabel);
// Result label
JLabel resultLabel = new JLabel("");
resultLabel.setBounds(20, 70, 400, 20);
frame.getContentPane().add(resultLabel);
// First number textField
JTextField firstNumberTextField = new JTextField("");
firstNumberTextField.setBounds(152, 20, 150, 20);
frame.getContentPane().add(firstNumberTextField);
// Second number textField
JTextField secondNumberTextField = new JTextField("");
secondNumberTextField.setBounds(152, 45, 150, 20);
frame.getContentPane().add(secondNumberTextField);
// Add button
JButton addButton = new JButton("+");
addButton.setBounds(20, 100, 65, 23);
frame.getContentPane().add(addButton);
addButton.addActionListener(e -> resultLabel.setText(sendMessage(firstNumberTextField.getText() + "," + secondNumberTextField.getText() + "," + 0))); // do something when button is clicked
// Subtract button
JButton subtractButton = new JButton("-");
subtractButton.setBounds(90, 100, 65, 23);
frame.getContentPane().add(subtractButton);
subtractButton.addActionListener(e -> resultLabel.setText(sendMessage(firstNumberTextField.getText() + "," + secondNumberTextField.getText() + "," + 1)));
// Multiply button
JButton multiplyButton = new JButton("x");
multiplyButton.setBounds(160, 100, 65, 23);
frame.getContentPane().add(multiplyButton);
multiplyButton.addActionListener(e -> resultLabel.setText(sendMessage(firstNumberTextField.getText() + "," + secondNumberTextField.getText() + "," + 2)));
// Divide button
JButton divideButton = new JButton("÷");
divideButton.setBounds(230, 100, 65, 23);
frame.getContentPane().add(divideButton);
divideButton.addActionListener(e -> resultLabel.setText(sendMessage(firstNumberTextField.getText() + "," + secondNumberTextField.getText() + "," + 3)));
// Maximum button
JButton maxButton = new JButton("Max");
maxButton.setBounds(300, 100, 65, 23);
frame.getContentPane().add(maxButton);
maxButton.addActionListener(e -> resultLabel.setText(sendMessage(firstNumberTextField.getText() + "," + secondNumberTextField.getText() + "," + 4)));
// Minimum button
JButton minButton = new JButton("Min");
minButton.setBounds(370, 100, 65, 23);
frame.getContentPane().add(minButton);
minButton.addActionListener(e -> resultLabel.setText(sendMessage(firstNumberTextField.getText() + "," + secondNumberTextField.getText() + "," + 5)));
// Set window visibility
frame.setVisible(true);
}
private static String sendMessage(String msg) {
try {
String[] messageComponents = msg.split(","); // split message into core components
Double.parseDouble(messageComponents[0]); // test if input data is valid, error will redirect to catch block
Double.parseDouble(messageComponents[1]); // test if input data is valid, error will redirect to catch block
Double.parseDouble(messageComponents[2]); // test if input data is valid, error will redirect to catch block
DatagramSocket clientSocket = new DatagramSocket(); // create UDP socket
InetAddress IPAddress = InetAddress.getByName("localhost"); // create an IP address
int port = 9876; // create an port number
// Send data to server
byte[] outgoingData = new byte[1024]; // create buffer with 1024 bytes of size
outgoingData = msg.getBytes(); // fill buffer with data
DatagramPacket outgoingPacket = new DatagramPacket(outgoingData, outgoingData.length, IPAddress, port); // create packet for outgoing data
clientSocket.send(outgoingPacket); // send packet across network using socket
// Receive result from server
byte[] incomingData = new byte[1024]; // create buffer with 1024 bytes of size
DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length); // create packet for incoming data
clientSocket.receive(incomingPacket); // receive packet from network using socket
String packetContent = new String(incomingPacket.getData()); // store packet content
System.out.println("Message from Server: " + packetContent); // display packet content
return packetContent.trim(); // return packet content with leading and trailing white spaces removed
} catch (NumberFormatException ex) {
return "ERROR: Invalid Input"; // return error
} catch (Exception ignored) {
return "ERROR: Unknown"; // return error
}
}
}
| 51.152542 | 196 | 0.665176 |
4d63e056048519f7fa8a6fad66c5a995381caa33 | 5,645 | package com.github.softbasic.micro.service;
import com.github.softbasic.micro.model.SchedulerModel;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import java.util.TimeZone;
@Service
@ConditionalOnProperty(prefix = "spring.task.scheduling", name = "enable", havingValue = "true")
public class SchedulerService {
// 任务调度
@Autowired
private Scheduler scheduler;
private final static String JOB_DEFAULT_GROUP = "JOB_DEFAULT_GROUP";
private final static String TRIGGER_DEFAULT_GROUP = "TRIGGER_DEFAULT_GROUP";
private final static String TRIGGER = "Trigger";
/**
* 启动一个定时任务
*
* @param schedulerModel
* @throws Exception
*/
public void startJob(SchedulerModel schedulerModel) throws Exception {
Class<Job> jobClass = (Class<Job>) Class.forName(schedulerModel.getJobClassName());
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("schedulerModel", schedulerModel);
JobDetail jobDetail = JobBuilder.newJob(jobClass)
.withIdentity(schedulerModel.getJobName(), JOB_DEFAULT_GROUP)
.setJobData(jobDataMap)
.build();
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withIdentity(schedulerModel.getJobName() + TRIGGER, TRIGGER_DEFAULT_GROUP)
.withSchedule(CronScheduleBuilder.cronSchedule(schedulerModel.getCron()))
.build();
scheduler.scheduleJob(jobDetail, cronTrigger);
}
/**
* 启动一个定时任务
*
* @param schedulerModel
* @throws Exception
*/
public void startJob(SchedulerModel schedulerModel, TimeZone timeZone) throws Exception {
Class<Job> jobClass = (Class<Job>) Class.forName(schedulerModel.getJobClassName());
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("schedulerModel", schedulerModel);
JobDetail jobDetail = JobBuilder.newJob(jobClass)
.withIdentity(schedulerModel.getJobName(), JOB_DEFAULT_GROUP)
.setJobData(jobDataMap)
.build();
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withIdentity(schedulerModel.getJobName() + TRIGGER, TRIGGER_DEFAULT_GROUP)
.withSchedule(CronScheduleBuilder.cronSchedule(schedulerModel.getCron()).inTimeZone(timeZone))
.build();
scheduler.scheduleJob(jobDetail, cronTrigger);
}
/**
* 获取Job信息
*
* @param schedulerModel
* @return
* @throws Exception
*/
public String getJobInfo(SchedulerModel schedulerModel) throws Exception {
TriggerKey triggerKey = new TriggerKey(schedulerModel.getJobName() + TRIGGER, TRIGGER_DEFAULT_GROUP);
CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
scheduler.getTriggerState(triggerKey).name());
}
/**
* 修改某个任务的执行时间
*
* @param schedulerModel
* @return
* @throws Exception
*/
public boolean modifyJob(SchedulerModel schedulerModel) throws Exception {
TriggerKey triggerKey = new TriggerKey(schedulerModel.getJobName() + TRIGGER, TRIGGER_DEFAULT_GROUP);
CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
String oldTime = cronTrigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(schedulerModel.getCron())) {
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(schedulerModel.getCron());
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(schedulerModel.getJobName() + TRIGGER, TRIGGER_DEFAULT_GROUP)
.withSchedule(cronScheduleBuilder)
.build();
return scheduler.rescheduleJob(triggerKey, trigger) != null;
}
return false;
}
/**
* 暂停某个任务
*
* @param schedulerModel
* @throws Exception
*/
public void pauseJob(SchedulerModel schedulerModel) throws Exception {
JobKey jobKey = new JobKey(schedulerModel.getJobName(), JOB_DEFAULT_GROUP);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return;
}
scheduler.pauseJob(jobKey);
}
/**
* 暂停所有任务
*
* @throws Exception
*/
public void pauseAllJob() throws Exception {
scheduler.pauseAll();
}
/**
* 恢复某个任务
*
* @param schedulerModel
* @throws Exception
*/
public void resumeJob(SchedulerModel schedulerModel) throws Exception {
JobKey jobKey = new JobKey(schedulerModel.getJobName(), JOB_DEFAULT_GROUP);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null)
return;
scheduler.resumeJob(jobKey);
}
/**
* 恢复所有任务
*
* @throws Exception
*/
public void resumeAllJob() throws Exception {
scheduler.resumeAll();
}
/**
* 删除某个任务
*
* @param schedulerModel
* @throws Exception
*/
public void deleteJob(SchedulerModel schedulerModel) throws Exception {
JobKey jobKey = new JobKey(schedulerModel.getJobName(), JOB_DEFAULT_GROUP);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return;
}
scheduler.deleteJob(jobKey);
}
}
| 34.212121 | 113 | 0.654916 |
5f77cecc2006bbdfe2c5b4f3c3adedcdd05a530d | 3,961 | /**
*
*/
package com.sina.util.dnscache.model;
import com.sina.util.dnscache.Tools;
import org.json.JSONException;
import org.json.JSONStringer;
/**
*
* 项目名称: DNSCache <br>
* 类名称: IpModel <br>
* 类描述: ip数据模型 - 对应ip表 <br>
* 创建人: fenglei <br>
* 创建时间: 2015-3-26 下午5:23:06 <br>
*
* 修改人: <br>
* 修改时间: <br>
* 修改备注: <br>
*
* @version V1.0
*/
public class IpModel {
public IpModel(){}
/**
* 自增id <br>
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_ID }字段 <br>
*/
public long id = -1 ;
/**
* domain id 关联id
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_DOMAIN_ID }字段 <br>
*/
public long d_id = -1 ;
/**
* 服务器ip地址
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_PORT }字段 <br>
*/
public String ip = "" ;
/**
* ip服务器对应的端口
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_PORT }字段 <br>
*/
public int port = -1 ;
/**
* ip服务器对应的sp运营商
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_SP }字段 <br>
*/
public String sp = "" ;
/**
* ip过期时间
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_TTL }字段 <br>
*/
public String ttl = "0" ;
/**
* ip服务器优先级-排序算法策略使用
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_PRIORITY }字段 <br>
*/
public String priority = "0" ;
/**
* 访问ip服务器的往返时延
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_PRIORITY }}字段 <br>
*/
public String rtt = "0" ;
/**
* ip服务器链接产生的成功数
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_SUCCESS_NUM }字段 <br>
*/
public String success_num = "0" ;
/**
* ip服务器链接产生的错误数
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_ERR_NUM }字段 <br>
*/
public String err_num = "0" ;
/**
* ip服务器最后成功链接时间
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_FINALLY_SUCCESS_TIME }字段 <br>
*/
public String finally_success_time = "0" ;
/**
* ip服务器最后失败链接时间
*
* 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants#IP_COLUMN_FINALLY_FAIL_TIME }字段 <br>
*/
public String finally_fail_time = "0" ;
/**
* 评估体系 评分分值
*/
public float grade = 0 ;
public String toString(){
String str = "*\n" ;
str += "-- 服务器id = " + id + "\n" ;
str += "-- 服务器ip = " + ip + "\n" ;
str += "-- 域名ID索引 = " + d_id + "\n" ;
str += "-- 服务器端口 = " + port + "\n" ;
str += "-- 运营商 = " + sp + "\n" ;
str += "-- 过期时间 = " + ttl + "\n" ;
str += "-- 优先级 = " + priority + "\n" ;
str += "-- 访问ip服务器的往返时延 = " + rtt + "\n" ;
str += "-- 历史成功次数 = " + success_num + "\n" ;
str += "-- 历史错误次数 = " + err_num + "\n" ;
str += "-- 最后一次访问成功时间 = " + Tools.getStringDateShort(finally_success_time) + "\n" ;
str += "-- 最后一次访问失败时间 = " + Tools.getStringDateShort(finally_fail_time) + "\n" ;
str += "-- 系统对服务器的评分 = " + grade + "\n" ;
str += "\n" ;
return str ;
}
public String toJson(){
JSONStringer jsonStringer = new JSONStringer();
try {
jsonStringer.object()//
.key("id").value(id)//
.key("d_id").value(d_id)//
.key("ip").value(ip)//
.key("port").value(port)//
.key("ttl").value(ttl)//
.key("priority").value(priority)//
.key("success_num").value(success_num)//
.key("err_num").value(err_num)//
.key("finally_success_time").value(finally_success_time)//
.key("finally_fail_time").value(finally_fail_time)//
.endObject();
} catch (JSONException e) {
e.printStackTrace();
return "{}";
}
return jsonStringer.toString();
}
}
| 23.861446 | 98 | 0.540015 |
6a59d30fbfc2da8fb9ecbb0b4564a23349aa7bc0 | 3,771 | package com.sprylab.xar.utils;
/**
* This is a minimal, stripped down version of {@code StringUtils} from <a href="https://commons.apache.org/proper/commons-lang/">Apache Commons Lang</a>.
*/
public final class StringUtils {
/**
* The empty String {@code ""}.
*
* @since 2.0
*/
public static final String EMPTY = "";
/**
* Represents a failed index search.
*
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
private StringUtils() {
}
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
/**
* <p>Gets the substring after the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* An empty or {@code null} separator will return the empty string if
* the input string is not {@code null}.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfterLast(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (isEmpty(separator)) {
return EMPTY;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
}
| 33.972973 | 154 | 0.582074 |
ddae0dc3ae25891e1e5c7bcceb4251b9a33f830c | 3,206 | package io.github.cottonmc.spinningmachinery.compat.rei;
import com.google.common.collect.ImmutableList;
import io.github.cottonmc.spinningmachinery.block.SpinningBlocks;
import io.github.cottonmc.spinningmachinery.block.entity.GrinderBlockEntity;
import io.github.cottonmc.spinningmachinery.compat.rei.widget.InfoWidget;
import io.github.cottonmc.spinningmachinery.compat.rei.widget.ProgressArrowWidget;
import io.github.cottonmc.spinningmachinery.compat.rei.widget.SMSlotWidget;
import io.github.cottonmc.spinningmachinery.recipe.GrindingRecipe;
import me.shedaniel.rei.api.RecipeCategory;
import me.shedaniel.rei.api.Renderable;
import me.shedaniel.rei.api.Renderer;
import me.shedaniel.rei.gui.widget.LabelWidget;
import me.shedaniel.rei.gui.widget.RecipeBaseWidget;
import me.shedaniel.rei.gui.widget.Widget;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.util.Identifier;
import java.awt.Rectangle;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
final class GrindingCategory implements RecipeCategory<GrindingDisplay> {
@Override
public Identifier getIdentifier() {
return SpinningREIPlugin.GRINDING;
}
@Override
public String getCategoryName() {
return I18n.translate("gui.spinning-machinery.grinding.category");
}
@Override
public Renderer getIcon() {
return Renderable.fromItemStack(new ItemStack(SpinningBlocks.GRINDER));
}
@Override
public List<Widget> setupDisplay(Supplier<GrindingDisplay> recipeDisplaySupplier, Rectangle bounds) {
GrindingDisplay display = recipeDisplaySupplier.get();
int x = (int) bounds.getX();
int y = (int) bounds.getCenterY() - 9;
List<ItemStack> bonusStacks = display.getBonusStacks();
int bonusChance = display.getRecipe()
.map(recipe -> (int) (display.getBonusChance() * 100.0))
.orElse(0);
ImmutableList.Builder<Widget> builder = ImmutableList.<Widget>builder()
.add(new RecipeBaseWidget(bounds))
.add(new ProgressArrowWidget(x + 2 * 18 + 6, y, 3 * 18 - 15, 18, GrinderBlockEntity.MAX_PROGRESS))
.add(new SMSlotWidget(x + 18, y, display.getInput().get(0), true, true))
.add(SMSlotWidget.createBig(x + 5 * 18, y, Collections.singletonList(display.getOutput().get(0)), true, true))
.add(new SMSlotWidget(x + 6 * 18 + 10, y, bonusStacks, true, true))
.add(new LabelWidget(
x + 7 * 18, y + 18,
bonusChance != 0
? I18n.translate("gui.spinning-machinery.grinding.bonus_chance_format", bonusChance)
: ""
));
if (display.getSourceMod() != null) {
builder.add(new InfoWidget(
x + 4, bounds.y + 4, 12, 12,
new TranslatableComponent("gui.spinning-machinery.grinding.from_source", display.getSourceMod())
));
}
return builder.build();
}
}
| 41.636364 | 126 | 0.674984 |
14c4ca77ad4fc07e44dc5fec865585d45cf623d3 | 1,521 | //Deobfuscated with https://github.com/PetoPetko/Minecraft-Deobfuscator3000 using mappings "mcp_snapshot-20171003-1.12"!
/*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.init.Items
* net.minecraft.item.ItemStack
* net.minecraft.item.crafting.Ingredient
* net.minecraft.util.ResourceLocation
* net.minecraftforge.fml.common.event.FMLInitializationEvent
* net.minecraftforge.fml.common.registry.GameRegistry
*/
package mod.mcreator;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class mcreator_basaltSwordRecipeC extends theworlditems2.ModElement {
@Override
public void load(FMLInitializationEvent event) {
ItemStack recStack = new ItemStack(mcreator_basaltSword.block, 1);
Object[] recipe = new Object[]{" 1 ", " 4 ", " 7 ", Character.valueOf('1'), Ingredient.fromStacks(new ItemStack[]{new ItemStack(mcreator_basalt.block, 1)}), Character.valueOf('4'), Ingredient.fromStacks(new ItemStack[]{new ItemStack(mcreator_basalt.block, 1)}), Character.valueOf('7'), Ingredient.fromStacks(new ItemStack[]{new ItemStack(Items.STICK, 1)})};
GameRegistry.addShapedRecipe(new ResourceLocation("theworlditems2:basaltswordrecipec"), new ResourceLocation("custom"), recStack, recipe);
}
}
| 47.53125 | 365 | 0.77449 |
a25d6d6e784756f8d0f06436032d930c6993c4b8 | 7,846 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.inputmethod.keyboard;
import android.content.res.Resources;
import android.text.InputType;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodSubtype;
import com.android.inputmethod.keyboard.internal.KeyboardIconsSet;
import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.utils.RunInLocale;
import com.android.inputmethod.latin.utils.SubtypeLocaleUtils;
import java.util.Locale;
abstract class KeyboardLayoutSetActionLabelBase extends KeyboardLayoutSetTestsBase {
public void testActionUnspecified() {
for (final InputMethodSubtype subtype : getAllSubtypesList()) {
final String tag = "unspecifiled "
+ SubtypeLocaleUtils.getSubtypeNameForLogging(subtype);
doTestActionKeyIcon(tag, subtype, EditorInfo.IME_ACTION_UNSPECIFIED,
KeyboardIconsSet.NAME_ENTER_KEY);
}
}
public void testActionNone() {
for (final InputMethodSubtype subtype : getAllSubtypesList()) {
final String tag = "none " + SubtypeLocaleUtils.getSubtypeNameForLogging(subtype);
doTestActionKeyIcon(tag, subtype, EditorInfo.IME_ACTION_NONE,
KeyboardIconsSet.NAME_ENTER_KEY);
}
}
public void testActionSearch() {
for (final InputMethodSubtype subtype : getAllSubtypesList()) {
final String tag = "search " + SubtypeLocaleUtils.getSubtypeNameForLogging(subtype);
doTestActionKeyIcon(tag, subtype, EditorInfo.IME_ACTION_SEARCH,
KeyboardIconsSet.NAME_SEARCH_KEY);
}
}
public abstract void testActionGo();
public abstract void testActionSend();
public abstract void testActionNext();
public abstract void testActionDone();
public abstract void testActionPrevious();
public void testActionCustom() {
for (final InputMethodSubtype subtype : getAllSubtypesList()) {
final String tag = "custom " + SubtypeLocaleUtils.getSubtypeNameForLogging(subtype);
final CharSequence customLabel = "customLabel";
final EditorInfo editorInfo = new EditorInfo();
editorInfo.imeOptions = EditorInfo.IME_ACTION_UNSPECIFIED;
editorInfo.actionLabel = customLabel;
doTestActionKeyLabel(tag, subtype, editorInfo, customLabel);
}
}
private static void doTestActionKey(final String tag, final KeyboardLayoutSet layoutSet,
final int elementId, final CharSequence label, final int iconId) {
final Keyboard keyboard = layoutSet.getKeyboard(elementId);
final Key enterKey = keyboard.getKey(Constants.CODE_ENTER);
assertNotNull(tag + " enter key on " + keyboard.mId, enterKey);
assertEquals(tag + " enter label " + enterKey, label, enterKey.getLabel());
assertEquals(tag + " enter icon " + enterKey, iconId, enterKey.getIconId());
}
protected void doTestActionKeyLabelResId(final String tag, final InputMethodSubtype subtype,
final int actionId, final int labelResId) {
final Locale labelLocale = subtype.getLocale().equals(SubtypeLocaleUtils.NO_LANGUAGE)
? null : SubtypeLocaleUtils.getSubtypeLocale(subtype);
doTestActionKeyLabelResIdInLocale(tag, subtype, actionId, labelLocale, labelResId);
}
protected void doTestActionKeyLabelResIdInLocale(final String tag,
final InputMethodSubtype subtype, final int actionId, final Locale labelLocale,
final int labelResId) {
final EditorInfo editorInfo = new EditorInfo();
editorInfo.imeOptions = actionId;
final RunInLocale<String> job = new RunInLocale<String>() {
@Override
protected String job(final Resources res) {
return res.getString(labelResId);
}
};
final String label = job.runInLocale(getContext().getResources(), labelLocale);
doTestActionKeyLabel(tag, subtype, editorInfo, label);
}
protected void doTestActionKeyLabel(final String tag, final InputMethodSubtype subtype,
final EditorInfo editorInfo, final CharSequence label) {
// Test text layouts.
editorInfo.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL;
final KeyboardLayoutSet layoutSet = createKeyboardLayoutSet(subtype, editorInfo);
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_ALPHABET,
label, KeyboardIconsSet.ICON_UNDEFINED);
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_SYMBOLS,
label, KeyboardIconsSet.ICON_UNDEFINED);
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_SYMBOLS_SHIFTED,
label, KeyboardIconsSet.ICON_UNDEFINED);
// Test phone number layouts.
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_PHONE,
label, KeyboardIconsSet.ICON_UNDEFINED);
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_PHONE_SYMBOLS,
label, KeyboardIconsSet.ICON_UNDEFINED);
// Test normal number layout.
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_NUMBER,
label, KeyboardIconsSet.ICON_UNDEFINED);
// Test number password layouts.
editorInfo.inputType =
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD;
final KeyboardLayoutSet passwordSet = createKeyboardLayoutSet(subtype, editorInfo);
doTestActionKey(tag, passwordSet, KeyboardId.ELEMENT_NUMBER,
label, KeyboardIconsSet.ICON_UNDEFINED);
}
protected void doTestActionKeyIcon(final String tag, final InputMethodSubtype subtype,
final int actionId, final String iconName) {
final int iconId = KeyboardIconsSet.getIconId(iconName);
final EditorInfo editorInfo = new EditorInfo();
editorInfo.imeOptions = actionId;
// Test text layouts.
editorInfo.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL;
final KeyboardLayoutSet layoutSet = createKeyboardLayoutSet(subtype, editorInfo);
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_ALPHABET, null /* label */, iconId);
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_SYMBOLS, null /* label */, iconId);
doTestActionKey(
tag, layoutSet, KeyboardId.ELEMENT_SYMBOLS_SHIFTED, null /* label */, iconId);
// Test phone number layouts.
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_PHONE, null /* label */, iconId);
doTestActionKey(
tag, layoutSet, KeyboardId.ELEMENT_PHONE_SYMBOLS, null /* label */, iconId);
// Test normal number layout.
doTestActionKey(tag, layoutSet, KeyboardId.ELEMENT_NUMBER, null /* label */, iconId);
// Test number password layout.
editorInfo.inputType =
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD;
final KeyboardLayoutSet passwordSet = createKeyboardLayoutSet(subtype, editorInfo);
doTestActionKey(tag, passwordSet, KeyboardId.ELEMENT_NUMBER, null /* label */, iconId);
}
}
| 49.974522 | 96 | 0.703416 |
4ea0c3f7b303eada9cd2066c4b417c9b0f38d26b | 2,989 | package com.smartgwt.mobile.client.internal;
import java.util.AbstractList;
import java.util.List;
import com.smartgwt.mobile.SGWTInternal;
import com.smartgwt.mobile.client.data.Record;
import com.smartgwt.mobile.client.util.IsCallback;
@SGWTInternal
public final class Array {
public static final Record LOADING = new Record();
static {
LOADING.put("__loading__", "LOADING...");
}
public static interface ArrayElementCallback extends IsCallback {
public void execute(int index, Object element);
}
public static boolean isArray(Object obj) {
// http://ideone.com/KiJXIA
return (obj != null && obj.getClass().isArray());
}
/**
* An implementation of {@link java.lang.reflect.Array#getLength(Object)} for GWT.
*/
public static int arrayLength(Object array) {
assert isArray(array);
if (array instanceof Object[]) return ((Object[])array).length;
else if (array instanceof char[]) return ((char[])array).length;
else if (array instanceof byte[]) return ((byte[])array).length;
else if (array instanceof short[]) return ((short[])array).length;
else if (array instanceof int[]) return ((int[])array).length;
else if (array instanceof long[]) return ((long[])array).length;
else if (array instanceof float[]) return ((float[])array).length;
else if (array instanceof double[]) return ((double[])array).length;
else return ((boolean[])array).length;
}
/**
* An implementation of {@link java.lang.reflect.Array#get(Object, int)} for GWT.
*/
public static Object arrayGet(Object array, int i) {
assert isArray(array);
if (array instanceof Object[]) return ((Object[])array)[i];
else if (array instanceof char[]) return ((char[])array)[i];
else if (array instanceof byte[]) return ((byte[])array)[i];
else if (array instanceof short[]) return ((short[])array)[i];
else if (array instanceof int[]) return ((int[])array)[i];
else if (array instanceof long[]) return ((long[])array)[i];
else if (array instanceof float[]) return ((float[])array)[i];
else if (array instanceof double[]) return ((double[])array)[i];
else return ((boolean[])array)[i];
}
public static void forEach(Object array, ArrayElementCallback callback) {
assert isArray(array);
final int len = arrayLength(array);
for (int i = 0; i < len; ++i) {
callback.execute(i, arrayGet(array, i));
}
}
public static List<?> asList(final Object array) {
assert isArray(array);
return new AbstractList<Object>() {
@Override
public Object get(int index) {
return arrayGet(array, index);
}
@Override
public int size() {
return arrayLength(array);
}
};
}
private Array() {}
}
| 35.164706 | 86 | 0.610572 |
c61c6f0a2fbadfa8ac69fc45ded70dfa6b7e7d70 | 1,272 | package dev.sheldan.abstracto.moderation.model.template.job;
import dev.sheldan.abstracto.core.models.ServerUser;
import dev.sheldan.abstracto.moderation.model.database.Warning;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import net.dv8tion.jda.api.entities.Member;
/**
* A single warning containing the full user instead of only the warning object when logging the decayed warnings
* The template is: "warnDecay_log_warn_entry_en_US.ftl"
*/
@Getter
@Setter
@Builder
public class WarnDecayWarning {
/**
* The persisted {@link Warning} object from the database containing the information about the warning
*/
private Warning warning;
/**
* The member which was warned, is null if the user left the server
*/
private Member warnedMember;
/**
* The user which casted the warn, is null if the user left the server
*/
private Member warningMember;
/**
* The {@link ServerUser serverUser} which was warned, can be used in case the {@link Member warningMember} is null
*/
private ServerUser warningUser;
/**
* The {@link ServerUser serverUser} who cast the warn, can be used in case the {@link Member warnedMember} is null
*/
private ServerUser warnedUser;
}
| 31.02439 | 119 | 0.720912 |
0bfce96346943d15fc5f799c66ed3bfc3e64a058 | 1,459 | class Solution {
public String longestPalindrome(String s) {
final String t = join('@' + s + '$', '#');
final int n = t.length();
// t[i - maxExtends[i]..i) ==
// t[i + 1..i + maxExtends[i]]
int[] maxExtends = new int[n];
int center = 0;
for (int i = 1; i < n - 1; ++i) {
final int rightBoundary = center + maxExtends[center];
final int mirrorIndex = center - (i - center);
maxExtends[i] =
rightBoundary > i && Math.min(rightBoundary - i, maxExtends[mirrorIndex]) > 0 ? 1 : 0;
// Attempt to expand palindrome centered at i
while (t.charAt(i + 1 + maxExtends[i]) == t.charAt(i - 1 - maxExtends[i]))
++maxExtends[i];
// If palindrome centered at i expand past rightBoundary,
// adjust center based on expanded palindrome.
if (i + maxExtends[i] > rightBoundary)
center = i;
}
// Find the maxExtend and bestCenter
int maxExtend = 0;
int bestCenter = -1;
for (int i = 0; i < n; ++i)
if (maxExtends[i] > maxExtend) {
maxExtend = maxExtends[i];
bestCenter = i;
}
return s.substring((bestCenter - maxExtend) / 2, (bestCenter + maxExtend) / 2);
}
private String join(final String s, char c) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
sb.append(s.charAt(i));
if (i != s.length() - 1)
sb.append(c);
}
return sb.toString();
}
}
| 29.77551 | 96 | 0.559973 |
2ff906682f7818e1c737503496fa2cbbb20168fe | 6,468 | /*
* Copyright 2018 The Exonum Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.exonum.binding.proxy;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.singleton;
import com.google.common.annotations.VisibleForTesting;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A proxy of a native object.
*
* <p>A native proxy references the corresponding native object by its
* implementation-specific handle. If handle is zero, the proxy is considered invalid
* and will not permit referencing any native object. It is perfectly possible to get
* an invalid proxy (e.g., if a native method fails to allocate a native object).
*
* <p>You must close a native proxy when it is no longer needed
* to release any resources it holds (e.g., destroy a native object).
* You may use a <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">try-with-resources</a>
* statement to do that in orderly fashion.
* When a proxy is closed, it becomes invalid.
*/
public abstract class AbstractCloseableNativeProxy extends AbstractNativeProxy
implements CloseableNativeProxy {
/**
* Whether this proxy shall dispose any resources when closed
* (e.g., if it owns the corresponding native object and is responsible to clean it up).
*/
private final boolean dispose;
/**
* Proxies that this one references, including transitive references.
* Each of these must be valid at each native call.
*/
private final Set<AbstractCloseableNativeProxy> referenced;
/**
* Creates a native proxy.
*
* @param nativeHandle an implementation-specific reference to a native object
* @param dispose true if this proxy is responsible to release any resources
* by calling {@link #disposeInternal}; false — otherwise
*/
protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose) {
this(nativeHandle, dispose, Collections.emptySet());
}
/**
* Creates a native proxy.
*
* @param nativeHandle an implementation-specific reference to a native object
* @param dispose true if this proxy is responsible to release any resources
* by calling {@link #disposeInternal}; false — otherwise
* @param referenced a referenced native object, that must be alive
* during the operation of this native proxy
*/
protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose,
AbstractCloseableNativeProxy referenced) {
this(nativeHandle, dispose, singleton(checkNotNull(referenced)));
}
/**
* Creates a native proxy.
*
* @param nativeHandle an implementation-specific reference to a native object
* @param dispose true if this proxy is responsible to release any resources
* by calling {@link #disposeInternal}; false — otherwise
* @param referenced a collection of referenced native objects, that must be alive
* during the operation of this native proxy
*/
protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose,
Collection<AbstractCloseableNativeProxy> referenced) {
super(new NativeHandle(nativeHandle));
this.dispose = dispose;
this.referenced = getTransitivelyReferenced(referenced);
}
private Set<AbstractCloseableNativeProxy> getTransitivelyReferenced(
Collection<AbstractCloseableNativeProxy> referenced) {
// You don't have to perform a recursive flat map because each of the proxies
// this proxy references has all its transitive dependencies.
return referenced.stream()
.flatMap((proxy) -> Stream.concat(Stream.of(proxy), proxy.referenced.stream()))
.collect(Collectors.toSet());
}
/**
* Returns a native implementation-specific handle if it may be safely used
* to access the native object.
*
* <p>The returned value shall only be passed as an argument to native methods.
*
* <p>Warning: do not cache the return value, as you won't be able to catch use-after-free.
*
* @throws IllegalStateException if this native proxy or any directly or transitively referenced
* proxies are invalid (closed or nullptr).
*/
@Override
protected final long getNativeHandle() {
checkAllRefsValid();
return super.getNativeHandle();
}
@Override
public final void close() {
if (isValidHandle()) {
try {
checkAllRefsValid();
if (dispose) {
disposeInternal();
}
} finally {
invalidate();
}
}
}
private void checkAllRefsValid() {
if (!allRefsValid()) {
throw new IllegalStateException(getInvalidProxyErrMessage());
}
}
private boolean allRefsValid() {
return isValidHandle() && referenced.stream()
.allMatch(AbstractCloseableNativeProxy::isValidHandle);
}
private String getInvalidProxyErrMessage() {
if (!isValidHandle()) {
return String.format("This proxy (%s) is not valid", this);
}
Set<AbstractCloseableNativeProxy> invalidReferenced = getInvalidReferences();
return String.format("This proxy (%s) references some invalid proxies: %s",
this, invalidReferenced);
}
@VisibleForTesting
Set<AbstractCloseableNativeProxy> getInvalidReferences() {
return referenced.stream()
.filter(p -> !p.isValidHandle())
.collect(Collectors.toSet());
}
/**
* Releases any resources owned by this proxy (e.g., the corresponding native object).
*
* <p>This method is only called once from {@link #close()} for a <strong>valid</strong>
* proxy and shall not be called directly.
*/
protected abstract void disposeInternal();
private void invalidate() {
nativeHandle.close();
}
}
| 36.134078 | 132 | 0.703309 |
b0d74c12f294bf46964dffab16fe3c54296f274b | 5,202 | package com.mesosphere.sdk.specification;
import com.mesosphere.sdk.scheduler.SchedulerConfig;
import com.mesosphere.sdk.scheduler.plan.Phase;
import com.mesosphere.sdk.scheduler.plan.Plan;
import com.mesosphere.sdk.scheduler.plan.PodInstanceRequirement;
import com.mesosphere.sdk.specification.yaml.RawPlan;
import com.mesosphere.sdk.specification.yaml.RawServiceSpec;
import com.mesosphere.sdk.state.ConfigStore;
import com.mesosphere.sdk.state.StateStore;
import com.mesosphere.sdk.storage.MemPersister;
import com.mesosphere.sdk.storage.Persister;
import com.mesosphere.sdk.testutils.SchedulerConfigTestUtils;
import org.junit.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Tests for {@link DefaultPlanGenerator}.
*/
public class DefaultPlanGeneratorTest {
private static final SchedulerConfig SCHEDULER_CONFIG = SchedulerConfigTestUtils.getTestSchedulerConfig();
private StateStore stateStore;
private ConfigStore<ServiceSpec> configStore;
@Test
public void testCustomPhases() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("custom-phases.yml").getFile());
RawServiceSpec rawServiceSpec = RawServiceSpec.newBuilder(file).build();
DefaultServiceSpec serviceSpec =
DefaultServiceSpec.newGenerator(rawServiceSpec, SCHEDULER_CONFIG, file.getParentFile()).build();
Persister persister = new MemPersister();
stateStore = new StateStore(persister);
configStore = new ConfigStore<>(DefaultServiceSpec.getConfigurationFactory(serviceSpec), persister);
Assert.assertNotNull(serviceSpec);
DefaultPlanGenerator generator = new DefaultPlanGenerator(configStore, stateStore);
for (Map.Entry<String, RawPlan> entry : rawServiceSpec.getPlans().entrySet()) {
Plan plan = generator.generate(entry.getValue(), entry.getKey(), serviceSpec.getPods());
Assert.assertNotNull(plan);
Assert.assertEquals(6, plan.getChildren().size());
Phase serverPhase = plan.getChildren().get(0);
Phase oncePhase = plan.getChildren().get(1);
Phase interleavePhase = plan.getChildren().get(2);
Phase fullCustomPhase = plan.getChildren().get(3);
Phase partialCustomPhase = plan.getChildren().get(4);
Phase omitStepPhase = plan.getChildren().get(5);
validatePhase(
serverPhase,
Arrays.asList(
Arrays.asList("server"),
Arrays.asList("server"),
Arrays.asList("server")));
validatePhase(
oncePhase,
Arrays.asList(
Arrays.asList("once"),
Arrays.asList("once"),
Arrays.asList("once")));
validatePhase(
interleavePhase,
Arrays.asList(
Arrays.asList("once"),
Arrays.asList("server"),
Arrays.asList("once"),
Arrays.asList("server"),
Arrays.asList("once"),
Arrays.asList("server")));
validatePhase(
fullCustomPhase,
Arrays.asList(
Arrays.asList("once"),
Arrays.asList("server"),
Arrays.asList("server"),
Arrays.asList("once"),
Arrays.asList("server")));
validatePhase(
partialCustomPhase,
Arrays.asList(
Arrays.asList("server"),
Arrays.asList("once"),
Arrays.asList("once"),
Arrays.asList("server"),
Arrays.asList("server"),
Arrays.asList("once")));
validatePhase(
omitStepPhase,
Arrays.asList(
Arrays.asList("once"),
Arrays.asList("server")));
Assert.assertEquals("hello-1:[once]", omitStepPhase.getChildren().get(0).getName());
Assert.assertEquals("hello-1:[server]", omitStepPhase.getChildren().get(1).getName());
}
}
private void validatePhase(Phase phase, List<List<String>> stepTasks) {
Assert.assertEquals(phase.getChildren().size(), stepTasks.size());
for (int i = 0; i < stepTasks.size(); i++) {
PodInstanceRequirement podInstanceRequirement = phase.getChildren().get(i).start().get();
List<String> tasksToLaunch = new ArrayList<>(podInstanceRequirement.getTasksToLaunch());
for (int j = 0; j < tasksToLaunch.size(); j++) {
Assert.assertEquals(tasksToLaunch.get(j), stepTasks.get(i).get(j));
}
}
}
}
| 42.292683 | 112 | 0.574587 |
f3665ac0f2f4501e0a973be719b62da8af80d2e0 | 4,695 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.transport.http.netty.client;
import java.io.IOException;
import org.apache.cxf.Bus;
import org.apache.cxf.buslifecycle.BusLifeCycleListener;
import org.apache.cxf.buslifecycle.BusLifeCycleManager;
import org.apache.cxf.common.util.SystemPropertyAction;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transport.http.HTTPConduitFactory;
import org.apache.cxf.transport.http.HTTPTransportFactory;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
public class NettyHttpConduitFactory implements HTTPConduitFactory {
//CXF specific
public static final String USE_POLICY = "org.apache.cxf.transport.http.netty.usePolicy";
public enum UseAsyncPolicy {
ALWAYS, ASYNC_ONLY, NEVER;
public static UseAsyncPolicy getPolicy(Object st) {
if (st instanceof UseAsyncPolicy) {
return (UseAsyncPolicy)st;
} else if (st instanceof String) {
String s = ((String)st).toUpperCase();
if ("ALWAYS".equals(s)) {
return ALWAYS;
} else if ("NEVER".equals(s)) {
return NEVER;
} else if ("ASYNC_ONLY".equals(s)) {
return ASYNC_ONLY;
} else {
st = Boolean.parseBoolean(s);
}
}
if (st instanceof Boolean) {
return ((Boolean)st).booleanValue() ? ALWAYS : NEVER;
}
return ASYNC_ONLY;
}
};
UseAsyncPolicy policy;
public NettyHttpConduitFactory() {
io.netty.util.Version.identify();
Object st = SystemPropertyAction.getPropertyOrNull(USE_POLICY);
policy = UseAsyncPolicy.getPolicy(st);
}
public UseAsyncPolicy getUseAsyncPolicy() {
return policy;
}
@Override
public HTTPConduit createConduit(HTTPTransportFactory f,
Bus bus,
EndpointInfo localInfo,
EndpointReferenceType target)
throws IOException {
// need to check if the EventLoopGroup is created or not
// if not create a new EventLoopGroup for it
EventLoopGroup eventLoopGroup = bus.getExtension(EventLoopGroup.class);
if (eventLoopGroup == null) {
final EventLoopGroup group = new NioEventLoopGroup();
// register a BusLifeCycleListener for it
bus.setExtension(group, EventLoopGroup.class);
registerBusLifeListener(bus, group);
}
return new NettyHttpConduit(bus, localInfo, target, this);
}
public HTTPConduit createConduit(Bus bus,
EndpointInfo localInfo,
EndpointReferenceType target)
throws IOException {
return createConduit(null, bus, localInfo, target);
}
protected void registerBusLifeListener(Bus bus, final EventLoopGroup group) {
BusLifeCycleManager lifeCycleManager = bus.getExtension(BusLifeCycleManager.class);
if (null != lifeCycleManager) {
lifeCycleManager.registerLifeCycleListener(new BusLifeCycleListener() {
@Override
public void initComplete() {
// do nothing here
}
@Override
public void preShutdown() {
// do nothing here
}
@Override
public void postShutdown() {
// shutdown the EventLoopGroup
group.shutdownGracefully().syncUninterruptibly();
}
});
}
}
}
| 35.839695 | 92 | 0.62279 |
76f57f409b7a0e7fbd83dab80ba7d93a957d98de | 3,927 | /*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate licenses this file
* to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.protocols.ssl;
import org.elasticsearch.test.ESTestCase;
import io.netty.handler.ssl.SslContext;
import org.elasticsearch.common.settings.Settings;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.security.Security;
import static io.crate.protocols.ssl.SslConfigurationTest.getAbsoluteFilePathFromClassPath;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
public class SslContextProviderTest extends ESTestCase {
private static File trustStoreFile;
private static File keyStoreFile;
private static String defaultKeyStoreType = KeyStore.getDefaultType();
@BeforeClass
public static void beforeTests() throws IOException {
trustStoreFile = getAbsoluteFilePathFromClassPath("truststore.jks");
keyStoreFile = getAbsoluteFilePathFromClassPath("keystore.jks");
Security.setProperty("keystore.type", "jks");
}
@AfterClass
public static void resetKeyStoreType() {
Security.setProperty("keystore.type", defaultKeyStoreType);
}
@Test
public void testClassLoadingWithInvalidConfiguration() {
// empty ssl configuration which is invalid
Settings settings = Settings.builder()
.put(SslConfigSettings.SSL_HTTP_ENABLED.getKey(), true)
.put(SslConfigSettings.SSL_PSQL_ENABLED.getKey(), true)
.build();
expectedException.expect(SslConfigurationException.class);
expectedException.expectMessage("Failed to build SSL configuration");
var sslContextProvider = new SslContextProviderImpl(settings);
sslContextProvider.getSslContext();
}
@Test
public void testClassLoadingWithValidConfiguration() {
Settings settings = Settings.builder()
.put(SslConfigSettings.SSL_HTTP_ENABLED.getKey(), true)
.put(SslConfigSettings.SSL_PSQL_ENABLED.getKey(), true)
.put(SslConfigSettings.SSL_TRUSTSTORE_FILEPATH.getKey(), trustStoreFile.getAbsolutePath())
.put(SslConfigSettings.SSL_TRUSTSTORE_PASSWORD.getKey(), "truststorePassword")
.put(SslConfigSettings.SSL_KEYSTORE_FILEPATH.getKey(), keyStoreFile.getAbsolutePath())
.put(SslConfigSettings.SSL_KEYSTORE_PASSWORD.getKey(), "keystorePassword")
.put(SslConfigSettings.SSL_KEYSTORE_KEY_PASSWORD.getKey(), "serverKeyPassword")
.build();
var sslContextProvider = new SslContextProviderImpl(settings);
SslContext sslContext = sslContextProvider.getSslContext();
assertThat(sslContext, instanceOf(SslContext.class));
assertThat(sslContext.isServer(), is(true));
assertThat(sslContext.cipherSuites(), not(empty()));
}
}
| 42.684783 | 102 | 0.743825 |
d220c00e30d04f2df3e6956c13a3c9da261479c0 | 4,017 | package com.vaadin.tests.components.table;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractReindeerTestUI;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.v7.data.Container;
import com.vaadin.v7.data.Item;
import com.vaadin.v7.data.util.IndexedContainer;
import com.vaadin.v7.ui.Table;
public class Footer extends AbstractReindeerTestUI {
@Override
protected void setup(VaadinRequest request) {
HorizontalLayout layout = new HorizontalLayout();
final Table table = new Table();
table.setWidth("400px");
table.setHeight("400px");
table.setContainerDataSource(createContainer());
table.setImmediate(true);
table.setColumnCollapsingAllowed(true);
table.setColumnReorderingAllowed(true);
table.setFooterVisible(true);
table.setColumnFooter("col1", "Footer1");
table.setColumnFooter("col2", "Footer2");
table.setColumnFooter("col3", "Footer3");
table.setColumnAlignment("col2", Table.ALIGN_CENTER);
table.setColumnAlignment("col3", Table.ALIGN_RIGHT);
layout.addComponent(table);
// Add some options to play with
VerticalLayout options = new VerticalLayout();
options.setMargin(false);
final CheckBox visible = new CheckBox("Footers Visible", true);
visible.addValueChangeListener(
event -> table.setFooterVisible(visible.getValue()));
options.addComponent(visible);
final TextField footer1Value = new TextField(null, "Footer1");
Button footer1Btn = new Button("Change", event ->
table.setColumnFooter("col1", footer1Value.getValue() == null
? ""
: footer1Value.getValue()));
HorizontalLayout footer1 = new HorizontalLayout();
footer1.setSpacing(false);
footer1.addComponent(footer1Value);
footer1.addComponent(footer1Btn);
options.addComponent(footer1);
final TextField footer2Value = new TextField(null, "Footer2");
Button footer2Btn = new Button("Change", event ->
table.setColumnFooter("col2", footer2Value.getValue() == null
? ""
: footer2Value.getValue()));
HorizontalLayout footer2 = new HorizontalLayout();
footer2.setSpacing(false);
footer2.addComponent(footer2Value);
footer2.addComponent(footer2Btn);
options.addComponent(footer2);
final TextField footer3Value = new TextField(null, "Footer3");
Button footer3Btn = new Button("Change", event ->
table.setColumnFooter("col3", footer3Value.getValue() == null
? ""
: footer3Value.getValue()));
HorizontalLayout footer3 = new HorizontalLayout();
footer3.setSpacing(false);
footer3.addComponent(footer3Value);
footer3.addComponent(footer3Btn);
options.addComponent(footer3);
layout.addComponent(options);
addComponent(layout);
}
@Override
protected String getTestDescription() {
return "Table with footer";
}
@Override
protected Integer getTicketNumber() {
return 1553;
}
private Container createContainer() {
IndexedContainer container = new IndexedContainer();
container.addContainerProperty("col1", String.class, "");
container.addContainerProperty("col2", String.class, "");
container.addContainerProperty("col3", String.class, "");
for (int i = 0; i < 100; i++) {
Item item = container.addItem("item " + i);
item.getItemProperty("col1").setValue("first" + i);
item.getItemProperty("col2").setValue("middle" + i);
item.getItemProperty("col3").setValue("last" + i);
}
return container;
}
}
| 34.333333 | 77 | 0.647249 |
488b250efe535efcb58638087eeb055deaa00f74 | 595 | import java.util.Scanner;
public class Factorial {
/*
* Problem- A positive number N is given to you and You need to calculate its factorial.
* Approach- Recursion
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a no. :");
int n = sc.nextInt();
if(n < 0)
System.out.println("Factorial is defined fro positive nos. only");
else
System.out.println("Factorial is : "+ factorial(n));
sc.close();
}
private static int factorial(int n) {
if( n == 0 )
return 1;
return n * factorial(n-1);
}
}
| 19.193548 | 89 | 0.638655 |
9eb5414dc62ca3029b9a84c9ae53a5210818cd13 | 1,418 | package com.ulfy.master.ui.cell;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.TextView;
import com.ulfy.android.image.ImageUtils;
import com.ulfy.android.mvvm.IViewModel;
import com.ulfy.android.ui_injection.Layout;
import com.ulfy.android.ui_injection.ViewById;
import com.ulfy.master.R;
import com.ulfy.master.application.cm.ContentSearchCM;
import com.ulfy.master.ui.base.BaseCell;
@Layout(id = R.layout.cell_content_search)
public class ContentSearchCell extends BaseCell {
@ViewById(id = R.id.coverIV) private ImageView coverIV;
@ViewById(id = R.id.nameTV) private TextView nameTV;
@ViewById(id = R.id.timeTV) private TextView timeTV;
private ContentSearchCM cm;
public ContentSearchCell(Context context) {
super(context);
init(context, null);
}
public ContentSearchCell(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
}
@Override public void bind(IViewModel model) {
cm = (ContentSearchCM) model;
ImageUtils.loadImage(cm.contentSearch.cover, R.drawable.drawable_loading, R.drawable.drawable_loading_false, coverIV);
nameTV.setText(cm.contentSearch.name);
timeTV.setText(String.format("%d次观看", cm.contentSearch.time));
}
} | 32.976744 | 126 | 0.737659 |
6b66c2ed84e830b470f72523b47a4bdf1e094e3c | 3,485 | package restx.tests;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.common.base.Charsets;
import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import org.hamcrest.MatcherAssert;
import restx.factory.Component;
import restx.specs.WhenHttpRequest;
import uk.co.datumedge.hamcrest.json.SameJSONAs;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static restx.specs.WhenHttpRequest.BASE_URL;
@Component
public class WhenHttpChecker implements WhenChecker<WhenHttpRequest> {
@Override
public Class<WhenHttpRequest> getWhenClass() {
return WhenHttpRequest.class;
}
@Override
public void check(WhenHttpRequest when, ImmutableMap<String, String> params) {
Stopwatch stopwatch = Stopwatch.createStarted();
String baseUrl = checkNotNull(params.get(BASE_URL),
BASE_URL + " param is required");
String url = baseUrl + "/" + when.getPath();
System.out.println("---------------------------------------------------------------------------------");
System.out.println(">> REQUEST");
System.out.println(when.getMethod() + " " + url);
System.out.println();
HttpTestClient httpTestClient = HttpTestClient.withBaseUrl(baseUrl);
for (Map.Entry<String, String> cookie : when.getCookies().entrySet()) {
httpTestClient = httpTestClient.withCookie(cookie.getKey(), cookie.getValue());
}
HttpRequest httpRequest = httpTestClient.http(when.getMethod(), when.getPath());
ImmutableMap<String, String> cookies = when.getCookies();
if (!cookies.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : cookies.entrySet()) {
sb.append(entry.getKey()).append("=\"").append(entry.getValue().replace("\"", "\\\"")).append("\"; ");
}
sb.setLength(sb.length() - 2);
httpRequest.header("Cookie", sb.toString());
}
if (!Strings.isNullOrEmpty(when.getBody())) {
httpRequest.contentType("application/json");
httpRequest.send(when.getBody());
System.out.println(when.getBody());
}
System.out.println();
int code = httpRequest.code();
System.out.println("<< RESPONSE");
System.out.println(code);
System.out.println();
String body = httpRequest.body(Charsets.UTF_8.name());
System.out.println(body);
System.out.println();
assertThat(code).isEqualTo(when.getThen().getExpectedCode());
if (isJSON(when.getThen().getExpected())) {
MatcherAssert.assertThat(body,
SameJSONAs.sameJSONAs(when.getThen().getExpected()).allowingExtraUnexpectedFields());
} else if (!when.getThen().getExpected().trim().isEmpty()) {
MatcherAssert.assertThat(body.trim(), equalTo(when.getThen().getExpected().trim()));
}
System.out.printf("checked %s /%s -- %s%n", when.getMethod(), when.getPath(), stopwatch.stop().toString());
}
private boolean isJSON(String s) {
// very basic impl of this, we could also parse it to check
return s.trim().startsWith("{") || s.trim().startsWith("[");
}
}
| 41 | 118 | 0.634433 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.