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 |
|---|---|---|---|---|---|
08edbd782a2184ca15931b76b8f1add9144db884 | 1,425 | package greeter;
import static org.junit.Assert.assertEquals;
import greeter.api.Greeter;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.jboss.modules.LocalModuleLoader;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.modules.ModuleUnloader;
import org.junit.BeforeClass;
import org.junit.Test;
public class Test4_UnloadAndDeleteModuleSuccessful {
@BeforeClass
public static void copyRepo() throws Exception {
FileUtils.deleteQuietly(new File("repo_copy"));
FileUtils.copyDirectory(new File("repo"), new File("repo_copy"));
}
@Test
public void test() throws Exception {
try (LocalModuleLoader moduleLoader = new LocalModuleLoader(new File[] { new File("repo_copy") })) {
// load and use module
Module module = moduleLoader.loadModule("greeter.english");
ModuleClassLoader classLoader = module.getClassLoader();
Greeter englishGreeter = (Greeter)classLoader.loadClass("greeter.impl.EnglishGreeter").newInstance();
assertEquals("Hello World!", englishGreeter.sayHello("World"));
// unload module with the hack...
ModuleUnloader.unload(moduleLoader, module);
// ... then use the close method of the hacked version of ModuleClassLoader...
classLoader.close();
// ... and it is possible to remove the directory :-)
FileUtils.deleteDirectory(new File("repo_copy/greeter/english"));
}
}
}
| 30.978261 | 104 | 0.748772 |
4f15306d7365cbfaefb6180e8c0295b84ec86df8 | 5,064 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.cli;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.status.InvalidArgumentException;
import alluxio.util.CommonUtils;
import org.apache.commons.cli.CommandLine;
import org.reflections.Reflections;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
/**
* Class for convenience methods used by instances of {@link Command}.
*/
@ThreadSafe
public final class CommandUtils {
private CommandUtils() {} // prevent instantiation
/**
* Get instances of all subclasses of {@link Command} in a sub-package called "command" the given
* package.
*
* @param pkgName package prefix to look in
* @param classArgs type of args to instantiate the class
* @param objectArgs args to instantiate the class
* @return a mapping from command name to command instance
*/
public static Map<String, Command> loadCommands(String pkgName, Class[] classArgs,
Object[] objectArgs) {
Map<String, Command> commandsMap = new HashMap<>();
Reflections reflections = new Reflections(Command.class.getPackage().getName());
for (Class<? extends Command> cls : reflections.getSubTypesOf(Command.class)) {
// Add commands from <pkgName>.command.*
if (cls.getPackage().getName().equals(pkgName + ".command")
&& !Modifier.isAbstract(cls.getModifiers())) {
// Only instantiate a concrete class
Command cmd = CommonUtils.createNewClassInstance(cls, classArgs, objectArgs);
commandsMap.put(cmd.getCommandName(), cmd);
}
}
return commandsMap;
}
/**
* Checks the number of non-option arguments equals n for command.
*
* @param cmd command instance
* @param cl parsed commandline arguments
* @param n an integer
* @throws InvalidArgumentException if the number does not equal n
*/
public static void checkNumOfArgsEquals(Command cmd, CommandLine cl, int n) throws
InvalidArgumentException {
if (cl.getArgs().length != n) {
throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_NUM
.getMessage(cmd.getCommandName(), n, cl.getArgs().length));
}
}
/**
* Checks the number of non-option arguments is no less than n for command.
*
* @param cmd command instance
* @param cl parsed commandline arguments
* @param n an integer
* @throws InvalidArgumentException if the number is smaller than n
*/
public static void checkNumOfArgsNoLessThan(Command cmd, CommandLine cl, int n) throws
InvalidArgumentException {
if (cl.getArgs().length < n) {
throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_NUM_INSUFFICIENT
.getMessage(cmd.getCommandName(), n, cl.getArgs().length));
}
}
/**
* Checks the number of non-option arguments is no more than n for command.
*
* @param cmd command instance
* @param cl parsed commandline arguments
* @param n an integer
* @throws InvalidArgumentException if the number is greater than n
*/
public static void checkNumOfArgsNoMoreThan(Command cmd, CommandLine cl, int n) throws
InvalidArgumentException {
if (cl.getArgs().length > n) {
throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_NUM_TOO_MANY
.getMessage(cmd.getCommandName(), n, cl.getArgs().length));
}
}
/**
* Reads a list of nodes from given file name ignoring comments and empty lines.
* Can be used to read conf/workers or conf/masters.
* @param confDir directory that holds the configuration
* @param fileName name of a file that contains the list of the nodes
* @return list of the node names, null when file fails to read
*/
@Nullable
public static List<String> readNodeList(String confDir, String fileName) {
List<String> lines;
try {
lines = Files.readAllLines(Paths.get(confDir, fileName), StandardCharsets.UTF_8);
} catch (IOException e) {
System.err.format("Failed to read file %s/%s. Ignored.", confDir, fileName);
return new ArrayList<>();
}
List<String> nodes = new ArrayList<>();
for (String line : lines) {
String node = line.trim();
if (node.startsWith("#") || node.length() == 0) {
continue;
}
nodes.add(node);
}
return nodes;
}
}
| 35.166667 | 99 | 0.707543 |
f47c5ff8a2bc0d09b1622ac5fec898dd415fa8b5 | 1,736 | import java.util.*;
class Q1
{
public void strconcat(String a,String b)
{
String c = a.concat(b);
System.out.println("CONCAT()");
System.out.println(c);
}
public void strequals(String a , String b)
{
System.out.println("EQUALS()");
if(a.equals(b))
System.out.println("TRUE");
else
System.out.println("FALSE");
}
public void equalsigc(String a , String b)
{
System.out.println("EQUALSIGNORECASE()");
if(a.equalsIgnoreCase(b))
System.out.println("TRUE");
else
System.out.println("FALSE");
}
public void struc(String a, String b)
{
String c = a.toUpperCase();
System.out.println("UPPERCASE()");
System.out.println(c);
}
public void pos(String a)
{
int n = a.length();
char f,l;
f = a.charAt(0);
l = a.charAt(n-1);
System.out.println("CHARAT()");
System.out.println("Character at 0:" + f +"\n"+"Character at n-1:" + l);
}
public void comp(String a , String b)
{
int c = a.compareTo(b);
System.out.println("COMPARETO()");
System.out.println(c);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String a,b;
System.out.println("Enter two strings:");
a = in.nextLine();
b= in.nextLine();
Q1 q = new Q1();
q.strconcat(a, b);
q.strequals(a, b);
q.equalsigc(a, b);
q.struc(a, b);
q.pos(a);
q.comp(a, b);
System.out.println("Divyam Kumar\n500083141");
}
} | 24.8 | 80 | 0.497696 |
be58bf2352fb9f951446768dfc66c00b86c29d75 | 919 | package loon.media;
public class SoundOpenAlSource {
private int sourceId;
private SoundOpenAlBuffer buffer;
public SoundOpenAlSource(SoundOpenAlBuffer buffer) {
this.buffer = buffer;
this.sourceId = OpenAlBridge.addSource(buffer.getId());
}
public void setPosition(float x, float y, float z) {
OpenAlBridge.setPosition(sourceId, x, y, z);
}
public void setPitch(float pitch) {
OpenAlBridge.setPitch(sourceId, pitch);
}
public void setGain(float gain) {
OpenAlBridge.setGain(sourceId, gain);
}
public void setRolloffFactor(float rollOff) {
OpenAlBridge.setRolloffFactor(sourceId, rollOff);
}
public void play(boolean loop) {
OpenAlBridge.play(sourceId, loop);
}
public void stop() {
OpenAlBridge.stop(sourceId);
}
public void release() {
OpenAlBridge.releaseSource(sourceId);
}
public String toString() {
return "source " + sourceId + " playing " + buffer;
}
}
| 19.978261 | 57 | 0.722524 |
7bc4e8211a11135f2409e0ab1329c099d0f5eb6d | 14,492 | /*
* Copyright 2021 EMBL - European Bioinformatics Institute
* 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 uk.ac.ebi.biosamples;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.Collections;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.StreamUtils;
import uk.ac.ebi.biosamples.model.Attribute;
import uk.ac.ebi.biosamples.model.Sample;
import uk.ac.ebi.biosamples.model.auth.SubmissionAccount;
import uk.ac.ebi.biosamples.model.structured.amr.AMREntry;
import uk.ac.ebi.biosamples.model.structured.amr.AMRTable;
import uk.ac.ebi.biosamples.model.structured.amr.AmrPair;
import uk.ac.ebi.biosamples.service.SampleService;
import uk.ac.ebi.biosamples.service.security.BioSamplesAapService;
import uk.ac.ebi.biosamples.service.security.BioSamplesWebinAuthenticationService;
import uk.ac.ebi.biosamples.validation.ElixirSchemaValidator;
import uk.ac.ebi.biosamples.validation.SchemaValidationService;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class AMRTest {
/*
@Autowired
private SampleRestController sampleRestController;
@Test
public void contextLoads() throws Exception {
assertThat(sampleRestController).isNotNull();
}
*/
@Autowired private MockMvc mockMvc;
private JacksonTester<Sample> json;
private ObjectMapper mapper;
@MockBean private BioSamplesAapService bioSamplesAapService;
@MockBean private BioSamplesWebinAuthenticationService bioSamplesWebinAuthenticationService;
@MockBean private SampleService sampleService;
@MockBean private SchemaValidationService schemaValidatorService;
@MockBean ElixirSchemaValidator validator;
private AMREntry getAMREntry() {
return new AMREntry.Builder()
.withAntibioticName(new AmrPair("ampicillin", ""))
.withResistancePhenotype("susceptible")
.withMeasure("==", "10", "mg/L")
.withVendor("in-house")
.withLaboratoryTypingMethod("CMAD")
.withAstStandard("CLD")
.build();
}
private AMRTable getAMRTable() {
return new AMRTable.Builder("http://schema.org", "self.test", null)
.addEntry(getAMREntry())
.build();
}
private Sample.Builder getTestSampleBuilder() {
return new Sample.Builder("testSample", "TEST1")
.withDomain("foozit")
.withRelease(Instant.now())
.withUpdate(Instant.now());
}
@Before
public void init() {
mapper = new ObjectMapper();
}
@Test
public void givenSample_whenGetSample_thenReturnJsonObject() throws Exception {
Sample sample = getTestSampleBuilder().build();
when(sampleService.fetch(eq(sample.getAccession()), any(), any(String.class)))
.thenReturn(Optional.of(sample));
when(bioSamplesAapService.isWriteSuperUser()).thenReturn(true);
mockMvc
.perform(
get("/samples/{accession}", sample.getAccession())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is(sample.getName())))
.andExpect(jsonPath("$.accession", is(sample.getAccession())));
}
@Test
public void givenSampleWithStructuredData_whenGetSample_thenReturnStructuredDataInJson()
throws Exception {
AMREntry amrEntry = getAMREntry();
AMRTable amrTable =
new AMRTable.Builder("http://schema.org", "self.test", null).addEntry(amrEntry).build();
Sample sample = getTestSampleBuilder().addData(amrTable).build();
when(sampleService.fetch(eq(sample.getAccession()), any(), any(String.class)))
.thenReturn(Optional.of(sample));
when(bioSamplesAapService.isWriteSuperUser()).thenReturn(true);
mockMvc
.perform(
get("/samples/{accession}", sample.getAccession()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data").exists())
.andExpect(jsonPath("$.data").isArray())
.andExpect(
jsonPath("$.data[0]")
.value(
allOf(
hasEntry("schema", "http://schema.org"),
hasEntry("type", "AMR"),
hasKey("content"))))
.andExpect(jsonPath("$.data[0].content").isArray())
.andExpect(
jsonPath("$.data[0].content[0]")
.value(
allOf(
hasEntry("resistance_phenotype", amrEntry.getResistancePhenotype()),
hasEntry("measurement_sign", amrEntry.getMeasurementSign()),
hasEntry("measurement_units", amrEntry.getMeasurementUnits()),
hasEntry("vendor", amrEntry.getVendor()),
hasEntry("laboratory_typing_method", amrEntry.getLaboratoryTypingMethod()),
hasEntry("ast_standard", amrEntry.getAstStandard()))))
.andExpect(
jsonPath("$.data[0].content[0].antibiotic_name")
.value(hasEntry("value", amrEntry.getAntibioticName().getValue())))
.andExpect(
jsonPath("$.data[0].content[0]")
.value(
hasEntry("measurement", amrEntry.getMeasurement()) // This needs to go here
// because the the
// hasEntry has
// a different signature - Only one having a number
// as a value. allOf wants all matchers of the same
// type
));
}
@Test
public void able_to_submit_sample_with_structuredData() throws Exception {
String json =
StreamUtils.copyToString(
new ClassPathResource("amr_sample.json").getInputStream(), Charset.defaultCharset());
JsonNode jsonSample = mapper.readTree(json);
JsonNode jsonAmr = jsonSample.at("/data/0/content/0");
AMREntry amrEntry =
new AMREntry.Builder()
.withAntibioticName(new AmrPair(jsonAmr.get("antibiotic_name").asText(), ""))
.withResistancePhenotype(jsonAmr.get("resistance_phenotype").asText())
.withMeasure(
jsonAmr.get("measurement_sign").asText(),
jsonAmr.get("measurement").asText(),
jsonAmr.get("measurement_units").asText())
.withVendor(jsonAmr.get("vendor").asText())
.withLaboratoryTypingMethod(jsonAmr.get("laboratory_typing_method").asText())
.withAstStandard(jsonAmr.get("ast_standard").asText())
.build();
Attribute organismAttribute = Attribute.build("organism", "Homo Sapiens");
Sample testSample =
new Sample.Builder(jsonSample.at("/name").asText())
.withDomain(jsonSample.at("/domain").asText())
.withUpdate(jsonSample.at("/update").asText())
.withRelease(jsonSample.at("/release").asText())
.addData(
new AMRTable.Builder(jsonSample.at("/data/0/schema").asText(), "self.test", null)
.addEntry(amrEntry)
.build())
.withAttributes(Collections.singletonList(organismAttribute))
.build();
when(bioSamplesAapService.isWriteSuperUser()).thenReturn(true);
when(bioSamplesAapService.handleSampleDomain(any(Sample.class))).thenReturn(testSample);
when(bioSamplesAapService.handleStructuredDataDomain(any(Sample.class))).thenReturn(testSample);
when(sampleService.store(testSample, true, "AAP")).thenReturn(testSample);
mockMvc
.perform(post("/samples").contentType(MediaType.APPLICATION_JSON_VALUE).content(json))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.data[0].content").isArray());
}
@Test
public void able_to_submit_amr_if_user_is_not_superuser() throws Exception {
String json =
StreamUtils.copyToString(
new ClassPathResource("amr_sample.json").getInputStream(), Charset.defaultCharset());
JsonNode jsonSample = mapper.readTree(json);
JsonNode jsonAmr = jsonSample.at("/data/0/content/0");
AMREntry amrEntry =
new AMREntry.Builder()
.withAntibioticName(new AmrPair(jsonAmr.get("antibiotic_name").asText(), ""))
.withResistancePhenotype(jsonAmr.get("resistance_phenotype").asText())
.withMeasure(
jsonAmr.get("measurement_sign").asText(),
jsonAmr.get("measurement").asText(),
jsonAmr.get("measurement_units").asText())
.withVendor(jsonAmr.get("vendor").asText())
.withLaboratoryTypingMethod(jsonAmr.get("laboratory_typing_method").asText())
.withAstStandard(jsonAmr.get("ast_standard").asText())
.build();
Attribute organismAttribute = Attribute.build("organism", "Homo Sapiens");
Sample testSample =
new Sample.Builder(jsonSample.at("/name").asText())
.withDomain(jsonSample.at("/domain").asText())
.withUpdate(jsonSample.at("/update").asText())
.withRelease(jsonSample.at("/release").asText())
.addData(
new AMRTable.Builder(jsonSample.at("/data/0/schema").asText(), "self.test", null)
.addEntry(amrEntry)
.build())
.withAttributes(Collections.singletonList(organismAttribute))
.build();
when(bioSamplesAapService.isWriteSuperUser()).thenReturn(false);
when(bioSamplesAapService.handleSampleDomain(any(Sample.class))).thenReturn(testSample);
when(bioSamplesAapService.handleStructuredDataDomain(any(Sample.class))).thenReturn(testSample);
ArgumentCaptor<Sample> generatedSample = ArgumentCaptor.forClass(Sample.class);
when(sampleService.store(generatedSample.capture(), eq(true), eq("AAP")))
.thenReturn(testSample);
mockMvc.perform(post("/samples").contentType(MediaType.APPLICATION_JSON_VALUE).content(json));
assert (!generatedSample.getValue().getData().isEmpty());
}
@Test
public void able_to_submit_amr_with_webin_id() throws Exception {
String json =
StreamUtils.copyToString(
new ClassPathResource("amr_sample_webin.json").getInputStream(),
Charset.defaultCharset());
JsonNode jsonSample = mapper.readTree(json);
JsonNode jsonAmr = jsonSample.at("/data/0/content/0");
SubmissionAccount submissionAccount = new SubmissionAccount();
submissionAccount.setId("Webin-57176");
AMREntry amrEntry =
new AMREntry.Builder()
.withAntibioticName(new AmrPair(jsonAmr.get("antibiotic_name").asText(), ""))
.withResistancePhenotype(jsonAmr.get("resistance_phenotype").asText())
.withMeasure(
jsonAmr.get("measurement_sign").asText(),
jsonAmr.get("measurement").asText(),
jsonAmr.get("measurement_units").asText())
.withVendor(jsonAmr.get("vendor").asText())
.withLaboratoryTypingMethod(jsonAmr.get("laboratory_typing_method").asText())
.withAstStandard(jsonAmr.get("ast_standard").asText())
.build();
Attribute organismAttribute = Attribute.build("organism", "Homo Sapiens");
Sample testSample =
new Sample.Builder(jsonSample.at("/name").asText())
.withUpdate(jsonSample.at("/update").asText())
.withRelease(jsonSample.at("/release").asText())
.addData(
new AMRTable.Builder(
jsonSample.at("/data/0/schema").asText(), "null", "Webin-57176")
.addEntry(amrEntry)
.build())
.withAttributes(Collections.singletonList(organismAttribute))
.build();
when(bioSamplesWebinAuthenticationService.getWebinSubmissionAccount(any(String.class)))
.thenReturn(ResponseEntity.ok(submissionAccount));
when(bioSamplesWebinAuthenticationService.handleWebinUser(any(Sample.class), any(String.class)))
.thenReturn(testSample);
when(bioSamplesWebinAuthenticationService.handleStructuredDataAccesibility(
any(Sample.class), eq("Webin-57176")))
.thenReturn(testSample);
ArgumentCaptor<Sample> generatedSample = ArgumentCaptor.forClass(Sample.class);
when(sampleService.store(generatedSample.capture(), eq(true), eq("WEBIN")))
.thenReturn(testSample);
mockMvc.perform(
post("/samples?authProvider=WEBIN")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(json)
.header("Authorization", "Bearer $TOKEN"));
assert (!generatedSample.getValue().getData().isEmpty());
}
}
| 42.374269 | 100 | 0.67727 |
c99a5e383c11b60be5a631b745e354e872bba5e2 | 1,435 | package info.source4code.jaxb;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.MarshalHelper;
import info.source4code.jaxb.model.Car;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(MarshalHelperTest.class);
public static Car car;
@BeforeClass
public static void setUpBeforeClass() {
car = new Car();
car.setMake("Passat");
car.setManufacturer("Volkswagen");
car.setId("ABC-123");
}
@Test
public void testMarshalError() throws JAXBException {
try {
MarshalHelper.marshalError(car);
fail("no exception thrown");
} catch (MarshalException e) {
logger.error("MarshalException", e);
assertTrue(e.toString().contains(
"is missing an @XmlRootElement annotation"));
}
}
@Test
public void testMarshal() throws JAXBException {
String xml = MarshalHelper.marshal(car);
assertTrue(xml.contains("<?xml"));
assertTrue(xml.contains("ABC-123"));
assertTrue(xml.contains("Passat"));
assertTrue(xml.contains("Volkswagen"));
}
}
| 27.596154 | 65 | 0.659233 |
4238bbca2f6363955445c6de2a50102c976c0edc | 3,448 | package com.me.gmall.realtime.app.dws;
import com.me.gmall.realtime.app.func.KeywordUDTF;
import com.me.gmall.realtime.bean.KeywordStats;
import com.me.gmall.realtime.common.GmallConstant;
import com.me.gmall.realtime.utils.ClickHouseUtil;
import com.me.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
/**
* Author: zs
* Date: 2021/5/22
* Desc: 关键词统计应用
*/
public class KeywordStatsSqlApp {
public static void main(String[] args) throws Exception {
//TODO 1.基本环境准备
//1.1 流处理环境
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//1.2 设置并行度
env.setParallelism(4);
//1.3 表执行环境
StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
//TODO 2.创建动态表 看官网 https://ci.apache.org/projects/flink/flink-docs-release-1.12/zh/dev/table/common.html
// 指定watermark以及提取事件时间,同时从kafka中消费数据
String topic = "dwd_page_log";
String groupId = "keyword_stats_group";
tableEnv.executeSql("CREATE TABLE page_view " +
"(common MAP<STRING,STRING>, " +
"page MAP<STRING,STRING>,ts BIGINT, " +
"rowtime AS TO_TIMESTAMP(FROM_UNIXTIME(ts/1000)) ," +
"WATERMARK FOR rowtime AS rowtime - INTERVAL '3' SECOND) " +
"WITH (" + MyKafkaUtil.getKafkaDDL(topic, groupId) + ")");
//TODO 3.注册自定义UDTF函数,自定义分词器
tableEnv.createTemporarySystemFunction("ik_analyze", KeywordUDTF.class);
//TODO 4.过滤数据,选出搜索商品且过滤不为空的数据
Table fullwordView = tableEnv.sqlQuery("select page['item'] fullword ," +
"rowtime from page_view " +
"where page['page_id']='good_list' " +
"and page['item'] IS NOT NULL ");
/* TODO 5.使用自定义UDTF函数进行分词 https://ci.apache.org/projects/flink/flink-docs-release-1.12/zh/dev/table/sql/queries.html#joins
将分开的词与时间戳进行join连接
类似:
小米 54564564564646
银灰 54564564564646
128G 54564564564646
*/
Table keywordView = tableEnv.sqlQuery("select keyword,rowtime from " + fullwordView + " ," +
" LATERAL TABLE(ik_analyze(fullword)) as T(keyword)");
//TODO 6.分组、开窗、聚合计算
Table keywordStatsSearch = tableEnv.sqlQuery("select keyword,count(*) ct, '"
+ GmallConstant.KEYWORD_SEARCH + "' source ," +
"DATE_FORMAT(TUMBLE_START(rowtime, INTERVAL '10' SECOND),'yyyy-MM-dd HH:mm:ss') stt," +
"DATE_FORMAT(TUMBLE_END(rowtime, INTERVAL '10' SECOND),'yyyy-MM-dd HH:mm:ss') edt," +
"UNIX_TIMESTAMP()*1000 ts from "+keywordView
+ " GROUP BY TUMBLE(rowtime, INTERVAL '10' SECOND ),keyword");
//TODO 7.将动态表转换为流
DataStream<KeywordStats> keywordStatsDS = tableEnv.toAppendStream(keywordStatsSearch, KeywordStats.class);
//TODO 8.将流中的数据写到CK中
keywordStatsDS.print(">>>>");
keywordStatsDS.addSink(
ClickHouseUtil.getJdbcSink("insert into keyword_stats_1116(keyword,ct,source,stt,edt,ts)" +
" values(?,?,?,?,?,?)")
);
env.execute();
}
}
| 41.047619 | 133 | 0.633701 |
523b71155200e799ac4b11c6e7e0425af3e5ebb5 | 8,576 | // Copyright (C) 2016 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.google.gerrit.acceptance.rest.project;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allow;
import static com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS;
import static com.google.gerrit.testing.GerritJUnit.assertThrows;
import static java.util.stream.Collectors.toList;
import static org.eclipse.jgit.lib.Constants.R_HEADS;
import static org.eclipse.jgit.lib.Constants.R_REFS;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.testsuite.project.ProjectOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.common.data.Permission;
import com.google.gerrit.extensions.api.projects.BranchInput;
import com.google.gerrit.extensions.api.projects.DeleteBranchesInput;
import com.google.gerrit.extensions.api.projects.ProjectApi;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.inject.Inject;
import java.util.HashMap;
import java.util.List;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.junit.Before;
import org.junit.Test;
@NoHttpd
public class DeleteBranchesIT extends AbstractDaemonTest {
private static final ImmutableList<String> BRANCHES =
ImmutableList.of("refs/heads/test-1", "refs/heads/test-2", "test-3", "refs/meta/foo");
@Inject private ProjectOperations projectOperations;
@Inject private RequestScopeOperations requestScopeOperations;
@Before
public void setUp() throws Exception {
projectOperations
.project(project)
.forUpdate()
.add(allow(Permission.CREATE).ref("refs/*").group(REGISTERED_USERS))
.add(allow(Permission.PUSH).ref("refs/*").group(REGISTERED_USERS))
.update();
for (String name : BRANCHES) {
project().branch(name).create(new BranchInput());
}
assertBranches(BRANCHES);
}
@Test
public void deleteBranches() throws Exception {
HashMap<String, RevCommit> initialRevisions = initialRevisions(BRANCHES);
DeleteBranchesInput input = new DeleteBranchesInput();
input.branches = BRANCHES;
project().deleteBranches(input);
assertBranchesDeleted(BRANCHES);
assertRefUpdatedEvents(initialRevisions);
}
@Test
public void deleteOneBranchWithoutPermissionForbidden() throws Exception {
ImmutableList<String> branchToDelete = ImmutableList.of("refs/heads/test-1");
DeleteBranchesInput input = new DeleteBranchesInput();
input.branches = branchToDelete;
requestScopeOperations.setApiUser(user.id());
AuthException thrown = assertThrows(AuthException.class, () -> project().deleteBranches(input));
assertThat(thrown).hasMessageThat().isEqualTo("not permitted: delete on refs/heads/test-1");
requestScopeOperations.setApiUser(admin.id());
assertBranches(BRANCHES);
}
@Test
public void deleteMultiBranchesWithoutPermissionForbidden() throws Exception {
DeleteBranchesInput input = new DeleteBranchesInput();
input.branches = BRANCHES;
requestScopeOperations.setApiUser(user.id());
ResourceConflictException thrown =
assertThrows(ResourceConflictException.class, () -> project().deleteBranches(input));
assertThat(thrown).hasMessageThat().isEqualTo(errorMessageForBranches(BRANCHES));
requestScopeOperations.setApiUser(admin.id());
assertBranches(BRANCHES);
}
@Test
public void deleteBranchesNotFound() throws Exception {
DeleteBranchesInput input = new DeleteBranchesInput();
List<String> branches = Lists.newArrayList(BRANCHES);
branches.add("refs/heads/does-not-exist");
input.branches = branches;
ResourceConflictException thrown =
assertThrows(ResourceConflictException.class, () -> project().deleteBranches(input));
assertThat(thrown)
.hasMessageThat()
.isEqualTo(errorMessageForBranches(ImmutableList.of("refs/heads/does-not-exist")));
assertBranchesDeleted(BRANCHES);
}
@Test
public void deleteBranchesNotFoundContinue() throws Exception {
// If it fails on the first branch in the input, it should still
// continue to process the remaining branches.
DeleteBranchesInput input = new DeleteBranchesInput();
List<String> branches = Lists.newArrayList("refs/heads/does-not-exist");
branches.addAll(BRANCHES);
input.branches = branches;
ResourceConflictException thrown =
assertThrows(ResourceConflictException.class, () -> project().deleteBranches(input));
assertThat(thrown)
.hasMessageThat()
.isEqualTo(errorMessageForBranches(ImmutableList.of("refs/heads/does-not-exist")));
assertBranchesDeleted(BRANCHES);
}
@Test
public void missingInput() throws Exception {
DeleteBranchesInput input = null;
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> project().deleteBranches(input));
assertThat(thrown).hasMessageThat().contains("branches must be specified");
}
@Test
public void missingBranchList() throws Exception {
DeleteBranchesInput input = new DeleteBranchesInput();
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> project().deleteBranches(input));
assertThat(thrown).hasMessageThat().contains("branches must be specified");
}
@Test
public void emptyBranchList() throws Exception {
DeleteBranchesInput input = new DeleteBranchesInput();
input.branches = Lists.newArrayList();
BadRequestException thrown =
assertThrows(BadRequestException.class, () -> project().deleteBranches(input));
assertThat(thrown).hasMessageThat().contains("branches must be specified");
}
private String errorMessageForBranches(List<String> branches) {
StringBuilder message = new StringBuilder();
for (String branch : branches) {
message
.append("Cannot delete ")
.append(prefixRef(branch))
.append(": it doesn't exist or you do not have permission ")
.append("to delete it\n");
}
return message.toString();
}
private HashMap<String, RevCommit> initialRevisions(List<String> branches) throws Exception {
HashMap<String, RevCommit> result = new HashMap<>();
for (String branch : branches) {
result.put(branch, projectOperations.project(project).getHead(branch));
}
return result;
}
private void assertRefUpdatedEvents(HashMap<String, RevCommit> revisions) throws Exception {
for (String branch : revisions.keySet()) {
RevCommit revision = revisions.get(branch);
eventRecorder.assertRefUpdatedEvents(
project.get(), prefixRef(branch), null, revision, revision, null);
}
}
private String prefixRef(String ref) {
return ref.startsWith(R_REFS) ? ref : R_HEADS + ref;
}
private ProjectApi project() throws Exception {
return gApi.projects().name(project.get());
}
private void assertBranches(List<String> branches) throws Exception {
List<String> expected = Lists.newArrayList("HEAD", RefNames.REFS_CONFIG, "refs/heads/master");
expected.addAll(branches.stream().map(this::prefixRef).collect(toList()));
try (Repository repo = repoManager.openRepository(project)) {
for (String branch : expected) {
assertThat(repo.exactRef(branch)).isNotNull();
}
}
}
private void assertBranchesDeleted(List<String> branches) throws Exception {
try (Repository repo = repoManager.openRepository(project)) {
for (String branch : branches) {
assertThat(repo.exactRef(branch)).isNull();
}
}
}
}
| 40.262911 | 100 | 0.743004 |
fc1abc354b5aa7a05770f16d29f262ed1844cd96 | 5,371 | package com.zjcoding.zmqttbroker.processor.message;
import com.zjcoding.zmqttcommon.factory.ZMqttMessageFactory;
import com.zjcoding.zmqttbroker.security.IAuth;
import com.zjcoding.zmqttcommon.message.CommonMessage;
import com.zjcoding.zmqttcommon.session.MqttSession;
import com.zjcoding.zmqttstore.message.IMessageStore;
import com.zjcoding.zmqttstore.session.ISessionStore;
import com.zjcoding.zmqttstore.subscribe.ISubscribeStore;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* CONNECT控制包处理器
*
* @author ZhangJun
* @date 13:48 2021/2/24
*/
@Component
public class ConnectProcessor {
@Resource
private IAuth auth;
@Resource
private ISessionStore sessionStore;
@Resource
private IMessageStore messageStore;
@Resource
private ISubscribeStore subscribeStore;
@Resource
private PublishProcessor publishProcessor;
/**
* CONNECT控制包处理
*
* @param ctx: ChannelHandler上下文
* @param connectMessage: CONNECT控制包
* @author ZhangJun
* @date 10:44 2021/2/27
*/
public void processConnect(ChannelHandlerContext ctx, MqttConnectMessage connectMessage) {
if (connectMessage.decoderResult().isFailure()) {
Throwable throwable = connectMessage.decoderResult().cause();
if (throwable instanceof MqttUnacceptableProtocolVersionException) {
ctx.channel().writeAndFlush(ZMqttMessageFactory.getConnAck(false, MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION));
} else if (throwable instanceof MqttIdentifierRejectedException) {
ctx.channel().writeAndFlush(ZMqttMessageFactory.getConnAck(false, MqttConnectReturnCode.CONNECTION_REFUSED_CLIENT_IDENTIFIER_NOT_VALID));
}
ctx.channel().close();
return;
}
String clientId = connectMessage.payload().clientIdentifier();
boolean isCleanSession = connectMessage.variableHeader().isCleanSession();
// 按照MQTTv3.1.1规范,clientId为空时服务端自动生成一个ClientId,且将cleanSession设置为1
if (!StringUtils.hasText(clientId)) {
clientId = UUID.randomUUID().toString();
isCleanSession = true;
}
// 校验用户名、密码
if (!auth.checkAuth(connectMessage)) {
ctx.channel().writeAndFlush(ZMqttMessageFactory.getConnAck(false, MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD));
ctx.channel().close();
return;
}
// 处理sessionPresent,清除客户端历史
if (isCleanSession) {
sessionStore.cleanSession(clientId);
subscribeStore.removeSubscribe(clientId);
messageStore.removeMessage(clientId);
messageStore.removeDump(clientId);
}
// 处理遗嘱消息
MqttSession mqttSession = new MqttSession(clientId, isCleanSession, ctx.channel(), false);
if (connectMessage.variableHeader().isWillFlag()) {
mqttSession.setHasWill(true);
mqttSession.setWillTopic(connectMessage.payload().willTopic());
mqttSession.setWillContent(new String(connectMessage.payload().willMessageInBytes(), StandardCharsets.UTF_8));
mqttSession.setWillRetain(connectMessage.variableHeader().isWillRetain());
}
// 处理keepAlive,达到1.5个心跳周期时断开连接
if (connectMessage.variableHeader().keepAliveTimeSeconds() > 0) {
if (ctx.channel().pipeline().names().contains("heartbeat")) {
ctx.channel().pipeline().remove("heartbeat");
}
ctx.pipeline().addFirst("heartbeat", new IdleStateHandler(0, 0, Math.round(connectMessage.variableHeader().keepAliveTimeSeconds() * 1.5f)));
}
// 给channel加上clientId作为属性,防止未经授权的连接直接发送控制包
ctx.channel().attr(AttributeKey.valueOf("clientId")).set(clientId);
// 存储会话信息、遗嘱
sessionStore.storeSession(clientId, mqttSession);
if (mqttSession.isHasWill() && mqttSession.isWillRetain()) {
messageStore.storeMessage(mqttSession.getWillTopic(), new CommonMessage(mqttSession.getWillTopic(), 0, mqttSession.getWillContent().getBytes(StandardCharsets.UTF_8), clientId));
}
// 返回CONNACK控制包
boolean sessionPresent = !isCleanSession && sessionStore.containsKey(clientId);
ctx.channel().writeAndFlush(ZMqttMessageFactory.getConnAck(sessionPresent, MqttConnectReturnCode.CONNECTION_ACCEPTED));
// Clean Session为0,恢复会话
if (!isCleanSession) {
Map<Integer, CommonMessage> dumpMessageMap = messageStore.getDump(clientId);
messageStore.removeDump(clientId);
if (!CollectionUtils.isEmpty(dumpMessageMap)) {
for (CommonMessage commonMessage : dumpMessageMap.values()) {
publishProcessor.forwardPublishMessages(commonMessage.getPayloadBytes(), commonMessage.getTopic(), commonMessage.getQos());
}
}
}
}
}
| 39.20438 | 189 | 0.696518 |
d84027424b4d2402ef392ed31fdc39f4bffcca96 | 10,003 | /*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package com.microsoft.azure.sdk.iot.service;
import com.microsoft.azure.sdk.iot.deps.serializer.*;
import com.microsoft.azure.sdk.iot.deps.twin.DeviceCapabilities;
import com.microsoft.azure.sdk.iot.service.auth.AuthenticationType;
import com.microsoft.azure.sdk.iot.service.auth.SymmetricKey;
/**
* The Device class extends the BaseDevice class
* implementing constructors and serialization functionality.
*/
public class Device extends BaseDevice
{
/**
* Static create function
* Creates device object using the given name.
* If input device status and symmetric key are null then they will be auto generated.
*
* @param deviceId - String containing the device name
* @param status - Device status. If parameter is null, then the status will be set to Enabled.
* @param symmetricKey - Device key. If parameter is null, then the key will be auto generated.
* @return Device object
* @throws IllegalArgumentException This exception is thrown if {@code deviceId} is {@code null} or empty.
*/
public static Device createFromId(String deviceId, DeviceStatus status, SymmetricKey symmetricKey)
throws IllegalArgumentException
{
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_12_002: [The function shall throw IllegalArgumentException if the input string is empty or null]
if (Tools.isNullOrEmpty(deviceId))
{
throw new IllegalArgumentException(deviceId);
}
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_12_003: [The function shall create a new instance
// of Device using the given deviceId and return it]
return new Device(deviceId, status, symmetricKey);
}
/**
* Static create function
* Creates device object using the given name that will use a Certificate Authority signed certificate for authentication.
* If input device status is null then it will be auto generated.
*
* @param deviceId - String containing the device name
* @param authenticationType - The type of authentication used by this device.
* @return Device object
* @throws IllegalArgumentException This exception is thrown if {@code deviceId} is {@code null} or empty.
*/
public static Device createDevice(String deviceId, AuthenticationType authenticationType)
{
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_34_009: [The function shall throw IllegalArgumentException if the provided deviceId or authenticationType is empty or null.]
if (Tools.isNullOrEmpty(deviceId))
{
throw new IllegalArgumentException("The provided device Id must not be null or empty");
}
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_34_009: [The function shall throw IllegalArgumentException if the provided deviceId or authenticationType is empty or null.]
if (authenticationType == null)
{
throw new IllegalArgumentException("The provided authentication type must not be null");
}
return new Device(deviceId, authenticationType);
}
/**
* Create an Device instance using the given device name
*
* @param deviceId Name of the device (used as device id)
* @param status - Device status. If parameter is null, then the status will be set to Enabled.
* @param symmetricKey - Device key. If parameter is null, then the key will be auto generated.
* @throws IllegalArgumentException This exception is thrown if the encryption method is not supported by the keyGenerator
*/
protected Device(String deviceId, DeviceStatus status, SymmetricKey symmetricKey)
throws IllegalArgumentException
{
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_28_001: [The constructor shall set the deviceId, status and symmetricKey.]
super(deviceId, symmetricKey);
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_12_006: [The constructor shall initialize all properties to default values]
this.setPropertiesToDefaultValues();
this.status = status != null ? status : DeviceStatus.Enabled;
}
/**
* Create an Device instance using the given device name that uses a Certificate Authority signed certificate
*
* @param deviceId Name of the device (used as device id)
* @param authenticationType - The type of authentication used by this device.
*/
private Device(String deviceId, AuthenticationType authenticationType)
{
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_28_002: [The constructor shall set the deviceId and symmetricKey.]
super(deviceId, authenticationType);
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_28_003: [The constructor shall initialize all properties to default values]
this.setPropertiesToDefaultValues();
}
// Codes_SRS_SERVICE_SDK_JAVA_DEVICE_12_001: [The Device class shall have the following properties: deviceId, Etag,
// SymmetricKey, ConnectionState, ConnectionStateUpdatedTime, LastActivityTime, symmetricKey, thumbprint, authentication]
/**
* "Enabled", "Disabled".
* If "Enabled", this device is authorized to connect.
* If "Disabled" this device cannot receive or send messages, and statusReason must be set.
*/
protected DeviceStatus status;
/**
* Getter for DeviceStatus object
* @return The deviceStatus object
*/
public DeviceStatus getStatus()
{
return status;
}
/**
* Setter for DeviceStatus object
*
* @param status status to be set
*/
public void setStatus(DeviceStatus status)
{
this.status = status;
}
/**
* A 128 char long string storing the reason of suspension.
* (all UTF-8 chars allowed).
*/
protected String statusReason;
private String scope;
/**
* Getter for status reason
*
* @return The statusReason string
*/
public String getStatusReason()
{
return statusReason;
}
/**
* Datetime of last time the state was updated.
*/
protected String statusUpdatedTime;
/**
* Getter for status updated time string
*
* @return The string containing the time when the statusUpdated parameter was updated
*/
public String getStatusUpdatedTime()
{
return statusUpdatedTime;
}
protected DeviceCapabilities capabilities;
/**
* Getter for capabilities
*
* @return The DeviceCapabilities containing capabilites that are enabled on the device
*/
public DeviceCapabilities getCapabilities()
{
return capabilities;
}
/**
* Setter for DeviceCapabilities object
*
* @param capabilities capabilities to be set
*/
public void setCapabilities(DeviceCapabilities capabilities)
{
this.capabilities = capabilities;
}
/**
* Get the security scope for this device
* @return the security scope for this device
*/
public String getScope()
{
return this.scope;
}
/**
* Set the security scope for this device
* @param scope the security scope to set
*/
public void setScope(String scope)
{
this.scope = scope;
}
/**
* Converts this into a DeviceParser object. To serialize a Device object, it must first be converted to a DeviceParser object.
* @return the DeviceParser object that can be serialized.
*/
DeviceParser toDeviceParser()
{
//Codes_SRS_SERVICE_SDK_JAVA_DEVICE_34_018: [This method shall return a new instance of a DeviceParser object that is populated using the properties of this.]
DeviceParser deviceParser = super.toDeviceParser();
deviceParser.setStatus(this.status.toString());
deviceParser.setStatusReason(this.statusReason);
deviceParser.setStatusUpdatedTime(ParserUtility.getDateTimeUtc(this.statusUpdatedTime));
if (this.capabilities != null)
{
deviceParser.setCapabilities(new DeviceCapabilitiesParser());
deviceParser.getCapabilities().setIotEdge(this.capabilities.isIotEdge());
}
deviceParser.setScope(this.scope);
return deviceParser;
}
/**
* Retrieves information from the provided parser and saves it to this. All information on this will be overwritten.
* @param parser the parser to read from
* @throws IllegalArgumentException if the provided parser is missing the authentication field, or the deviceId field. It also shall
* be thrown if the authentication object in the parser uses SAS authentication and is missing one of the symmetric key fields,
* or if it uses SelfSigned authentication and is missing one of the thumbprint fields.
*/
Device(DeviceParser parser) throws IllegalArgumentException
{
//Codes_SRS_SERVICE_SDK_JAVA_DEVICE_34_014: [This constructor shall create a new Device object using the values within the provided parser.]
super(parser);
this.statusReason = parser.getStatusReason();
if (parser.getCapabilities() != null)
{
this.capabilities = new DeviceCapabilities();
capabilities.setIotEdge(parser.getCapabilities().getIotEdge());
}
if (parser.getStatusUpdatedTime() != null)
{
this.statusUpdatedTime = ParserUtility.getDateStringFromDate(parser.getStatusUpdatedTime());
}
if (parser.getStatus() != null)
{
this.status = DeviceStatus.fromString(parser.getStatus());
}
this.scope = parser.getScope();
}
/*
* Set default properties for a device
*/
private void setPropertiesToDefaultValues()
{
this.status = DeviceStatus.Enabled;
this.statusReason = "";
this.statusUpdatedTime = UTC_TIME_DEFAULT;
this.scope = "";
}
}
| 36.641026 | 169 | 0.688893 |
0bd6ae4b56e6fdc38ff288f0727350a39b11ddbf | 2,055 | package com.octopus.quizon.viewmodel;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.octopus.quizon.data.ListActiveGame;
import com.octopus.quizon.data.ResponseGameId;
import com.octopus.quizon.data.ResponseMoreResult;
import com.octopus.quizon.data.ResponseUser;
import com.octopus.quizon.data.TableResultGame;
import com.octopus.quizon.repos.MenuRepo;
import com.octopus.quizon.repos.RepoRequestState;
import java.util.List;
public class MenuViewModel extends AndroidViewModel {
private MenuRepo mMenuRepo;
private LiveData<TableResultGame> mLastGamesResultsLiveData;
private LiveData<ListActiveGame> mActiveGamesIdsLiveData;
private LiveData<ResponseGameId> mResponseCreateGameLiveData;
private LiveData<ResponseGameId> mResponseJoinGameLiveData;
private LiveData<ResponseUser> mResponseUserLiveData;
private LiveData<RepoRequestState> mRepoRequestStateLiveData;
public MenuViewModel(@NonNull Application application) {
super(application);
mMenuRepo = new MenuRepo(application);
}
public LiveData<TableResultGame> getLastGamesResults() {
mLastGamesResultsLiveData = mMenuRepo.getResult();
return mLastGamesResultsLiveData;
}
public LiveData<ListActiveGame> getActiveGames() {
mActiveGamesIdsLiveData = mMenuRepo.getActiveGames();
return mActiveGamesIdsLiveData;
}
public LiveData<RepoRequestState> getRepoRequestState() {
mRepoRequestStateLiveData = mMenuRepo.getRepoRequestState();
return mRepoRequestStateLiveData;
}
public LiveData<ResponseGameId> createGame(ResponseUser user) {
mResponseCreateGameLiveData = mMenuRepo.createGame(user);
return mResponseCreateGameLiveData;
}
public LiveData<ResponseGameId> joinGame(Long idGame, ResponseUser user) {
mResponseJoinGameLiveData = mMenuRepo.joinGame(idGame, user);
return mResponseJoinGameLiveData;
}
}
| 33.688525 | 78 | 0.778589 |
ffe19e95321fc0704df3f12acc58208d9e60dc69 | 4,862 | /***
Copyright (c) 2014 CommonsWare, LLC
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.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.print;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.support.v4.print.PrintHelper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
public class MainActivity extends Activity {
private static final int IMAGE_REQUEST_ID=1337;
private EditText prose=null;
private WebView wv=null;
private PrintManager mgr=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prose=(EditText)findViewById(R.id.prose);
mgr=(PrintManager)getSystemService(PRINT_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.bitmap:
Intent i=
new Intent(Intent.ACTION_GET_CONTENT).setType("image/*");
startActivityForResult(i, IMAGE_REQUEST_ID);
return(true);
case R.id.web:
printWebPage();
return(true);
case R.id.report:
printReport();
return(true);
case R.id.pdf:
print("Test PDF",
new PdfDocumentAdapter(getApplicationContext()),
new PrintAttributes.Builder().build());
return(true);
}
return(super.onOptionsItemSelected(item));
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == IMAGE_REQUEST_ID
&& resultCode == Activity.RESULT_OK) {
try {
PrintHelper help=new PrintHelper(this);
help.setScaleMode(PrintHelper.SCALE_MODE_FIT);
help.printBitmap("Photo!", data.getData());
}
catch (FileNotFoundException e) {
Log.e(getClass().getSimpleName(), "Exception printing bitmap",
e);
}
}
}
private void printWebPage() {
WebView print=prepPrintWebView(getString(R.string.web_page));
print.loadUrl("https://commonsware.com/Android");
}
private void printReport() {
Template tmpl=
Mustache.compiler().compile(getString(R.string.report_body));
WebView print=prepPrintWebView(getString(R.string.tps_report));
print.loadData(tmpl.execute(new TpsReportContext(prose.getText()
.toString())),
"text/html", "UTF-8");
}
private WebView prepPrintWebView(final String name) {
WebView result=getWebView();
result.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
print(name, view.createPrintDocumentAdapter(),
new PrintAttributes.Builder().build());
}
});
return(result);
}
private WebView getWebView() {
if (wv == null) {
wv=new WebView(this);
}
return(wv);
}
private PrintJob print(String name, PrintDocumentAdapter adapter,
PrintAttributes attrs) {
startService(new Intent(this, PrintJobMonitorService.class));
return(mgr.print(name, adapter, attrs));
}
private static class TpsReportContext {
private static final SimpleDateFormat fmt=
new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String msg;
TpsReportContext(String msg) {
this.msg=msg;
}
@SuppressWarnings("unused")
String getReportDate() {
return(fmt.format(new Date()));
}
@SuppressWarnings("unused")
String getMessage() {
return(msg);
}
}
}
| 27.942529 | 79 | 0.680173 |
14cc455a7551b14833b37f6c090c3e0dbdbd03cd | 2,993 | package etl.model;
import java.math.BigInteger;
/**
* A single store-format record to be inserted. A dumb data structure.
*/
public class FileRecord {
private BigInteger productId;
private String productDescription;
private Money regularSingularPrice;
private Money promotionalSingularPrice;
private Money regularSplitPrice;
private Money promotionalSplitPrice;
private BigInteger regularForX;
private BigInteger promotionalForX;
private boolean[] flags;
private String productSize;
private String sourceFilename;
private long sourceFileLastModified;
public BigInteger getProductId() {
return productId;
}
public void setProductId(BigInteger productId) {
this.productId = productId;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public Money getRegularSingularPrice() {
return regularSingularPrice;
}
public void setRegularSingularPrice(Money regularSingularPrice) {
this.regularSingularPrice = regularSingularPrice;
}
public Money getPromotionalSingularPrice() {
return promotionalSingularPrice;
}
public void setPromotionalSingularPrice(Money promotionalSingularPrice) {
this.promotionalSingularPrice = promotionalSingularPrice;
}
public Money getRegularSplitPrice() {
return regularSplitPrice;
}
public void setRegularSplitPrice(Money regularSplitPrice) {
this.regularSplitPrice = regularSplitPrice;
}
public Money getPromotionalSplitPrice() {
return promotionalSplitPrice;
}
public void setPromotionalSplitPrice(Money promotionalSplitPrice) {
this.promotionalSplitPrice = promotionalSplitPrice;
}
public BigInteger getRegularForX() {
return regularForX;
}
public void setRegularForX(BigInteger regularForX) {
this.regularForX = regularForX;
}
public BigInteger getPromotionalForX() {
return promotionalForX;
}
public void setPromotionalForX(BigInteger promotionalForX) {
this.promotionalForX = promotionalForX;
}
public boolean[] getFlags() {
return flags;
}
public void setFlags(boolean[] flags) {
this.flags = flags;
}
public String getProductSize() {
return productSize;
}
public void setProductSize(String productSize) {
this.productSize = productSize;
}
public String getSourceFilename() {
return sourceFilename;
}
public void setSourceFilename(String filename) {
sourceFilename = filename;
}
public long getSourceFileLastModified() {
return sourceFileLastModified;
}
public void setSourceFileLastModified(long timeInMsPastTheEpoch) {
sourceFileLastModified = timeInMsPastTheEpoch;
}
}
| 24.941667 | 77 | 0.702974 |
6655469ce6a383c7e7d19c6d5201fe6e1b3c3780 | 2,076 | package people.jobs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import people.conf.PeopleConfig;
import people.dict.NamesDictionary;
import people.dict.WordDictionaryWriter;
import people.dict.model.Gender;
import people.dict.model.PersonName;
import people.dict.model.NounDeclination;
import people.dict.model.WordRef;
/**
* Filter Polish dictionary published by SJP.pl and filter all first names
*
*/
public class NamesFromSJPGenerator {
private static NamesDictionary dict = new NamesDictionary();
public static void main(final String[] args) {
System.out.println("Processing...");
try {
dict.loadNamesFromResource();
WordDictionaryWriter output = new WordDictionaryWriter(PeopleConfig.DATA_FOLDER + "/names_fulldict2.csv");
readSPJDict("d:/databases/aspell/odm.txt", output);
output.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
System.out.println("Done.");
}
private static void readSPJDict(String filePath, WordDictionaryWriter output) throws IOException {
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.forEach(line -> {
String[] args = line.split(", ?");
if (args != null && args[0] != null) {
PersonName name = dict.getFirst(args[0]);
if (name != null) {
PersonName mainForm = generateMainForm(name.getText(), name.getGender());
output.accept(mainForm);
for (int i=1; i < args.length; ++i) {
output.accept(generateDeclinedForm(mainForm, args[i]));
}
}
}
});
}
}
private static PersonName generateMainForm(String text, Gender gender) {
PersonName fn = new PersonName(text, NounDeclination.M);
fn.setGender(gender);
return fn;
}
private static PersonName generateDeclinedForm(PersonName mainForm, String text) {
PersonName fn = new PersonName(text, NounDeclination.UNKNOWN);
fn.setGender(mainForm.getGender());
fn.setRef(new WordRef(mainForm));
return fn;
}
}
| 29.657143 | 109 | 0.712909 |
856aaaa3d8df3f132cc82f81b1a0ade7b7e52d86 | 8,424 | package com.example.awesometic.facetalk;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Singleton single = Singleton.getInstance();
private DBConnect dbConn = new DBConnect(MainActivity.this, MainActivity.this);
/* NavigationView References:
Android navigation drawer reference project
http://www.android4devs.com/2015/06/navigation-view-material-design-support.html
http://www.technotalkative.com/part-4-playing-with-navigationview/
*/
private DrawerLayout drawer;
private MainFragment fragMain;
private FriendsFragment fragFriends;
private SetupFragment fragSetup;
private NavigationView navigationView;
private SubMenu subMenu;
private BackPressCloseHandler backPressCloseHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Close when press back button twice
backPressCloseHandler = new BackPressCloseHandler(this);
// Fragments
fragMain = MainFragment.newInstance();
fragFriends = FriendsFragment.newInstance();
fragSetup = SetupFragment.newInstance();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
updateNavigationView();
// Change nickname and email at navigation header
View navHeaderView = navigationView.inflateHeaderView(R.layout.nav_header);
TextView tvNavHeadNick = (TextView) navHeaderView.findViewById(R.id.nav_head_nickname);
TextView tvNavHeadEmail = (TextView) navHeaderView.findViewById(R.id.nav_head_email);
tvNavHeadNick.setText(single.getCurrentUserNickname());
tvNavHeadEmail.setText(single.getCurrentUserEmail());
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragMain)
.detach(fragMain).attach(fragMain)
.commit();
}
@Override
public void onBackPressed() {
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
// super.onBackPressed();
backPressCloseHandler.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
Toast.makeText(MainActivity.this, "logout", Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("logout", true);
startActivity(intent);
finish();
return true;
} else if (id == R.id.action_exit) {
moveTaskToBack(true);
finish();
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
int id = item.getItemId();
switch (id) {
case R.id.nav_home:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragMain)
.detach(fragMain).attach(fragMain)
.commit();
break;
case R.id.nav_add_friend:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragFriends)
.detach(fragFriends).attach(fragFriends)
.commit();
break;
case R.id.nav_remove_friend:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragFriends)
.detach(fragFriends).attach(fragFriends)
.commit();
break;
case R.id.nav_setup:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragSetup)
.detach(fragSetup).attach(fragSetup)
.commit();
break;
default:
// http://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android
ChatFragment fragChat = ChatFragment.newInstance();
Bundle bundle = new Bundle();
int index = -1;
for (int i = 0; i < subMenu.size(); i++) {
if (subMenu.getItem(i).getTitle().toString().contains(item.getTitle().toString())
&& i != subMenu.size() - 1) {
index = Integer.valueOf(subMenu.getItem(i + 1).getTitle().toString().split("::")[1]);
break;
}
}
bundle.putInt("friendidx", index);
fragChat.setArguments(bundle);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragChat)
.detach(fragChat).attach(fragChat)
.commit();
break;
}
if (id == R.id.nav_home)
setTitle(R.string.app_name);
else
setTitle(item.getTitle());
drawer.closeDrawers();
return true;
}
private String[] getFriendList(int useridx) {
try {
JSONArray jsonArr_friends = dbConn.getFriend(useridx);
single.setCurrentFriends(jsonArr_friends);
List<String> list_friends = new ArrayList<>();
for (int i = 0; i < jsonArr_friends.length(); i++) {
JSONObject jsonObj_friend = jsonArr_friends.getJSONObject(i);
list_friends.add(jsonObj_friend.getString("nickname") + "::" + jsonObj_friend.getString("idx"));
}
return list_friends.toArray(new String[list_friends.size()]);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public void updateNavigationView() {
String[] mDrawerTitles = getFriendList(single.getCurrentUserIdx());
final Menu menu = navigationView.getMenu();
menu.clear();
subMenu = menu.addSubMenu("Friends: " + dbConn.getFriendCount(single.getCurrentUserIdx()));
for (int i = 0; i < mDrawerTitles.length; i++) {
subMenu.add(mDrawerTitles[i].split("::")[0]);
subMenu.add(mDrawerTitles[i]).setVisible(false);
}
navigationView.inflateMenu(R.menu.nav_list_item);
}
}
| 37.110132 | 112 | 0.621201 |
22c067f1e8a43cace8fa4eb52cb006ebf0bacc7a | 12,405 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver13;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFPortDescPropOpticalTransportVer13 implements OFPortDescPropOpticalTransport {
private static final Logger logger = LoggerFactory.getLogger(OFPortDescPropOpticalTransportVer13.class);
// version: 1.3
final static byte WIRE_VERSION = 4;
final static int LENGTH = 8;
private final static int DEFAULT_TYPE = 0x0;
private final static short DEFAULT_PORT_SIGNAL_TYPE = (short) 0x0;
private final static short DEFAULT_RESERVED = (short) 0x0;
private final static short DEFAULT_PORT_TYPE = (short) 0x0;
// OF message fields
private final int type;
private final short portSignalType;
private final short reserved;
private final short portType;
//
// Immutable default instance
final static OFPortDescPropOpticalTransportVer13 DEFAULT = new OFPortDescPropOpticalTransportVer13(
DEFAULT_TYPE, DEFAULT_PORT_SIGNAL_TYPE, DEFAULT_RESERVED, DEFAULT_PORT_TYPE
);
// package private constructor - used by readers, builders, and factory
OFPortDescPropOpticalTransportVer13(int type, short portSignalType, short reserved, short portType) {
this.type = type;
this.portSignalType = portSignalType;
this.reserved = reserved;
this.portType = portType;
}
// Accessors for OF message fields
@Override
public int getType() {
return type;
}
@Override
public short getPortSignalType() {
return portSignalType;
}
@Override
public short getReserved() {
return reserved;
}
@Override
public short getPortType() {
return portType;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
public OFPortDescPropOpticalTransport.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFPortDescPropOpticalTransport.Builder {
final OFPortDescPropOpticalTransportVer13 parentMessage;
// OF message fields
private boolean typeSet;
private int type;
private boolean portSignalTypeSet;
private short portSignalType;
private boolean reservedSet;
private short reserved;
private boolean portTypeSet;
private short portType;
BuilderWithParent(OFPortDescPropOpticalTransportVer13 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public int getType() {
return type;
}
@Override
public OFPortDescPropOpticalTransport.Builder setType(int type) {
this.type = type;
this.typeSet = true;
return this;
}
@Override
public short getPortSignalType() {
return portSignalType;
}
@Override
public OFPortDescPropOpticalTransport.Builder setPortSignalType(short portSignalType) {
this.portSignalType = portSignalType;
this.portSignalTypeSet = true;
return this;
}
@Override
public short getReserved() {
return reserved;
}
@Override
public OFPortDescPropOpticalTransport.Builder setReserved(short reserved) {
this.reserved = reserved;
this.reservedSet = true;
return this;
}
@Override
public short getPortType() {
return portType;
}
@Override
public OFPortDescPropOpticalTransport.Builder setPortType(short portType) {
this.portType = portType;
this.portTypeSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
@Override
public OFPortDescPropOpticalTransport build() {
int type = this.typeSet ? this.type : parentMessage.type;
short portSignalType = this.portSignalTypeSet ? this.portSignalType : parentMessage.portSignalType;
short reserved = this.reservedSet ? this.reserved : parentMessage.reserved;
short portType = this.portTypeSet ? this.portType : parentMessage.portType;
//
return new OFPortDescPropOpticalTransportVer13(
type,
portSignalType,
reserved,
portType
);
}
}
static class Builder implements OFPortDescPropOpticalTransport.Builder {
// OF message fields
private boolean typeSet;
private int type;
private boolean portSignalTypeSet;
private short portSignalType;
private boolean reservedSet;
private short reserved;
private boolean portTypeSet;
private short portType;
@Override
public int getType() {
return type;
}
@Override
public OFPortDescPropOpticalTransport.Builder setType(int type) {
this.type = type;
this.typeSet = true;
return this;
}
@Override
public short getPortSignalType() {
return portSignalType;
}
@Override
public OFPortDescPropOpticalTransport.Builder setPortSignalType(short portSignalType) {
this.portSignalType = portSignalType;
this.portSignalTypeSet = true;
return this;
}
@Override
public short getReserved() {
return reserved;
}
@Override
public OFPortDescPropOpticalTransport.Builder setReserved(short reserved) {
this.reserved = reserved;
this.reservedSet = true;
return this;
}
@Override
public short getPortType() {
return portType;
}
@Override
public OFPortDescPropOpticalTransport.Builder setPortType(short portType) {
this.portType = portType;
this.portTypeSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
//
@Override
public OFPortDescPropOpticalTransport build() {
int type = this.typeSet ? this.type : DEFAULT_TYPE;
short portSignalType = this.portSignalTypeSet ? this.portSignalType : DEFAULT_PORT_SIGNAL_TYPE;
short reserved = this.reservedSet ? this.reserved : DEFAULT_RESERVED;
short portType = this.portTypeSet ? this.portType : DEFAULT_PORT_TYPE;
return new OFPortDescPropOpticalTransportVer13(
type,
portSignalType,
reserved,
portType
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFPortDescPropOpticalTransport> {
@Override
public OFPortDescPropOpticalTransport readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
int type = U16.f(bb.readShort());
int length = U16.f(bb.readShort());
if(length != 8)
throw new OFParseError("Wrong length: Expected=8(8), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
short portSignalType = U8.f(bb.readByte());
short reserved = U8.f(bb.readByte());
// pad: 1 bytes
bb.skipBytes(1);
short portType = U8.f(bb.readByte());
OFPortDescPropOpticalTransportVer13 portDescPropOpticalTransportVer13 = new OFPortDescPropOpticalTransportVer13(
type,
portSignalType,
reserved,
portType
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", portDescPropOpticalTransportVer13);
return portDescPropOpticalTransportVer13;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFPortDescPropOpticalTransportVer13Funnel FUNNEL = new OFPortDescPropOpticalTransportVer13Funnel();
static class OFPortDescPropOpticalTransportVer13Funnel implements Funnel<OFPortDescPropOpticalTransportVer13> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFPortDescPropOpticalTransportVer13 message, PrimitiveSink sink) {
sink.putInt(message.type);
// fixed value property length = 8
sink.putShort((short) 0x8);
sink.putShort(message.portSignalType);
sink.putShort(message.reserved);
// skip pad (1 bytes)
sink.putShort(message.portType);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFPortDescPropOpticalTransportVer13> {
@Override
public void write(ByteBuf bb, OFPortDescPropOpticalTransportVer13 message) {
bb.writeShort(U16.t(message.type));
// fixed value property length = 8
bb.writeShort((short) 0x8);
bb.writeByte(U8.t(message.portSignalType));
bb.writeByte(U8.t(message.reserved));
// pad: 1 bytes
bb.writeZero(1);
bb.writeByte(U8.t(message.portType));
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFPortDescPropOpticalTransportVer13(");
b.append("type=").append(type);
b.append(", ");
b.append("portSignalType=").append(portSignalType);
b.append(", ");
b.append("reserved=").append(reserved);
b.append(", ");
b.append("portType=").append(portType);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFPortDescPropOpticalTransportVer13 other = (OFPortDescPropOpticalTransportVer13) obj;
if( type != other.type)
return false;
if( portSignalType != other.portSignalType)
return false;
if( reserved != other.reserved)
return false;
if( portType != other.portType)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + type;
result = prime * result + portSignalType;
result = prime * result + reserved;
result = prime * result + portType;
return result;
}
}
| 32.137306 | 124 | 0.644095 |
a561102e38f13c6890102f39321b5c8d1a2d0c1c | 1,058 | package org.davidmoten.executors.more;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public final class Executors {
private Executors() {
// prevent instantiation
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return newThreadPool(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, false,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime,
TimeUnit unit, boolean allowThreadCoreTimeout, BlockingQueue<Runnable> workQueue) {
return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, allowThreadCoreTimeout,
workQueue);
}
public static ThreadFactory defaultThreadFactory() {
return java.util.concurrent.Executors.defaultThreadFactory();
}
}
| 34.129032 | 113 | 0.747637 |
b63cda8ed521b35f6f81c49887c6c8de77bc7a7b | 694 | package org.smartframework.cloud.examples.mall.rpc.enums.order;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 支付状态(1:待支付;2:支付成功;3:支付失败;4:待退款;5:退款成功;6:退款失败)
*
* @author liyulin
* @date 2019-04-16
*/
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public enum PayStateEnum {
/**
* 待支付
*/
PENDING_PAY((byte) 1),
/**
* 支付成功
*/
PAY_SUCCESS((byte) 2),
/**
* 支付失败
*/
PAY_FAIL((byte) 3),
/**
* 待退款
*/
PENDING_REFUND((byte) 4),
/**
* 退款成功
*/
PENDING_SUCCESS((byte) 5),
/**
* 退款失败
*/
PENDING_FAIL((byte) 6);
private byte value;
} | 15.772727 | 63 | 0.563401 |
100650d43bd86ebb8fcac7006e732ae7417af47c | 19,794 | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.state;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.AbstractModule;
import com.yahoo.component.Vtag;
import com.yahoo.container.core.ApplicationMetadataConfig;
import com.yahoo.container.jdisc.config.HealthMonitorConfig;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.Timer;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.application.MetricConsumer;
import com.yahoo.jdisc.handler.BufferedContentChannel;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
import com.yahoo.metrics.MetricsPresentationConfig;
import com.yahoo.vespa.defaults.Defaults;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Simon Thoresen Hult
*/
public class StateHandlerTest {
private final static long SNAPSHOT_INTERVAL = TimeUnit.SECONDS.toMillis(300);
private final static long META_GENERATION = 69;
private TestDriver driver;
private StateMonitor monitor;
private Metric metric;
private volatile long currentTimeMillis = 0;
@Before
public void startTestDriver() {
driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@Override
protected void configure() {
bind(Timer.class).toInstance(new Timer() {
@Override
public long currentTimeMillis() {
return currentTimeMillis;
}
});
}
});
ContainerBuilder builder = driver.newContainerBuilder();
builder.guiceModules().install(new AbstractModule() {
@Override
protected void configure() {
bind(HealthMonitorConfig.class)
.toInstance(new HealthMonitorConfig(new HealthMonitorConfig.Builder().snapshot_interval(
TimeUnit.MILLISECONDS.toSeconds(SNAPSHOT_INTERVAL))));
}
});
monitor = builder.guiceModules().getInstance(StateMonitor.class);
builder.guiceModules().install(new AbstractModule() {
@Override
protected void configure() {
bind(StateMonitor.class).toInstance(monitor);
bind(MetricConsumer.class).toProvider(MetricConsumerProviders.wrap(monitor));
bind(ApplicationMetadataConfig.class).toInstance(new ApplicationMetadataConfig(
new ApplicationMetadataConfig.Builder().generation(META_GENERATION)));
bind(MetricsPresentationConfig.class)
.toInstance(new MetricsPresentationConfig(new MetricsPresentationConfig.Builder()));
}
});
builder.serverBindings().bind("http://*/*", builder.getInstance(StateHandler.class));
driver.activateContainer(builder);
metric = builder.getInstance(Metric.class);
}
@After
public void stopTestDriver() {
assertTrue(driver.close());
}
@Test
public void testReportPriorToFirstSnapshot() throws Exception {
metric.add("foo", 1, null);
metric.set("bar", 4, null);
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertEquals(json.toString(), "up", json.get("status").get("code").asText());
assertFalse(json.toString(), json.get("metrics").has("values"));
}
@Test
public void testReportIncludesMetricsAfterSnapshot() throws Exception {
metric.add("foo", 1, null);
metric.set("bar", 4, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json1 = requestAsJson("http://localhost/state/v1/metrics");
assertEquals(json1.toString(), "up", json1.get("status").get("code").asText());
assertEquals(json1.toString(), 2, json1.get("metrics").get("values").size());
metric.add("fuz", 1, metric.createContext(new HashMap<>(0)));
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json2 = requestAsJson("http://localhost/state/v1/metrics");
assertEquals(json2.toString(), "up", json2.get("status").get("code").asText());
assertEquals(json2.toString(), 3, json2.get("metrics").get("values").size());
}
/**
* Tests that we restart an metric when it changes type from gauge to counter or back.
* This may happen in practice on config reloads.
*/
@Test
public void testMetricTypeChangeIsAllowed() {
String metricName = "myMetric";
Metric.Context metricContext = null;
{
// Add a count metric
metric.add(metricName, 1, metricContext);
metric.add(metricName, 2, metricContext);
// Change it to a gauge metric
metric.set(metricName, 9, metricContext);
incrementCurrentTime(SNAPSHOT_INTERVAL);
MetricValue resultingMetric = monitor.snapshot().iterator().next().getValue().get(metricName);
assertEquals(GaugeMetric.class, resultingMetric.getClass());
assertEquals("Value was reset and produces the last gauge value",
9.0, ((GaugeMetric) resultingMetric).getLast(), 0.000001);
}
{
// Add a gauge metric
metric.set(metricName, 9, metricContext);
// Change it to a count metric
metric.add(metricName, 1, metricContext);
metric.add(metricName, 2, metricContext);
incrementCurrentTime(SNAPSHOT_INTERVAL);
MetricValue resultingMetric = monitor.snapshot().iterator().next().getValue().get(metricName);
assertEquals(CountMetric.class, resultingMetric.getClass());
assertEquals("Value was reset, and changed to add semantics giving 1+2",
3, ((CountMetric) resultingMetric).getCount());
}
}
@Test
public void testAverageAggregationOfValues() throws Exception {
metric.set("bar", 4, null);
metric.set("bar", 5, null);
metric.set("bar", 7, null);
metric.set("bar", 2, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertEquals(json.toString(), "up", json.get("status").get("code").asText());
assertEquals(json.toString(), 1, json.get("metrics").get("values").size());
assertEquals(json.toString(), 4.5,
json.get("metrics").get("values").get(0).get("values").get("average").asDouble(), 0.001);
}
@Test
public void testSumAggregationOfCounts() throws Exception {
metric.add("foo", 1, null);
metric.add("foo", 1, null);
metric.add("foo", 2, null);
metric.add("foo", 1, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertEquals(json.toString(), "up", json.get("status").get("code").asText());
assertEquals(json.toString(), 1, json.get("metrics").get("values").size());
assertEquals(json.toString(), 5,
json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001);
}
@Test
public void testReadabilityOfJsonReport() throws Exception {
metric.add("foo", 1, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
assertEquals("{\n" +
" \"metrics\": {\n" +
" \"snapshot\": {\n" +
" \"from\": 0,\n" +
" \"to\": 300\n" +
" },\n" +
" \"values\": [{\n" +
" \"name\": \"foo\",\n" +
" \"values\": {\n" +
" \"count\": 1,\n" +
" \"rate\": 0.0033333333333333335\n" +
" }\n" +
" }]\n" +
" },\n" +
" \"status\": {\"code\": \"up\"},\n" +
" \"time\": 300000\n" +
"}",
requestAsString("http://localhost/state/v1/all"));
Metric.Context ctx = metric.createContext(Collections.singletonMap("component", "test"));
metric.set("bar", 2, ctx);
metric.set("bar", 3, ctx);
metric.set("bar", 4, ctx);
metric.set("bar", 5, ctx);
incrementCurrentTime(SNAPSHOT_INTERVAL);
assertEquals("{\n" +
" \"metrics\": {\n" +
" \"snapshot\": {\n" +
" \"from\": 300,\n" +
" \"to\": 600\n" +
" },\n" +
" \"values\": [\n" +
" {\n" +
" \"name\": \"foo\",\n" +
" \"values\": {\n" +
" \"count\": 0,\n" +
" \"rate\": 0\n" +
" }\n" +
" },\n" +
" {\n" +
" \"dimensions\": {\"component\": \"test\"},\n" +
" \"name\": \"bar\",\n" +
" \"values\": {\n" +
" \"average\": 3.5,\n" +
" \"count\": 4,\n" +
" \"last\": 5,\n" +
" \"max\": 5,\n" +
" \"min\": 2,\n" +
" \"rate\": 0.013333333333333334\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"status\": {\"code\": \"up\"},\n" +
" \"time\": 600000\n" +
"}",
requestAsString("http://localhost/state/v1/all"));
}
@Test
public void testNotAggregatingCountsBeyondSnapshots() throws Exception {
metric.add("foo", 1, null);
metric.add("foo", 1, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
metric.add("foo", 2, null);
metric.add("foo", 1, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertEquals(json.toString(), "up", json.get("status").get("code").asText());
assertEquals(json.toString(), 1, json.get("metrics").get("values").size());
assertEquals(json.toString(), 3,
json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001);
}
@Test
public void testSnapshottingTimes() throws Exception {
metric.add("foo", 1, null);
metric.set("bar", 3, null);
// At this time we should not have done any snapshotting
incrementCurrentTime(SNAPSHOT_INTERVAL - 1);
{
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertFalse(json.toString(), json.get("metrics").has("snapshot"));
}
// At this time first snapshot should have been generated
incrementCurrentTime(1);
{
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertTrue(json.toString(), json.get("metrics").has("snapshot"));
assertEquals(0.0, json.get("metrics").get("snapshot").get("from").asDouble(), 0.00001);
assertEquals(300.0, json.get("metrics").get("snapshot").get("to").asDouble(), 0.00001);
}
// No new snapshot at this time
incrementCurrentTime(SNAPSHOT_INTERVAL - 1);
{
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertTrue(json.toString(), json.get("metrics").has("snapshot"));
assertEquals(0.0, json.get("metrics").get("snapshot").get("from").asDouble(), 0.00001);
assertEquals(300.0, json.get("metrics").get("snapshot").get("to").asDouble(), 0.00001);
}
// A new snapshot
incrementCurrentTime(1);
{
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertTrue(json.toString(), json.get("metrics").has("snapshot"));
assertEquals(300.0, json.get("metrics").get("snapshot").get("from").asDouble(), 0.00001);
assertEquals(600.0, json.get("metrics").get("snapshot").get("to").asDouble(), 0.00001);
}
}
@Test
public void testFreshStartOfValuesBeyondSnapshot() throws Exception {
metric.set("bar", 4, null);
metric.set("bar", 5, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
metric.set("bar", 4, null);
metric.set("bar", 2, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json = requestAsJson("http://localhost/state/v1/all");
assertEquals(json.toString(), "up", json.get("status").get("code").asText());
assertEquals(json.toString(), 1, json.get("metrics").get("values").size());
assertEquals(json.toString(), 3,
json.get("metrics").get("values").get(0).get("values").get("average").asDouble(), 0.001);
}
@Test
public void snapshotsPreserveLastGaugeValue() throws Exception {
metric.set("bar", 4, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json = requestAsJson("http://localhost/state/v1/all");
JsonNode metricValues = getFirstMetricValueNode(json);
assertEquals(json.toString(), 4, metricValues.get("last").asDouble(), 0.001);
// Use 'last' as avg/min/max when none has been set explicitly during snapshot period
assertEquals(json.toString(), 4, metricValues.get("average").asDouble(), 0.001);
assertEquals(json.toString(), 4, metricValues.get("min").asDouble(), 0.001);
assertEquals(json.toString(), 4, metricValues.get("max").asDouble(), 0.001);
// Count is tracked per period.
assertEquals(json.toString(), 0, metricValues.get("count").asInt());
}
private JsonNode getFirstMetricValueNode(JsonNode root) {
assertEquals(root.toString(), 1, root.get("metrics").get("values").size());
JsonNode metricValues = root.get("metrics").get("values").get(0).get("values");
assertTrue(root.toString(), metricValues.has("last"));
return metricValues;
}
@Test
public void gaugeSnapshotsTracksCountMinMaxAvgPerPeriod() throws Exception {
metric.set("bar", 10000, null); // Ensure any cross-snapshot noise is visible
incrementCurrentTime(SNAPSHOT_INTERVAL);
metric.set("bar", 20, null);
metric.set("bar", 40, null);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json = requestAsJson("http://localhost/state/v1/all");
JsonNode metricValues = getFirstMetricValueNode(json);
assertEquals(json.toString(), 40, metricValues.get("last").asDouble(), 0.001);
// Last snapshot had explicit values set
assertEquals(json.toString(), 30, metricValues.get("average").asDouble(), 0.001);
assertEquals(json.toString(), 20, metricValues.get("min").asDouble(), 0.001);
assertEquals(json.toString(), 40, metricValues.get("max").asDouble(), 0.001);
assertEquals(json.toString(), 2, metricValues.get("count").asInt());
}
@Test
public void testHealthAggregation() throws Exception {
Map<String, String> dimensions1 = new TreeMap<>();
dimensions1.put("port", String.valueOf(Defaults.getDefaults().vespaWebServicePort()));
Metric.Context context1 = metric.createContext(dimensions1);
Map<String, String> dimensions2 = new TreeMap<>();
dimensions2.put("port", "80");
Metric.Context context2 = metric.createContext(dimensions2);
metric.add("serverNumSuccessfulResponses", 4, context1);
metric.add("serverNumSuccessfulResponses", 2, context2);
metric.set("serverTotalSuccessfulResponseLatency", 20, context1);
metric.set("serverTotalSuccessfulResponseLatency", 40, context2);
metric.add("random", 3, context1);
incrementCurrentTime(SNAPSHOT_INTERVAL);
JsonNode json = requestAsJson("http://localhost/state/v1/health");
assertEquals(json.toString(), "up", json.get("status").get("code").asText());
assertEquals(json.toString(), 2, json.get("metrics").get("values").size());
assertEquals(json.toString(), "requestsPerSecond",
json.get("metrics").get("values").get(0).get("name").asText());
assertEquals(json.toString(), 6,
json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001);
assertEquals(json.toString(), "latencySeconds",
json.get("metrics").get("values").get(1).get("name").asText());
assertEquals(json.toString(), 0.03,
json.get("metrics").get("values").get(1).get("values").get("average").asDouble(), 0.001);
}
@Test
public void testStateConfig() throws Exception {
JsonNode root = requestAsJson("http://localhost/state/v1/config");
JsonNode config = root.get("config");
JsonNode container = config.get("container");
assertEquals(META_GENERATION, container.get("generation").asLong());
}
@Test
public void testStateVersion() throws Exception {
JsonNode root = requestAsJson("http://localhost/state/v1/version");
JsonNode version = root.get("version");
assertEquals(Vtag.currentVersion.toString(), version.asText());
}
private void incrementCurrentTime(long val) {
currentTimeMillis += val;
monitor.checkTime();
}
private String requestAsString(String requestUri) throws Exception {
final BufferedContentChannel content = new BufferedContentChannel();
Response response = driver.dispatchRequest(requestUri, new ResponseHandler() {
@Override
public ContentChannel handleResponse(Response response) {
return content;
}
}).get(60, TimeUnit.SECONDS);
assertNotNull(response);
assertEquals(Response.Status.OK, response.getStatus());
StringBuilder str = new StringBuilder();
Reader in = new InputStreamReader(content.toStream(), StandardCharsets.UTF_8);
for (int c; (c = in.read()) != -1; ) {
str.append((char)c);
}
return str.toString();
}
private JsonNode requestAsJson(String requestUri) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(mapper.getFactory().createParser(requestAsString(requestUri)));
}
}
| 45.925754 | 118 | 0.577953 |
48f8f84c488c187af73d27f48758d446a48cdec6 | 93 | package com.artezio.arttime.web;
public enum EffortsGrouping {
BY_PROJECTS, BY_EMPLOYEES
}
| 15.5 | 32 | 0.806452 |
491a13f5a5f69324bec20f844bb5f2211a0b2e6e | 779 | package designs.ecommerce;
import java.util.List;
//Subject
public class InventoryProduct {
Product product;
public InventoryProduct(Product p) {
this.product = p;
}
List<InventoryProductObservers> observers;
void RegisterObserver(InventoryProductObservers observer) {
observers.add(observer);
}
void DeRegisterObserver(InventoryProductObservers observer) {
observers.removeIf(e -> e.equals(observer));
}
void notifyCartsToAddQuantity(int increasedQuantity) {
observers.forEach(o -> o.notificationToAddProduct(this));
}
void notifyCartsTodecreaseQuantity(int decreasedQuantity) {
observers.forEach(o -> o.notificationToRemoveProduct(this));
}
public Product getP() {
return product;
}
public void setP(Product p) {
this.product = p;
}
}
| 19 | 62 | 0.757381 |
10372ff655ae8d4d01acb29e7ee59f61413144ef | 3,050 | // SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2020-2021 MariaDB Corporation Ab
package org.mariadb.r2dbc.client;
public class ServerVersion {
public static final ServerVersion UNKNOWN_VERSION = new ServerVersion("0.0.0", true);
private final String serverVersion;
private final int majorVersion;
private final int minorVersion;
private final int patchVersion;
private final boolean mariaDBServer;
private final boolean supportReturning;
public ServerVersion(String serverVersion, boolean mariaDBServer) {
this.serverVersion = serverVersion;
this.mariaDBServer = mariaDBServer;
int[] parsed = parseVersion(serverVersion);
this.majorVersion = parsed[0];
this.minorVersion = parsed[1];
this.patchVersion = parsed[2];
this.supportReturning = mariaDBServer && versionGreaterOrEqual(10, 5, 1);
}
public boolean isMariaDBServer() {
return mariaDBServer;
}
public int getMajorVersion() {
return majorVersion;
}
public int getMinorVersion() {
return minorVersion;
}
public int getPatchVersion() {
return patchVersion;
}
public String getServerVersion() {
return serverVersion;
}
public boolean supportReturning() {
return supportReturning;
}
/**
* Utility method to check if database version is greater than parameters.
*
* @param major major version
* @param minor minor version
* @param patch patch version
* @return true if version is greater than parameters
*/
public boolean versionGreaterOrEqual(int major, int minor, int patch) {
if (this.majorVersion > major) {
return true;
}
if (this.majorVersion < major) {
return false;
}
/*
* Major versions are equal, compare minor versions
*/
if (this.minorVersion > minor) {
return true;
}
if (this.minorVersion < minor) {
return false;
}
// Minor versions are equal, compare patch version.
return this.patchVersion >= patch;
}
private int[] parseVersion(String serverVersion) {
int length = serverVersion.length();
char car;
int offset = 0;
int type = 0;
int val = 0;
int majorVersion = 0;
int minorVersion = 0;
int patchVersion = 0;
main_loop:
for (; offset < length; offset++) {
car = serverVersion.charAt(offset);
if (car < '0' || car > '9') {
switch (type) {
case 0:
majorVersion = val;
break;
case 1:
minorVersion = val;
break;
case 2:
patchVersion = val;
break main_loop;
default:
break;
}
type++;
val = 0;
} else {
val = val * 10 + car - 48;
}
}
// serverVersion finished by number like "5.5.57", assign patchVersion
if (type == 2) {
patchVersion = val;
}
return new int[] {majorVersion, minorVersion, patchVersion};
}
@Override
public String toString() {
return "ServerVersion{" + serverVersion + '}';
}
}
| 24.015748 | 87 | 0.628525 |
581a6979cd34dcda99342cd85e7a3636d52b9f2f | 1,694 | /*
* Copyright 2017-2021 original 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
*
* https://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.micronaut.data.model.jpa.criteria.impl;
import io.micronaut.core.annotation.Internal;
import io.micronaut.data.model.jpa.criteria.PersistentPropertyPath;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Order;
/**
* The implementation of {@link Order}.
*
* @param <T> The property type
* @author Denis Stepanov
* @since 3.2
*/
@Internal
public final class PersistentPropertyOrder<T> implements Order {
private final PersistentPropertyPath<T> persistentPropertyPath;
private final boolean ascending;
public PersistentPropertyOrder(PersistentPropertyPath<T> persistentPropertyPath, boolean ascending) {
this.persistentPropertyPath = persistentPropertyPath;
this.ascending = ascending;
}
@Override
public Order reverse() {
return new PersistentPropertyOrder<>(persistentPropertyPath, !ascending);
}
@Override
public boolean isAscending() {
return ascending;
}
@Override
public Expression<?> getExpression() {
return persistentPropertyPath;
}
}
| 30.25 | 105 | 0.739079 |
8945951eef850787fe0fb534cfa9d64282fed367 | 12,385 | package com.touwolf.mailchimp.api.lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.touwolf.mailchimp.MailchimpException;
import com.touwolf.mailchimp.data.MailchimpResponse;
import com.touwolf.mailchimp.impl.MailchimpBuilder;
import com.touwolf.mailchimp.impl.MailchimpUtils;
import com.touwolf.mailchimp.model.list.interestcategories.*;
import org.apache.commons.lang.StringUtils;
import org.bridje.ioc.Component;
/**
* Manage interest categories for a specific list. Interest categories organize interests,
* which are used to group subscribers based on their preferences.
* These correspond to ‘group titles’ in the MailChimp application. Learn more about groups in MailChimp.
*/
@Component
public class ListsInterestCategories {
private final Gson GSON = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
private MailchimpBuilder builder;
public ListsInterestCategories builder(MailchimpBuilder builder) {
this.builder = builder;
return this;
}
/**
* Create a new interest category
*
* @param listId The unique id for the list.
* @param request Request body parameters
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesResponse> create(String listId, ListsInterestCategoriesRequest request) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
String url = "/lists/" + listId + "/interest-categories";
String payload = GSON.toJson(request);
return builder.post(url, payload, ListsInterestCategoriesResponse.class);
}
/**
* Get information about a list’s interest categories
*
* @param listId The unique id for the list.
* @param request Query string parameters
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesReadResponse> read(String listId, ListsInterestCategoriesReadRequest request) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
String url = "/lists/" + listId + "/interest-categories";
url = MailchimpUtils.formatQueryString(url, "fields", request.getFields());
url = MailchimpUtils.formatQueryString(url, "exclude_fields", request.getExcludeFields());
url = MailchimpUtils.formatQueryString(url, "count", request.getCount());
url = MailchimpUtils.formatQueryString(url, "offset", request.getOffset());
url = MailchimpUtils.formatQueryString(url, "type", request.getType());
return builder.get(url, ListsInterestCategoriesReadResponse.class);
}
/**
* Get information about a specific interest category.
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
* @param fields A comma-separated list of fields to return. Reference parameters of sub-objects with dot notation.
* @param excludeFields A comma-separated list of fields to exclude. Reference parameters of sub-objects with dot notation.
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesResponse> read(String listId, String interestCategoryId, String fields, String excludeFields) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId;
url = MailchimpUtils.formatQueryString(url, "fields", fields);
url = MailchimpUtils.formatQueryString(url, "exclude_fields", excludeFields);
return builder.get(url, ListsInterestCategoriesResponse.class);
}
/**
* Update a specific interest category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
* @param request Request body parameters
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesResponse> edit(String listId, String interestCategoryId, ListsInterestCategoriesRequest request) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId;
String payload = GSON.toJson(request);
return builder.patch(url, payload, ListsInterestCategoriesResponse.class);
}
/**
* Delete a specific interest category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
* @throws MailchimpException
*/
public MailchimpResponse<Void> delete(String listId, String interestCategoryId) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field campaign_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId;
return builder.delete(url, Void.class);
}
/**
* Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together.
* Interests are referred to as ‘group names’ in the MailChimp application. Learn more about using groups in MailChimp.
*/
/**
* Create a new interest in a specific category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
* @param name The name of the interest. This can be shown publicly on a subscription form.
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesInterestResponse> createInterest(String listId, String interestCategoryId, String name) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId;
String payload = "{name: " + name + "}";
return builder.post(url, payload, ListsInterestCategoriesInterestResponse.class);
}
/**
* Get all interests in a specific category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.
* @param request Query string parameters
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesInterestReadResponse> readInterest(String listId, String interestCategoryId, ListsInterestCategoriesReadRequest request) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId + "/interests";
url = MailchimpUtils.formatQueryString(url, "fields", request.getFields());
url = MailchimpUtils.formatQueryString(url, "exclude_fields", request.getExcludeFields());
url = MailchimpUtils.formatQueryString(url, "count", request.getCount());
url = MailchimpUtils.formatQueryString(url, "offset", request.getOffset());
return builder.get(url, ListsInterestCategoriesInterestReadResponse.class);
}
/**
* Get interests in a specific category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.tegoryId
* @param interestId The specific interest or ‘group name’.
* @param fields A comma-separated list of fields to return. Reference parameters of sub-objects with dot notation.
* @param excludeFields A comma-separated list of fields to exclude. Reference parameters of sub-objects with dot notation.
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesInterestResponse> readInterest(String listId, String interestCategoryId, String interestId, String fields, String excludeFields) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
if (StringUtils.isBlank(interestId)) {
throw new MailchimpException("The field interest_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId + "/interests/" + interestId;
url = MailchimpUtils.formatQueryString(url, "fields", fields);
url = MailchimpUtils.formatQueryString(url, "exclude_fields", excludeFields);
return builder.get(url, ListsInterestCategoriesInterestResponse.class);
}
/**
* Update interests in a specific category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.tegoryId
* @param interestId The specific interest or ‘group name’.
* @param request Request body parameters
* @throws MailchimpException
*/
public MailchimpResponse<ListsInterestCategoriesInterestResponse> editInterest(String listId, String interestCategoryId, String interestId, ListsInterestCategoriesInterestRequest request) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field list_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
if (StringUtils.isBlank(interestId)) {
throw new MailchimpException("The field interest_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId + "/interests/" + interestId;
String payload = GSON.toJson(request);
return builder.patch(url, payload, ListsInterestCategoriesInterestResponse.class);
}
/**
* Delete interests in a specific category
*
* @param listId The unique id for the list.
* @param interestCategoryId The unique id for the interest category.tegoryId
* @param interestId The specific interest or ‘group name’.
* @throws MailchimpException
*/
public MailchimpResponse<Void> deleteInterest(String listId, String interestCategoryId, String interestId) throws MailchimpException {
if (StringUtils.isBlank(listId)) {
throw new MailchimpException("The field campaign_id is required");
}
if (StringUtils.isBlank(interestCategoryId)) {
throw new MailchimpException("The field interest_category_id is required");
}
if (StringUtils.isBlank(interestId)) {
throw new MailchimpException("The field interest_id is required");
}
String url = "/lists/" + listId + "/interest-categories/" + interestCategoryId + "/interests/" + interestId;
return builder.delete(url, Void.class);
}
}
| 45.533088 | 219 | 0.689625 |
e197d1ad778162aca1090e46b8cb28ba397942ab | 1,319 | package io.resourcepool.dashboard.model.metadata;
import java.util.List;
/**
* TODO class details.
*
* @author Loïc Ortola on 03/03/2017
*/
public class Feed {
private String uuid;
private String name;
private List<String> bundleTags;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getBundleTags() {
return bundleTags;
}
public void setBundleTags(List<String> bundleTags) {
this.bundleTags = bundleTags;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String uuid;
private String name;
private List<String> bundles;
private Builder() {
}
public Builder uuid(String uuid) {
this.uuid = uuid;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder bundles(List<String> bundles) {
this.bundles = bundles;
return this;
}
public Feed build() {
Feed feed = new Feed();
feed.setUuid(uuid);
feed.setName(name);
feed.setBundleTags(bundles);
return feed;
}
}
}
| 17.355263 | 54 | 0.62699 |
9159e53cc41da7eee96ed1e008ba7800d8200f6a | 134 | package vn.bhxh.bhxhmail.mail.store.imap;
interface UntaggedHandler {
void handleAsyncUntaggedResponse(ImapResponse response);
}
| 22.333333 | 60 | 0.813433 |
ee7787262c663b20128337d9607f3379d5517a3a | 3,490 | package src.train.common.items;
import java.util.List;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import src.train.common.Traincraft;
import src.train.common.core.handlers.ConfigHandler;
import src.train.common.entity.zeppelin.EntityZeppelinOneBalloon;
import src.train.common.entity.zeppelin.EntityZeppelinTwoBalloons;
import src.train.common.library.Info;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemZeppelins extends Item {
private int type;
public ItemZeppelins(int i,int type) {
super(i);
maxStackSize = 5;
setCreativeTab(Traincraft.tcTab);
this.type=type;
}
@Override
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) {
float f = 1.0F;
float f1 = entityplayer.prevRotationPitch + (entityplayer.rotationPitch - entityplayer.prevRotationPitch) * f;
float f2 = entityplayer.prevRotationYaw + (entityplayer.rotationYaw - entityplayer.prevRotationYaw) * f;
double d = entityplayer.prevPosX + (entityplayer.posX - entityplayer.prevPosX) * (double) f;
double d1 = (entityplayer.prevPosY + (entityplayer.posY - entityplayer.prevPosY) * (double) f + 1.6200000000000001D) - (double) entityplayer.yOffset;
double d2 = entityplayer.prevPosZ + (entityplayer.posZ - entityplayer.prevPosZ) * (double) f;
Vec3 vec3d = Vec3.fakePool.getVecFromPool(d, d1, d2);
float f3 = MathHelper.cos(-f2 * 0.01745329F - 3.141593F);
float f4 = MathHelper.sin(-f2 * 0.01745329F - 3.141593F);
float f5 = -MathHelper.cos(-f1 * 0.01745329F);
float f6 = MathHelper.sin(-f1 * 0.01745329F);
float f7 = f4 * f5;
float f8 = f6;
float f9 = f3 * f5;
double d3 = 5D;
Vec3 vec3d1 = vec3d.addVector((double) f7 * d3, (double) f8 * d3, (double) f9 * d3);
MovingObjectPosition movingobjectposition = world.rayTraceBlocks_do_do(vec3d, vec3d1, true, false);
if (movingobjectposition == null) { return itemstack; }
if (!world.isRemote && !ConfigHandler.ENABLE_ZEPPELIN) {
if (entityplayer != null) entityplayer.addChatMessage("Zeppelin has been deactivated by the OP");
return itemstack;
}
if (movingobjectposition.typeOfHit == EnumMovingObjectType.TILE) {
int i = movingobjectposition.blockX;
int j = movingobjectposition.blockY;
int k = movingobjectposition.blockZ;
if (!world.isRemote) {
if(type==0)world.spawnEntityInWorld(new EntityZeppelinTwoBalloons(world, (float) i + 0.5F, (float) j + 1.5F, (float) k + 0.5F));
if(type==1)world.spawnEntityInWorld(new EntityZeppelinOneBalloon(world, (float) i + 0.5F, (float) j + 1.5F, (float) k + 0.5F));
}
itemstack.stackSize--;
}
return itemstack;
}
@SideOnly(Side.CLIENT)
@Override
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) {
par3List.add("\u00a77" + "More info in the guidebook.");
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister iconRegister) {
if(type==0)this.itemIcon = iconRegister.registerIcon(Info.modID.toLowerCase() + ":zeppelin");
if(type==1)this.itemIcon = iconRegister.registerIcon(Info.modID.toLowerCase() + ":zeppelin_one_balloon");
}
}
| 43.08642 | 151 | 0.751289 |
e1d4587dc38c28839f1586997471742747ae17e1 | 592 | package imnotjahan.mod.danmachi.objects.itemblocks;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class DungeonWallItem extends ItemBlock
{
public DungeonWallItem(Block block)
{
super(block);
setHasSubtypes(true);
}
@Override
public String getUnlocalizedName(ItemStack stack)
{
return super.getUnlocalizedName() + (stack.getMetadata() != 0 ? "." + stack.getMetadata() : "");
}
@Override
public int getMetadata(int damage)
{
return damage;
}
}
| 21.925926 | 104 | 0.673986 |
dd84d78c36e63948e6f3c0bbaf98a741c067beca | 2,747 | // Copyright (C) 2016 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.google.gerrit.server.config;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
public class GerritServerIdProvider implements Provider<String> {
public static final String SECTION = "gerrit";
public static final String KEY = "serverId";
public static String generate() {
return UUID.randomUUID().toString();
}
private final String id;
@Inject
GerritServerIdProvider(@GerritServerConfig Config cfg, SitePaths sitePaths)
throws IOException, ConfigInvalidException {
String origId = cfg.getString(SECTION, null, KEY);
if (!Strings.isNullOrEmpty(origId)) {
id = origId;
return;
}
// We're not generally supposed to do work in provider constructors, but this is a bit of a
// special case because we really need to have the ID available by the time the dbInjector
// is created. This even applies during MigrateToNoteDb, which otherwise would have been a
// reasonable place to do the ID generation. Fortunately, it's not much work, and it happens
// once.
id = generate();
Config newCfg = readGerritConfig(sitePaths);
newCfg.setString(SECTION, null, KEY, id);
Files.write(sitePaths.gerrit_config, newCfg.toText().getBytes(UTF_8));
}
@Override
public String get() {
return id;
}
private static Config readGerritConfig(SitePaths sitePaths)
throws IOException, ConfigInvalidException {
// Reread gerrit.config from disk before writing. We can't just use
// cfg.toText(), as the @GerritServerConfig only has gerrit.config as a
// fallback.
FileBasedConfig cfg = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED);
if (!cfg.getFile().exists()) {
return new Config();
}
cfg.load();
return cfg;
}
}
| 35.217949 | 96 | 0.733892 |
64b8d58010e488693db1653b74b75f137fb99bde | 1,812 | package pizza.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pizza.mapper.OrderItemMapper;
import pizza.pojo.OrderItem;
import pizza.pojo.OrderItemExample;
import pizza.pojo.Product;
import pizza.service.OrderItemService;
import pizza.service.ProductService;
@Service
public class OrderItemServiceImpl implements OrderItemService {
@Autowired
OrderItemMapper orderItemMapper;
@Autowired
ProductService productService;
@Override
public void add(OrderItem c) {
orderItemMapper.insert(c);
}
@Override
public void delete(int id) {
orderItemMapper.deleteByPrimaryKey(id);
}
@Override
public void update(OrderItem c) {
orderItemMapper.updateByPrimaryKeySelective(c);
}
@Override
public OrderItem get(int id) {
OrderItem result = orderItemMapper.selectByPrimaryKey(id);
setProduct(result);
return result;
}
public List<OrderItem> list(){
OrderItemExample example =new OrderItemExample();
example.setOrderByClause("id desc");
return orderItemMapper.selectByExample(example);
}
@Override
public List<OrderItem> listByUser(int uid) {
OrderItemExample example =new OrderItemExample();
example.createCriteria().andUidEqualTo(uid).andOidIsNull();
List<OrderItem> result =orderItemMapper.selectByExample(example);
setProduct(result);
return result;
}
public void setProduct(List<OrderItem> ois){
for (OrderItem oi: ois) {
setProduct(oi);
}
}
private void setProduct(OrderItem oi) {
Product p = productService.get(oi.getPid());
oi.setProduct(p);
}
}
| 24.821918 | 73 | 0.691501 |
a6f2a8bd2e5bf40c3143eac6b460994f379a9875 | 2,457 | package com.revature.shop.daos;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.revature.shop.connection.DatabaseConnection;
import com.revature.shop.models.Product;
public class ProductDAO implements CrudDAO<Product> {
Connection con = DatabaseConnection.getCon();
@Override
public int save(Product obj) {
int n = 0;
try {
PreparedStatement ps = con.prepareStatement("INSERT into products (brand, name, quantity, price) VALUES (?, ?, ?, ?)");
ps.setString(1, obj.getBrand());
ps.setString(2, obj.getItemName());
ps.setInt(3, obj.getQuantity());
ps.setFloat(4, obj.getPrice());
n = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return n;
}
@Override
public List<Product> findAll() {
List<Product> productList = new ArrayList<>();
try {
PreparedStatement ps = con.prepareStatement("SELECT * FROM products");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Product product = new Product();
product.setItemId(rs.getInt("item_id"));
product.setBrand(rs.getString("brand"));
product.setItemName(rs.getString("item_name"));
product.setPrice(rs.getFloat("item_price"));
product.setQuantity(rs.getInt("quantity"));
productList.add(product);
}
} catch (SQLException e) {
e.printStackTrace();
}
return productList;
}
@Override
public Product findById(int id) {
return null;
}
@Override
public List<Product> findAllById(int id) {
return null;
}
@Override
public boolean update(Product updatedObj) {
return false;
}
@Override
public boolean removeById(String id) {
return false;
}
public boolean removeItemById(int ItemId) {
int n = 0;
try {
PreparedStatement ps = con.prepareStatement("DELETE FROM shopping_carts WHERE item_id = ?");
// ps.setInt(1, obj.getItemId);
n = ps.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
| 24.088235 | 127 | 0.586895 |
90ce86619e00ac0d4c32136dd81fe6809a01acdd | 808 | package so.sample.worker;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import so.engine.IWorker;
import so.engine.ProcessResult;
import so.engine.ResultStatusEnum;
/**
* A woker that join a list of int into a single int
*
* Basically it sums values of the given list
*
* @author marc_alx
*/
public class IntToIntJoiner implements IWorker<List<Integer>,Integer>{
@Override
public CompletableFuture<ProcessResult<Integer>> process(List<Integer> input) {
CompletableFuture<ProcessResult<Integer>> res = CompletableFuture.supplyAsync(()->{
int tmp = 0;
for(Integer i : (List<Integer>)input){
tmp+=i;
}
return new ProcessResult<>(tmp,ResultStatusEnum.SUCCESS,null);
});
return res;
}
}
| 25.25 | 91 | 0.675743 |
c63eace09062e48937d0044b4f5d0ce9bdb0b003 | 1,277 | package com.qa.ims.persistence.dao;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.qa.ims.persistence.domain.Items;
import com.qa.ims.utils.DBUtils;
public class ItemDAOTest {
private final ItemsDAO DAO = new ItemsDAO();
@Before
public void setup() {
DBUtils.connect();
DBUtils.getInstance().init("src/test/resources/sql-schema.sql", "src/test/resources/sql-data.sql");
}
@Test
public void testCreate() {
final Items created = new Items(2L, "ball", 40L);
assertEquals(created, DAO.create(created));
}
@Test
public void testReadAll() {
List<Items> expected = new ArrayList<>();
expected.add(new Items(1L, "tennis racket", 40L));
assertEquals(expected, DAO.readAll());
}
@Test
public void testReadLatest() {
assertEquals(new Items(1L, "tennis racket", 40L), DAO.readLatest());
}
@Test
public void testRead() {
final long itemID = 1L;
assertEquals(new Items(itemID, "tennis racket", 40L), DAO.read(itemID));
}
@Test
public void testUpdate() {
final Items updated = new Items(1L, "football", 30L);
assertEquals(updated, DAO.update(updated));
}
@Test
public void testDelete() {
assertEquals(1, DAO.delete(1));
}
}
| 22.017241 | 101 | 0.707126 |
6e4e8100b33ddc78251e6af93e4348162ed427db | 2,704 | package com.koch.ambeth.cache.chunk;
/*-
* #%L
* jambeth-cache
* %%
* Copyright (C) 2017 Koch Softwaredevelopment
* %%
* 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.
* #L%
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import com.koch.ambeth.service.cache.model.IObjRelation;
import com.koch.ambeth.stream.binary.ReusableByteArrayInputStream;
import com.koch.ambeth.util.collections.ArrayList;
public class ChunkProviderStubInputStream extends InputStream {
private static final byte[] EMPTY_BYTES = new byte[0];
private long position = 0;
private final Inflater inflater = new Inflater();
private final ReusableByteArrayInputStream bis = new ReusableByteArrayInputStream(EMPTY_BYTES);
private InputStream is;
private boolean deflated, lastChunkReceived;
protected final IObjRelation self;
protected final IChunkProvider chunkProvider;
public ChunkProviderStubInputStream(IObjRelation self, IChunkProvider chunkProvider) {
this.self = self;
this.chunkProvider = chunkProvider;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int length = deflated ? is.read(b, off, len) : bis.read(b, off, len);
if (length != -1) {
return length;
}
if (lastChunkReceived) {
return -1;
}
// length is zero so we have not enough bytes to read at least one byte. So we read the next
// chunk
ArrayList<IChunkedRequest> chunkedRequests = new ArrayList<>();
chunkedRequests.add(new ChunkedRequest(self, position, len));
position += len;
List<IChunkedResponse> chunkedResponses = chunkProvider.getChunkedContents(chunkedRequests);
IChunkedResponse chunkedResponse = chunkedResponses.get(0);
byte[] payload = chunkedResponse.getPayload();
deflated = chunkedResponse.isDeflated();
lastChunkReceived = chunkedResponse.getPayloadSize() < len;
bis.reset(payload);
if (deflated) {
is = new InflaterInputStream(bis, inflater);
return is.read(b, off, len);
}
is = null;
return bis.read(b, off, len);
}
@Override
public int read() throws IOException {
throw new UnsupportedOperationException("Should never be called");
}
}
| 30.727273 | 96 | 0.756287 |
be28d8cf2d782e34abade6bded8af9da9e0724d3 | 400 | /** Fetches the names of the available ALC device specifiers.
Equivalent to the C call alcGetString(NULL, ALC_DEVICE_SPECIFIER). */
public java.lang.String[] alcGetDeviceSpecifiers();
/** Fetches the names of the available ALC capture device specifiers.
Equivalent to the C call alcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER). */
public java.lang.String[] alcGetCaptureDeviceSpecifiers();
| 50 | 81 | 0.785 |
939cbde1e1646dbfa7ebeee97c93897ff1f93e80 | 17,759 | package com.gat.data.book;
import com.gat.common.util.MZDebug;
import com.gat.data.api.GatApi;
import com.gat.data.exception.CommonException;
import com.gat.data.id.LongId;
import com.gat.data.response.BookResponse;
import com.gat.data.response.DataResultListResponse;
import com.gat.data.response.ResultInfoList;
import com.gat.data.response.ResultInfoObject;
import com.gat.data.response.ServerResponse;
import com.gat.data.response.UserResponse;
import com.gat.data.response.impl.BookInfo;
import com.gat.data.response.impl.BookInstanceInfo;
import com.gat.data.response.impl.BookReadingInfo;
import com.gat.data.response.impl.BorrowResponse;
import com.gat.data.response.impl.EvaluationItemResponse;
import com.gat.data.response.impl.Keyword;
import com.gat.dependency.DataComponent;
import com.gat.repository.datasource.BookDataSource;
import com.gat.repository.entity.Author;
import com.gat.repository.entity.Book;
import com.google.gson.internal.LinkedTreeMap;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import retrofit2.Response;
/**
* Created by ducbtsn on 5/6/17.
*/
public class BookDataSourceImpl implements BookDataSource {
private final DataComponent dataComponent;
public BookDataSourceImpl(DataComponent dataComponent) {
this.dataComponent = dataComponent;
}
private List<Book> listOfBooks(Book... books){
ArrayList list = new ArrayList();
if(books != null)
Collections.addAll(list, books);
return Collections.unmodifiableList(list);
}
private List<Author> listOfAuthors(String... names){
ArrayList list = new ArrayList();
if(names != null)
for(String name : names)
list.add(Author.instance(name));
return Collections.unmodifiableList(list);
}
@Override
public Observable<List<Book>> searchBookByKeyword(String keyword, int page, int sizeOfPage) {
return Observable.fromCallable(() -> {
if(keyword.contains("empty"))
return listOfBooks();
int max = Integer.MAX_VALUE;
if(keyword.contains("max"))
max = Integer.parseInt(keyword.replaceAll("[^\\d.]", ""));
int length = Math.max(0, Math.min(sizeOfPage, max - page * sizeOfPage));
Book[] books = new Book[length];
long baseId = keyword.hashCode() * 1000;
Random rand = new Random();
for (int i = 0; i < books.length; i++) {
long id = page * sizeOfPage + i;
books[i] = Book.builder()
.id(LongId.instance(baseId + id))
.title("Book " + keyword + " " + id)
.publisher("NXB ABC")
.publishedDate(System.currentTimeMillis())
.pages(100)
.authors(listOfAuthors("Author " + id))
.rating(rand.nextFloat() * 5f)
.build();
}
return listOfBooks(books);
}).delay(1000, TimeUnit.MILLISECONDS);
}
@Override
public Observable<Integer> searchBookByIsbn(String isbn) {
MZDebug.w("______________ searchBookByIsbn______________________________________________");
GatApi gatApi = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse>> bookResponse = gatApi.getBookByIsbn(isbn);
return bookResponse.map(response -> {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
MZDebug.w("____________________________________________________ searchBookByIsbn");
LinkedTreeMap<String, Double> data = (LinkedTreeMap<String, Double>) serverResponse.data();
if (data != null && data.get("editionId") != null)
return data.get("editionId").intValue();
else
throw new CommonException("Bad response.");
} else {
JSONObject jsonObject = new JSONObject(response.errorBody().string());
if (jsonObject.has("message"))
throw new CommonException(jsonObject.getString("message"));
else
throw new CommonException("Bad response.");
}
});
}
@Override
public Observable<List<BookResponse>> suggestMostBorrowing() {
MZDebug.i("_____________________________________ suggestMostBorrowing ___________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<ResultInfoList<BookResponse>>>> responseObservable;
responseObservable = api.suggestMostBorrowing();
return responseObservable.map(response -> {
List<BookResponse> list = response.body().data().getResultInfo();
MZDebug.i("__list most borrowing size: " + list.size());
MZDebug.i("__item 0: " + list.get(0).toString());
return list;
});
}
@Override
public Observable<List<BookResponse>> suggestBooksWithoutLogin() {
MZDebug.i("____________________________ suggestBooksWithoutLogin ________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<ResultInfoList<BookResponse>>>> responseObservable;
responseObservable = api.suggestWithoutLogin();
return responseObservable.map( response -> {
List<BookResponse> list = response.body().data().getResultInfo();
return list;
});
}
@Override
public Observable<List<BookResponse>> suggestBooksAfterLogin() {
MZDebug.i("____________________________ suggestBooksAfterLogin __________________________");
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse<ResultInfoList<BookResponse>>>> responseObservable;
responseObservable = api.suggestAfterLogin();
return responseObservable.map( response -> {
List<BookResponse> list = response.body().data().getResultInfo();
return list;
});
}
@Override
public Observable<DataResultListResponse<BookResponse>> searchBookByTitle
(String title, int page, int sizeOfPage) {
MZDebug.i("____________________________ searchBookByTitle _______________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<DataResultListResponse<BookResponse>>>> responseObservable;
responseObservable = api.searchBookByTitle(title, page, sizeOfPage);
return responseObservable.map( response -> {
DataResultListResponse<BookResponse> data = response.body().data();
return data;
});
}
@Override
public Observable<DataResultListResponse<BookResponse>> searchBookByAuthor
(String author, int page, int sizeOfPage) {
MZDebug.i("____________________________ searchBookByAuthor ______________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<DataResultListResponse<BookResponse>>>> responseObservable;
responseObservable = api.searchBookByAuthor(author, page, sizeOfPage);
return responseObservable.map( response -> {
DataResultListResponse<BookResponse> data = response.body().data();
return data;
});
}
@Override
public Observable<DataResultListResponse> searchBookByTitleTotal(String title, int userId) {
MZDebug.i("____________________________ searchBookByTitleTotal __________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<DataResultListResponse>>> responseObservable;
responseObservable = api.searchBookByTitleTotal(title, userId);
return responseObservable.map( response -> {
DataResultListResponse data = response.body().data();
return data;
});
}
@Override
public Observable<DataResultListResponse> searchBookByAuthorTotal(String author, int userId) {
MZDebug.i("____________________________ searchBookByAuthorTotal _________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<DataResultListResponse>>> responseObservable;
responseObservable = api.searchBookByAuthorTotal(author, userId);
return responseObservable.map( response -> {
DataResultListResponse data = response.body().data();
return data;
});
}
@Override
public Observable<List<Keyword>> getBooksSearchedKeyword() {
MZDebug.i("________________________ getBooksSearchedKeyword _____________________________");
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse<ResultInfoList<Keyword>>>> responseObservable;
responseObservable = api.getBooksSearchedKeyword();
// List<String> list = new ArrayList<String>();
// list.add("book 1");
// list.add("book 2");
// list.add("book 3");
// list.add("book 4");
// list.add("book 5");
return responseObservable.map( response -> {
List<Keyword> list = response.body().data().getResultInfo();
return list;
});
}
@Override
public Observable<List<Keyword>> getAuthorsSearchedKeyword() {
MZDebug.i("________________________ getAuthorsSearchedKeyword ___________________________");
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse<ResultInfoList<Keyword>>>> responseObservable;
responseObservable = api.getAuthorsSearchedKeyword();
// List<String> list = new ArrayList<String>();
// list.add("author 1");
// list.add("author 2");
// list.add("author 3");
// list.add("author 4");
// list.add("author 5");
return responseObservable.map( response -> {
List<Keyword> list = response.body().data().getResultInfo();
return list;
});
}
@Override
public Observable<BookInfo> getBookInfo(int editionId) {
MZDebug.w("_____________________________________ getBookInfo ____________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<ResultInfoObject<BookInfo>>>> responseObservable;
responseObservable = api.getBookInfo(editionId);
return responseObservable.map( response -> {
MZDebug.w("book info response: " + response.body().toString());
return response.body().data().getResultInfo();
});
}
@Override
public Observable<List<EvaluationItemResponse>> getBookEditionEvaluation(int editionId) {
MZDebug.w("________________________ getBookEditionEvaluation ____________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<DataResultListResponse<EvaluationItemResponse>>>> responseObservable;
responseObservable = api.getBookEditionEvaluation(editionId);
return responseObservable.map(response -> {
List<EvaluationItemResponse> list = response.body().data().getResultInfo();
return list;
});
}
@Override
public Observable<BookReadingInfo> getReadingStatus(int editionId) {
MZDebug.w("________________________________ getReadingStatus ____________________________");
// BookReadingInfo bookReadingInfo = new BookReadingInfo();
// bookReadingInfo.setReadingStatus(-1);
// bookReadingInfo.setEditionId(12);
//
// return Observable.fromCallable(() -> {
// return bookReadingInfo;
// }).delay(0, TimeUnit.MILLISECONDS);
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse<BookReadingInfo>>> responseObservable;
responseObservable = api.getReadingStatus(editionId);
return responseObservable.map(response -> response.body().data());
}
@Override
public Observable<EvaluationItemResponse> getBookEvaluationByUser(int editionId) {
MZDebug.w("____________________________ getBookEvaluationByUser _________________________");
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse<ResultInfoObject<EvaluationItemResponse>>>> responseObservable;
responseObservable = api.getBookEvaluationByUser(editionId);
return responseObservable.map(response -> response.body().data().getResultInfo());
}
@Override
public Observable<List<UserResponse>> getEditionSharingUser(int editionId, Integer userId, Float latitude, Float longitude) {
MZDebug.w("____________________________ getEditionSharingUser ___________________________");
GatApi api = dataComponent.getPublicGatApi();
Observable<Response<ServerResponse<DataResultListResponse<UserResponse>>>> responseObservable;
responseObservable = api.getEditionSharingUser(editionId, userId, latitude, longitude);
return responseObservable.map(response -> {
List<UserResponse> list = response.body().data().getResultInfo();
return list;
});
}
@Override
public Observable<ServerResponse> postComment(int editionId, int value, String review, boolean spoiler, Integer evaluationId, Integer readingId, int bookId) {
MZDebug.w("______________________________________ postComment ___________________________");
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse>> responseObservable;
responseObservable = api.postComment(editionId, value, review, spoiler, evaluationId, readingId, bookId);
return responseObservable.map(response -> response.body());
}
@Override
public Observable<BookInstanceInfo> getSelfInstanceInfo(int editionId) {
MZDebug.w("______________________________ getSelfInstanceInfo _________________ [ DEBUG ]");
// BookInstanceInfo bookInstanceInfo = new BookInstanceInfo();
// bookInstanceInfo.setBorrowingTotal(2);
// bookInstanceInfo.setLostTotal(2);
// bookInstanceInfo.setNotSharingToal(0);
// bookInstanceInfo.setSharingTotal(2);
//
// return Observable.fromCallable(() -> {
// return bookInstanceInfo;
// }).delay(0, TimeUnit.MILLISECONDS);
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse<BookInstanceInfo>>> responseObservable;
responseObservable = api.getSelfInstanceInfo(editionId);
return responseObservable.map( response -> {
MZDebug.w("response: " + response.body().data().toString());
return response.body().data();
});
}
@Override
public Observable<ServerResponse> selfAddInstance(int editionId, int sharingStatus, int numberOfBook, int bookId, Integer readingId) {
MZDebug.w("______________________________________ selfAddInstance ______________________ ");
// ServerResponse serverResponse = new ServerResponse("Success", 200, null);
// return Observable.fromCallable(() -> {
// return serverResponse;
// }).delay(0, TimeUnit.MILLISECONDS);
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse>> responseObservable;
responseObservable = api.selfAddInstance(editionId, sharingStatus, numberOfBook, bookId, readingId);
return responseObservable.map(response -> {
MZDebug.w("selfAddInstance: response :" + response.message());
return response.body();
});
}
@Override
public Observable<ServerResponse> selfUpdateReadingStatus(int editionId, int readingStatus, Integer readingId, int bookId) {
MZDebug.w("________________ selfUpdateReadingStatus :" + editionId + " = " + readingStatus);
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse>> responseObservable;
responseObservable = api.selfUpdateReadingStatus(editionId, readingStatus, readingId, bookId);
return responseObservable.map(response -> response.body());
}
@Override
public Observable<BorrowResponse> requestBorrow(int editionId, int ownerId) {
MZDebug.w("____________________________________ requestBorrow _________________ [ DEBUG ]");
// BorrowResponse borrowResponse = new BorrowResponse();
// borrowResponse.setRecordId(103);
// borrowResponse.setBookId(150);
// borrowResponse.setBorrowerId(156);
// borrowResponse.setOwnerId(2);
// borrowResponse.setRequestTime("2017-04-17 13:02:25");
// borrowResponse.setRecordStatus(0);
//
// return Observable.fromCallable(() -> {
// return borrowResponse;
// }).delay(1000, TimeUnit.MILLISECONDS);
GatApi api = dataComponent.getPrivateGatApi();
Observable<Response<ServerResponse<ResultInfoObject<BorrowResponse>>>> responseObservable;
responseObservable = api.requestBorrow(editionId, ownerId);
return responseObservable.map(response -> {
BorrowResponse borrowResponse = response.body().data().getResultInfo();
MZDebug.w("DEBUG: borrow response \n\r" + borrowResponse.toString());
return borrowResponse;
});
}
} | 40.731651 | 162 | 0.677966 |
8bfcb8c2aed208975e00099e125d18b11d897722 | 9,389 | /*
* Copyright (C) 2016 Square, Inc.
*
* 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 okhttp3;
import java.security.GeneralSecurityException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLPeerUnverifiedException;
import okhttp3.internal.HeldCertificate;
import okhttp3.internal.tls.CertificateChainCleaner;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public final class CertificateChainCleanerTest {
@Test public void normalizeSingleSelfSignedCertificate() throws Exception {
HeldCertificate root = new HeldCertificate.Builder()
.serialNumber("1")
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate);
assertEquals(list(root), cleaner.clean(list(root), "hostname"));
}
@Test public void normalizeUnknownSelfSignedCertificate() throws Exception {
HeldCertificate root = new HeldCertificate.Builder()
.serialNumber("1")
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get();
try {
cleaner.clean(list(root), "hostname");
fail();
} catch (SSLPeerUnverifiedException expected) {
}
}
@Test public void orderedChainOfCertificatesWithRoot() throws Exception {
HeldCertificate root = new HeldCertificate.Builder()
.serialNumber("1")
.build();
HeldCertificate certA = new HeldCertificate.Builder()
.serialNumber("2")
.issuedBy(root)
.build();
HeldCertificate certB = new HeldCertificate.Builder()
.serialNumber("3")
.issuedBy(certA)
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate);
assertEquals(list(certB, certA, root), cleaner.clean(list(certB, certA, root), "hostname"));
}
@Test public void orderedChainOfCertificatesWithoutRoot() throws Exception {
HeldCertificate root = new HeldCertificate.Builder()
.serialNumber("1")
.build();
HeldCertificate certA = new HeldCertificate.Builder()
.serialNumber("2")
.issuedBy(root)
.build();
HeldCertificate certB = new HeldCertificate.Builder()
.serialNumber("3")
.issuedBy(certA)
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate);
assertEquals(list(certB, certA, root),
cleaner.clean(list(certB, certA), "hostname")); // Root is added!
}
@Test public void unorderedChainOfCertificatesWithRoot() throws Exception {
HeldCertificate root = new HeldCertificate.Builder()
.serialNumber("1")
.build();
HeldCertificate certA = new HeldCertificate.Builder()
.serialNumber("2")
.issuedBy(root)
.build();
HeldCertificate certB = new HeldCertificate.Builder()
.serialNumber("3")
.issuedBy(certA)
.build();
HeldCertificate certC = new HeldCertificate.Builder()
.serialNumber("4")
.issuedBy(certB)
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate);
assertEquals(list(certC, certB, certA, root),
cleaner.clean(list(certC, certA, root, certB), "hostname"));
}
@Test public void unorderedChainOfCertificatesWithoutRoot() throws Exception {
HeldCertificate root = new HeldCertificate.Builder()
.serialNumber("1")
.build();
HeldCertificate certA = new HeldCertificate.Builder()
.serialNumber("2")
.issuedBy(root)
.build();
HeldCertificate certB = new HeldCertificate.Builder()
.serialNumber("3")
.issuedBy(certA)
.build();
HeldCertificate certC = new HeldCertificate.Builder()
.serialNumber("4")
.issuedBy(certB)
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate);
assertEquals(list(certC, certB, certA, root),
cleaner.clean(list(certC, certA, certB), "hostname"));
}
@Test public void unrelatedCertificatesAreOmitted() throws Exception {
HeldCertificate root = new HeldCertificate.Builder()
.serialNumber("1")
.build();
HeldCertificate certA = new HeldCertificate.Builder()
.serialNumber("2")
.issuedBy(root)
.build();
HeldCertificate certB = new HeldCertificate.Builder()
.serialNumber("3")
.issuedBy(certA)
.build();
HeldCertificate certUnnecessary = new HeldCertificate.Builder()
.serialNumber("4")
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root.certificate);
assertEquals(list(certB, certA, root),
cleaner.clean(list(certB, certUnnecessary, certA, root), "hostname"));
}
@Test public void chainGoesAllTheWayToSelfSignedRoot() throws Exception {
HeldCertificate selfSigned = new HeldCertificate.Builder()
.serialNumber("1")
.build();
HeldCertificate trusted = new HeldCertificate.Builder()
.serialNumber("2")
.issuedBy(selfSigned)
.build();
HeldCertificate certA = new HeldCertificate.Builder()
.serialNumber("3")
.issuedBy(trusted)
.build();
HeldCertificate certB = new HeldCertificate.Builder()
.serialNumber("4")
.issuedBy(certA)
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(
selfSigned.certificate, trusted.certificate);
assertEquals(list(certB, certA, trusted, selfSigned),
cleaner.clean(list(certB, certA), "hostname"));
assertEquals(list(certB, certA, trusted, selfSigned),
cleaner.clean(list(certB, certA, trusted), "hostname"));
assertEquals(list(certB, certA, trusted, selfSigned),
cleaner.clean(list(certB, certA, trusted, selfSigned), "hostname"));
}
@Test public void trustedRootNotSelfSigned() throws Exception {
HeldCertificate unknownSigner = new HeldCertificate.Builder()
.serialNumber("1")
.build();
HeldCertificate trusted = new HeldCertificate.Builder()
.issuedBy(unknownSigner)
.serialNumber("2")
.build();
HeldCertificate intermediateCa = new HeldCertificate.Builder()
.issuedBy(trusted)
.serialNumber("3")
.build();
HeldCertificate certificate = new HeldCertificate.Builder()
.issuedBy(intermediateCa)
.serialNumber("4")
.build();
CertificateChainCleaner cleaner = CertificateChainCleaner.get(trusted.certificate);
assertEquals(list(certificate, intermediateCa, trusted),
cleaner.clean(list(certificate, intermediateCa), "hostname"));
assertEquals(list(certificate, intermediateCa, trusted),
cleaner.clean(list(certificate, intermediateCa, trusted), "hostname"));
}
@Test public void chainMaxLength() throws Exception {
List<HeldCertificate> heldCertificates = chainOfLength(10);
List<Certificate> certificates = new ArrayList<>();
for (HeldCertificate heldCertificate : heldCertificates) {
certificates.add(heldCertificate.certificate);
}
X509Certificate root = heldCertificates.get(heldCertificates.size() - 1).certificate;
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root);
assertEquals(certificates, cleaner.clean(certificates, "hostname"));
assertEquals(certificates, cleaner.clean(certificates.subList(0, 9), "hostname"));
}
@Test public void chainTooLong() throws Exception {
List<HeldCertificate> heldCertificates = chainOfLength(11);
List<Certificate> certificates = new ArrayList<>();
for (HeldCertificate heldCertificate : heldCertificates) {
certificates.add(heldCertificate.certificate);
}
X509Certificate root = heldCertificates.get(heldCertificates.size() - 1).certificate;
CertificateChainCleaner cleaner = CertificateChainCleaner.get(root);
try {
cleaner.clean(certificates, "hostname");
fail();
} catch (SSLPeerUnverifiedException expected) {
}
}
/** Returns a chain starting at the leaf certificate and progressing to the root. */
private List<HeldCertificate> chainOfLength(int length) throws GeneralSecurityException {
List<HeldCertificate> result = new ArrayList<>();
for (int i = 1; i <= length; i++) {
result.add(0, new HeldCertificate.Builder()
.issuedBy(!result.isEmpty() ? result.get(0) : null)
.serialNumber(Integer.toString(i))
.build());
}
return result;
}
private List<Certificate> list(HeldCertificate... heldCertificates) {
List<Certificate> result = new ArrayList<>();
for (HeldCertificate heldCertificate : heldCertificates) {
result.add(heldCertificate.certificate);
}
return result;
}
}
| 37.110672 | 96 | 0.691021 |
2ee78730e7b2946022bf386c4ab0a723620957ba | 3,321 |
package koodi.selenium;
import java.io.Console;
import java.util.concurrent.TimeUnit;
import koodi.Main;
import org.fluentlenium.adapter.FluentTest;
import org.fluentlenium.core.annotation.AjaxElement;
import org.fluentlenium.core.domain.FluentWebElement;
import org.hibernate.cfg.AvailableSettings;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.FindBy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class QuestionAnsweringTest extends FluentTest {
@Value("${local.server.port}")
private int serverPort;
private WebDriver webDriver = new HtmlUnitDriver();
@FindBy(id = "question-send-1")
@AjaxElement(timeOutInSeconds = 5)
FluentWebElement submitButton;
private String getUrl() {
return "http://localhost:" + serverPort;
}
@Override
public WebDriver getDefaultDriver() {
return webDriver;
}
@Test
public void mainPageIsShownWithNoSpecifiedAddress() {
goTo(getUrl());
assertTrue(pageSource().contains("Koodihommia!"));
assertEquals("Koodi", title());
}
//@Test
public void answeringQuestionWorks() {
loginAsJustRegisteredUser();
getDefaultDriver().manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
try{
getDefaultDriver().manage().timeouts().wait(5000);
} catch(Exception exc){
}
assertTrue(pageSource().contains("oletususer"));
find("a[href='/vastaukset/topic/1']").click();
assertTrue(pageSource().contains("Vastaa tehtäviin"));
assertTrue(pageSource().contains("Sarja 1"));
assertTrue(pageSource().contains("test question"));
assertEquals(2, find("input[type='radio']").size());
assertEquals(1, find("input[type='submit']").size());
findFirst("input[type='radio']").click();
submitButton.click();
//find("input[type='submit']").get(0).click();
// click("button");
// assertTrue(pageSource().contains("undefined"));
// assertTrue(pageSource().contains("Väärin..."));
assertTrue(pageSource().contains("test comment"));
}
private void login(String username, String password) {
goTo(getUrl());
click(find("a").get(2));
assertTrue(pageSource().contains("Kirjaudu koodi-järjestelmään"));
fill(find("#j_username")).with(username);
fill(find("#j_password")).with(password);
submit(find("form").first());
}
private void loginAsJustRegisteredUser() {
login("b", "b");
}
private void loginAsAdmin() {
login("a", "a");
}
}
| 32.242718 | 83 | 0.671183 |
b0ecec70e1933d15fd0b5ec3b655f0efb7fde63a | 1,077 | package uk.gov.hmcts.ccd.definition.store.domain.validation.casetype;
import org.springframework.stereotype.Component;
import uk.gov.hmcts.ccd.definition.store.domain.validation.ValidationResult;
import uk.gov.hmcts.ccd.definition.store.domain.validation.authorization.AuthorisationValidationContext;
import uk.gov.hmcts.ccd.definition.store.repository.entity.CaseTypeACLEntity;
import uk.gov.hmcts.ccd.definition.store.repository.entity.CaseTypeEntity;
@Component
public class CaseTypeEntityACLValidatorImpl implements CaseTypeEntityValidator {
@Override
public ValidationResult validate(final CaseTypeEntity caseType) {
final ValidationResult validationResult = new ValidationResult();
for (CaseTypeACLEntity entity : caseType.getCaseTypeACLEntities()) {
if (null == entity.getAccessProfile()) {
validationResult.addError(new CaseTypeEntityInvalidAccessProfileValidationError(entity,
new AuthorisationValidationContext(caseType)));
}
}
return validationResult;
}
}
| 39.888889 | 104 | 0.766017 |
486673df547a959d830ca0d0b8214b1b9cace299 | 3,278 | package org.kaelbastos.view.CLI;
import org.kaelbastos.Domain.Entities.Client.Client;
import org.kaelbastos.Domain.Entities.Client.ResidenceType;
import org.kaelbastos.Domain.Entities.Product.Product;
import org.kaelbastos.Domain.Entities.Product.ProductCategory;
import org.kaelbastos.Domain.Entities.Service.Service;
import org.kaelbastos.Domain.Entities.Service.ServiceCategory;
import org.kaelbastos.Domain.Entities.Service.ServiceStatus;
import org.kaelbastos.Domain.Entities.Worker.Worker;
import org.kaelbastos.Domain.Entities.utils.Address;
import org.kaelbastos.Domain.UseCases.ServiceUseCases.CancelScheduledService;
import org.kaelbastos.Domain.UseCases.ServiceUseCases.FinishService;
import org.kaelbastos.Domain.UseCases.ServiceUseCases.ScheduleService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class ServiceCLI {
public static void run(){
int id = 0;
LocalDateTime start = LocalDateTime.of(2021, 1, 6, 22 , 14);
float servicePrice = 100F;
int workerPercentage = 50;
ServiceStatus status = ServiceStatus.Scheduled;
ServiceCategory category = new ServiceCategory(0, "name", 1.5);
Client client = new Client("00000000000", "Name", "00000000000", "client@client.com", new Address("rua dos bobos", "neighborhood", "city", "state", "0", "2", null), ResidenceType.House);
Product product = new Product(1, "broom", 10F,ProductCategory.Utensil);
ArrayList<Product> products = new ArrayList<>(List.of(product));
Worker worker = new Worker("00000000000", "Name", "00000000000", "11111111111","client@client.com", new Address("rua dos bobos", "neighborhood", "city", "state", "0", "2", null));
ArrayList<Worker> workers = new ArrayList<>(List.of(worker));
Service service = new Service(id, start, servicePrice, workerPercentage, status , category, client, products, workers);
System.out.println("\nSchedule Service\n");
scheduleService(service);
System.out.println(service.toString());
System.out.println("\nCancel Service\n");
cancelSchedule(service.getId());
System.out.println(service.toString());
System.out.println("\nFinish Service\n");
finishService(service.getId());
System.out.println(service.toString() + "\n\n");
}
public static void scheduleService(Service service) {
ScheduleService scheduleService = new ScheduleService();
try{
System.out.println(scheduleService.schedule(service));
} catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void cancelSchedule(int serviceId){
CancelScheduledService cancelScheduledService = new CancelScheduledService();
try{
System.out.println(cancelScheduledService.cancel(serviceId));
} catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void finishService(int serviceId){
FinishService finishService = new FinishService();
try{
System.out.println(finishService.finish(serviceId));
} catch(Exception e){
System.out.println(e.getMessage());
}
}
}
| 37.678161 | 194 | 0.693716 |
416df048718bfbc807a11107831bc469c16d1b23 | 865 | package org.example.com.leetcode.array.middle;
/**
* 713. 乘积小于K的子数组
* https://leetcode-cn.com/problems/subarray-product-less-than-k/
*/
public class Q78 {
// 连续子数组:固定一边,动态修改另一边界
// 对于长度为n的数组,当一侧边界固定时,连续子数组数量为: n(长度1~n)
public int numSubarrayProductLessThanK(int[] nums, int k) {
if (k <= 1) {
return 0;
}
int prod = 1;
int ans = 0;
int left = 0;
for (int right= 0; right < nums.length; right++) {
prod *= nums[right];
while (prod >= k) {
prod /= nums[left];
left++;
}
ans+= (right - left +1);
}
return ans;
}
public static void main(String[] args) {
Q78 q = new Q78();
int[] nums = new int[]{10, 5, 2, 6};
q.numSubarrayProductLessThanK(nums, 100);
}
}
| 22.763158 | 65 | 0.495954 |
0216b079743d47262a4c94f55aa16b77ae6f67f2 | 2,539 | package com.openxava.naviox.web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.openxava.controller.*;
import org.openxava.jpa.*;
import org.openxava.util.*;
import com.openxava.naviox.*;
import com.openxava.naviox.impl.*;
import com.openxava.naviox.model.*;
import com.openxava.naviox.util.*;
/**
*
* @author Javier Paniza
*/
public class NaviOXFilter implements Filter {
public void init(FilterConfig cfg) throws ServletException {
Modules.init(cfg.getServletContext().getContextPath().substring(1));
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
XPersistence.reset();
Initializer.init(request);
HttpSession session = ((HttpServletRequest) request).getSession();
Modules modules = (Modules) session.getAttribute("modules");
if (modules == null) {
modules = new Modules();
session.setAttribute("modules", modules);
}
if (Is.empty(session.getAttribute("xava.user"))) {
String autologinUser = NaviOXPreferences.getInstance().getAutologinUser();
if (!Is.emptyString(autologinUser)) {
if (SignInHelper.isAuthorized(autologinUser, NaviOXPreferences.getInstance().getAutologinPassword())) {
SignInHelper.signIn(session, autologinUser);
}
}
}
session.setAttribute("xava.user", session.getAttribute("naviox.user")); // We use naviox.user instead of working only
// with xava.user in order to prevent some security hole using UrlParameters.setUser
HttpServletRequest secureRequest = new HttpServletRequestWrapper((HttpServletRequest)request) {
public String getRemoteUser() {
return (String) ((HttpServletRequest) getRequest()).getSession().getAttribute("naviox.user");
}
};
Users.setCurrent(secureRequest);
if (modules.isModuleAuthorized(secureRequest)) {
chain.doFilter(secureRequest, response);
}
else {
char base = secureRequest.getRequestURI().split("/")[2].charAt(0)=='p'?'p':'m';
String originalURI = secureRequest.getRequestURI();
String organization = Organizations.getCurrent(request);
if (organization != null) originalURI = originalURI.replace("/modules/", "/o/" + organization + "/m/");
RequestDispatcher dispatcher = request.getRequestDispatcher("/" + base + "/SignIn?originalURI=" + originalURI);
dispatcher.forward(request, response);
}
}
finally {
XPersistence.commit();
}
}
public void destroy() {
}
}
| 31.345679 | 129 | 0.708547 |
6dc308fe46de90ab0bba54c3d4037c98fe2aeb94 | 405 | package service.impl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import service.SubjectService;
/**
* @author tmblount
*/
@Service("subjectService")
public class SubjectServiceImpl implements SubjectService
{
@Override
public Subject getLoginSubject()
{
return SecurityUtils.getSubject();
}
}
| 20.25 | 57 | 0.755556 |
038b9f6667c94ab011fe3693c7e99b20bc293557 | 963 | // Test case for kelloggm 214
// https://github.com/kelloggm/checker-framework/issues/214
import org.checkerframework.checker.index.qual.IndexFor;
import org.checkerframework.checker.index.qual.IndexOrHigh;
import org.checkerframework.checker.index.qual.LTLengthOf;
public class ShiftRight {
void indexFor(Object[] a, @IndexFor("#1") int i) {
@IndexFor("a") int o = i >> 2;
@IndexFor("a") int p = i >>> 2;
}
void indexOrHigh(Object[] a, @IndexOrHigh("#1") int i) {
@IndexOrHigh("a") int o = i >> 2;
@IndexOrHigh("a") int p = i >>> 2;
// Not true if a.length == 0
// :: error: (assignment.type.incompatible)
@IndexFor("a") int q = i >> 2;
}
void negative(Object[] a, @LTLengthOf(value = "#1", offset = "100") int i) {
// Not true for some negative i
// :: error: (assignment.type.incompatible)
@LTLengthOf(value = "#1", offset = "100") int q = i >> 2;
}
}
| 34.392857 | 80 | 0.596054 |
1ec23e71e8a6245e2a8da793d2a4c9c7fbe8c2c7 | 726 | package com.evg.ss.lib.msc;
import com.evg.ss.SimpleScript;
import com.evg.ss.parser.ast.Expression;
import com.evg.ss.parser.ast.ExpressionStatement;
import com.evg.ss.parser.ast.Statement;
public final class MSCGenerator {
private SimpleScript.CompiledScript script;
public MSCGenerator(SimpleScript.CompiledScript script) {
this.script = script;
}
public MSCGenerator(Statement astRoot) {
this.script = SimpleScript.fromProgram(astRoot);
}
public MSCGenerator(Expression expression) {
this.script = SimpleScript.fromProgram(new ExpressionStatement(expression));
}
public String generate() {
return script.acceptResultVisitor(new MSCVisitor());
}
} | 25.928571 | 84 | 0.727273 |
7187f221c77dc3b8747293354e75f7d47dd5257b | 6,020 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.webkit;
import android.annotation.SystemApi;
import java.util.Set;
/**
* This class is used to manage permissions for the WebView's Geolocation
* JavaScript API.
*
* Geolocation permissions are applied to an origin, which consists of the
* host, scheme and port of a URI. In order for web content to use the
* Geolocation API, permission must be granted for that content's origin.
*
* This class stores Geolocation permissions. An origin's permission state can
* be either allowed or denied. This class uses Strings to represent
* an origin.
*
* When an origin attempts to use the Geolocation API, but no permission state
* is currently set for that origin,
* {@link WebChromeClient#onGeolocationPermissionsShowPrompt(String,GeolocationPermissions.Callback) WebChromeClient.onGeolocationPermissionsShowPrompt()}
* is called. This allows the permission state to be set for that origin.
*
* The methods of this class can be used to modify and interrogate the stored
* Geolocation permissions at any time.
*/
// Within WebKit, Geolocation permissions may be applied either temporarily
// (for the duration of the page) or permanently. This class deals only with
// permanent permissions.
public class GeolocationPermissions {
/**
* A callback interface used by the host application to set the Geolocation
* permission state for an origin.
*/
public interface Callback {
/**
* Sets the Geolocation permission state for the supplied origin.
*
* @param origin the origin for which permissions are set
* @param allow whether or not the origin should be allowed to use the
* Geolocation API
* @param retain whether the permission should be retained beyond the
* lifetime of a page currently being displayed by a
* WebView
*/
public void invoke(String origin, boolean allow, boolean retain);
};
/**
* Gets the singleton instance of this class. This method cannot be
* called before the application instantiates a {@link WebView} instance.
*
* @return the singleton {@link GeolocationPermissions} instance
*/
public static GeolocationPermissions getInstance() {
return WebViewFactory.getProvider().getGeolocationPermissions();
}
/**
* Gets the set of origins for which Geolocation permissions are stored.
*
* @param callback a {@link ValueCallback} to receive the result of this
* request. This object's
* {@link ValueCallback#onReceiveValue(T) onReceiveValue()}
* method will be invoked asynchronously with a set of
* Strings containing the origins for which Geolocation
* permissions are stored.
*/
// Note that we represent the origins as strings. These are created using
// WebCore::SecurityOrigin::toString(). As long as all 'HTML 5 modules'
// (Database, Geolocation etc) do so, it's safe to match up origins based
// on this string.
public void getOrigins(ValueCallback<Set<String> > callback) {
// Must be a no-op for backward compatibility: see the hidden constructor for reason.
}
/**
* Gets the Geolocation permission state for the specified origin.
*
* @param origin the origin for which Geolocation permission is requested
* @param callback a {@link ValueCallback} to receive the result of this
* request. This object's
* {@link ValueCallback#onReceiveValue(T) onReceiveValue()}
* method will be invoked asynchronously with a boolean
* indicating whether or not the origin can use the
* Geolocation API.
*/
public void getAllowed(String origin, ValueCallback<Boolean> callback) {
// Must be a no-op for backward compatibility: see the hidden constructor for reason.
}
/**
* Clears the Geolocation permission state for the specified origin.
*
* @param origin the origin for which Geolocation permissions are cleared
*/
public void clear(String origin) {
// Must be a no-op for backward compatibility: see the hidden constructor for reason.
}
/**
* Allows the specified origin to use the Geolocation API.
*
* @param origin the origin for which Geolocation API use is allowed
*/
public void allow(String origin) {
// Must be a no-op for backward compatibility: see the hidden constructor for reason.
}
/**
* Clears the Geolocation permission state for all origins.
*/
public void clearAll() {
// Must be a no-op for backward compatibility: see the hidden constructor for reason.
}
/**
* This class should not be instantiated directly, applications must only use
* {@link #getInstance()} to obtain the instance.
* Note this constructor was erroneously public and published in SDK levels prior to 16, but
* applications using it would receive a non-functional instance of this class (there was no
* way to call createHandler() and createUIHandler(), so it would not work).
* @hide Only for use by WebViewProvider implementations
*/
@SystemApi
public GeolocationPermissions() {}
}
| 41.805556 | 154 | 0.680731 |
c2aa69825bf25cf5793b0d032ce3058fe79f9f01 | 18,437 | package com.ggxiaozhi.lib.class13;
import java.util.ArrayList;
import java.util.List;
/**
* @Description:
* @Author: ggxz
* @CreateDate: 2020/3/25 21:21
* @UpdateUser:
* @UpdateDate: 2020/3/25 21:21
* @UpdateRemark: 更新说明
* @Version: 1.0
* <p>
* 首先 在二分搜索树中
* <p>
* 刚开始是平衡的 比如
* ---A
* 一个节点或者null都是平衡二叉树, 当下面这种情况
* TODO 这个情况是我们考虑的是往左子树去添加 同时最后是通过右旋转去达到平衡 右子树添加 使用左旋转达到平衡原理相同
* -----A
* ----/
* ---B
* --/
* -C
* <p>
* -----A
* ----/-\
* ---B---C
* --/-\
* -C---F
* /
* E
* 那么A节点就是不平衡的 但是当添加B 节点的时候是平衡的
* 也就是说 导致二分搜索树不平衡的原因有2点:
* 1. 一定是出现了添加操作
* 2. 出现不平衡的位置 一定是出现不平衡的第一个节点的左侧的左侧(这里是A节点出现不平衡 平衡因子为2 是由于添加了C导致的)
*/
@SuppressWarnings("SuspiciousNameCombination")
public class AVLTree<K extends Comparable<K>, V> {
private class Node {
private K key;
private V value;
public Node left, right;
//每个节点维护自己的高度
private int height;
public Node(K key, V value, Node left, Node right) {
this.key = key;
this.value = value;
this.left = left;
this.right = right;
//根据二分搜索树的性质 新创建的节点 一定在叶子节点上 那么他的高度是1
this.height = 1;
}
public Node(K key, V value) {
this.key = key;
this.value = value;
this.left = null;
this.right = null;
//根据二分搜索树的性质 新创建的节点 一定在叶子节点上 那么他的高度是1
this.height = 1;
}
public Node() {
this.key = null;
this.value = null;
this.left = null;
this.right = null;
//根据二分搜索树的性质 新创建的节点 一定在叶子节点上 那么他的高度是1
this.height = 1;
}
@Override
public String toString() {
return String.format("[key = %s,value = %s]", key.toString(), value.toString());
}
}
private Node root;
private int size;
public AVLTree() {
root = null;
size = 0;
}
public void add(K key, V value) {
root = add(root, key, value);
}
/**
* 求出指定节点的height
*
* @param node
* @return
*/
private int getHeight(Node node) {
if (node == null) {
return 0;
}
return node.height;
}
/**
* 计算指定节点的平衡因子
* 平衡因子=node节点左子树-node节点右子树
* <p>
* 判断一个树是否是平衡二叉树 就是判断Math.abs(balanceFactor) > 1 平衡因子的绝对值是否大于1
*
* @param node
* @return 这里返回的可能是正数 也可能是0 也可能是负数
* 正数 说明 左子树的高度>0 且左子树比右子树高度要高
* 0 说明 左右子树高度相等 >=0
* 负数 说明 右子树的高度>0 且右子树比左子树高度要高
*/
private int getBalanceFactor(Node node) {
if (node == null) {
return 0;
}
return getHeight(node.left) - getHeight(node.right);
}
/**
* 递归 添加元素 如果找到已经添加元素 就将value修改
*
* @param root
* @param key
* @param value
* @return 返回添加元素后的根节点
*/
private Node add(Node root, K key, V value) {
if (root == null) {
//新创建的节点的高度维护 我们已经在构造函数中维护了 所以这里的逻辑没问题
root = new Node(key, value);
size++;
return root;
}
if (key.compareTo(root.key) > 0) {//右子树
root.right = add(root.right, key, value);
} else if (key.compareTo(root.key) < 0) {
root.left = add(root.left, key, value);
} else {
root.value = value;
}
//经过上面的递归我们递归的向上返回我们添加新节点后的根节点
//所以在返回之前我们要维护node的高度
//每个节点的高度是由左右孩子最高的高度+1得到的
// 这里的1可以理解 代表节点本身高度1 +左右节点的高度
//如果是修改的值的话 本身左右子树的高度没有变化 那么根据每个节点的计算公式 root节点的高度就会保持原高度不变
root.height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
int balanceFactor = getBalanceFactor(root);
// if (Math.abs(balanceFactor) > 1) {
// System.out.println("unbalanced : " + balanceFactor);
// }
//平衡二叉树 代码要写在这个位置
//因为 在递归中 我们是下面的 return root; 一层一层向上返回
//我们需要在向上返回值之前判断平衡因子 是否会出现添加节点后导致二分搜索树不平衡
//如果出现不平衡 就要在这里判断后解决
/**
* 我们要清楚这个条件的含义
* 首先 balanceFactor > 1 说明这个节点的平衡因子破环了 出现了不平衡
* 根据getBalanceFactor() 方法的含义 说明左子树的高度比右子树高 那么破坏的地方一定在左子树
* getBalanceFactor(root.left) >= 0 是判断这个节点的平衡因子被打破是左子树打破的还是右子树打破的
*
* 这里的getBalanceFactor(root.left) >= 0 其实可以写成>1 因为在添加的时候是在节点左边的左边
* 那么节点左边的BalanceFactor值一定大于0 但是如果remove的时候会出现=0的情况 这里是为了统一代码
* 如果remove方法用到这里就会有问题 加上也没问题
* 集体参考 https://coding.imooc.com/learn/questiondetail/59846.html
*
*/
/**
* TODO 旋转节点的位置在平衡因子被打破的下一个节点为基准 Y的下一个节点X
* LL 进行右旋转
* - y x
* - / \ / \
* - x T4 z y
* - / \ 右旋转 / \ / \
* - z T3 ----->T1 T2 T3 T4
* - / \
* - T1 T2
*/
if (balanceFactor > 1 && getBalanceFactor(root.left) >= 0) {
return rightRotate(root);
}
/**
* 首先 balanceFactor < -1 说明右子树的高度比左子树高 那么破坏的地方一定在右子树
* 其他逻辑与上面相同
*/
/**
* //RR 进行右旋转 进行左旋转
* //
* // y x
* // / \ / \
* // T1 x 左旋转 y z
* // / \ --------> / \ / \
* // T2 z T1 T2 T3 T4
* // / \
* // T3 T4
* //
*/
if (balanceFactor < -1 && getBalanceFactor(root.right) <= 0) {
return leftRotate(root);
}
/**
*
* LR 先左旋转 再右旋转
* //
* //
* // y y z
* // / \ / \ / \
* // x T4 左旋转 z T4 右旋转 x y
* // / \ -------> / \ ------> / \ / \
* // T1 z x T3 T1 T2 T3 T4
* // / \ / \
* // T2 T3 T1 T2
* //
* //
*/
if (balanceFactor > 1 && getBalanceFactor(root.left) < 0) {
root.left = leftRotate(root.left);
return rightRotate(root);
}
/**
* //RL 先右旋转 再左旋转 这里可以看到经过对x
* // 的右旋转已经转换成RR的问题了
* //
* // y y z
* // / \ 先右旋转 / \ 左旋转 / \
* // T1 x ---------> T1 z ------> y x
* // / \ / \ / \ / \
* // z T4 T2 x T1 T2 T3 T4
* // / \ / \
* // T2 T3 T3 4
*/
if (balanceFactor < -1 && getBalanceFactor(root.right) > 0) {
//先右旋转 返回的是旋转后的根节点 所以变换之后我们要用原根节点去接住 旋转之后的根节点
root.right = rightRotate(root.right);
//再进行左旋转 还是对root的右子树 然后返回
return leftRotate(root.right);
}
//平衡因子 =<1 那么就是平衡的直接返回 不平衡 那么经过上面的4个if 转化平衡后向上返回
return root;
}
/**
* 原来的结构满足二分搜索树的性质:T1<z<T2<x<T3<y<T4
* <p>
* 向右旋转y:
* <p>
* - y x
* - / \ / \
* - x T4 z y
* - / \ / \ / \
* - z T3 ----->T1 T2 T3 T4
* - / \
* - T1 T2
* <p>
* 对于x节点来说 将j进行了右旋转
* 这个过程是:
* 1. 先将T3取出来 用临时变量存起来
* 2. 然后将y节点整个节点放到x的右子树上
* 3. 将T3放到y的左子树上
* <p>
* //1.
* Node childRightNode = root.left.right;
* //2.
* root.left.right = root;
* //3.
* root.left = childRightNode;
* <p>
* 在这里由于z节点没有变化 高度不用更新
* 但是x,y的节点都发生了变化 所以要更新x和y的高度
* TODO 细节注意 这里要先更新y的高度 在更新x的高度
* x高度是用过y的高度+1得到的
*
* @param y
* @return 右旋转的结果
*/
@SuppressWarnings("SuspiciousNameCombination")
private Node rightRotate(Node y) {
Node x = y.left;
//1.
Node T3 = x.right;
//2.
x.right = y;
//3.
y.left = T3;
y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
return x;
}
/**
* 左旋转的结果 逻辑与右旋转相同
*
* @param y
* @return
*/
// 对节点y进行向左旋转操作,返回旋转后新的根节点x
// y x
// / \ / \
// T1 x 向左旋转 (y) y z
// / \ - - - - - - - -> / \ / \
// T2 z T1 T2 T3 T4
// / \
// T3 T4
private Node leftRotate(Node y) {
Node x = y.right;
Node T2 = x.left;
x.left = y;
y.right = T2;
y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
return x;
}
/**
* 删除 BST中的任意元素 在删除后可以选择右子树的最小值 也可以选择左子树的最大值
*
* @param key
* @return
*/
public V remove(K key) {
Node node = getNode(root, key);
if (node != null) {
root = removeElement(root, key);
return node.value;
}
return null;
}
/**
* 返回最小值的那个节点
*
* @param root
* @return
*/
private Node minimum(Node root) {
if (root.left == null)
return root;
return minimum(root.left);
}
/**
* 删除最小值 返回新的BST的根节点
*
* @param root
* @return
*/
// private Node removeMin(Node root) {
// if (root.left == null) {
// return root;
// }
//
// Node node = removeMin(root.left);
// if (node.right != null) {
// root.left = node.right;
// node.right = null;
// size--;
// }
//
// return root;
// }
/**
* 判断一个二叉树的节点是否是平衡二叉树
* BST的特点是一个节点的左子树小于父节点右子树大于父节点
* 中序遍历是升序的
*
* @return
*/
public boolean isBST() {
// if (root == null)//空节点也是BST
// throw new IllegalArgumentException("node is null");
List<K> list = new ArrayList<>();
inOrder(root, list);
// if (list.size() > 1) {//如果node不为空 那么至少size=1 1个节点也是BST
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1).compareTo(list.get(i)) > 0) {
return false;
}
}
// }
return true;
}
/**
* 判断这个二叉树是否是平衡二叉树
*
* @return
*/
public boolean isBalance() {
return isBalance(root);
}
private boolean isBalance(Node node) {
if (node == null) {
return true;
}
int balanceFactor = getBalanceFactor(node);
if (Math.abs(balanceFactor) > 1) {
return false;
}
return isBalance(node.left) && isBalance(node.right);
}
/**
* 中序遍历 将遍历结果方法list中
*
* @param node
* @param list
*/
private void inOrder(Node node, List<K> list) {
if (node == null) {
return;
}
inOrder(node.left, list);
list.add(node.key);
inOrder(node.right, list);
}
/**
* 删除指定的任意元素
* https://coding.imooc.com/learn/questiondetail/102451.html
* @return 返回删除元素后新的bst的根
*/
public Node removeElement(Node root, K key) {
if (root == null) {
return null;
}
//要返回删除后的根节点的临时存储
//因为在节点后可能就会出现平衡被打破
//所以我们用个临时的变量进行存储每个要返回上一次递归的根节点前 进行统一处理
Node retNode;
if (key.compareTo(root.key) > 0) {//在右子树上
root.right = removeElement(root.right, key);
//删除节点再赋值根节点后 可能平衡被打破了
//所以再返回之前要先判断和处理
retNode = root;
} else if (key.compareTo(root.key) < 0) {//在左子树上
root.left = removeElement(root.left, key);
retNode = root;
} else {//相等 这里不能用if if if 因为之前是直接return了 进入条件语句后就返回了
//现在不返回 每次只能进入一个分支 所以要用 if elseif else
if (root.left == null) {
Node rightNode = root.right;
root.right = null;
size--;
retNode = rightNode;
} else if (root.right == null) {
Node leftNode = root.left;
root.left = null;
size--;
retNode = leftNode;
} else {
Node successor = minimum(root.right);
//TODO 虽然我们下面进行了同一的处理 但是 再删除removeMin最小值的时候 我们没有去维护是否平衡 所有这里有两个解决方案:
//1. 给removeMin添加平衡的代码
//2. 直接调用removeElement方法 如下
successor.right = removeElement(root.right, successor.key);
successor.left = root.left;
root.left = root.right = null;
retNode = successor;
}
}
//再计算平衡因子的之前 可能要删除的节点是叶子节点 那么我们 获取null节点的retNode.left可能会空指针所以
if (retNode == null) {
return null;
}
// 更新height
retNode.height = 1 + Math.max(getHeight(retNode.left), getHeight(retNode.right));
// 计算平衡因子
int balanceFactor = getBalanceFactor(retNode);
// 平衡维护
if (balanceFactor > 1 && getBalanceFactor(retNode.left) >= 0)
return rightRotate(retNode);
if (balanceFactor < -1 && getBalanceFactor(retNode.right) <= 0)
return leftRotate(retNode);
if (balanceFactor > 1 && getBalanceFactor(retNode.left) < 0) {
retNode.left = leftRotate(retNode.left);
return rightRotate(retNode);
}
if (balanceFactor < -1 && getBalanceFactor(retNode.right) > 0) {
retNode.right = rightRotate(retNode.right);
return leftRotate(retNode);
}
return retNode;
}
public void set(K key, V newValue) {
Node node = getNode(root, key);
if (node == null) {
throw new IllegalArgumentException("key 不存在");
}
node.value = newValue;
}
public V get(K key) {
Node node = getNode(root, key);
if (node == null) {
throw new IllegalArgumentException("key没有对应的value");
}
return node.value;
}
public boolean contains(K key) {
Node node = getNode(this.root, key);
return node != null;
}
private Node getNode(Node node, K key) {
if (node == null) {
return null;
}
if (key.compareTo(node.key) > 0) {//在右子树上
return getNode(node.right, key);
} else if (key.compareTo(node.key) < 0) {//在左子树上
return getNode(node.left, key);
} else {//相等
return node;
}
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public static void main(String[] args) {
// Map<Integer, String> map = new BSTMap<>();
// for (int i = 0; i < 5; i++) {
// map.add(i, "value" + i);
// }
// System.out.println(map.getSize());
//
// String remove = map.remove(2);
// System.out.println(remove);
// System.out.println(map.getSize());
// System.out.println("Pride and Prejudice");
//
ArrayList<String> words = new ArrayList<>();
if (FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
AVLTree<String, Integer> map = new AVLTree<>();
for (String word : words) {
if (map.contains(word))
map.set(word, map.get(word) + 1);
else
map.add(word, 1);
}
System.out.println("Total different words: " + map.getSize());
System.out.println("Frequency of PRIDE: " + map.get("pride"));
System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
System.out.println("is BST " + map.isBST());
System.out.println("is Balance " + map.isBalance());
for(String word: words){
map.remove(word);
if(!map.isBST() || !map.isBalance())
throw new RuntimeException("Error");
}
}
System.out.println();
System.out.println();
System.out.println("===================性能测试=====================");
performanceTesting();
}
private static void performanceTesting() {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if (FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
// Collections.sort(words);
// Test BST
long startTime = System.nanoTime();
BST<String, Integer> bst = new BST<>();
for (String word : words) {
if (bst.contains(word))
bst.set(word, bst.get(word) + 1);
else
bst.add(word, 1);
}
for (String word : words)
bst.contains(word);
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
System.out.println("BST: " + time + " s");
// Test AVL Tree
startTime = System.nanoTime();
AVLTree<String, Integer> avl = new AVLTree<>();
for (String word : words) {
if (avl.contains(word))
avl.set(word, avl.get(word) + 1);
else
avl.add(word, 1);
}
for (String word : words)
avl.contains(word);
endTime = System.nanoTime();
time = (endTime - startTime) / 1000000000.0;
System.out.println("AVL: " + time + " s");
}
System.out.println();
}
}
| 27.153166 | 92 | 0.453436 |
3c5285db11ab26f294d3b82f22320f40cf517605 | 28,279 | package org.adligo.tests4j_v1_tests.gwt_refs.v2_6;
import java.util.Set;
import org.adligo.gwt_refs.v2_6.GWT_2_6_Lang;
import org.adligo.tests4j.models.shared.reference_groups.jse.JSE_Lang;
import org.adligo.tests4j.shared.asserts.reference.AllowedReferences;
import org.adligo.tests4j.shared.asserts.reference.I_ClassAttributes;
import org.adligo.tests4j.shared.asserts.reference.I_FieldSignature;
import org.adligo.tests4j.shared.asserts.reference.I_MethodSignature;
import org.adligo.tests4j.shared.asserts.reference.MethodSignature;
import org.adligo.tests4j.shared.common.ClassMethods;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_tests.base_trials.I_CountType;
import org.adligo.tests4j_tests.base_trials.SourceFileCountingTrial;
import org.adligo.tests4j_tests.references_groups.Tests4J_Gwt_v2_6_GwtReferenceGroup;
//try to keep coverage above 10 for the 0.1 release
@SourceFileScope (sourceClass=GWT_2_6_Lang.class, minCoverage=40.0)
@AllowedReferences (groups=Tests4J_Gwt_v2_6_GwtReferenceGroup.class)
public class GWT_2_6_LangTrial extends SourceFileCountingTrial {
private GWT_2_6_LangDelegates delegates;
public GWT_2_6_LangTrial() {
delegates = new GWT_2_6_LangDelegates(this);
}
@Test
public void testAppendable() {
I_ClassAttributes result = GWT_2_6_Lang.getAppendable();
assertEquals("java.lang.Appendable", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateAppendableMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(3, ms.size());
}
@Test
public void testAutoCloseable() {
I_ClassAttributes result = GWT_2_6_Lang.getAutoCloseable();
assertEquals("java.lang.AutoCloseable", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateAutoCloseableMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(1, ms.size());
}
@Test
public void testBoolean() {
I_ClassAttributes result = GWT_2_6_Lang.getBoolean();
assertEquals("java.lang.Boolean", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.BOOLEAN}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateBooleanMemberAsserts(result);
assertEquals(3, fs.size());
assertEquals(12, ms.size());
}
@Test
public void testObject() {
I_ClassAttributes result = GWT_2_6_Lang.getObject();
assertEquals("java.lang.Object", result.getName());
Set<I_MethodSignature> ms = result.getMethods();
assertNotNull(ms);
assertContains(ms, new MethodSignature("<init>"));
delegates.delegateObjectMemberAsserts(result);
Set<I_FieldSignature> fs = result.getFields();
assertEquals(0, fs.size());
assertEquals(5, ms.size());
}
@Test
public void testStackTraceElement() {
I_ClassAttributes result = GWT_2_6_Lang.getStackTraceElement();
assertEquals("java.lang.StackTraceElement", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.STRING, JSE_Lang.STRING, ClassMethods.INT}));
delegates.delegateStackTraceElementMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(10, ms.size());
}
@Test
public void testThrowable() {
I_ClassAttributes result = GWT_2_6_Lang.getThrowable();
assertEquals("java.lang.Throwable", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.THROWABLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.THROWABLE}));
delegates.delegateThrowableMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(19, ms.size());
}
@Test
public void testException() {
I_ClassAttributes result = GWT_2_6_Lang.getException();
assertEquals("java.lang.Exception", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.THROWABLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.THROWABLE}));
delegates.delegateExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(19, ms.size());
}
@Test
public void testRuntimeException() {
I_ClassAttributes result = GWT_2_6_Lang.getRuntimeException();
assertEquals("java.lang.RuntimeException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.THROWABLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.THROWABLE}));
delegates.delegateRuntimeExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(19, ms.size());
}
@Test
public void testRunnable() {
I_ClassAttributes result = GWT_2_6_Lang.getRunnable();
assertEquals("java.lang.Runnable", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateRunnableMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(1, ms.size());
}
@Test
public void testArithmeticException() {
I_ClassAttributes result = GWT_2_6_Lang.getArithmeticException();
assertEquals("java.lang.ArithmeticException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateArithmeticExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testIndexOutOfBoundsException() {
I_ClassAttributes result = GWT_2_6_Lang.getIndexOutOfBoundsException();
assertEquals("java.lang.IndexOutOfBoundsException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateIndexOutOfBoundsExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testFloat() {
I_ClassAttributes result = GWT_2_6_Lang.getFloat();
assertEquals("java.lang.Float", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.DOUBLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.FLOAT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateFloatMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(23, ms.size());
}
@Test
public void testArrayIndexOutOfBoundsException() {
I_ClassAttributes result = GWT_2_6_Lang.getArrayIndexOutOfBoundsException();
assertEquals("java.lang.ArrayIndexOutOfBoundsException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateArrayIndexOutOfBoundsExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(18, ms.size());
}
@Test
public void testArrayStoreException() {
I_ClassAttributes result = GWT_2_6_Lang.getArrayStoreException();
assertEquals("java.lang.ArrayStoreException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateArrayStoreExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testError() {
I_ClassAttributes result = GWT_2_6_Lang.getError();
assertEquals("java.lang.Error", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.THROWABLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.THROWABLE}));
delegates.delegateErrorMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(19, ms.size());
}
@Test
public void testAssertionError() {
I_ClassAttributes result = GWT_2_6_Lang.getAssertionError();
assertEquals("java.lang.AssertionError", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.BOOLEAN}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.CHAR}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.DOUBLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.FLOAT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.OBJECT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.LONG}));
delegates.delegateAssertionErrorMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(23, ms.size());
}
@Test
public void testClassCastException() {
I_ClassAttributes result = GWT_2_6_Lang.getClassCastException();
assertEquals("java.lang.ClassCastException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateClassCastExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testIllegalArgumentException() {
I_ClassAttributes result = GWT_2_6_Lang.getIllegalArgumentException();
assertEquals("java.lang.IllegalArgumentException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.THROWABLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.THROWABLE}));
delegates.delegateIllegalArgumentExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(19, ms.size());
}
@Test
public void testIllegalStateException() {
I_ClassAttributes result = GWT_2_6_Lang.getIllegalStateException();
assertEquals("java.lang.IllegalStateException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.THROWABLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.THROWABLE}));
delegates.delegateIllegalStateExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(19, ms.size());
}
@Test
public void testNegativeArraySizeException() {
I_ClassAttributes result = GWT_2_6_Lang.getNegativeArraySizeException();
assertEquals("java.lang.NegativeArraySizeException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateNegativeArraySizeExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testNoSuchMethodException() {
I_ClassAttributes result = GWT_2_6_Lang.getNoSuchMethodException();
assertEquals("java.lang.NoSuchMethodException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateNoSuchMethodExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testNullPointerException() {
I_ClassAttributes result = GWT_2_6_Lang.getNullPointerException();
assertEquals("java.lang.NullPointerException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateNullPointerExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testNumberFormatException() {
I_ClassAttributes result = GWT_2_6_Lang.getNumberFormatException();
assertEquals("java.lang.NumberFormatException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateNumberFormatExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(17, ms.size());
}
@Test
public void testNumber() {
I_ClassAttributes result = GWT_2_6_Lang.getNumber();
assertEquals("java.lang.Number", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateNumberMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(10, ms.size());
}
@Test
public void testStringIndexOutOfBoundsException() {
I_ClassAttributes result = GWT_2_6_Lang.getStringIndexOutOfBoundsException();
assertEquals("java.lang.StringIndexOutOfBoundsException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateStringIndexOutOfBoundsExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(18, ms.size());
}
@Test
public void testUnsupportedOperationException() {
I_ClassAttributes result = GWT_2_6_Lang.getUnsupportedOperationException();
assertEquals("java.lang.UnsupportedOperationException", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING, JSE_Lang.THROWABLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.THROWABLE}));
delegates.delegateUnsupportedOperationExceptionMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(19, ms.size());
}
@Test
public void testCharSequence() {
I_ClassAttributes result = GWT_2_6_Lang.getCharSequence();
assertEquals("java.lang.CharSequence", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateCharSequenceMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(4, ms.size());
}
@Test
public void testCharacter() {
I_ClassAttributes result = GWT_2_6_Lang.getCharacter();
assertEquals("java.lang.Character", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.CHAR}));
delegates.delegateCharacterMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(39, ms.size());
}
@Test
public void testByte() {
I_ClassAttributes result = GWT_2_6_Lang.getByte();
assertEquals("java.lang.Byte", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.BYTE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateByteMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(20, ms.size());
}
@Test
public void testClass() {
I_ClassAttributes result = GWT_2_6_Lang.getClassAttributeMembers();
assertEquals("java.lang.Class", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateClassMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(14, ms.size());
}
@Test
public void testCloneable() {
I_ClassAttributes result = GWT_2_6_Lang.getCloneable();
assertEquals("java.lang.Cloneable", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertEquals(0, fs.size());
assertEquals(0, ms.size());
}
@Test
public void testComparable() {
I_ClassAttributes result = GWT_2_6_Lang.getComparable();
assertEquals("java.lang.Comparable", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateComparableMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(1, ms.size());
}
@Test
public void testDeprecated() {
I_ClassAttributes result = GWT_2_6_Lang.getDeprecated();
assertEquals("java.lang.Deprecated", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertEquals(0, fs.size());
assertEquals(0, ms.size());
}
@Test
public void testOverride() {
I_ClassAttributes result = GWT_2_6_Lang.getOverride();
assertEquals("java.lang.Override", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertEquals(0, fs.size());
assertEquals(0, ms.size());
}
@Test
public void testSuppressWarnings() {
I_ClassAttributes result = GWT_2_6_Lang.getSuppressWarnings();
assertEquals("java.lang.SuppressWarnings", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateSuppressWarningsMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(1, ms.size());
}
@Test
public void testIterable() {
I_ClassAttributes result = GWT_2_6_Lang.getIterable();
assertEquals("java.lang.Iterable", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateIterableMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(1, ms.size());
}
@Test
public void testEnum() {
I_ClassAttributes result = GWT_2_6_Lang.getEnum();
assertEquals("java.lang.Enum", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateEnumMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(10, ms.size());
}
@Test
public void testDouble() {
I_ClassAttributes result = GWT_2_6_Lang.getDouble();
assertEquals("java.lang.Double", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.DOUBLE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateDoubleMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(20, ms.size());
}
@Test
public void testInteger() {
I_ClassAttributes result = GWT_2_6_Lang.getInteger();
assertEquals("java.lang.Integer", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateIntegerMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(35, ms.size());
}
@Test
public void testLong() {
I_ClassAttributes result = GWT_2_6_Lang.getLong();
assertEquals("java.lang.Long", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.LONG}));
delegates.delegateLongMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(35, ms.size());
}
@Test
public void testMath() {
I_ClassAttributes result = GWT_2_6_Lang.getMath();
assertEquals("java.lang.Math", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateMathMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(45, ms.size());
}
@Test
public void testShort() {
I_ClassAttributes result = GWT_2_6_Lang.getShort();
assertEquals("java.lang.Short", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.SHORT}));
delegates.delegateShortMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(22, ms.size());
}
@Test
public void testString() {
I_ClassAttributes result = GWT_2_6_Lang.getString();
assertEquals("java.lang.String", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {"[" + ClassMethods.BYTE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {"[" + ClassMethods.BYTE, ClassMethods.INT,
ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {"[" + ClassMethods.BYTE, ClassMethods.INT,
ClassMethods.INT, JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {"[" + ClassMethods.BYTE, JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {"[" + ClassMethods.CHAR}));
assertContains(ms, new MethodSignature("<init>",
new String[] {"[" + ClassMethods.CHAR, ClassMethods.INT, ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {"[" + ClassMethods.INT, ClassMethods.INT, ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING_BUFFER}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING_BUILDER}));
delegates.delegateStringMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(71, ms.size());
}
@Test
public void testStringBuffer() {
I_ClassAttributes result = GWT_2_6_Lang.getStringBuffer();
assertEquals("java.lang.StringBuffer", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.CHAR_SEQUENCE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateStringBufferMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(52, ms.size());
}
@Test
public void testStringBuilder() {
I_ClassAttributes result = GWT_2_6_Lang.getStringBuilder();
assertEquals("java.lang.StringBuilder", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
assertContains(ms, new MethodSignature("<init>"));
assertContains(ms, new MethodSignature("<init>",
new String[] {ClassMethods.INT}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.CHAR_SEQUENCE}));
assertContains(ms, new MethodSignature("<init>",
new String[] {JSE_Lang.STRING}));
delegates.delegateStringBuilderMemberAsserts(result);
assertEquals(0, fs.size());
assertEquals(53, ms.size());
}
@Test
public void testSystem() {
I_ClassAttributes result = GWT_2_6_Lang.getSystem();
assertEquals("java.lang.System", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateSystemMemberAsserts(result);
assertEquals(2, fs.size());
assertEquals(7, ms.size());
}
@Test
public void testVoid() {
I_ClassAttributes result = GWT_2_6_Lang.getVoid();
assertEquals("java.lang.Void", result.getName());
Set<I_FieldSignature> fs = result.getFields();
Set<I_MethodSignature> ms = result.getMethods();
delegates.delegateVoidMemberAsserts(result);
assertEquals(1, fs.size());
assertEquals(0, ms.size());
}
/**keep at the bottom of the file
*
*/
@Override
public int getTests(I_CountType type) {
return super.getTests(type, 47, true);
}
@Override
public int getAsserts(I_CountType type) {
int thisAsserts = 1106;
if (type.isFromMetaWithCoverage()) {
//code coverage and circular dependencies +
//custom afterTrialTests
return super.getAsserts(type, thisAsserts + 3);
} else {
return super.getAsserts(type, thisAsserts);
}
}
@Override
public int getUniqueAsserts(I_CountType type) {
int thisUniqueAsserts = 1037;
if (type.isFromMetaWithCoverage()) {
//code coverage and circular dependencies +
//custom afterTrialTests
return super.getUniqueAsserts(type, thisUniqueAsserts + 3);
} else {
return super.getUniqueAsserts(type, thisUniqueAsserts);
}
}
}
| 37.258235 | 88 | 0.736412 |
4ffb376d791c776ebf78b48c574aaca4ae413ebb | 723 | package me.osm.dkiselev.intervaltimer.persistence;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import java.util.List;
import me.osm.dkiselev.intervaltimer.model.Timer;
/**
* Created by dkiselev on 2/2/18.
*/
@Dao
public interface TimerDao {
@Query("SELECT * FROM timers")
List<Timer> getAll();
@Query("SELECT * FROM timers WHERE id IN (:ids)")
List<Timer> loadAllByIds(int[] ids);
@Insert
long[] insertAll(Timer... timers);
@Delete
void delete(Timer timer);
@Update
void update(Timer timer);
}
| 20.657143 | 53 | 0.715076 |
543fde4e253c73a2e201eaa16717d8fef4ec0107 | 2,579 | /*
* 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 hu.cherubits.wonderjam.entities;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
/**
*
* @author lordoftheflies
*/
@MappedSuperclass
public abstract class UniqueEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen")
@org.hibernate.annotations.Type(type = "pg-uuid")
private UUID id;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
@Basic
@Column(length = 1000)
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@ManyToOne
private ContainerContentEntity parent;
public ContainerContentEntity getParent() {
return parent;
}
public void setParent(ContainerContentEntity parent) {
this.parent = parent;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof UniqueEntity)) {
return false;
}
UniqueEntity other = (UniqueEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.digitaldefense.christeam.entities.ContentEntity[ id=" + id + " ]";
}
}
| 26.050505 | 102 | 0.675843 |
2e97e8d29cbdfa6707bdc9cb5e33d8cb0a929f25 | 114 | package com.itheilv.mybatisplus.test;
/**
* @author WSQ
* @since 2020-09-25
*/
public class MybatisTest {
}
| 10.363636 | 37 | 0.666667 |
3f39b8d5460c5895a3685c5e2511a9e6fcf67ab9 | 773 | package com.javamaster.b2c.cloud.test.pattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created on 2018/10/13.<br/>
*
* @author yudong
*/
//当属性有变更时,调用/refresh接口会刷新属性,从而得到变更后的属性值
@RefreshScope
@RestController
@RequestMapping("/greenmail")
public class RefreshPropController {
@Value("${greenmail.company}")
private String company;
@GetMapping("/company")
public String test() {
System.out.println("the value is:" + company);
return company;
}
}
| 24.15625 | 72 | 0.751617 |
061ad23da4f38d74f770c1741722e263e840ef6f | 980 | // Unique Email Addresses
// Leetcode problem 929
// https://leetcode.com/problems/unique-email-addresses/
class Solution {
// Implementation that prioritizes low memory usage over
// low running time.
public int numUniqueEmails(String[] emails) {
String[] processedEmails = new String[emails.length];
Map<String, Integer> map = new HashMap<>();
for(int i = 0; i < emails.length; i++){
String[] temp = emails[i].split("@");
String local = temp[0];
String domain = temp[1];
if(local.indexOf('+') >= 0)
local = local.substring(0, local.indexOf('+'));
local = local.replaceAll("\\.", "");
processedEmails[i] = local + '@' + domain;
System.out.println(processedEmails[i]);
}
for(String x: processedEmails)
map.put(x, map.getOrDefault(x, 0)+1);
return map.size();
}
} | 32.666667 | 63 | 0.539796 |
75a885c86982a912463b5c214d9b75e9c5c5da3e | 371 | package com.hunk.route.domain;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author hunk
* @date 2022/2/24
* <p>
*/
public interface BankInfoRepository extends JpaRepository<BankInfo, Long> {
/**
* 查询银行信息根据bankId
*
* @param bankId id
* @return BankInfo
*/
BankInfo findBankInfoByBankId(String bankId);
}
| 18.55 | 75 | 0.665768 |
8dbc638b30b561ed35c930a03de6cd1d1542e66b | 1,654 | /*
* Copyright 2017-2018 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.sketches.datasketches.sampling.binaryoperator;
import com.yahoo.sketches.sampling.ReservoirItemsUnion;
import uk.gov.gchq.koryphe.Since;
import uk.gov.gchq.koryphe.Summary;
import uk.gov.gchq.koryphe.binaryoperator.KorypheBinaryOperator;
/**
* A {@code ReservoirItemsUnionAggregator} is a {@link java.util.function.BinaryOperator} that aggregates
* {@link ReservoirItemsUnion}s. It does this by extracting a {@link com.yahoo.sketches.sampling.ReservoirItemsSketch}
* from each {@link ReservoirItemsUnion} and merges that using
* {@link ReservoirItemsUnion#update(com.yahoo.sketches.sampling.ReservoirItemsSketch)}.
*
* @param <T> The type of object in the reservoir.
*/
@Since("1.0.0")
@Summary("Aggregates ReservoirItemsUnions")
public class ReservoirItemsUnionAggregator<T> extends KorypheBinaryOperator<ReservoirItemsUnion<T>> {
@Override
public ReservoirItemsUnion<T> _apply(final ReservoirItemsUnion<T> a, final ReservoirItemsUnion<T> b) {
a.update(b.getResult());
return a;
}
}
| 39.380952 | 118 | 0.76179 |
38e3de7e0f893afb773b84fa9d945ca454910754 | 1,733 | package br.com.zup.anaminadakis.transacao.compra.controller;
import br.com.zup.anaminadakis.transacao.cartao.model.Cartao;
import br.com.zup.anaminadakis.transacao.cartao.repository.CartaoRepository;
import br.com.zup.anaminadakis.transacao.novatransacao.dto.TransacaoDto;
import br.com.zup.anaminadakis.transacao.novatransacao.model.Transacao;
import br.com.zup.anaminadakis.transacao.novatransacao.repository.TransacaoRepository;
import br.com.zup.anaminadakis.transacao.validacao.TratamentoDeErro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/cartoes")
public class CompraController {
@Autowired
CartaoRepository cartaoRepository;
@Autowired
TransacaoRepository transacaoRepository;
@GetMapping("/{id}")
public ResponseEntity<?> buscaUtlimasCompras(@PathVariable String id) {
Optional<Cartao> cartaoVerificado = cartaoRepository.findById(id);
if (cartaoVerificado.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new TratamentoDeErro("Cartao id", "ID do cartão inválido."));
}
List<Transacao> ultimasCompras = transacaoRepository.findTop10ByCartaoIdOrderByEfetivadaEmDesc(id);
return ResponseEntity.ok(ultimasCompras.stream().map(TransacaoDto::new));
}
}
| 39.386364 | 107 | 0.788806 |
4f92a882afb13e35afdd7d9b0db592564c2bc641 | 3,349 | package com.bnd.math.task;
import java.util.Collection;
import com.bnd.core.domain.task.Task;
import com.bnd.math.domain.evo.Chromosome;
import com.bnd.math.domain.evo.EvoGaSetting;
import com.bnd.math.domain.evo.EvoRun;
import com.bnd.math.domain.evo.EvoTask;
import com.bnd.math.task.EvoTaskParts.EvoRunHolder;
import com.bnd.math.task.EvoTaskParts.EvoTaskHolder;
public class EvoRunTask extends Task implements EvoTaskHolder, EvoRunHolder {
// TODO: move gaSetting here
private EvoTask evoTask;
private EvoPopulationContentStoreOption populationContentStoreOption;
private EvoPopulationSelection populationSelection;
private boolean autoSave = true;
private EvoRun<?> evoRun;
private Collection<Chromosome<?>> initChromosomes;
private Chromosome<?> initChromosome; // optional, normally initial chromosomes are generated randomly
public EvoRunTask() {
super();
}
public EvoPopulationContentStoreOption getPopulationContentStoreOption() {
return populationContentStoreOption;
}
public void setPopulationContentStoreOption(EvoPopulationContentStoreOption storeOption) {
this.populationContentStoreOption = storeOption;
}
public EvoPopulationSelection getPopulationSelection() {
return populationSelection;
}
public void setPopulationSelection(EvoPopulationSelection populationSelection) {
this.populationSelection = populationSelection;
}
@Override
public EvoTask getEvoTask() {
return evoTask;
}
@Override
public void setEvoTask(EvoTask task) {
this.evoTask = task;
}
@Override
public boolean isEvoTaskDefined() {
return evoTask != null;
}
@Override
public boolean isEvoTaskComplete() {
return isEvoTaskDefined() && evoTask.getName() != null;
}
public void setEvoTaskId(Long id) {
if (id != null) {
evoTask = new EvoTask();
evoTask.setId(id);
}
}
public Long getEvoTaskId() {
if (isEvoTaskDefined()) {
return evoTask.getId();
}
return null;
}
public void setEvoRunId(Long id) {
if (id != null) {
evoRun = new EvoRun();
evoRun.setId(id);
}
}
public Long getEvoRunId() {
if (evoRun != null) {
return evoRun.getId();
}
return null;
}
@Override
public EvoRun<?> getEvoRun() {
return evoRun;
}
@Override
public void setEvoRun(EvoRun<?> evoRun) {
this.evoRun = evoRun;
}
@Override
public boolean isEvoRunDefined() {
return evoRun != null;
}
@Override
public boolean isEvoRunComplete() {
return isEvoRunDefined() && evoRun.getEvoTask() != null;
}
public Chromosome<?> getInitChromosome() {
return initChromosome;
}
public void setInitChromosome(Chromosome<?> initChromosome) {
this.initChromosome = initChromosome;
}
public boolean hasInitChromosome() {
return initChromosome != null;
}
public Collection<Chromosome<?>> getInitChromosomes() {
return initChromosomes;
}
public void setInitChromosomes(Collection<Chromosome<?>> initChromosomes) {
this.initChromosomes = initChromosomes;
}
public boolean hasInitChromosomes() {
return initChromosomes != null && !initChromosomes.isEmpty();
}
public boolean getAutoSave() {
return autoSave;
}
public boolean isAutoSave() {
return autoSave;
}
public void setAutoSave(boolean autoSave) {
this.autoSave = autoSave;
}
public EvoGaSetting getGaSetting() {
return evoTask != null ? evoTask.getGaSetting() : null;
}
} | 21.888889 | 114 | 0.739922 |
ff58415075e9f158946fe0366cd50b472478b0d6 | 2,894 | package com.taobao.atlas.update.util;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Created by wuzhong on 2016/11/23.
*/
public class ZipUtils {
private static int BUFFEREDSIZE = 1024;
public static void unzip(String zipFilename, String outputDirectory)
throws IOException {
File outFile = new File(outputDirectory);
if (!outFile.exists()) {
outFile.mkdirs();
}
if (!outFile.exists()) {
throw new IOException("file not exist");
}
ZipFile zipFile = new ZipFile(zipFilename);
Enumeration en = zipFile.entries();
ZipEntry zipEntry = null;
while (en.hasMoreElements()) {
zipEntry = (ZipEntry) en.nextElement();
if (zipEntry.isDirectory()) {
String dirName = zipEntry.getName();
dirName = dirName.substring(0, dirName.length() - 1);
File f = new File(outFile.getPath() + File.separator + dirName);
f.mkdirs();
} else {
String strFilePath = outFile.getPath() + File.separator
+ zipEntry.getName();
File f = new File(strFilePath);
// 判断文件不存在的话,就创建该文件所在文件夹的目录
if (!f.exists()) {
String[] arrFolderName = zipEntry.getName().split("/");
String strRealFolder = "";
for (int i = 0; i < (arrFolderName.length - 1); i++) {
strRealFolder += arrFolderName[i] + File.separator;
}
strRealFolder = outFile.getPath() + File.separator
+ strRealFolder;
File tempDir = new File(strRealFolder);
tempDir.mkdirs();
}
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
try {
int c;
byte[] by = new byte[BUFFEREDSIZE];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.flush();
} catch (IOException e) {
throw e;
} finally {
closeQuitely(out);
closeQuitely(in);
}
}
}
zipFile.close();
}
private static void closeQuitely(Closeable stream) {
try {
if (stream != null)
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 33.264368 | 80 | 0.493435 |
b8d45ab549962494abdf73fc297fd63530037a25 | 508 | package com.project.lithodemo.recyclerview.viewholder;
import android.view.View;
import android.widget.TextView;
import com.project.lithodemo.R;
import com.project.lithodemo.data.Article;
public class TextViewHolder extends ItemViewHolder {
protected TextView mTitleLabel;
public TextViewHolder(View v) {
super(v);
mTitleLabel = (TextView) v.findViewById(R.id.lbl_title);
}
public void setData(Article article) {
mTitleLabel.setText(article.getTitle());
}
}
| 23.090909 | 64 | 0.730315 |
011687f3226e93c7e5cd0de3a39ed5ab7a1d573e | 15,587 | /*
* Copyright (c) 2016, Kinvey, Inc. All rights reserved.
*
* This software is licensed to you under the Kinvey terms of service located at
* http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this
* software, you hereby accept such terms of service (and any agreement referenced
* therein) and agree that you have read, understand and agree to be bound by such
* terms of service and are of legal age to agree to such terms with Kinvey.
*
* This software contains valuable confidential and proprietary information of
* KINVEY, INC and is subject to applicable licensing agreements.
* Unauthorized reproduction, transmission or distribution of this file and its
* contents is a violation of applicable laws.
*
*/
package com.kinvey.java;
import com.google.common.base.Preconditions;
import com.kinvey.java.query.AbstractQuery;
import com.kinvey.java.query.MongoQueryFilter;
import com.kinvey.java.query.AbstractQuery.SortOrder;
import com.kinvey.java.query.QueryFilter.QueryFilterBuilder;
import java.io.Serializable;
/**
* Query API for creating query requests to NetworkManager store.
*
* @author mjsalinger
* @since 2.0
*/
public class Query extends AbstractQuery implements Serializable {
private static final long serialVersionUID = 5635939847038496849L;
private int limit;
private int skip;
/**
* Constructor for Query API. Used to instantiate a query request.
*
* @param builder that implements QueryFilter.builder
*/
public Query(QueryFilterBuilder builder) {
super(builder);
}
/**
* Constructor for Query API. Used to instantiate a query request.
*
* defaults to using a Mongo DB Query Filter.
*/
public Query(){
this(new MongoQueryFilter.MongoQueryFilterBuilder());
}
public boolean isQueryEmpty(){
return(getQueryFilterMap().size() == 0);
}
// Comparison Operators
/**
* Add a filter condition for a specific field being equal to a value
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query equals(String key, Object value) {
Preconditions.checkNotNull(key);
builder.equals(key, value);
return this;
}
/**
* Add a filter condition for a specific field being greater than a value
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query greaterThan(String key, Object value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.GREATERTHAN), key, value);
return this;
}
/**
* Add a filter condition for a specific field being less than than a value
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query lessThan(String key, Object value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.LESSTHAN), key, value);
return this;
}
/**
* Add a filter condition for a specific field being greater than or equal to a value
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query greaterThanEqualTo(String key, Object value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.GREATERTHANEQUAL), key, value);
return this;
}
/**
* Add a filter condition for a specific field being less than or equal to a value
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query lessThanEqualTo(String key, Object value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.LESSTHANEQUAL), key, value);
return this;
}
/**
* Adds a sort sort condition to the Query
*
* @param field Field to sort on
* @param order Order to sort values (Ascending/Descending)
* @return Query object
*/
public Query addSort(String field, SortOrder order) {
super.addSort(field, order);
return this;
}
/**
* Sets the raw query string
*
* @param queryString
* @return this
*/
public Query setQueryString(String queryString){
super.setQueryString(queryString);
return this;
}
/**
* Add a filter condition for a specific field being not equal to a value
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query notEqual(String key, Object value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.NOTEQUAL), key, value);
return this;
}
/**
* Add a filter condition for a specific field being in an array of values
*
* @param key Field to filter on
* @param value An array of values
* @return Query object
*/
public Query in(String key, Object[] value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.IN), key, value);
return this;
}
/**
* Add a filter condition for a specific field being not in an array of values
*
* @param key Field to filter on
* @param value An array of values
* @return Query object
*/
public Query notIn(String key, Object[] value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.NOTIN), key, value);
return this;
}
/**
* Add a filter condition for a specific field compared to a regular expression
* <p/>
* A regex must begin with a carat `^`, and case-insensitive queries `/i` are not supported.
* <p/>
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query regEx(String key, Object value) {
if (value.toString().contains("/i")){
throw new UnsupportedOperationException("Cannot perform regex which contains an `/i`");
}
if (!value.toString().startsWith("^")){
throw new UnsupportedOperationException("All regex must be anchored, it must begin with a carat `^`");
}
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.REGEX), key, value);
return this;
}
/**
* Add a filter condition for a specific field for strings that start with the given value.
*
* @param key Field to filter on
* @param value Value condition for filter
* @return Query object
*/
public Query startsWith(String key, Object value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.REGEX), key, "^" + value);
return this;
}
// /**
// * Add a filter condition for a specific field for strings that ends with the given value.
// *
// * @param key Field to filter on
// * @param value Value condition for filter
// * @return Query object
// */
// @Deprecated
// public Query endsWith(String key, Object value) {
// Preconditions.checkNotNull(key);
// builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.REGEX), key, value + "$");
// return this;
// }
/**
* Add a filter condition for a specific field holds an array and contains all the values
*
* @param key Field to filter on
* @param value An array of values Values
* @return Query object
*/
public Query all(String key, Object[] value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.ALL), key, value);
return this;
}
/**
* Add a filter for any array that is of the given size
*
* @param key Field to filter on
* @param value The expected size of the array
* @return Query object
*/
public Query size(String key, int value) {
Preconditions.checkNotNull(key);
builder.addFilter(builder.getOperator(QueryFilterBuilder.Operators.SIZE), key, value);
return this;
}
// Logical Operators
/**
* Joins a second Query filter to the current query object and connects them with a logical AND
*
* @param query The query which contains the QueryFilter to be joined
* @return Query object
*/
public Query and(AbstractQuery query) {
Preconditions.checkNotNull(query);
builder.joinFilter(builder.getOperator(QueryFilterBuilder.Operators.AND), query);
return this;
}
/**
* Joins a second Query filter to the current query object and connects them with a logical OR
*
* @param query The query which contains the QueryFilter to be joined
* @return Query object
*/
public Query or(AbstractQuery query) {
Preconditions.checkNotNull(query);
builder.joinFilter(builder.getOperator(QueryFilterBuilder.Operators.OR), query);
return this;
}
/**
* Negates the current query's comparison operators
*
* @return Query object
*/
public Query not() {
builder.negateQuery();
return this;
}
/**
* Sets the maximum number of records to return
*
* @param limit The maximum number of records to return
* @return Query
*/
public Query setLimit(int limit) {
this.limit=limit;
return this;
}
/**
*
* @return Current limit
*/
public int getLimit() {
return this.limit;
}
/**
* @return current sort string
*/
public String getSortString() {
StringBuilder sortStringBuilder = new StringBuilder();
if (sort.size() > 0) {
sortStringBuilder.append("{");
for (String field : sort.keySet()) {
sortStringBuilder.append("\"");
sortStringBuilder.append(field);
sortStringBuilder.append("\" : ");
sortStringBuilder.append(sort.get(field) == SortOrder.ASC ? 1 : -1);
sortStringBuilder.append(",");
}
sortStringBuilder.deleteCharAt(sortStringBuilder.length()-1);
sortStringBuilder.append("}");
}
return sortStringBuilder.toString();
}
/**
* Sets the number of records to skip before returning the results (useful for pagination).
*
* @return Query object
*/
public Query setSkip(int skip) {
this.skip=skip;
return this;
}
/**
* @return Current skip setting
*/
public int getSkip() {
return this.skip;
}
// Geolocation Queries
/**
* Used on Geospatial fields to return all points near a given point.
*
* @param field The geolocation field to filter on
* @param lat latitude
* @param lon longitude
* @return Query object
*/
public Query nearSphere(String field, double lat, double lon) {
Preconditions.checkNotNull(field);
Preconditions.checkArgument(lat >= -90 && lat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(lon >= -180 && lon <=180, "Lon must be between -180 and 180");
return nearSphere(field, lat, lon, -1);
}
/**
* Used on Geospatial fields to return all points near a given point.
*
* @param field The geolocation field to filter on
* @param lat latitude
* @param lon longitude
* @param maxDistance The maximum distance a geolocation point can be from the given point
* @return
*/
public Query nearSphere(String field, double lat, double lon, double maxDistance) {
Preconditions.checkNotNull(field);
Preconditions.checkArgument(lat >= -90 && lat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(lon >= -180 && lon <=180, "Lon must be between -180 and 180");
double[] arrayPoint = new double[2];
arrayPoint[0] = lat;
arrayPoint[1] = lon;
builder.addLocationFilter(field, builder.getOperator(QueryFilterBuilder.Operators.NEARSPHERE),
arrayPoint, maxDistance);
return this;
}
@Override
public AbstractQuery withinBox(String field, double pointOneLat, double pointOneLon, double pointTwoLat,
double pointTwoLon) {
Preconditions.checkNotNull(field);
Preconditions.checkArgument(pointOneLat >= -90 && pointOneLat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(pointOneLon >= -180 && pointOneLon <=180, "Lon must be between -180 and 180");
Preconditions.checkArgument(pointTwoLat >= -90 && pointTwoLat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(pointTwoLon >= -180 && pointTwoLon <=180, "Lon must be between -180 and 180");
double[][] arrayPoints = new double[2][2];
arrayPoints[0][0] = pointOneLat;
arrayPoints[0][1] = pointOneLon;
arrayPoints[1][0] = pointTwoLat;
arrayPoints[1][1] = pointTwoLon;
builder.addLocationWhereFilter(field, builder.getOperator(QueryFilterBuilder.Operators.WITHINBOX),arrayPoints);
return this;
}
@Override
public AbstractQuery withinPolygon(String field, double pointOneLat, double pointOneLon, double pointTwoLat,
double pointTwoLon, double pointThreeLat, double pointThreeLon,
double pointFourLat, double pointFourLon) {
Preconditions.checkNotNull(field);
Preconditions.checkArgument(pointOneLat >= -90 && pointOneLat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(pointOneLon >= -180 && pointOneLon <=180, "Lon must be between -180 and 180");
Preconditions.checkArgument(pointTwoLat >= -90 && pointTwoLat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(pointTwoLon >= -180 && pointTwoLon <=180, "Lon must be between -180 and 180");
Preconditions.checkArgument(pointThreeLat >= -90 && pointThreeLat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(pointThreeLon >= -180 && pointThreeLon <=180, "Lon must be between -180 and 180");
Preconditions.checkArgument(pointFourLat >= -90 && pointFourLat <=90, "Lat must be between -90 and 90");
Preconditions.checkArgument(pointFourLon >= -180 && pointFourLon <=180, "Lon must be between -180 and 180");
double[][] arrayPoints = new double[4][2];
arrayPoints[0][0] = pointOneLat;
arrayPoints[0][1] = pointOneLon;
arrayPoints[1][0] = pointTwoLat;
arrayPoints[1][1] = pointTwoLon;
arrayPoints[2][0] = pointThreeLat;
arrayPoints[2][1] = pointThreeLon;
arrayPoints[3][0] = pointFourLat;
arrayPoints[3][1] = pointFourLon;
builder.addLocationWhereFilter(field, builder.getOperator(QueryFilterBuilder.Operators.WITHINPOLYGON),
arrayPoints);
return this;
}
}
| 34.792411 | 119 | 0.642458 |
91d19a9805aee3e9b5b6b74980ebac998efa0718 | 1,519 | package explorviz.server.login;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import explorviz.server.database.DBConnection;
import explorviz.shared.auth.User;
import explorviz.visualization.login.LoginService;
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {
private static final long serialVersionUID = 4691982194784805198L;
@Override
public Boolean isLoggedIn() {
final Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isAuthenticated()) {
return true;
} else {
return false;
}
}
@Override
public void logout() {
final Subject currentUser = SecurityUtils.getSubject();
final User user = DBConnection.getUserByName(getCurrentUsernameStatic());
user.setFirstLogin(false);
DBConnection.updateUser(user);
currentUser.logout();
}
@Override
public User getCurrentUser() {
return DBConnection.getUserByName(getCurrentUsernameStatic());
}
@Override
public void setFinishedExperimentState(final boolean finishedState) {
final User user = DBConnection.getUserByName(getCurrentUsernameStatic());
user.setExperimentFinished(finishedState);
DBConnection.updateUser(user);
}
public static String getCurrentUsernameStatic() {
final Subject currentUser = SecurityUtils.getSubject();
if ((currentUser == null) || (currentUser.getPrincipal() == null)) {
return "";
}
return currentUser.getPrincipal().toString();
}
} | 26.649123 | 84 | 0.77551 |
de325aa228efdda6e5449ebf1a9a322eef5c2896 | 174 | package com.example.hellostudiotesting;
/**
* Created by ian on 2016-07-13.
*/
public class DataModel {
public String getName() {
return "Robin Good";
}
}
| 15.818182 | 39 | 0.637931 |
bbacbd857b57c7a7e832a41d126f5e05c3b275b4 | 6,679 | package com.example.sagar.helpthem;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class QuestionPage extends AppCompatActivity {
public String response;
public int countQuestion;
public TextView tv;
public TextView question;
public static String diagnosis;
public String string2 = "This is sample question 2";
public String string3 = "This is sample question 3";
public String string4 = "This is sample question 4";
public String string5 = "This is sample question 5";
FirebaseDatabase database;
DatabaseReference myRef;
DatabaseReference myRef2;
public String newQuestion;
private static final String TAG = "Questions";
Resources res;
static String[] planets;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question_page);
res = getResources();
planets = res.getStringArray(R.array.planets_array);
Button buttonYES = (Button) findViewById(R.id.buttonYES);
Button buttonNO = (Button) findViewById(R.id.buttonNO);
tv = (TextView) findViewById(R.id.number);
question = (TextView) findViewById(R.id.question);
String tvValue = tv.getText().toString();
countQuestion = Integer.parseInt(tvValue);
buttonYES.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
response = "YES";
updateQuestion(response);
}
});
buttonNO.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
response = "NO";
updateQuestion(response);
}
});
database = FirebaseDatabase.getInstance();
myRef = database.getReference("message");
myRef.setValue("Hello, World!");
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void updateQuestion(String response) {
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
// Send value of response to firebase
//GETS TWO QUESTIONS
for (int i = 0; i < 2; i++){
database = FirebaseDatabase.getInstance();
myRef2 = database.getReference("Questions");
myRef2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
newQuestion = dataSnapshot.getValue(String.class);
//Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
countQuestion += 1;
String lastChar = newQuestion.substring(newQuestion.length() - 1);
if (lastChar.equals("?")) {
tv.setText(countQuestion + "");
question.setText(newQuestion);
} else {
diagnosis = newQuestion;
Intent sendStuff = new Intent(this, FinalPage.class);
sendStuff.putExtra("diagnosis", diagnosis);
startActivity(sendStuff);
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("QuestionPage Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
| 35.152632 | 92 | 0.647402 |
319bddb752ddb5e5e25f9b6c5209b8544bbfb5a2 | 6,783 | package com.gempukku.swccgo.cards.set9.dark;
import com.gempukku.swccgo.cards.AbstractLostInterrupt;
import com.gempukku.swccgo.cards.GameConditions;
import com.gempukku.swccgo.common.*;
import com.gempukku.swccgo.filters.Filter;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.GameUtils;
import com.gempukku.swccgo.logic.TriggerConditions;
import com.gempukku.swccgo.logic.actions.CancelCardActionBuilder;
import com.gempukku.swccgo.logic.actions.PlayInterruptAction;
import com.gempukku.swccgo.logic.effects.*;
import com.gempukku.swccgo.logic.modifiers.MayNotBeBattledModifier;
import com.gempukku.swccgo.logic.timing.Action;
import com.gempukku.swccgo.logic.timing.Effect;
import com.gempukku.swccgo.logic.timing.EffectResult;
import com.gempukku.swccgo.logic.timing.results.LostFromTableResult;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Set: Death Star II
* Type: Interrupt
* Subtype: Lost
* Title: Young Fool
*/
public class Card9_141 extends AbstractLostInterrupt {
public Card9_141() {
super(Side.DARK, 6, "Young Fool", Uniqueness.UNIQUE);
setLore("'Now, young Skywalker ... you will die.'");
setGameText("If opponent's character present with Emperor was just lost, lose 1 Force to place that character out of play. OR Release frozen Luke at your Throne Room (Luke may not be battled until end of your next turn) OR Cancel NOOOOOOOOOOOO!");
addIcons(Icon.DEATH_STAR_II);
}
@Override
protected List<PlayInterruptAction> getGameTextOptionalAfterActions(final String playerId, final SwccgGame game, EffectResult effectResult, final PhysicalCard self) {
// Check condition(s)
if (TriggerConditions.justLostWasPresentWith(game, effectResult, Filters.and(Filters.opponents(self), Filters.character), Filters.Emperor)) {
final PhysicalCard justLostCard = ((LostFromTableResult) effectResult).getCard();
final PlayInterruptAction action = new PlayInterruptAction(game, self);
action.setText("Place " + GameUtils.getFullName(justLostCard) + " out of play");
// Pay cost(s)
action.appendCost(
new LoseForceEffect(action, playerId, 1, true));
// Allow response(s)
action.allowResponses("Place " + GameUtils.getCardLink(justLostCard) + " out of play",
new RespondablePlayCardEffect(action) {
@Override
protected void performActionResults(Action targetingAction) {
// Perform result(s)
action.appendEffect(
new PlaceCardOutOfPlayFromOffTableEffect(action, justLostCard));
}
}
);
return Collections.singletonList(action);
}
return null;
}
@Override
protected List<PlayInterruptAction> getGameTextTopLevelActions(final String playerId, final SwccgGame game, final PhysicalCard self) {
List<PlayInterruptAction> actions = new LinkedList<PlayInterruptAction>();
Filter lukeFilter = Filters.and(Filters.Luke, Filters.frozenCaptive, Filters.at(Filters.and(Filters.your(self), Filters.Throne_Room)));
// Check condition(s)
if (GameConditions.canTarget(game, self, SpotOverride.INCLUDE_CAPTIVE, lukeFilter)) {
final PlayInterruptAction action = new PlayInterruptAction(game, self);
action.setText("Release frozen Luke");
// Choose target(s)
action.appendTargeting(
new TargetCardOnTableEffect(action, playerId, "Choose frozen Luke", lukeFilter) {
@Override
protected void cardTargeted(final int targetGroupId, final PhysicalCard targetedCard) {
action.addAnimationGroup(targetedCard);
// Allow response(s)
action.allowResponses("Release " + GameUtils.getCardLink(targetedCard),
new RespondablePlayCardEffect(action) {
@Override
protected void performActionResults(Action targetingAction) {
// Get the targeted card(s) from the action using the targetGroupId.
// This needs to be done in case the target(s) were changed during the responses.
final PhysicalCard finalTarget = targetingAction.getPrimaryTargetCard(targetGroupId);
// Perform result(s)
action.appendEffect(
new ReleaseCaptiveEffect(action, finalTarget));
action.appendEffect(
new AddUntilEndOfPlayersNextTurnModifierEffect(action,
playerId, new MayNotBeBattledModifier(self, finalTarget),
"Makes " + GameUtils.getCardLink(finalTarget) + " not able to be battled"));
}
}
);
}
}
);
actions.add(action);
}
// Check condition(s)
if (GameConditions.canTargetToCancel(game, self, Filters.NOOOOOOOOOOOO)) {
final PlayInterruptAction action = new PlayInterruptAction(game, self);
// Build action using common utility
CancelCardActionBuilder.buildCancelCardAction(action, Filters.NOOOOOOOOOOOO, Title.NOOOOOOOOOOOO);
actions.add(action);
}
return actions;
}
@Override
protected List<PlayInterruptAction> getGameTextOptionalBeforeActions(final String playerId, SwccgGame game, final Effect effect, final PhysicalCard self) {
// Check condition(s)
if (TriggerConditions.isPlayingCard(game, effect, Filters.NOOOOOOOOOOOO)
&& GameConditions.canCancelCardBeingPlayed(game, self, effect)) {
final PlayInterruptAction action = new PlayInterruptAction(game, self);
// Build action using common utility
CancelCardActionBuilder.buildCancelCardBeingPlayedAction(action, effect);
return Collections.singletonList(action);
}
return null;
}
} | 51.386364 | 255 | 0.613593 |
3abf5c1a37c05a36e04d475a4297942e6523d4e7 | 230 | package com.huiketong.cofpasgers.json.data;
import lombok.Data;
@Data
public class VoucherDetailData {
String price;
String title;
String context;
String user_count;
String start_time;
String end_time;
}
| 16.428571 | 43 | 0.721739 |
4bc936eca5703a41fe1e98b6062075d0b3cc7688 | 3,480 | package com.planetpeopleplatform.mybakingapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.planetpeopleplatform.mybakingapp.adapter.IngredientAdapter;
import com.planetpeopleplatform.mybakingapp.model.Step;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Hammedopejin on 5/24/2018.
*/
public class IngredientActivity extends AppCompatActivity implements IngredientAdapter.IngredientAdapterOnClickHandler {
private List<Step> mStepArray;
@BindView(R.id.ingredients_tv)
public TextView mStepDescriptionTV;
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredients);
ButterKnife.bind(this);
final SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(
(getString(R.string.my_baking_app)), MODE_PRIVATE);
if(findViewById(R.id.activity_ingredients_linear_layout) != null) {
// This LinearLayout will only initially exist in the two-pane tablet case
mTwoPane = true;
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.tablet), mTwoPane);
editor.apply();
Bundle extra = getIntent().getBundleExtra("bundle");
mStepArray = extra.getParcelableArrayList(getString(R.string.steps));
assert mStepArray != null;
String videoUrl = mStepArray.get(0).getVideoURL();
if(savedInstanceState == null) {
// In two-pane mode, add initial BodyPartFragments to the screen
FragmentManager fragmentManager = getSupportFragmentManager();
// Create a new head BodyPartFragment
HeadFragment headFragment = new HeadFragment();
fragmentManager.beginTransaction()
.add(R.id.head_container, headFragment)
.commit();
headFragment.setVideoUrl(videoUrl);
// Create and display the body BodyPartFragments
BodyFragment bodyFragment = new BodyFragment();
BodyFragment.setStepData(mStepArray, 0);
fragmentManager.beginTransaction()
.add(R.id.body_container, bodyFragment)
.commit();
}
} else {
mTwoPane = false;
}
}
@Override
public void onClick(int position) {
if(mTwoPane) {
String videoUrl = mStepArray.get(position).getVideoURL();
FragmentManager fragmentManager = getSupportFragmentManager();
HeadFragment headFragment = new HeadFragment();
headFragment.setVideoUrl(videoUrl);
fragmentManager.beginTransaction()
.replace(R.id.head_container, headFragment)
.commit();
BodyFragment bodyFragment = new BodyFragment();
BodyFragment.setStepData(mStepArray, position);
fragmentManager.beginTransaction()
.replace(R.id.body_container, bodyFragment)
.commit();
}
}
}
| 33.461538 | 120 | 0.645402 |
f04fb84a7a22daf625a3cdb3ad6dbf187f1b38a1 | 4,088 | package jetbrains.mps.lang.constraints.rules.editor;
/*Generated by MPS */
import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.lang.constraints.rules.editor.Rules_Styles_StyleSheet.AndDefsAreDefinedHintStyleClass;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import jetbrains.mps.nodeEditor.AbstractCellProvider;
import jetbrains.mps.baseLanguage.closures.runtime._FunctionTypes;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.lang.constraints.rules.util.RequiredDefsCalculator;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
/*package*/ class HintIsApplicable_ComponentBuilder_a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
public HintIsApplicable_ComponentBuilder_a(@NotNull EditorContext context, @NotNull SNode node) {
super(context);
myNode = node;
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
/*package*/ EditorCell createCell() {
return createCollection_0();
}
private EditorCell createCollection_0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_vdat08_a");
Style style = new StyleImpl();
new AndDefsAreDefinedHintStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
editorCell.addEditorCell(createCustom_0());
editorCell.addEditorCell(createAlternation_0());
return editorCell;
}
private EditorCell createCustom_0() {
AbstractCellProvider provider = new _FunctionTypes._return_P0_E0<HintDefsCustomEditorCell>() {
public HintDefsCustomEditorCell invoke() {
return new HintDefsCustomEditorCell(myNode);
}
}.invoke();
EditorCell editorCell = provider.createEditorCell(getEditorContext());
editorCell.setCellId("Custom_vdat08_a0");
Style style = new StyleImpl();
new AndDefsAreDefinedHintStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
return editorCell;
}
private EditorCell createAlternation_0() {
boolean alternationCondition = true;
alternationCondition = nodeCondition_vdat08_a1a();
EditorCell editorCell = null;
if (alternationCondition) {
editorCell = createConstant_0();
} else {
editorCell = createConstant_1();
}
Style style = new StyleImpl();
new AndDefsAreDefinedHintStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
return editorCell;
}
private boolean nodeCondition_vdat08_a1a() {
return ListSequence.fromList(new RequiredDefsCalculator().calculate(myNode)).count() == 1;
}
private EditorCell createConstant_0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "is defined");
editorCell.setCellId("Constant_vdat08_a1a");
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_1() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "are defined");
editorCell.setCellId("Constant_vdat08_a1a_0");
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
}
| 40.078431 | 118 | 0.769569 |
2bc3b87d897fa10c81e13f4b526475d3f360a055 | 1,471 | /*
* Copyright (c) 2018. houbinbin Inc.
* markdown-toc All rights reserved.
*/
package com.github.houbb.markdown.toc.core.impl;
import com.github.houbb.markdown.toc.util.TestPathUtil;
import org.junit.Assert;
import org.junit.Test;
import java.util.Locale;
/**
* AtxMarkdownToc 国家化编码测试
*
* @author author
* @version 1.0
* @since 2018-01-30 15:11:47.256
*/
public class AtxMarkdownI18NTest {
@Test
public void pathMustDirEnglish() {
try {
Locale.setDefault(new Locale("en", "US"));
String path = TestPathUtil.getAppRootPath("subNotExists");
AtxMarkdownToc.newInstance()
.genTocDir(path);
} catch (Exception e) {
final String expectedMsg = "D:\\github\\markdown-toc/src/test/resources/subNotExists path is not a directory";
final String msg = e.getMessage();
Assert.assertEquals(expectedMsg, msg);
}
}
@Test
public void pathMustDirChinese() {
try {
Locale.setDefault(new Locale("zh", "CN"));
String path = TestPathUtil.getAppRootPath("subNotExists");
AtxMarkdownToc.newInstance()
.genTocDir(path);
} catch (Exception e) {
final String expectedMsg = "D:\\github\\markdown-toc/src/test/resources/subNotExists 文件路径必须是文件夹";
final String msg = e.getMessage();
Assert.assertEquals(expectedMsg, msg);
}
}
}
| 28.288462 | 122 | 0.613188 |
cea4a32703771ef123a6e4295ba33e00f1ffc150 | 3,456 | package org.xcolab.view.pages.contestmanagement.beans;
import org.xcolab.client.contest.ContestClientUtil;
import org.xcolab.client.contest.pojo.Contest;
import org.xcolab.view.pages.contestmanagement.wrappers.WikiPageWrapper;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
public class ContestAdminBean implements Serializable {
private static final long serialVersionUID = 1L;
private String emailTemplateUrl;
private ContestModelSettingsBean contestModelSettings;
private boolean hideRibbons;
@NotNull(message = "A contest URL name must be specified")
private String contestUrlName;
@NotNull(message = "A contest year must be specified")
private Long contestYear;
@NotNull(message = "A contest tier must be selected.")
private Long contestTier;
@NotNull(message = "A contest type must be selected.")
private Long contestType;
public ContestAdminBean() { }
public ContestAdminBean(Contest contest) {
if (contest != null) {
contestUrlName = contest.getContestUrlName();
contestYear = contest.getContestYear();
contestTier = contest.getContestTier();
contestType = contest.getContestTypeId();
hideRibbons = contest.getHideRibbons();
emailTemplateUrl = contest.getEmailTemplateUrl();
contestModelSettings = new ContestModelSettingsBean(contest);
}
}
public void persist(Contest contest) {
updateContest(contest);
WikiPageWrapper.updateContestWiki(contest);
}
private void updateContest(Contest contest) {
contest.setContestUrlName(contestUrlName);
contest.setContestYear(contestYear);
contest.setEmailTemplateUrl(emailTemplateUrl);
contest.setContestTier(contestTier);
contest.setContestTypeId(contestType);
contest.setHideRibbons(hideRibbons);
ContestClientUtil.updateContest(contest);
contestModelSettings.persist(contest);
}
public String getEmailTemplateUrl() {
if (emailTemplateUrl != null) {
return emailTemplateUrl;
} else {
return "";
}
}
public void setEmailTemplateUrl(String emailTemplateUrl) {
this.emailTemplateUrl = emailTemplateUrl;
}
public String getContestUrlName() {
return contestUrlName;
}
public void setContestUrlName(String contestUrlName) {
this.contestUrlName = contestUrlName;
}
public Long getContestYear() {
return contestYear;
}
public void setContestYear(Long contestYear) {
this.contestYear = contestYear;
}
public Long getContestTier() {
return contestTier;
}
public void setContestTier(Long contestTier) {
this.contestTier = contestTier;
}
public Long getContestType() {
return contestType;
}
public void setContestType(Long contestType) {
this.contestType = contestType;
}
public ContestModelSettingsBean getContestModelSettings() {
return contestModelSettings;
}
public void setContestModelSettings(ContestModelSettingsBean contestModelSettings) {
this.contestModelSettings = contestModelSettings;
}
public boolean isHideRibbons() {
return hideRibbons;
}
public void setHideRibbons(boolean hideRibbons) {
this.hideRibbons = hideRibbons;
}
}
| 27.428571 | 88 | 0.689525 |
094a39ab24efe069590842d64cc16030b90177fd | 318 | package com.emerchantpay.gateway.api.constants;
public class ReminderConstants {
public static String REMINDERS_CHANNEL_EMAIL = "email";
public static String REMINDERS_CHANNEL_SMS = "sms";
public static Integer MIN_ALLOWED_REMINDER_MINUTES = 1;
public static Integer MAX_ALLOWED_REMINDER_DAYS = 31;
}
| 35.333333 | 59 | 0.789308 |
778067e4f0e94bcd0a62cc49f8516405d7d1d04f | 716 | import java.util.Comparator;
public class WorkerComparator implements Comparator<Worker> {
@Override
public int compare(Worker worker1, Worker worker2) {
Integer exp1 = worker1.getExp();
Integer exp2 = worker2.getExp();
Integer result1 = exp2 - exp1;
if (result1 == 0) {
Integer age1 = worker1.getAge();
Integer age2 = worker2.getAge();
Integer result2 = age1 - age2;
if (result2 == 0) {
String name1 = worker1.getLastName();
String name2 = worker2.getLastName();
return name1.compareTo(name2);
}
return result2;
}
return result1;
}
}
| 31.130435 | 61 | 0.553073 |
cc5269281718015a1f4ae4f563c2ae901d76d09a | 611 | package org.pcsoft.framework.jfex.controls.ui.component.workflow.component.cell;
import javafx.scene.control.ListCell;
import org.pcsoft.framework.jfex.controls.ui.component.workflow.type.WorkflowElementInfoDescriptor;
public class WorkflowElementListCell extends ListCell<WorkflowElementInfoDescriptor> {
@Override
protected void updateItem(WorkflowElementInfoDescriptor item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (item != null && !empty) {
setGraphic(new WorkflowElementCellPane(item));
}
}
}
| 30.55 | 99 | 0.731588 |
b31fbc3a935dec106499bdefb2b13ed17a15ac81 | 1,147 | package com.vehicle.framework.mvc.render;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.vehicle.common.RESULT_BEAN_STATUS_CODE;
import com.vehicle.common.ResultBean;
import com.vehicle.framework.mvc.param.RequestChain;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* @author HALOXIAO
**/
@Slf4j
public class JsonRender implements Render {
@Override
public void handler(RequestChain requestChain) {
HttpServletResponse response = requestChain.getHttpServletResponse();
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try (PrintWriter printWriter = response.getWriter()) {
printWriter.write(JSON.toJSONString(requestChain.getResultBean(),SerializerFeature.WriteMapNullValue));
printWriter.flush();
} catch (IOException e) {
log.error("can not open PrintWriter", e);
}
}
}
| 31 | 115 | 0.738448 |
675d7200dfa980f3a1192639b1ccd4b448dd76ef | 4,272 | /*
* Copyright 2017 Software Engineering and Synthesis Group
*
* 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.sesygroup.choreography.abstractparticipantbehavior.model;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.collections.Sets;
import com.sesygroup.choreography.abstractparticipantbehavior.model.AbstractParticipantBehavior;
import com.sesygroup.choreography.abstractparticipantbehavior.model.State;
import com.sesygroup.choreography.abstractparticipantbehavior.model.action.SendActionTransition;
import com.sesygroup.choreography.abstractparticipantbehavior.model.message.OutputMessage;
/**
*
* @author Alexander Perucci (http://www.alexanderperucci.com/)
*
*/
public class AbstractParticipantBehaviorTest {
private static AbstractParticipantBehavior mockedAbstractParticipantBehavior;
private static AbstractParticipantBehavior abstractParticipantBehavior;
@BeforeClass
public static void setUp() {
State initialState = new State("initialState");
State targetState = new State("targetState");
OutputMessage outputMessage = new OutputMessage("outputMessage");
SendActionTransition transition = new SendActionTransition(initialState, targetState, outputMessage);
abstractParticipantBehavior = new AbstractParticipantBehavior();
abstractParticipantBehavior.getStates().add(initialState);
abstractParticipantBehavior.getStates().add(targetState);
abstractParticipantBehavior.setInitialState(initialState);
abstractParticipantBehavior.getMessages().add(outputMessage);
abstractParticipantBehavior.getTransitions().add(transition);
mockedAbstractParticipantBehavior = Mockito.mock(AbstractParticipantBehavior.class);
Mockito.when(mockedAbstractParticipantBehavior.getStates()).thenReturn(Sets.newSet(initialState, targetState));
Mockito.when(mockedAbstractParticipantBehavior.getInitialState()).thenReturn(initialState);
Mockito.when(mockedAbstractParticipantBehavior.getMessages()).thenReturn(Sets.newSet(outputMessage));
Mockito.when(mockedAbstractParticipantBehavior.getTransitions()).thenReturn(Sets.newSet(transition));
Mockito.when(mockedAbstractParticipantBehavior.validate()).thenReturn(true);
}
@Test
public void testGetStates() {
Assert.assertEquals(mockedAbstractParticipantBehavior.getStates(), abstractParticipantBehavior.getStates());
}
@Test
public void testGetInitialState() {
Assert.assertEquals(mockedAbstractParticipantBehavior.getInitialState(),
abstractParticipantBehavior.getInitialState());
}
@Test
public void testGetMessages() {
Assert.assertEquals(mockedAbstractParticipantBehavior.getMessages(), abstractParticipantBehavior.getMessages());
}
@Test
public void testGetTransitions() {
Assert.assertEquals(mockedAbstractParticipantBehavior.getTransitions(),
abstractParticipantBehavior.getTransitions());
}
@Test
public void testValidate() {
Assert.assertEquals(mockedAbstractParticipantBehavior.validate(), abstractParticipantBehavior.validate());
}
@Test()
public void testNotValidate() {
AbstractParticipantBehavior abstractParticipantBehavior = new AbstractParticipantBehavior();
abstractParticipantBehavior.getTransitions().add(new SendActionTransition(new State("initialState"),
new State("targetState"), new OutputMessage("outputMessage")));
Assert.assertFalse(abstractParticipantBehavior.validate());
}
@Test()
public void testValidateEmptyAbstractParticipantBehavior() {
Assert.assertTrue(new AbstractParticipantBehavior().validate());
}
}
| 42.29703 | 118 | 0.781601 |
e800d1408929f367713f3970b2aab1b9caaa8127 | 529 | package com.microservice.backend.entity;
import com.microservice.backend.enums.OrderStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserOrder {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
long id;
@Column(name= "status")
OrderStatus orderStatus;
@Column(name= "itemsJson")
String items;
}
| 18.241379 | 51 | 0.746692 |
a77c4967818ced6e9e4e2fb4cd403263a2e8940e | 1,685 | /*
* Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.dynamodb.sessionmanager;
import java.io.Serializable;
/**
* Class to test serialization/deserialization of a custom object class in the session data
*/
public class CustomSessionClass implements Serializable {
private static final long serialVersionUID = -4704592898757232021L;
private final String data;
public CustomSessionClass(String data) {
this.data = data;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomSessionClass other = (CustomSessionClass) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
return true;
}
} | 30.636364 | 91 | 0.64273 |
cc9c54821bb8d51d3d48173f73de5a4aeaabb05a | 748 | package edu.pdx.cs410J.jcaillie;
import edu.pdx.cs410J.InvokeMainTestCase;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.StringContains.containsString;
public class KataIT extends InvokeMainTestCase {
@Test
public void invokingMainWithNoArgumentsHasExitCodeOf1() {
InvokeMainTestCase.MainMethodResult result = invokeMain(Kata.class);
assertThat(result.getExitCode(), equalTo(1));
}
@Test
public void invokingMainPrintsItsArguments() {
InvokeMainTestCase.MainMethodResult result = invokeMain(Kata.class, "20", "5", "/");
assertThat(result.getTextWrittenToStandardOut(), containsString("20\n5\n/\n"));
}
}
| 31.166667 | 88 | 0.779412 |
ac27de5d1613e8fe82ce19d24f999b5886477cba | 4,649 | package com.sequenceiq.cloudbreak.converter.v4.environment.network;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import com.sequenceiq.cloudbreak.cloud.model.CloudSubnet;
import com.sequenceiq.cloudbreak.core.network.SubnetTest;
import com.sequenceiq.common.api.type.OutboundInternetTraffic;
import com.sequenceiq.common.api.type.PublicEndpointAccessGateway;
import com.sequenceiq.environment.api.v1.environment.model.response.EnvironmentNetworkResponse;
@ExtendWith(MockitoExtension.class)
public class SubnetSelectorTest extends SubnetTest {
private static final String USER_CRN = "crn:cdp:iam:us-west-1:" + UUID.randomUUID() + ":user:" + UUID.randomUUID();
private static final Set<String> NETWORK_CIDRS = Set.of("1.2.3.4/32", "0.0.0.0/0");
@InjectMocks
private SubnetSelector underTest;
@Test
public void testNoSubnetInAvailabilityZone() {
EnvironmentNetworkResponse source = new EnvironmentNetworkResponse();
source.setSubnetMetas(Map.of("key", getCloudSubnet("any")));
Optional<CloudSubnet> subnet = underTest.chooseSubnet(source.getPreferedSubnetId(), source.getSubnetMetas(), AZ_1, true);
assert subnet.isEmpty();
}
@Test
public void testSubnetFoundInAvailabilityZone() {
EnvironmentNetworkResponse source = setupResponse();
source.setSubnetMetas(Map.of("key", getCloudSubnet(AZ_1)));
Optional<CloudSubnet> subnet = underTest.chooseSubnet(source.getPreferedSubnetId(), source.getSubnetMetas(), AZ_1, true);
assert subnet.isPresent();
assertEquals(PRIVATE_ID_1, subnet.get().getId());
}
@Test
public void testChooseEndpointGatewaySubnetFromEndpointSubnetst() {
EnvironmentNetworkResponse source = setupResponse();
source.setSubnetMetas(Map.of("key", getCloudSubnet(AZ_1)));
source.setPublicEndpointAccessGateway(PublicEndpointAccessGateway.ENABLED);
source.setGatewayEndpointSubnetMetas(Map.of("public-key", getPublicCloudSubnet(PUBLIC_ID_1, AZ_1)));
Optional<CloudSubnet> subnet =
underTest.chooseSubnetForEndpointGateway(source, PRIVATE_ID_1);
assert subnet.isPresent();
assertEquals(PUBLIC_ID_1, subnet.get().getId());
}
@Test
public void testChooseEndpointGatewaySubnetFromEnvironmentSubnetst() {
EnvironmentNetworkResponse source = setupResponse();
source.setSubnetMetas(Map.of(
"key1", getPrivateCloudSubnet(PRIVATE_ID_1, AZ_1),
"key2", getPublicCloudSubnet(PUBLIC_ID_1, AZ_1)
));
source.setPublicEndpointAccessGateway(PublicEndpointAccessGateway.ENABLED);
Optional<CloudSubnet> subnet =
underTest.chooseSubnetForEndpointGateway(source, PRIVATE_ID_1);
assert subnet.isPresent();
assertEquals(PUBLIC_ID_1, subnet.get().getId());
}
@Test
public void testChooseEndpointGatewaySubnetNoPublicEndpointSubnets() {
EnvironmentNetworkResponse source = setupResponse();
source.setSubnetMetas(Map.of("key", getPrivateCloudSubnet(PRIVATE_ID_1, AZ_1)));
source.setPublicEndpointAccessGateway(PublicEndpointAccessGateway.ENABLED);
source.setGatewayEndpointSubnetMetas(Map.of("private-key", getPrivateCloudSubnet(PRIVATE_ID_1, AZ_1)));
Optional<CloudSubnet> subnet =
underTest.chooseSubnetForEndpointGateway(source, PRIVATE_ID_1);
assert subnet.isEmpty();
}
@Test
public void testChooseEndpointGatewaySubnetNoPublicEnvironmentSubnets() {
EnvironmentNetworkResponse source = setupResponse();
source.setSubnetMetas(Map.of("key", getPrivateCloudSubnet(PRIVATE_ID_1, AZ_1)));
source.setPublicEndpointAccessGateway(PublicEndpointAccessGateway.ENABLED);
Optional<CloudSubnet> subnet =
underTest.chooseSubnetForEndpointGateway(source, PRIVATE_ID_1);
assert subnet.isEmpty();
}
private CloudSubnet getCloudSubnet(String availabilityZone) {
return new CloudSubnet(PRIVATE_ID_1, "name", availabilityZone, "cidr");
}
private EnvironmentNetworkResponse setupResponse() {
EnvironmentNetworkResponse source = new EnvironmentNetworkResponse();
source.setNetworkCidrs(NETWORK_CIDRS);
source.setOutboundInternetTraffic(OutboundInternetTraffic.DISABLED);
return source;
}
}
| 39.398305 | 129 | 0.739084 |
02a0c70e9207923bd9dc3b9ee0e81357a17487e2 | 1,321 | package com.github.jenya705.mcapi.rest;
import com.github.jenya705.mcapi.BoundingBox;
import com.github.jenya705.mcapi.Vector3;
import lombok.*;
import java.util.Objects;
/**
* @author Jenya705
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class RestBoundingBox {
private double x0;
private double y0;
private double z0;
private double x1;
private double y1;
private double z1;
public static RestBoundingBox from(BoundingBox boundingBox) {
return new RestBoundingBox(
boundingBox.getMinCorner().getX(),
boundingBox.getMinCorner().getY(),
boundingBox.getMinCorner().getZ(),
boundingBox.getMaxCorner().getX(),
boundingBox.getMaxCorner().getY(),
boundingBox.getMaxCorner().getZ()
);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RestBoundingBox)) return false;
if (this == obj) return true;
RestBoundingBox other = (RestBoundingBox) obj;
return Objects.equals(asBoundingBox(), other.asBoundingBox());
}
public BoundingBox asBoundingBox() {
return new BoundingBox(
Vector3.of(x0, y0, z0),
Vector3.of(x1, y1, z1)
);
}
}
| 24.924528 | 70 | 0.626798 |
7dd8f7c0c061bbead98aba8fbd46d2e4f3d132e1 | 330 | package heavy.test.plugin.model.data.assertion.data;
import heavy.test.plugin.model.data.Assertion;
/**
* Created by heavy on 2017/6/2.
*/
public class EndWith extends Assertion {
public EndWith(String content) {
description = content;
}
public String getContent() {
return description;
}
}
| 17.368421 | 52 | 0.672727 |
6ca2b0011b128e78f8756ad97c107cd02bf0ba4a | 3,569 | package io.prplz.skypixel.gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.util.MathHelper;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
public abstract class Pane extends GuiItem {
protected int contentHeight = 0;
protected float scrollPosition = 0;
protected int scrollbarTicks = 0;
protected List<GuiItem> elements = new ArrayList<>();
@Override
public void setSize(int width, int height) {
clampScrollPosition();
super.setSize(width, height);
}
@Override
public void draw(int mouseX, int mouseY, float partialTicks) {
ScaledResolution res = new ScaledResolution(mc);
double scaleW = mc.displayWidth / res.getScaledWidth_double();
double scaleH = mc.displayHeight / res.getScaledHeight_double();
drawRect(x, y, x + width, y + height, 0x80000000);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor((int) (x * scaleW), (int) (mc.displayHeight - (y + height) * scaleH), (int) (width * scaleW), (int) (height * scaleH));
GL11.glPushMatrix();
GL11.glTranslatef(x, y - (int) scrollPosition, 0);
drawContents(mouseX - x, mouseY + (int) scrollPosition - y, partialTicks);
GL11.glPopMatrix();
GL11.glDisable(GL11.GL_SCISSOR_TEST);
if (scrollbarTicks > 0) {
int scrollbarWidth = 3;
int scrollbarHeight = height / 5; // TODO: should scale according to content height
int scrollbarX = x + width - scrollbarWidth;
int scrollbarY = y + (int) (scrollPosition / (contentHeight - height) * (height - scrollbarHeight));
int alpha = Math.min(255, scrollbarTicks * 10);
drawRect(scrollbarX, scrollbarY, scrollbarX + scrollbarWidth, scrollbarY + scrollbarHeight, 0x808080 | alpha << 24);
}
}
public void drawContents(int mouseX, int mouseY, float partialTicks) {
for (GuiItem element : elements) {
element.draw(mouseX, mouseY, partialTicks);
}
}
@Override
public void update() {
if (scrollbarTicks > 0) {
scrollbarTicks--;
}
}
private void clampScrollPosition() {
if (contentHeight < height) {
scrollPosition = 0;
} else {
scrollPosition = MathHelper.clamp_float(scrollPosition, 0.0f, contentHeight - height);
}
}
public void handleMouseInput() {
ScaledResolution res = new ScaledResolution(mc);
int mouseX = (int) (res.getScaledWidth_double() / mc.displayWidth * Mouse.getEventX());
int mouseY = (int) (res.getScaledHeight_double() / mc.displayHeight * (mc.displayHeight - Mouse.getEventY()));
if (containsPoint(mouseX, mouseY)) {
int wheel = Mouse.getEventDWheel();
if (wheel != 0 && height < contentHeight) {
scrollbarTicks = 50;
scrollPosition -= wheel * 0.1f;
clampScrollPosition();
}
int mouseButton = Mouse.getEventButton();
if (Mouse.getEventButtonState()) {
mouseClicked(mouseX - x, mouseY - y + (int) scrollPosition, mouseButton);
}
}
}
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
for (GuiItem element : elements) {
if (element.containsPoint(mouseX, mouseY)) {
element.mouseClicked(mouseX, mouseY, mouseButton);
}
}
}
} | 37.177083 | 142 | 0.616139 |
74fbefe0ef97de2c2310f5e7e24f4f50f070c9c3 | 6,577 | /*
* Maintained by brightSPARK Labs.
* www.brightsparklabs.com
*
* Refer to LICENSE at repository root for license details.
*/
package com.brightsparklabs.asanti.model.schema.type;
import static com.google.common.base.Preconditions.*;
import com.brightsparklabs.asanti.model.schema.DecodingSession;
import com.brightsparklabs.asanti.model.schema.constraint.AsnSchemaConstraint;
import com.brightsparklabs.asanti.model.schema.primitive.AsnPrimitiveTypes;
import com.brightsparklabs.asanti.model.schema.tag.AsnSchemaTag;
import com.brightsparklabs.asanti.schema.AsnBuiltinType;
import com.brightsparklabs.asanti.schema.AsnPrimitiveType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.text.ParseException;
import java.util.Optional;
/**
* A type used to model the types for objects within ASN.1 schema that are Collections, meaning that
* they are the equivalent of a List of the element type they surround. These objects can be either
* Type Definitions, e.g. Type ::= SomeType, or components within a constructed type (SEQUENCE etc),
* e.g. component SomeType
*
* @author brightSPARK Labs
*/
public class AsnSchemaTypeCollection extends BaseAsnSchemaType {
// -------------------------------------------------------------------------
// CLASS VARIABLES
// -------------------------------------------------------------------------
/** built-in types which are considered 'collection'. Currently: SET OF and SEQUENCE OF */
private static final ImmutableSet<AsnPrimitiveType> validTypes =
ImmutableSet.of(AsnPrimitiveTypes.SET_OF, AsnPrimitiveTypes.SEQUENCE_OF);
// -------------------------------------------------------------------------
// INSTANCE VARIABLES
// -------------------------------------------------------------------------
/** name of the type for the elements in this collection */
private final AsnSchemaType elementType;
/** the Universal tag we should expect */
private String myUniversalTag = "";
// -------------------------------------------------------------------------
// CONSTRUCTION
// -------------------------------------------------------------------------
/**
* Default constructor.
*
* @param primitiveType the underlying primitiveType of the defined primitiveType
* @param constraint The constraint on the type. Use {@link AsnSchemaConstraint#NULL} if no
* constraint.
* <p>Example 1<br>
* For {@code SET (SIZE (1..100) OF OCTET STRING (SIZE (10))} this would be {@code (SIZE
* (10)}.
* <p>Example 2<br>
* For {@code INTEGER (1..256)} this would be {@code (1..256)}.
* @param elementType the name of the type for the elements in the SET OF / SEQUENCE OF. E.g.
* for {@code SEQUENCE (SIZE (1..100)) OF OCTET STRING (SIZE (256))}, this would be {@code
* OCTET STRING}
* @throws NullPointerException if {@code primitiveType} is {@code null}
* @throws IllegalArgumentException if {@code primitiveType} is not a collection type
* (Currently: SET OF and SEQUENCE OF)
*/
public AsnSchemaTypeCollection(
AsnPrimitiveType primitiveType,
AsnSchemaConstraint constraint,
AsnSchemaType elementType) {
super(primitiveType, constraint);
checkArgument(
validTypes.contains(primitiveType), "Type must be either SET OF or SEQUENCE OF");
checkNotNull(elementType);
this.elementType = elementType;
}
// -------------------------------------------------------------------------
// PUBLIC METHODS
// -------------------------------------------------------------------------
/**
* Returns the type that this Collection surrounds
*
* @return the underlying type for this Collection, e.g. if the definition was SEQUENCE OF Foo
* then the type for Foo will be returned
*/
public AsnSchemaType getElementType() {
return elementType;
}
/**
* When decoding we are expecting only certain values. Some of those values are the Universal
* tag for the element type. We may not know the element type's actual type at construction so
* as a post parsing step this function will be called to allow us to calculate the tags we
* expect to receive.
*/
public void performTagging() {
myUniversalTag = AsnSchemaTag.createUniversalPortion(elementType.getBuiltinType());
}
// -------------------------------------------------------------------------
// IMPLEMENTATION: BaseAsnSchemaType
// -------------------------------------------------------------------------
@Override
public ImmutableList<AsnSchemaComponentType> getAllComponents() {
return elementType.getAllComponents();
}
@Override
public Optional<AsnSchemaComponentType> getMatchingChild(
String rawTag, DecodingSession decodingSession) {
final AsnSchemaTag tag = AsnSchemaTag.create(rawTag);
if (elementType.getBuiltinType() == AsnBuiltinType.Choice) {
// We have a collection of Choice, so we need to insert the choice option
// We could pre-calculate the options here like we do with Constructed, but given
// that we have to do work here to sort out the index there is little to be saved
final Optional<AsnSchemaComponentType> child =
elementType.getMatchingChild(rawTag, decodingSession);
if (child.isPresent()) {
final String newTag = "[" + tag.getTagIndex() + "]/" + child.get().getName();
// TODO ASN-152
// As with the other ASN-152 "code smells" - good enough for now but if there is
// a refactor done later then think about this a dependency issue.
// This makes it hard to test etc. Ditto a couple of lines lower.
return Optional.of(
new AsnSchemaComponentType(newTag, rawTag, false, child.get().getType()));
}
}
if (tag.getTagPortion().equals(myUniversalTag)) {
return Optional.of(
new AsnSchemaComponentType(
"[" + tag.getTagIndex() + "]", rawTag, false, elementType));
}
return Optional.empty();
}
@Override
public Object accept(final AsnSchemaTypeVisitor<?> visitor) throws ParseException {
return visitor.visit(this);
}
}
| 42.432258 | 100 | 0.587958 |
988053ede217304990cdf63e5e73c78183c6dc0d | 305 | package com.javainsider.apisimulator.apiserver;
import org.springframework.web.bind.annotation.RequestMapping;
@org.springframework.web.bind.annotation.RestController
public class RestController {
@RequestMapping("/api/hello")
public String welcome() {
return "Welcome to API Server app!!!";
}
}
| 21.785714 | 62 | 0.783607 |
6282c9db6e4c9f14a9d330c63a3eb15fc69b54b2 | 332 | package com.example.jdbcexamples.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserAddress {
private Long Id;
private Long userId;
private String name;
private String detail;
}
| 17.473684 | 37 | 0.783133 |
065109231ea584cfe084d11a113387c7642167b6 | 1,375 | /*
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.graalvm.compiler.core.amd64.test;
import static org.graalvm.compiler.core.common.GraalOptions.RegisterPressure;
import static org.junit.Assume.assumeTrue;
import jdk.vm.ci.amd64.AMD64;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.graalvm.compiler.core.test.backend.AllocatorTest;
public class AMD64AllocatorTest extends AllocatorTest {
@Before
public void checkAMD64() {
assumeTrue("skipping AMD64 specific test", getTarget().arch instanceof AMD64);
assumeTrue("RegisterPressure is set -> skip", RegisterPressure.getValue(getInitialOptions()) == null);
}
@Test
public void test1() {
testAllocation("test1snippet", 3, 0, 0);
}
public static long test1snippet(long x) {
return x + 5;
}
@Test
public void test2() {
testAllocation("test2snippet", 3, 0, 0);
}
public static long test2snippet(long x) {
return x * 5;
}
@Ignore
@Test
public void test3() {
testAllocation("test3snippet", 4, 1, 0);
}
public static long test3snippet(long x) {
return x / 3 + x % 3;
}
}
| 18.581081 | 110 | 0.641455 |
e2ce9a06d0599d02ea7a4d6d8a4d9529b9b4296d | 608 | package com.diguage.didp.singleton;
import java.io.Serializable;
/**
* 带 <code>volatile</code> 修饰的懒汉式单例类
*
* @author D瓜哥, https://www.diguage.com/
* @since 2014-5-26.
*/
public class VolatileLazySingleton implements Serializable {
private static volatile VolatileLazySingleton instance = null;
private VolatileLazySingleton() {}
public static VolatileLazySingleton getInstance() {
if (null == instance) {
synchronized (VolatileLazySingleton.class) {
if (null == instance) {
instance = new VolatileLazySingleton();
}
}
}
return instance;
}
}
| 22.518519 | 64 | 0.675987 |
d4209f2d554dd7d96d3b1891ee806c4d066dbd09 | 1,666 | package com.dchprojects.mydictionaryrestapi.service.impl;
import com.dchprojects.mydictionaryrestapi.domain.dto.CreateLanguageRequest;
import com.dchprojects.mydictionaryrestapi.domain.dto.CreateUserRequest;
import com.dchprojects.mydictionaryrestapi.domain.entity.LanguageEntity;
import com.dchprojects.mydictionaryrestapi.domain.entity.UserEntity;
import com.dchprojects.mydictionaryrestapi.service.AdminService;
import com.dchprojects.mydictionaryrestapi.service.LanguageService;
import com.dchprojects.mydictionaryrestapi.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.validation.ValidationException;
import java.util.List;
@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {
private final UserService userService;
private final LanguageService languageService;
@Override
public List<UserEntity> userList() {
return userService.listAll();
}
@Override
public LanguageEntity createLanguage(CreateLanguageRequest createLanguageRequest) {
try {
return languageService.create(createLanguageRequest);
} catch (ValidationException validationException) {
throw new ValidationException(validationException.getLocalizedMessage());
}
}
@Override
public UserEntity registerAdmin(CreateUserRequest createUserRequest) {
try {
return userService.createAdmin(createUserRequest);
} catch (ValidationException validationException) {
throw new ValidationException(validationException.getLocalizedMessage());
}
}
}
| 35.446809 | 87 | 0.783914 |
ec08b7c118ad3c9e95f987d2855eb37c922542f3 | 3,997 | package com.lizhy.model;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Map;
/**
* jetty请求上下文信息
* Created by lizhiyang on 2017-04-26 14:45.
*/
public class JettyProxyContext implements Serializable {
private static final long serialVersionUID = -5582085897172928953L;
private HttpServletRequest request;
private HttpServletResponse response;
//接收请求时间
private Long requestTime;
//请求转发时间
private Long sendTime;
//客户端请求IP
private String requestIP;
private String requestURI;
//转发url地址,从url参数中获取
private String dispatcherUrl;
//url中的参数信息(去除转发路径)
private Map<String, String[]> urlParameterMap;
//body体中的参数信息
private Map<String, String[]> bodyParameterMap;
//所有的参数信息(url和body体)
private Map<String, String[]> parameterMap;
private Map<String, String[]> headerMap;
//请求编码
private String charset;
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public Long getRequestTime() {
return requestTime;
}
public void setRequestTime(Long requestTime) {
this.requestTime = requestTime;
}
public Long getSendTime() {
return sendTime;
}
public void setSendTime(Long sendTime) {
this.sendTime = sendTime;
}
public String getRequestIP() {
return requestIP;
}
public void setRequestIP(String requestIP) {
this.requestIP = requestIP;
}
public String getRequestURI() {
return requestURI;
}
public void setRequestURI(String requestURI) {
this.requestURI = requestURI;
}
public Map<String, String[]> getUrlParameterMap() {
return urlParameterMap;
}
public void setUrlParameterMap(Map<String, String[]> urlParameterMap) {
this.urlParameterMap = urlParameterMap;
}
public Map<String, String[]> getBodyParameterMap() {
return bodyParameterMap;
}
public void setBodyParameterMap(Map<String, String[]> bodyParameterMap) {
this.bodyParameterMap = bodyParameterMap;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
public String getDispatcherUrl() {
return dispatcherUrl;
}
public void setDispatcherUrl(String dispatcherUrl) {
this.dispatcherUrl = dispatcherUrl;
}
public Map<String, String[]> getHeaderMap() {
return headerMap;
}
public void setHeaderMap(Map<String, String[]> headerMap) {
this.headerMap = headerMap;
}
@Override
public String toString() {
try {
String str = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
StringBuilder builder = new StringBuilder(str);
builder.append(";headerMap:").append(JSON.toJSONString(headerMap));
builder.append(";urlParameterMap:").append(JSON.toJSONString(urlParameterMap));
builder.append(";bodyParameterMap:").append(JSON.toJSONString(bodyParameterMap));
builder.append(";parameterMap:").append(JSON.toJSONString(parameterMap));
return builder.toString();
} catch (Exception e) {
return super.toString();
}
}
}
| 26.646667 | 100 | 0.668752 |
28efc7b9dc38828cbfba62fc04714be56c54c33b | 475 | package javassist.expr;
static final class LoopContext
{
NewOp newList;
int maxLocals;
int maxStack;
LoopContext(final int a1) {
super();
this.maxLocals = a1;
this.maxStack = 0;
this.newList = null;
}
void updateMax(final int a1, final int a2) {
if (this.maxLocals < a1) {
this.maxLocals = a1;
}
if (this.maxStack < a2) {
this.maxStack = a2;
}
}
}
| 19 | 48 | 0.517895 |
16fac718ef32c047ead73d62df090e8491099764 | 2,048 | package dynamic_programming;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Boj14846 {
private static final String NEW_LINE = "\n";
private static final int INF = 11;
private static int[][][] dp;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
int[][] arr = new int[N + 1][N + 1];
for(int i = 1; i < N + 1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 1; j < N + 1; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
dp = new int[N + 1][N + 1][INF];
process(N, arr);
int Q = Integer.parseInt(br.readLine());
while(Q-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int[] coordinate = {Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())
, Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())};
sb.append(countArea(coordinate)).append(NEW_LINE);
}
System.out.print(sb);
}
private static void process(int n, int[][] arr) {
for(int i = 1; i < n + 1; i++) {
for(int j = 1; j < n + 1; j++) {
for(int k = 1; k < INF; k++) {
dp[i][j][k] += (dp[i - 1][j][k] + dp[i][j - 1][k] - dp[i - 1][j - 1][k]); // 0부터 각 칸까지의 숫자의 갯수
}
dp[i][j][arr[i][j]]++; // i, j에서 arr[i][j]의 값을 가지는 수의 갯수
}
}
}
private static int countArea(int[] coor) { // coor[0]: x1, coor[1]: y1, coor[2]: x2, coor[3]: y2
int[] count = new int[INF];
for(int i = 1; i < INF; i++) { // 해당 범위 전체 사각형에서 i값을 가지는 수의 갯수
count[i] = dp[coor[2]][coor[3]][i];
}
for(int i = 1; i < INF; i++) { // 전체 범위를 쿼리에 맞게 구역 제한
count[i] += dp[coor[0] - 1][coor[1] - 1][i] - (dp[coor[0] - 1][coor[3]][i] + dp[coor[2]][coor[1] - 1][i]);
}
int result = 0;
for(int i = 1; i < INF; i++) {
if(count[i] > 0) result++;
}
return result;
}
}
| 28.444444 | 109 | 0.566895 |
d489d630c2e2bdeb6408529614a3e3f967048325 | 4,144 | /* */ package com.birosoft.liquid;
/* */
/* */ import java.awt.event.MouseWheelEvent;
/* */ import java.awt.event.MouseWheelListener;
/* */ import java.beans.PropertyChangeEvent;
/* */ import java.beans.PropertyChangeListener;
/* */ import javax.swing.JComponent;
/* */ import javax.swing.JScrollBar;
/* */ import javax.swing.JScrollPane;
/* */ import javax.swing.plaf.ComponentUI;
/* */ import javax.swing.plaf.basic.BasicScrollPaneUI;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class LiquidScrollPaneUI
/* */ extends BasicScrollPaneUI
/* */ implements PropertyChangeListener
/* */ {
/* 38 */ public static ComponentUI createUI(JComponent c) { return new LiquidScrollPaneUI(); }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected class MouseWheelHandler
/* */ implements MouseWheelListener
/* */ {
/* */ private final LiquidScrollPaneUI this$0;
/* */
/* */
/* */
/* */
/* */
/* */
/* 55 */ protected MouseWheelHandler(LiquidScrollPaneUI this$0) { this.this$0 = this$0; }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void mouseWheelMoved(MouseWheelEvent e) {
/* 66 */ if (this.this$0.scrollpane.isWheelScrollingEnabled() && e.getScrollAmount() != 0) {
/* */
/* 68 */ JScrollBar toScroll = this.this$0.scrollpane.getVerticalScrollBar();
/* 69 */ int direction = 0;
/* 70 */ int length = toScroll.getHeight();
/* */
/* 72 */ e; if (toScroll == null || !toScroll.isVisible() || e.getModifiers() == 8) {
/* */
/* 74 */ toScroll = this.this$0.scrollpane.getHorizontalScrollBar();
/* 75 */ if (toScroll == null || !toScroll.isVisible()) {
/* */ return;
/* */ }
/* */
/* 79 */ length = toScroll.getWidth();
/* */ }
/* 81 */ direction = (e.getWheelRotation() < 0) ? -1 : 1;
/* 82 */ if (e.getScrollType() == 0) {
/* */
/* 84 */ int newValue = toScroll.getValue() + e.getWheelRotation() * length / toScroll.getUnitIncrement() * 2;
/* 85 */ toScroll.setValue(newValue);
/* */ }
/* 87 */ else if (e.getScrollType() == 1) {
/* */
/* 89 */ int newValue = toScroll.getValue() + e.getWheelRotation() * length / toScroll.getBlockIncrement() * 2;
/* 90 */ toScroll.setValue(newValue);
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 108 */ protected MouseWheelListener createMouseWheelListener() { return new MouseWheelHandler(this); }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void installUI(JComponent c) {
/* 119 */ super.installUI(c);
/* */
/* 121 */ this.scrollpane.getHorizontalScrollBar().putClientProperty("JScrollBar.isFreeStanding", Boolean.FALSE);
/* */
/* 123 */ this.scrollpane.getVerticalScrollBar().putClientProperty("JScrollBar.isFreeStanding", Boolean.FALSE);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 135 */ protected PropertyChangeListener createScrollBarSwapListener() { return this; }
/* */
/* */ public void propertyChange(PropertyChangeEvent event) {}
/* */ }
/* Location: C:\Users\emill\Dropbox\slimmerWorden\2018-2019-Semester2\THESIS\iPlasma6\tools\iPlasma\liquidlnf.jar!\com\birosoft\liquid\LiquidScrollPaneUI.class
* Java compiler version: 2 (46.0)
* JD-Core Version: 1.0.7
*/ | 28.777778 | 172 | 0.454875 |
14135f5a2bbc31fa4140167a8ac2b42067e266da | 4,829 | package com.battlelancer.seriesguide.util;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.battlelancer.seriesguide.R;
public class ViewTools {
private ViewTools() {
}
// Note: VectorDrawableCompat has features/fixes backported to API 21-23.
// https://medium.com/androiddevelopers/using-vector-assets-in-android-apps-4318fd662eb9
public static void setVectorDrawableTop(TextView textView, @DrawableRes int vectorRes) {
Drawable drawable = AppCompatResources.getDrawable(textView.getContext(), vectorRes);
setCompoundDrawablesWithIntrinsicBounds(textView, null, drawable);
}
public static void setVectorDrawableLeft(TextView textView, @DrawableRes int vectorRes) {
Drawable drawable = AppCompatResources.getDrawable(textView.getContext(), vectorRes);
setCompoundDrawablesWithIntrinsicBounds(textView, drawable, null);
}
/**
* Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the
* text. Use null if you do not want a Drawable there. The Drawables' bounds will be set to
* their intrinsic bounds.
*/
private static void setCompoundDrawablesWithIntrinsicBounds(TextView textView,
Drawable left, Drawable top) {
if (left != null) {
left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
}
if (top != null) {
top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
}
textView.setCompoundDrawables(left, top, null, null);
}
public static void setValueOrPlaceholder(View view, final String value) {
TextView field = (TextView) view;
if (value == null || value.length() == 0) {
field.setText(R.string.unknown);
} else {
field.setText(value);
}
}
/**
* If the given string is not null or empty, will make the label and value field {@link
* View#VISIBLE}. Otherwise both {@link View#GONE}.
*
* @return True if the views are visible.
*/
public static boolean setLabelValueOrHide(View label, TextView text, final String value) {
if (TextUtils.isEmpty(value)) {
label.setVisibility(View.GONE);
text.setVisibility(View.GONE);
return false;
} else {
label.setVisibility(View.VISIBLE);
text.setVisibility(View.VISIBLE);
text.setText(value);
return true;
}
}
/**
* If the given double is larger than 0, will make the label and value field {@link
* View#VISIBLE}. Otherwise both {@link View#GONE}.
*
* @return True if the views are visible.
*/
public static boolean setLabelValueOrHide(View label, TextView text, double value) {
if (value > 0.0) {
label.setVisibility(View.VISIBLE);
text.setVisibility(View.VISIBLE);
text.setText(String.valueOf(value));
return true;
} else {
label.setVisibility(View.GONE);
text.setVisibility(View.GONE);
return false;
}
}
public static void setMenuItemActiveString(@NonNull MenuItem item) {
item.setTitle(item.getTitle() + " ◀");
}
public static void setSwipeRefreshLayoutColors(Resources.Theme theme,
SwipeRefreshLayout swipeRefreshLayout) {
int accentColorResId = Utils.resolveAttributeToResourceId(theme, R.attr.colorAccent);
swipeRefreshLayout.setColorSchemeResources(accentColorResId, R.color.sg_color_secondary);
}
public static void showSoftKeyboardOnSearchView(final Context context, final View searchView) {
searchView.postDelayed(() -> {
if (searchView.requestFocus()) {
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 200); // have to add a little delay (http://stackoverflow.com/a/27540921/1000543)
}
public static void openUriOnClick(View button, final String uri) {
if (button != null) {
button.setOnClickListener(v -> Utils.launchWebsite(v.getContext(), uri));
}
}
}
| 38.632 | 99 | 0.661006 |
6aef56cfc42c443b5d50fdc578c7206a6d41d3da | 5,012 | package hierCluster;
import java.util.ArrayList;
import java.util.List;
public class upgma {
private double[][] dmatrix;
public List<int[]> TreeList;
private node[] nodes;
private int[] nums;
private int n, global_n;
private boolean[] state;
public upgma(double[][] matrix) {
this.dmatrix = matrix;
this.n = matrix.length;
this.nums = new int[this.n];
this.nodes = new node[this.n];
this.state = new boolean[this.n];
for (int i = 0; i < n; i++) {
this.nums[i] = 1;
node temp = new leafnode("" + i, i);
this.nodes[i] = temp;
state[i] = true;
}
this.global_n = this.n;
this.TreeList = new ArrayList<>();
}
// for clusterTree
public upgma(double[][] matrix, int[] idxs, int globaln) {
this.dmatrix = matrix;
this.n = matrix.length;
this.nums = new int[this.n];
this.nodes = new node[this.n];
this.state = new boolean[this.n];
for (int i = 0; i < n; i++) {
this.nums[i] = 1;
node temp = new leafnode("" + idxs[i], idxs[i]);
this.nodes[i] = temp;
state[i] = true;
}
this.global_n = globaln;
this.TreeList = new ArrayList<>();
}
/**
* find the minimum value and its idx idxj > idxi
*/
private int[] findMinimum() {
int idxi = 0;
int idxj = 1;
double minimum = this.dmatrix[idxi][idxj];
for (int i = 0; i < dmatrix.length; i++) {
if (!state[i])
continue;
for (int j = i + 1; j < dmatrix.length; j++) {
if (!state[j])
continue;
if (this.dmatrix[i][j] > minimum) {
idxi = i;
idxj = j;
minimum = dmatrix[idxi][idxj];
}
}
}
return new int[] { idxi, idxj };
}
/**
* combine the two nodes
*/
private void combineNodes(int idxi, int idxj) {
double minimum = 1 - this.dmatrix[idxi][idxj];
node newnode = new midnode(this.nodes[idxi], this.nodes[idxj], this.global_n++);
this.nodes[idxi].setLen(minimum / 2 - this.nodes[idxi].getDistance());
this.nodes[idxj].setLen(minimum / 2 - this.nodes[idxj].getDistance());
int[] treelist = { this.nodes[idxi].getNum(), this.nodes[idxj].getNum(), this.global_n - 1 };
this.TreeList.add(treelist.clone());
this.nodes[idxi] = newnode;
this.nodes[idxj] = new leafnode("pass", -1);
}
/**
* renew upright area of the distance matrix
*/
private void renewDist(int idxi, int idxj) {
for (int i = 0; i < idxi; i++) {
if (!state[i])
continue;
dmatrix[i][idxi] = (dmatrix[i][idxi] * nums[idxi] + dmatrix[i][idxj] * nums[idxj])
/ (nums[idxi] + nums[idxj]);
}
for (int j = idxi + 1; j < this.n; j++) {
if (!state[j])
continue;
if (j < idxj)
dmatrix[idxj][j] = dmatrix[j][idxj];
dmatrix[idxi][j] = (dmatrix[idxi][j] * nums[idxi] + dmatrix[idxj][j] * nums[idxj])
/ (nums[idxi] + nums[idxj]);
}
for (int i = 0; i < idxj; i++)
dmatrix[i][idxj] = Double.NEGATIVE_INFINITY;
for (int j = idxj + 1; j < this.n; j++)
dmatrix[idxj][j] = Double.NEGATIVE_INFINITY;
}
/**
* renew nums
*/
private void renewNum(int idxi, int idxj) {
// renew n
this.n--;
this.nums[idxi] += nums[idxj];
this.nums[idxj] = 0;
state[idxj] = false;
}
public void genTree() {
if (this.n < 2) {
throw new IllegalArgumentException("The number of strings is smaller than 2!");
}
while (this.n > 2) {
// find the minimum value and its idx
int[] idxij = findMinimum();
// combine the two nodes
combineNodes(idxij[0], idxij[1]);
// renew upright area of the distance matrix
renewDist(idxij[0], idxij[1]);
// renew nums
renewNum(idxij[0], idxij[1]);
}
int idxi = -1, idxj = -1;
for (int i = 0; i < state.length; i++) {
if (state[i]) {
if (idxi == -1)
idxi = i;
else {
idxj = i;
break;
}
}
}
new midnode(this.nodes[idxi], this.nodes[idxj], this.global_n);
double len = (1 - this.dmatrix[idxi][idxj]) / 2;
this.nodes[idxi].setLen(len - this.nodes[idxi].getDistance());
this.nodes[idxj].setLen(len - this.nodes[idxj].getDistance());
int[] treelist = { this.nodes[idxi].getNum(), this.nodes[idxj].getNum(), this.global_n };
this.TreeList.add(treelist.clone());
}
} | 33.192053 | 101 | 0.485235 |
6980de99fe7e01390ff859af7a26c139660766e1 | 18,075 | package com.igormaznitsa.GameKit_FE652.Slalom;
import com.igormaznitsa.GameAPI.GameStateRecord;
import com.igormaznitsa.GameAPI.PlayerBlock;
import com.igormaznitsa.GameAPI.StrategicBlock;
import com.igormaznitsa.GameAPI.GameActionListener;
import com.igormaznitsa.GameAPI.Utils.RndGenerator;
import java.io.*;
public class Slalom_SB implements StrategicBlock
{
public static final int ROAD_WIDTH = 101;
public static final int ROAD_HEIGHT = 64;
public static final int ROAD_LENGTH = 3000;
public static final int LEVEL0 = 0;
public static final int LEVEL1 = 1;
public static final int LEVEL2 = 2;
public static final int LEVEL_DEMO = 3;
public static final int LEVEL0_OBSTACLE = 20;
public static final int LEVEL0_MOVE_OBSTACLE = 3;
public static final int LEVEL0_MOVING_TRIGGER = ROAD_LENGTH - (ROAD_LENGTH / 3);
public static final int LEVEL0_SCORE_NORMAL = 2;
public static final int LEVEL0_SCORE_MOVE = 2;
public static final int LEVEL0_SCORE_ROAD = 2;
public static final int LEVEL1_OBSTACLE = 40;
public static final int LEVEL1_MOVE_OBSTACLE = 8;
public static final int LEVEL1_MOVING_TRIGGER = ROAD_LENGTH - (ROAD_LENGTH /4);
public static final int LEVEL1_SCORE_NORMAL = 4;
public static final int LEVEL1_SCORE_MOVE = 4;
public static final int LEVEL1_SCORE_ROAD = 4;
public static final int LEVEL2_OBSTACLE = 55;
public static final int LEVEL2_MOVE_OBSTACLE = 10;
public static final int LEVEL2_MOVING_TRIGGER = ROAD_LENGTH - (ROAD_LENGTH / 6);
public static final int LEVEL2_SCORE_NORMAL = 5;
public static final int LEVEL2_SCORE_MOVE = 5;
public static final int LEVEL2_SCORE_ROAD = 5;
public static final int USER_ATTEMPTION_NUMBER = 3;
public static final int ROAD_SCROLL_SPEED = -4;
public static final int PLAYER_SPEED = -2;
public static final int MOVING_OBSTACLE_SPEED = 2;
public static final int HORIZ_PLAYER_SPEED = 2;
public static final int PLAYER_IMG_WIDTH = 15;
public static final int PLAYER_IMG_HEIGHT = 15;
public static final int PLAYER_OFF_X = 4;
public static final int PLAYER_OFF_Y = 6;
public static final int PLAYER_CELL_WIDTH = 7;
public static final int PLAYER_CELL_HEIGHT = 7;
public static final int OBSTACLE_IMG_WIDTH = 15;
public static final int OBSTACLE_IMG_HEIGHT = 15;
public static final int OBSTACLE_OFF_X = 4;
public static final int OBSTACLE_OFF_Y = 7;
public static final int OBSTACLE_CELL_WIDTH = 7;
public static final int OBSTACLE_CELL_HEIGHT = 7;
private static final int VIRTUAL_CELL_WIDTH = OBSTACLE_IMG_WIDTH;
protected static final int DOWN_BORDER = ROAD_HEIGHT - (PLAYER_IMG_HEIGHT + (PLAYER_IMG_HEIGHT >>1));
public static final int START_X_POSITION = (ROAD_WIDTH - PLAYER_IMG_WIDTH) >> 1;
public static final int START_Y_POSITION = (ROAD_HEIGHT - PLAYER_IMG_HEIGHT) >> 1;;
private static final int PLAYER_RIGHT_BORDER = ROAD_WIDTH - PLAYER_IMG_WIDTH;
public static final int OBSTACLES_PER_LINE = (ROAD_WIDTH+VIRTUAL_CELL_WIDTH-1) / VIRTUAL_CELL_WIDTH;
public static final int TURNOFF_OBSTACLES_TRIGGER = ROAD_HEIGHT * 2;
protected Slalom_GSR _game_state;
protected int _skierarray_len;
protected Obstacle[] _skierrray;
protected int _emptarray_len;
protected Obstacle[] _emptarray;
protected int _flagarray_len;
protected Obstacle[] _flagrray;
protected int _skier_obstacles;
protected int _current_player_y;
protected RndGenerator _rnd;
protected PlayerBlock _player;
protected int _game_level;
protected int _harray_len = 0;
protected int _larray_len = 0;
protected GameActionListener _action_listener = null;
public static final int ACTION_SOUNDSTART = 0;
public static final int ACTION_SOUNDHIT = 1;
public static final int ACTION_SOUNDWIN = 2;
public static final int ACTION_SOUNDLOST = 3;
public Slalom_SB(GameActionListener actionListener)
{
_action_listener = actionListener;
_rnd = new RndGenerator(System.currentTimeMillis());
}
protected boolean isPlayerOutField()
{
if ((_game_state.getPlayerX() < 0) || ((_game_state.getPlayerX() + PLAYER_CELL_WIDTH) >= ROAD_WIDTH)) return true;
return false;
}
protected Obstacle isCollision(Obstacle obst)
{
if (obst == null)
{
int dx = _game_state._player_x + PLAYER_OFF_X;
int dy = _game_state._player_y + PLAYER_OFF_Y;
// Check player's collisions
int lx0 = (dx/ VIRTUAL_CELL_WIDTH) * VIRTUAL_CELL_WIDTH;
int lx1 = ((dx+PLAYER_CELL_WIDTH + Slalom_SB.PLAYER_CELL_WIDTH) / VIRTUAL_CELL_WIDTH) * VIRTUAL_CELL_WIDTH;
// Check for trees
for (int li = 0; li < _flagarray_len; li++)
{
Obstacle _ob = _flagrray[li];
if ((_ob._x == lx0) || (_ob._x == lx1))
{
int ly = Math.abs(dy - (_ob._y+OBSTACLE_OFF_Y));
int lx = Math.abs(dx - (_ob._x+OBSTACLE_OFF_X));
if ((ly <= OBSTACLE_CELL_HEIGHT) && (lx <= OBSTACLE_CELL_WIDTH)) return _ob;
}
}
// Check for other skiers
for (int li = 0; li < _skierarray_len; li++)
{
Obstacle _ob = _skierrray[li];
if ((_ob._x == lx0) || (_ob._x == lx1))
{
int ly = Math.abs(dy - (_ob._y+OBSTACLE_OFF_Y));
int lx = Math.abs(dx - (_ob._x+OBSTACLE_OFF_X));
if ((ly < OBSTACLE_CELL_HEIGHT) && (lx < OBSTACLE_CELL_WIDTH)) return _ob;
}
}
return null;
}
else
{
// Check moving obstacles collisions
int lx = obst._x;
int ly = obst._y+OBSTACLE_OFF_Y;
for (int li = 0; li < _flagarray_len; li++)
{
Obstacle _ob = _flagrray[li];
if (_ob._x == lx)
{
int lly = (_ob._y+OBSTACLE_OFF_Y) - ly;
if (Math.abs(lly) <= OBSTACLE_CELL_HEIGHT) return _ob;
}
}
}
return null;
}
protected void clearAllArrays()
{
_emptarray_len = 0;
_skierarray_len = 0;
_flagarray_len = 0;
Obstacle[] _obst = _game_state.getObstacleArray();
for (int li = 0; li < _obst.length; li++)
{
_obst[li]._type = Obstacle.NONE;
}
}
protected void fillObsArrays()
{
// Creating of the list of top and empty obstacles
_emptarray_len = 0;
_skierarray_len = 0;
_harray_len = 0;
_larray_len = 0;
_flagarray_len = 0;
Obstacle[] _arr = _game_state.getObstacleArray();
for (int li = 0; li < _arr.length; li++)
{
Obstacle _obj = _arr[li];
switch (_obj._type)
{
case Obstacle.NONE:
{
_emptarray[_emptarray_len] = _obj;
_emptarray_len++;
}
;
break;
case Obstacle.DROPPED_SKIER:
;
case Obstacle.NORMAL_SKIER:
{
if (_obj._y < (OBSTACLE_IMG_HEIGHT << 1))
{
_larray_len++;
}
_skierrray[_skierarray_len] = _obj;
_skierarray_len++;
}
;
break;
default :
{
if (_obj._y >= DOWN_BORDER)
{
_harray_len++;
}
_flagrray[_flagarray_len] = _obj;
_flagarray_len++;
}
}
}
}
public void resumeGame()
{
clearAllArrays();
_game_state._player_x = Slalom_SB.START_X_POSITION;
_game_state._player_y = Slalom_SB.START_Y_POSITION;
_game_state._player_state = Slalom_GSR.PLAYER_NORMAL;
}
protected void generateNewObstacles()
{
// Generate normal obstactles
if (_harray_len == 0)
{
int lo = 0;
boolean ust = false;
for (int li = 0; li < OBSTACLES_PER_LINE; li++)
{
if (lo == _emptarray_len) break;
if (ust)
{
ust = false;
continue;
}
int lid = _rnd.getInt(8);
if (lid == 4)
{
_emptarray[lo]._type = Obstacle.FLAG;
_emptarray[lo]._x = li * VIRTUAL_CELL_WIDTH;
_emptarray[lo]._y = ROAD_HEIGHT;
_emptarray[lo]._speed = PLAYER_SPEED;
lo++;
ust = true;
}
}
}
// Generate moving obstactles
if (_skier_obstacles == _game_state._max_skiers) return;
if (_game_state.getCurrentRoadPosition() < _game_state._move_trigger)
{
if (_larray_len == 0)
{
Obstacle lemptyo = _emptarray[0];
int lx = _rnd.getInt(20);
if (lx == 15)
{
lx = _rnd.getInt(OBSTACLES_PER_LINE - 1);
lemptyo._type = Obstacle.NORMAL_SKIER;
lemptyo._x = lx * VIRTUAL_CELL_WIDTH;
lemptyo._y = -OBSTACLE_IMG_HEIGHT;
lemptyo._speed = MOVING_OBSTACLE_SPEED;
_skier_obstacles++;
}
}
}
}
protected void processObstacles()
{
Obstacle[] arr = _game_state.getObstacleArray();
for (int li = 0; li < arr.length; li++)
{
Obstacle obs = arr[li];
switch (obs._type)
{
case Obstacle.SKIER_ON_FLAG:
;
case Obstacle.FLAG:
{
obs._y += obs._speed;
if (obs._y <= -OBSTACLE_IMG_HEIGHT)
{
obs._type = Obstacle.NONE;
_game_state.normal_counter++;
}
}
;
break;
case Obstacle.DROPPED_SKIER:
;
case Obstacle.NORMAL_SKIER:
{
obs._y += obs._speed;
Obstacle _col = isCollision(obs);
if (_col != null)
{
int lk = _rnd.getInt(6);
if (lk != 3)
{
_col._type = Obstacle.SKIER_ON_FLAG;
_col._speed = PLAYER_SPEED;
obs._type = Obstacle.NONE;
_game_state.move_counter++;
_skier_obstacles--;
}
else
{
obs._type = Obstacle.DROPPED_SKIER;
_col._type = Obstacle.NONE;
_game_state.move_counter++;
}
}
else
{
if (obs._y >= ROAD_HEIGHT)
{
obs._type = Obstacle.NONE;
_skier_obstacles--;
_game_state.move_counter++;
}
}
}
;
break;
}
}
}
public void newGame(int level)
{
_game_state = new Slalom_GSR(level);
_game_level = level;
_skierrray = new Obstacle[_game_state.getObstacleArray().length];
_emptarray = new Obstacle[_game_state.getObstacleArray().length];
_flagrray = new Obstacle[_game_state.getObstacleArray().length];
if (_player != null) _player.initPlayer();
if (_action_listener!=null) _action_listener.actionEvent(ACTION_SOUNDSTART);
}
public void saveGameState(OutputStream outputStream) throws IOException
{
System.gc();
DataOutputStream dis = new DataOutputStream(outputStream);
// Saving the game level value
dis.writeByte(_game_level);
// Saving obstacles from stream
Obstacle[] arra = _game_state.getObstacleArray();
for (int li = 0; li < arra.length; li++)
{
dis.writeByte(arra[li]._x);
dis.writeByte(arra[li]._y);
dis.writeByte(arra[li]._type);
dis.writeByte(arra[li]._speed);
}
// Saving of current number of player's attemptions
dis.writeByte(_game_state._current_user_attemption);
// Saving of current player's state
dis.writeByte(_game_state._player_state);
// Saving of current player's X coordinate
dis.writeByte(_game_state._player_x);
// Saving of current player's Y coordinate
dis.writeByte(_game_state._player_y);
// Saving of current player's road position
dis.writeInt(_game_state._current_road_position);
// Loading of current game state
dis.writeByte(_game_state._game_state);
dis = null;
System.gc();
}
public void loadGameState(InputStream inputStream) throws IOException
{
System.gc();
DataInputStream dis = new DataInputStream(inputStream);
// Load the game level value
_game_level = dis.readByte();
newGame(_game_level);
// Loading obstacles from stream
Obstacle[] arra = _game_state.getObstacleArray();
for (int li = 0; li < arra.length; li++)
{
arra[li]._x = dis.readUnsignedByte();
arra[li]._y = dis.readUnsignedByte();
arra[li]._type = dis.readUnsignedByte();
arra[li]._speed = dis.readByte();
}
// Loading of current number of player's attemptions
_game_state._current_user_attemption = dis.readUnsignedByte();
// Loading of current player's state
_game_state._player_state = dis.readUnsignedByte();
// Loading of current player's X coordinate
_game_state._player_x = dis.readUnsignedByte();
// Loading of current player's Y coordinate
_game_state._player_y = dis.readByte();
// Loading of current player's road position
_game_state._current_road_position = dis.readInt();
// Loading of current game state
_game_state._game_state = dis.readByte();
fillObsArrays();
dis = null;
System.gc();
}
public void nextGameStep()
{
if (_player == null) return;
Slalom_PMR _record = (Slalom_PMR) _player.getPlayerMoveRecord(_game_state);
switch (_record.getDirect())
{
case Slalom_PMR.DIRECT_LEFT:
{
_game_state._player_x -= HORIZ_PLAYER_SPEED;
_game_state._player_state = Slalom_GSR.PLAYER_LEFT;
if (_game_state._player_x < 0)
{
_game_state._player_state = Slalom_GSR.PLAYER_NORMAL;
_game_state._player_x = 0;
}
}
;
break;
case Slalom_PMR.DIRECT_RIGHT:
{
_game_state._player_x += HORIZ_PLAYER_SPEED;
_game_state._player_state = Slalom_GSR.PLAYER_RIGHT;
if (_game_state._player_x > Slalom_SB.PLAYER_RIGHT_BORDER)
{
_game_state._player_state = Slalom_GSR.PLAYER_NORMAL;
_game_state._player_x = Slalom_SB.PLAYER_RIGHT_BORDER;
}
};break;
}
if (_game_level == LEVEL_DEMO) return;
processObstacles();
fillObsArrays();
Obstacle _colobj = isCollision(null);
if (_colobj != null)
{
_game_state._player_state = Slalom_GSR.PLAYER_COLLIDED;
_game_state._current_user_attemption--;
if (_game_state._current_user_attemption < 0) {
_game_state._game_state = Slalom_GSR.GAMESTATE_OVER;
if (_action_listener!=null) _action_listener.actionEvent(ACTION_SOUNDLOST);
}
if (_action_listener!=null) _action_listener.actionEvent(ACTION_SOUNDHIT);
return;
}
_game_state._current_road_position--;
if (_game_state._current_road_position <= 0)
{
_game_state._player_state = Slalom_GSR.PLAYER_FINISHED;
_game_state._game_state = Slalom_GSR.GAMESTATE_OVER;
if (_action_listener!=null) _action_listener.actionEvent(ACTION_SOUNDWIN);
}
if (_game_state._current_road_position > TURNOFF_OBSTACLES_TRIGGER) generateNewObstacles();
}
public GameStateRecord getGameStateRecord()
{
return _game_state;
}
public void setPlayerBlock(PlayerBlock playerBlock)
{
_player = playerBlock;
}
public void setAIBlock(PlayerBlock aiBlock)
{
}
public boolean isLoadSaveSupporting()
{
return true;
}
public String getGameID()
{
return "Slalom";
}
public int getMaxSizeOfSavedGameBlock()
{
return 800;
}
}
| 33.659218 | 122 | 0.543071 |
22cac4bfd3813f871fe289a38f9a7f8933693757 | 9,107 | /*
* Copyright (C) 2019 The Turms Project
* https://github.com/turms-im/turms
*
* 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 im.turms.plugin.antispam;
import im.turms.plugin.antispam.ac.AhoCorasickDoubleArrayTrie;
import im.turms.server.common.infra.lang.FastStringBuilder;
import im.turms.server.common.infra.lang.StringUtil;
import javax.annotation.Nullable;
import java.util.Arrays;
/**
* @author James Chen
*/
public class SpamDetector extends AhoCorasickDoubleArrayTrie {
/**
* "Record Separator"
*/
public static final byte UNWANTED_WORD_DELIMITER = 0x1E;
private final TextPreprocessor textPreprocessor;
public SpamDetector(TextPreprocessor textPreprocessor, AhoCorasickDoubleArrayTrie trie) {
super(trie.fail, trie.output, trie.dat, trie.words);
this.textPreprocessor = textPreprocessor;
}
@Nullable
public String mask(String str, byte mask) {
char code;
Object newChars;
int firstCharIndex = 0;
int currentState = 0;
int nextState;
byte[] maskedBytes = null;
int length = str.length();
byte coder = StringUtil.getCoder(str);
boolean isLatin1 = StringUtil.isLatin1(coder);
for (int i = 0; i < length; i++) {
code = str.charAt(i);
newChars = textPreprocessor.process(code);
if (currentState == ROOT_STATUS) {
firstCharIndex = i;
}
if (newChars instanceof char[] chars) {
for (char c : chars) {
nextState = transition(currentState, c);
while (nextState == STATUS_NOT_FOUND) {
currentState = fail[currentState];
if (currentState == ROOT_STATUS) {
firstCharIndex = i;
}
nextState = transition(currentState, c);
}
currentState = nextState;
if (output[currentState] != null) {
if (maskedBytes == null) {
byte[] bytes = StringUtil.getBytes(str);
maskedBytes = Arrays.copyOf(bytes, bytes.length);
}
if (isLatin1) {
for (int j = firstCharIndex; j <= i; j++) {
maskedBytes[j] = mask;
}
} else {
for (int j = firstCharIndex; j <= i; j++) {
int k = j << 1;
maskedBytes[k] = mask;
maskedBytes[k + 1] = 0;
}
}
}
}
} else if (newChars instanceof Character c) {
nextState = transition(currentState, c);
while (nextState == STATUS_NOT_FOUND) {
currentState = fail[currentState];
if (currentState == ROOT_STATUS) {
firstCharIndex = i;
}
nextState = transition(currentState, c);
}
currentState = nextState;
if (output[currentState] != null) {
if (maskedBytes == null) {
byte[] bytes = StringUtil.getBytes(str);
maskedBytes = Arrays.copyOf(bytes, bytes.length);
}
if (isLatin1) {
for (int j = firstCharIndex; j <= i; j++) {
maskedBytes[j] = mask;
}
} else {
for (int j = firstCharIndex; j <= i; j++) {
int k = j << 1;
maskedBytes[k] = mask;
maskedBytes[k + 1] = 0;
}
}
}
}
}
if (maskedBytes == null) {
return null;
}
return StringUtil.newString(maskedBytes, coder);
}
public boolean containsUnwantedWords(String text) {
int currentState = 0;
int length = text.length();
for (int i = 0; i < length; i++) {
char code = text.charAt(i);
Object newChars = textPreprocessor.process(code);
if (newChars instanceof char[] chars) {
for (char c : chars) {
currentState = findNextState(currentState, c);
if (output[currentState] != null) {
return true;
}
}
} else if (newChars instanceof Character c) {
currentState = findNextState(currentState, c);
if (output[currentState] != null) {
return true;
}
}
}
return false;
}
/**
* @param maxNumberOfUnwantedWordsToReturn should be greater than 0
*/
@Nullable
public String findUnwantedWords(String text, int maxNumberOfUnwantedWordsToReturn) {
char code;
Object newChars;
int firstByteIndex = 0;
int currentState = 0;
int nextState;
FastStringBuilder builder = null;
int length = text.length();
byte[] textInternalBytes = null;
byte coder = StringUtil.getCoder(text);
boolean isLatin1 = StringUtil.isLatin1(coder);
for (int i = 0; i < length; i++) {
code = text.charAt(i);
newChars = textPreprocessor.process(code);
if (currentState == ROOT_STATUS) {
firstByteIndex = isLatin1 ? i : i * 2;
}
if (newChars instanceof char[] chars) {
for (char c : chars) {
nextState = transition(currentState, c);
while (nextState == STATUS_NOT_FOUND) {
currentState = fail[currentState];
if (currentState == ROOT_STATUS) {
firstByteIndex = isLatin1 ? i : i * 2;
}
nextState = transition(currentState, c);
}
currentState = nextState;
if (output[currentState] != null) {
if (builder == null) {
builder = new FastStringBuilder();
textInternalBytes = StringUtil.getBytes(text);
}
if (isLatin1) {
builder.append(textInternalBytes, firstByteIndex, i + 1 - firstByteIndex);
} else {
builder.append(textInternalBytes, firstByteIndex, (i + 1) * 2 - firstByteIndex);
}
if (builder.entryCount() >= maxNumberOfUnwantedWordsToReturn) {
return builder.build(coder, UNWANTED_WORD_DELIMITER);
}
}
}
} else if (newChars instanceof Character c) {
nextState = transition(currentState, c);
while (nextState == STATUS_NOT_FOUND) {
currentState = fail[currentState];
if (currentState == ROOT_STATUS) {
firstByteIndex = isLatin1 ? i : i * 2;
}
nextState = transition(currentState, c);
}
currentState = nextState;
if (output[currentState] != null) {
if (builder == null) {
builder = new FastStringBuilder();
textInternalBytes = StringUtil.getBytes(text);
}
if (isLatin1) {
builder.append(textInternalBytes, firstByteIndex, i + 1 - firstByteIndex);
} else {
builder.append(textInternalBytes, firstByteIndex, (i + 1) * 2 - firstByteIndex);
}
if (builder.entryCount() >= maxNumberOfUnwantedWordsToReturn) {
return builder.build(coder, UNWANTED_WORD_DELIMITER);
}
}
}
}
if (builder == null) {
return null;
}
return builder.build(coder, UNWANTED_WORD_DELIMITER);
}
}
| 39.942982 | 108 | 0.478643 |
2160c3cc1c0cec4634923b1e8822f1e300d66166 | 8,907 | /*
* Copyright 2006-2009, 2017, 2020 United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA World Wind Java (WWJ) platform is 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.
*
* NASA World Wind Java (WWJ) also contains the following 3rd party Open Source
* software:
*
* Jackson Parser – Licensed under Apache 2.0
* GDAL – Licensed under MIT
* JOGL – Licensed under Berkeley Software Distribution (BSD)
* Gluegen – Licensed under Berkeley Software Distribution (BSD)
*
* A complete listing of 3rd Party software notices and licenses included in
* NASA World Wind Java (WWJ) can be found in the WorldWindJava-v2.2 3rd-party
* notices and licenses PDF found in code directory.
*/
package gov.nasa.worldwind.formats.dds;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.avlist.AVList;
import gov.nasa.worldwind.data.BufferedImageRaster;
import gov.nasa.worldwind.data.DataRaster;
import gov.nasa.worldwind.data.MipMappedBufferedImageRaster;
import gov.nasa.worldwind.exception.WWRuntimeException;
import gov.nasa.worldwind.geom.Sector;
import gov.nasa.worldwind.util.Logging;
import gov.nasa.worldwind.util.WWIO;
import gov.nasa.worldwind.util.WWMath;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
/**
* @author Lado Garakanidze
* @version $Id: DDSDecompressor.java 1171 2013-02-11 21:45:02Z dcollins $
*/
public class DDSDecompressor
{
public DDSDecompressor()
{
}
/**
* Reconstructs image raster from a DDS source. The source type may be one of the following: <ul><li>{@link java.net.URL}</li> <li>{@link
* java.net.URI}</li> <li>{@link java.io.File}</li> <li>{@link String} containing a valid URL description, a valid
* URI description, or a valid path to a local file.</li> </ul>
*
* @param source the source to convert to local file path.
* @param params The AVList is a required parameter, Cannot be null. Requires AVK.Sector to be present.
* @return MipMappedBufferedImageRaster if the DDS source contains mipmaps, otherwise returns a BufferedImageRaster
* @throws Exception when source or params is null
*/
public DataRaster decompress(Object source, AVList params) throws Exception
{
return this.doDecompress(source, params);
}
protected DataRaster doDecompress(Object source, AVList params) throws Exception
{
if (null == params || !params.hasKey(AVKey.SECTOR))
{
String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR);
Logging.logger().severe(message);
throw new WWRuntimeException(message);
}
File file = WWIO.getFileForLocalAddress(source);
if (null == file)
{
String message = Logging.getMessage("generic.UnrecognizedSourceType", source.getClass().getName());
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (!file.exists())
{
String message = Logging.getMessage("generic.FileNotFound", file.getAbsolutePath());
Logging.logger().severe(message);
throw new FileNotFoundException(message);
}
if (!file.canRead())
{
String message = Logging.getMessage("generic.FileNoReadPermission", file.getAbsolutePath());
Logging.logger().severe(message);
throw new IOException(message);
}
RandomAccessFile raf = null;
FileChannel channel = null;
DataRaster raster = null;
try
{
raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
java.nio.MappedByteBuffer buffer = this.mapFile(channel, 0, channel.size());
buffer.position(0);
DDSHeader header = DDSHeader.readFrom(source);
int width = header.getWidth();
int height = header.getHeight();
if (!WWMath.isPowerOfTwo(width) || !WWMath.isPowerOfTwo(height))
{
String message = Logging.getMessage("generic.InvalidImageSize", width, height);
Logging.logger().severe(message);
throw new WWRuntimeException(message);
}
int mipMapCount = header.getMipMapCount();
// int ddsFlags = header.getFlags();
DDSPixelFormat pixelFormat = header.getPixelFormat();
if (null == pixelFormat)
{
String reason = Logging.getMessage("generic.MissingRequiredParameter", "DDSD_PIXELFORMAT");
String message = Logging.getMessage("generic.InvalidImageFormat", reason);
Logging.logger().severe(message);
throw new WWRuntimeException(message);
}
DXTDecompressor decompressor = null;
int dxtFormat = pixelFormat.getFourCC();
if (dxtFormat == DDSConstants.D3DFMT_DXT3)
{
decompressor = new DXT3Decompressor();
}
else if (dxtFormat == DDSConstants.D3DFMT_DXT1)
{
decompressor = new DXT1Decompressor();
}
if (null == decompressor)
{
String message = Logging.getMessage("generic.UnsupportedCodec", dxtFormat);
Logging.logger().severe(message);
throw new WWRuntimeException(message);
}
Sector sector = (Sector) params.getValue(AVKey.SECTOR);
params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE);
if (mipMapCount == 0)
{
// read max resolution raster
buffer.position(DDSConstants.DDS_DATA_OFFSET);
BufferedImage image = decompressor.decompress(buffer, header.getWidth(), header.getHeight());
raster = new BufferedImageRaster(sector, image, params);
}
else if (mipMapCount > 0)
{
ArrayList<BufferedImage> list = new ArrayList<BufferedImage>();
int mmLength = header.getLinearSize();
int mmOffset = DDSConstants.DDS_DATA_OFFSET;
for (int i = 0; i < mipMapCount; i++)
{
int zoomOut = (int) Math.pow(2d, (double) i);
int mmWidth = header.getWidth() / zoomOut;
int mmHeight = header.getHeight() / zoomOut;
if (mmWidth < 4 || mmHeight < 4)
{
break;
}
buffer.position(mmOffset);
BufferedImage image = decompressor.decompress(buffer, mmWidth, mmHeight);
list.add(image);
mmOffset += mmLength;
mmLength /= 4;
}
BufferedImage[] images = new BufferedImage[list.size()];
images = (BufferedImage[]) list.toArray(images);
raster = new MipMappedBufferedImageRaster(sector, images);
}
return raster;
}
finally
{
String name = (null != file) ? file.getAbsolutePath() : ((null != source) ? source.toString() : "unknown");
WWIO.closeStream(channel, name);
WWIO.closeStream(raf, name);
}
}
protected java.nio.MappedByteBuffer mapFile(FileChannel channel, long offset, long length) throws Exception
{
if (null == channel || !channel.isOpen())
{
String message = Logging.getMessage("nullValue.ChannelIsNull");
Logging.logger().fine(message);
throw new IllegalArgumentException(message);
}
if (channel.size() < (offset + length))
{
String reason = channel.size() + " < " + (offset + length);
String message = Logging.getMessage("generic.LengthIsInvalid", reason);
Logging.logger().severe(message);
throw new IOException(message);
}
return channel.map(FileChannel.MapMode.READ_ONLY, offset, length);
}
}
| 37.741525 | 141 | 0.615696 |
a2993d3c6271ed84a0f729488c28e78e161dbc3e | 2,806 | /**
* 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.storm.streams;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.storm.streams.processors.BatchProcessor;
import org.apache.storm.streams.processors.Processor;
import org.apache.storm.streams.processors.ProcessorContext;
import org.apache.storm.tuple.Fields;
/**
* Node that wraps a processor in the stream.
*/
public class ProcessorNode extends Node {
private final Processor<?> processor;
private final boolean isBatch;
private final boolean preservesKey;
// Windowed parent streams
private Set<String> windowedParentStreams = Collections.emptySet();
public ProcessorNode(Processor<?> processor, String outputStream, Fields outputFields, boolean preservesKey) {
super(outputStream, outputFields);
this.isBatch = processor instanceof BatchProcessor;
this.processor = processor;
this.preservesKey = preservesKey;
}
public ProcessorNode(Processor<?> processor, String outputStream, Fields outputFields) {
this(processor, outputStream, outputFields, false);
}
public Processor<?> getProcessor() {
return processor;
}
public boolean isBatch() {
return isBatch;
}
public Set<String> getWindowedParentStreams() {
return Collections.unmodifiableSet(windowedParentStreams);
}
void setWindowedParentStreams(Set<String> windowedParentStreams) {
this.windowedParentStreams = new HashSet<>(windowedParentStreams);
}
void initProcessorContext(ProcessorContext context) {
processor.init(context);
}
public boolean isPreservesKey() {
return preservesKey;
}
@Override
public String toString() {
return "ProcessorNode{" +
"processor=" + processor +
", isBatch=" + isBatch +
", preservesKey=" + preservesKey +
", windowedParentStreams=" + windowedParentStreams +
"} " + super.toString();
}
}
| 35.974359 | 139 | 0.710264 |
47ce0143374988ca183c610f1bb72e0c6cbe6c3a | 1,250 | package multithread;
// Author : iTimeTraveler
// Date : 2018-01-23
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicMutex {
public static void main(String[] args) {
int THREAD_NUM = 10;
TestMutex test = new TestMutex();
Thread[] threads = new Thread[THREAD_NUM];
// 创建10个线程,让它们不断地去增加test.sum的值
for (int i = 0; i < THREAD_NUM; i++) {
Thread t = new Thread() {
public void run() {
for (int j = 0; j < 1000; j++) {
test.add();
}
}
};
t.start();
threads[i] = t;
}
for (Thread t : threads) {
try {
t.join(); //等待子线程执行完成
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(test.sum);
}
public static class TestMutex {
private int sum = 0;
private AtomicInteger atomicInteger = new AtomicInteger(0);
// private SpinLock lock = new SpinLock();
private BlockLock lock = new BlockLock();
public void add() {
// if(!atomicInteger.compareAndSet(0, 1)){
// return;
// }
lock.lock();
if (sum < 3000) {
try {
// 这sleep一下,增加线程切换的概率里
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
sum += 1;
}
lock.unlock();
// atomicInteger.set(0);
}
}
}
| 18.656716 | 61 | 0.5992 |
31745873a22e3af7592b0b748d9d60c33b14bdb0 | 2,853 | package com.github.mrglassdanny.mdk.lang.groovy.util;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.syntax.SyntaxException;
import com.github.mrglassdanny.mdk.lang.util.Position;
import com.github.mrglassdanny.mdk.lang.util.Range;
public class GroovyLanguageUtils {
public static final String GROOVY_DEFAULT_IMPORTS = "import java.lang.*; import java.util.*; import java.io.*; import java.net.*; import groovy.lang.*; import groovy.util.*; import java.math.BigInteger; import java.math.BigDecimal; ";
public static final String MOCA_DEFAULT_IMPORTS = "import com.redprairie.moca.*; import com.redprairie.moca.util.*; import com.redprairie.moca.exceptions.*;";
public static final String MOCA_DEFAULT_DECLARATIONS = "MocaContext moca; ";
public static final String MOCA_GROOVY_SCRIPT_PREFIX = MOCA_DEFAULT_IMPORTS + MOCA_DEFAULT_DECLARATIONS;
public static boolean importIsContainedInDefaultGroovyImports(String fullClassName) {
String packageName = fullClassName.substring(0, fullClassName.lastIndexOf("."));
if (GroovyLanguageUtils.MOCA_DEFAULT_IMPORTS.contains(packageName)
|| GroovyLanguageUtils.GROOVY_DEFAULT_IMPORTS.contains(packageName)) {
return true;
} else {
return false;
}
}
// Since we could have multiple groovy ranges in script, we need to pass in the
// range of the groovy script we are referring to.
public static Position createMocaPosition(int groovyLine, int groovyColumn, Range groovyScriptRange) {
int lspLine = groovyLine;
if (lspLine > 0) {
lspLine--;
}
int lspColumn = groovyColumn;
if (lspColumn > 0) {
lspColumn--;
}
// If the line is 0, we need to keep the char offset in mind.
if (lspLine == 0) {
return new Position(lspLine + groovyScriptRange.getStart().getLine(),
lspColumn + groovyScriptRange.getStart().getCharacter() + 2); // +2 for '[['.
} else {
return new Position(lspLine + groovyScriptRange.getStart().getLine(), lspColumn);
}
}
public static Range syntaxExceptionToRange(SyntaxException exception, Range groovyScriptRange) {
return new Range(createMocaPosition(exception.getStartLine(), exception.getStartColumn(), groovyScriptRange),
createMocaPosition(exception.getEndLine(), exception.getEndColumn(), groovyScriptRange));
}
// Also takes current groovy context range index.
public static Range astNodeToRange(ASTNode node, Range groovyScriptRange) {
return new Range(createMocaPosition(node.getLineNumber(), node.getColumnNumber(), groovyScriptRange),
createMocaPosition(node.getLastLineNumber(), node.getLastColumnNumber(), groovyScriptRange));
}
} | 49.189655 | 238 | 0.702769 |
2f9fd6daf4421eca3226616425dec3d716b6fc62 | 1,389 | package it.polimi.ingsw.server.model.game.match_Tests;
import it.polimi.ingsw.server.model.cards.GlassWindow;
import it.polimi.ingsw.server.model.cards.schemeCard.Battlo;
import it.polimi.ingsw.server.model.cards.schemeCard.Virtus;
import it.polimi.ingsw.server.model.dice.Sack;
import it.polimi.ingsw.server.model.game.Match;
import it.polimi.ingsw.server.model.game.Player;
import it.polimi.ingsw.server.model.game.Round;
import it.polimi.ingsw.server.model.game.Stock;
import org.junit.jupiter.api.Test;
public class RuotaTurni2_Test{
@Test
void rotateturn2Players() {
GlassWindow windowA = new Battlo();
GlassWindow windowB = new Virtus();
Player a = new Player("mario");
Player b = new Player("daniele");
a.setWindow(windowA);
b.setWindow(windowB);
Match game = new Match(a,b);
Round round = new Round(game);
Stock stock = new Stock();
Sack sacktest = new Sack();
stock.setDicestock(sacktest.extractfromSack(game));
stock.show_stock();
int z = 0;
for (int i = 0; i < 2 * game.getnumberPlayers(); i++) {
round.getTurns().get(i).getOneplayer().getWindow().getSlot(2, 3).setDie(stock.extract_die(z));
}
System.out.println(a.getWindow().getSlot(2, 3).getDice());
System.out.println(b.getWindow().getSlot(2, 3).getDice());
}
}
| 38.583333 | 106 | 0.668826 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.