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 |
|---|---|---|---|---|---|
47bc8037412983b0736d477b18bea3735c9f7002 | 6,177 | /*
* Copyright 2004 - 2012 Mirko Nasato and contributors
* 2016 - 2020 Simon Braconnier and contributors
*
* This file is part of JODConverter - Java OpenDocument Converter.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jodconverter.local.task;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.jodconverter.local.ResourceUtil.documentFile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.sun.star.document.UpdateDocMode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.document.DocumentFormat;
import org.jodconverter.core.job.SourceDocumentSpecsFromFile;
import org.jodconverter.core.job.TargetDocumentSpecsFromFile;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.LocalOfficeManagerExtension;
/** Test the {@link LocalConversionTask} class. */
@ExtendWith(LocalOfficeManagerExtension.class)
public class LocalConvertionTaskITest {
private static final File SOURCE_FILE = documentFile("test.txt");
@Test
public void execute_WithoutCustomLoadProperties_UseDefaultLoadProperties(
final OfficeManager manager, final @TempDir File testFolder) {
final SourceDocumentSpecsFromFile source = new SourceDocumentSpecsFromFile(SOURCE_FILE);
final TargetDocumentSpecsFromFile target =
new TargetDocumentSpecsFromFile(new File(testFolder, "target.pdf")) {
@Override
public DocumentFormat getFormat() {
return DefaultDocumentFormatRegistry.PDF;
}
};
final LocalConversionTask task =
new LocalConversionTask(source, target, null, null, null) {
@Override
protected Map<String, Object> getLoadProperties() {
final Map<String, Object> props = super.getLoadProperties();
assertThat(props)
.hasSize(3)
.hasEntrySatisfying("Hidden", o -> assertThat(o).isEqualTo(true))
.hasEntrySatisfying("ReadOnly", o -> assertThat(o).isEqualTo(true))
.hasEntrySatisfying(
"UpdateDocMode", o -> assertThat(o).isEqualTo(UpdateDocMode.QUIET_UPDATE));
return props;
}
};
assertThatCode(() -> manager.execute(task)).doesNotThrowAnyException();
}
@Test
public void execute_WithCustomLoadProperties_UseCustomLoadProperties(
final OfficeManager manager, final @TempDir File testFolder) {
final SourceDocumentSpecsFromFile source = new SourceDocumentSpecsFromFile(SOURCE_FILE);
final TargetDocumentSpecsFromFile target =
new TargetDocumentSpecsFromFile(new File(testFolder, "target.pdf")) {
@Override
public DocumentFormat getFormat() {
return DefaultDocumentFormatRegistry.PDF;
}
};
final Map<String, Object> loadProperties = new HashMap<>();
loadProperties.put("Hidden", true);
loadProperties.put("ReadOnly", false);
loadProperties.put("UpdateDocMode", UpdateDocMode.NO_UPDATE);
final LocalConversionTask task =
new LocalConversionTask(source, target, loadProperties, null, null) {
@Override
protected Map<String, Object> getLoadProperties() {
final Map<String, Object> props = super.getLoadProperties();
assertThat(props)
.hasSize(3)
.hasEntrySatisfying("Hidden", o -> assertThat(o).isEqualTo(true))
.hasEntrySatisfying("ReadOnly", o -> assertThat(o).isEqualTo(false))
.hasEntrySatisfying(
"UpdateDocMode", o -> assertThat(o).isEqualTo(UpdateDocMode.NO_UPDATE));
return props;
}
};
assertThatCode(() -> manager.execute(task)).doesNotThrowAnyException();
}
// @Test
// public void execute_WithCustomLoadProperties_UseCustomLoadProperties(
// final OfficeManager manager, final @TempDir File testFolder) throws OfficeException {
//
// final SourceDocumentSpecsFromFile source = new SourceDocumentSpecsFromFile(SOURCE_FILE);
// final TargetDocumentSpecsFromFile target =
// new TargetDocumentSpecsFromFile(new File(testFolder, "target.pdf")) {
// @Override
// public DocumentFormat getFormat() {
// return DefaultDocumentFormatRegistry.PDF;
// }
// };
// final Map<String, Object> loadProperties = new HashMap<>();
// loadProperties.put("Hidden", true);
// loadProperties.put("ReadOnly", false);
// loadProperties.put("UpdateDocMode", UpdateDocMode.NO_UPDATE);
// final LocalConversionTask task =
// new LocalConversionTask(source, target, loadProperties, null, null) {
// @Override
// protected Map<String, Object> getLoadProperties() {
// final Map<String, Object> props = super.getLoadProperties();
//
// assertThat(props)
// .hasSize(3)
// .hasEntrySatisfying("Hidden", o -> assertThat(o).isEqualTo(true))
// .hasEntrySatisfying("ReadOnly", o -> assertThat(o).isEqualTo(false))
// .hasEntrySatisfying(
// "UpdateDocMode", o -> assertThat(o).isEqualTo(UpdateDocMode.NO_UPDATE));
//
// return props;
// }
// };
//
// assertThatCode(() -> manager.execute(task)).doesNotThrowAnyException();
// }
}
| 40.372549 | 96 | 0.676542 |
d9fb193efbda88a8abe7977ca1756505eaf64229 | 2,363 | /*
* Copyright (c) 2021 Mastercard
*
* 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.mastercard.developers.carboncalculator.service;
import com.mastercard.developers.carboncalculator.exception.ServiceException;
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.api.EnvironmentalImpactApi;
import org.openapitools.client.model.Transaction;
import org.openapitools.client.model.TransactionFootprint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import static com.mastercard.developers.carboncalculator.util.JSON.deserializeErrors;
@Service
public class EnvironmentalImpactService {
private static final Logger LOGGER = LoggerFactory.getLogger(EnvironmentalImpactService.class);
private final EnvironmentalImpactApi environmentalImpactApi;
@Autowired
public EnvironmentalImpactService(ApiClient apiClient) {
LOGGER.info("Initializing Calculate Transaction Footprint API");
environmentalImpactApi = new EnvironmentalImpactApi(apiClient);
}
public List<TransactionFootprint> calculateFootprints(List<Transaction> mcTransactions) throws ServiceException {
LOGGER.info("Calling Calculate Transaction Footprint API");
try {
List<TransactionFootprint> footprints = environmentalImpactApi.footprintsByTransactionData(
mcTransactions);
LOGGER.info("Calculate Transaction Footprint API call successful, returning Transaction Footprints.");
return footprints;
} catch (ApiException e) {
throw new ServiceException(e.getMessage(), deserializeErrors(e.getResponseBody()));
}
}
}
| 35.80303 | 117 | 0.766399 |
3b128fcf65b5275f302b9756fe76a231071f2c8b | 23,155 | /**
* 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.pulsar.io.kinesis;
import static java.util.Base64.getDecoder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.schema.GenericObject;
import org.apache.pulsar.client.api.schema.GenericRecord;
import org.apache.pulsar.client.api.schema.GenericSchema;
import org.apache.pulsar.client.api.schema.RecordSchemaBuilder;
import org.apache.pulsar.client.api.schema.SchemaBuilder;
import org.apache.pulsar.common.api.EncryptionContext;
import org.apache.pulsar.common.api.EncryptionContext.EncryptionKey;
import org.apache.pulsar.common.schema.KeyValueEncodingType;
import org.apache.pulsar.common.schema.SchemaType;
import org.apache.pulsar.functions.api.Record;
import org.apache.pulsar.functions.source.PulsarRecord;
import org.apache.pulsar.io.kinesis.fbs.KeyValue;
import org.apache.pulsar.io.kinesis.fbs.Message;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.collections.Maps;
/**
* Unit test of {@link UtilsTest}.
*/
public class UtilsTest {
@DataProvider(name = "encryption")
public Object[][] encryptionProvider() {
return new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}};
}
@Test
public void testJsonSerialization() {
final String[] keyNames = {"key1", "key2"};
final String key1Value = "test1";
final String key2Value = "test2";
final byte[][] keyValues = {key1Value.getBytes(), key2Value.getBytes()};
final String param = "param";
final String algo = "algo";
int batchSize = 10;
int compressionMsgSize = 10;
// serialize to json
byte[] data = "payload".getBytes();
Map<String, String> properties = Maps.newHashMap();
properties.put("prop1", "value");
Map<String, String> metadata1 = Maps.newHashMap();
metadata1.put("version", "v1");
metadata1.put("ckms", "cmks-1");
Map<String, String> metadata2 = Maps.newHashMap();
metadata2.put("version", "v2");
metadata2.put("ckms", "cmks-2");
Record<GenericObject> recordCtx =
createRecord(data, algo, keyNames, keyValues, param.getBytes(), metadata1, metadata2,
batchSize, compressionMsgSize, properties, true);
String json = Utils.serializeRecordToJson(recordCtx);
// deserialize from json and assert
KinesisMessageResponse kinesisJsonResponse = deSerializeRecordFromJson(json);
assertEquals(data, getDecoder().decode(kinesisJsonResponse.getPayloadBase64()));
EncryptionCtx encryptionCtxDeser = kinesisJsonResponse.getEncryptionCtx();
assertEquals(key1Value.getBytes(),
getDecoder().decode(encryptionCtxDeser.getKeysMapBase64().get(keyNames[0])));
assertEquals(key2Value.getBytes(),
getDecoder().decode(encryptionCtxDeser.getKeysMapBase64().get(keyNames[1])));
assertEquals(param.getBytes(), getDecoder().decode(encryptionCtxDeser.getEncParamBase64()));
assertEquals(algo, encryptionCtxDeser.getAlgorithm());
assertEquals(metadata1, encryptionCtxDeser.getKeysMetadataMap().get(keyNames[0]));
assertEquals(metadata2, encryptionCtxDeser.getKeysMetadataMap().get(keyNames[1]));
assertEquals(properties, kinesisJsonResponse.getProperties());
}
@Test(dataProvider = "encryption")
public void testFbSerialization(boolean isEncryption) {
final String[] keyNames = {"key1", "key2"};
final String param = "param";
final String algo = "algo";
int batchSize = 10;
int compressionMsgSize = 10;
for (int k = 0; k < 5; k++) {
String payloadString = RandomStringUtils.random(142342 * k, String.valueOf(System.currentTimeMillis()));
final String key1Value = payloadString + "test1";
final String key2Value = payloadString + "test2";
final byte[][] keyValues = {key1Value.getBytes(), key2Value.getBytes()};
byte[] data = payloadString.getBytes();
Map<String, String> properties = Maps.newHashMap();
properties.put("prop1", payloadString);
Map<String, String> metadata1 = Maps.newHashMap();
metadata1.put("version", "v1");
metadata1.put("ckms", "cmks-1");
Map<String, String> metadata2 = Maps.newHashMap();
metadata2.put("version", "v2");
metadata2.put("ckms", "cmks-2");
Record<GenericObject> record = createRecord(data, algo, keyNames, keyValues, param.getBytes(), metadata1,
metadata2, batchSize, compressionMsgSize, properties, isEncryption);
ByteBuffer flatBuffer = Utils.serializeRecordToFlatBuffer(record);
Message kinesisJsonResponse = Message.getRootAsMessage(flatBuffer);
byte[] fbPayloadBytes = new byte[kinesisJsonResponse.payloadLength()];
kinesisJsonResponse.payloadAsByteBuffer().get(fbPayloadBytes);
assertEquals(data, fbPayloadBytes);
if (isEncryption) {
org.apache.pulsar.io.kinesis.fbs.EncryptionCtx encryptionCtxDeser = kinesisJsonResponse.encryptionCtx();
byte compressionType = encryptionCtxDeser.compressionType();
int fbBatchSize = encryptionCtxDeser.batchSize();
boolean isBathcMessage = encryptionCtxDeser.isBatchMessage();
int fbCompressionMsgSize = encryptionCtxDeser.uncompressedMessageSize();
int totalKeys = encryptionCtxDeser.keysLength();
Map<String, Map<String, String>> fbKeyMetadataResult = Maps.newHashMap();
Map<String, byte[]> fbKeyValueResult = Maps.newHashMap();
for (int i = 0; i < encryptionCtxDeser.keysLength(); i++) {
org.apache.pulsar.io.kinesis.fbs.EncryptionKey encryptionKey = encryptionCtxDeser.keys(i);
String keyName = encryptionKey.key();
byte[] keyValueBytes = new byte[encryptionKey.valueLength()];
encryptionKey.valueAsByteBuffer().get(keyValueBytes);
fbKeyValueResult.put(keyName, keyValueBytes);
Map<String, String> fbMetadata = Maps.newHashMap();
for (int j = 0; j < encryptionKey.metadataLength(); j++) {
KeyValue encMtdata = encryptionKey.metadata(j);
fbMetadata.put(encMtdata.key(), encMtdata.value());
}
fbKeyMetadataResult.put(keyName, fbMetadata);
}
byte[] paramBytes = new byte[encryptionCtxDeser.paramLength()];
encryptionCtxDeser.paramAsByteBuffer().get(paramBytes);
assertEquals(totalKeys, 2);
assertEquals(batchSize, fbBatchSize);
assertTrue(isBathcMessage);
assertEquals(compressionMsgSize, fbCompressionMsgSize);
assertEquals(keyValues[0], fbKeyValueResult.get(keyNames[0]));
assertEquals(keyValues[1], fbKeyValueResult.get(keyNames[1]));
assertEquals(metadata1, fbKeyMetadataResult.get(keyNames[0]));
assertEquals(metadata2, fbKeyMetadataResult.get(keyNames[1]));
assertEquals(compressionType, org.apache.pulsar.io.kinesis.fbs.CompressionType.LZ4);
assertEquals(param.getBytes(), paramBytes);
assertEquals(algo, encryptionCtxDeser.algo());
}
Map<String, String> fbproperties = Maps.newHashMap();
for (int i = 0; i < kinesisJsonResponse.propertiesLength(); i++) {
KeyValue property = kinesisJsonResponse.properties(i);
fbproperties.put(property.key(), property.value());
}
assertEquals(properties, fbproperties);
}
}
private Record<GenericObject> createRecord(byte[] data, String algo, String[] keyNames, byte[][] keyValues,
byte[] param,
Map<String, String> metadata1, Map<String, String> metadata2,
int batchSize, int compressionMsgSize,
Map<String, String> properties, boolean isEncryption) {
EncryptionContext ctx = null;
if (isEncryption) {
ctx = new EncryptionContext();
ctx.setAlgorithm(algo);
ctx.setBatchSize(Optional.of(batchSize));
ctx.setCompressionType(CompressionType.LZ4);
ctx.setUncompressedMessageSize(compressionMsgSize);
Map<String, EncryptionKey> keys = Maps.newHashMap();
EncryptionKey encKeyVal = new EncryptionKey();
encKeyVal.setKeyValue(keyValues[0]);
encKeyVal.setMetadata(metadata1);
EncryptionKey encKeyVal2 = new EncryptionKey();
encKeyVal2.setKeyValue(keyValues[1]);
encKeyVal2.setMetadata(metadata2);
keys.put(keyNames[0], encKeyVal);
keys.put(keyNames[1], encKeyVal2);
ctx.setKeys(keys);
ctx.setParam(param);
}
org.apache.pulsar.client.api.Message<GenericObject> message = mock(org.apache.pulsar.client.api.Message.class);
when(message.getData()).thenReturn(data);
when(message.getProperties()).thenReturn(properties);
when(message.getEncryptionCtx()).thenReturn(Optional.ofNullable(ctx));
return PulsarRecord.<GenericObject>builder().message(message).build();
}
public static KinesisMessageResponse deSerializeRecordFromJson(String jsonRecord) {
if (StringUtils.isNotBlank(jsonRecord)) {
return new Gson().fromJson(jsonRecord, KinesisMessageResponse.class);
}
return null;
}
@ToString
@Setter
@Getter
public static class KinesisMessageResponse {
// Encryption-context if message has been encrypted
private EncryptionCtx encryptionCtx;
// user-properties
private Map<String, String> properties;
// base64 encoded payload
private String payloadBase64;
}
@ToString
@Setter
@Getter
public static class EncryptionCtx {
// map of encryption-key value. (key-value is base64 encoded)
private Map<String, String> keysMapBase64;
// map of encryption-key metadata
private Map<String, Map<String, String>> keysMetadataMap;
// encryption param which is base64 encoded
private String encParamBase64;
// encryption algorithm
private String algorithm;
// compression type if message is compressed
private CompressionType compressionType;
private int uncompressedMessageSize;
// number of messages in the batch if msg is batched message
private Integer batchSize;
}
@DataProvider(name = "schemaType")
public Object[] schemaType() {
return new Object[]{SchemaType.JSON, SchemaType.AVRO};
}
@Test(dataProvider = "schemaType")
public void testSerializeRecordToJsonExpandingValue(SchemaType schemaType) throws Exception {
RecordSchemaBuilder valueSchemaBuilder = org.apache.pulsar.client.api.schema.SchemaBuilder.record("value");
valueSchemaBuilder.field("c").type(SchemaType.STRING).optional().defaultValue(null);
valueSchemaBuilder.field("d").type(SchemaType.INT32).optional().defaultValue(null);
RecordSchemaBuilder udtSchemaBuilder = SchemaBuilder.record("type1");
udtSchemaBuilder.field("a").type(SchemaType.STRING).optional().defaultValue(null);
udtSchemaBuilder.field("b").type(SchemaType.BOOLEAN).optional().defaultValue(null);
udtSchemaBuilder.field("d").type(SchemaType.DOUBLE).optional().defaultValue(null);
udtSchemaBuilder.field("f").type(SchemaType.FLOAT).optional().defaultValue(null);
udtSchemaBuilder.field("i").type(SchemaType.INT32).optional().defaultValue(null);
udtSchemaBuilder.field("l").type(SchemaType.INT64).optional().defaultValue(null);
GenericSchema<GenericRecord> udtGenericSchema = Schema.generic(udtSchemaBuilder.build(schemaType));
valueSchemaBuilder.field("e", udtGenericSchema).type(schemaType).optional().defaultValue(null);
GenericSchema<GenericRecord> valueSchema = Schema.generic(valueSchemaBuilder.build(schemaType));
GenericRecord valueGenericRecord = valueSchema.newRecordBuilder()
.set("c", "1")
.set("d", 1)
.set("e", udtGenericSchema.newRecordBuilder()
.set("a", "a")
.set("b", true)
.set("d", 1.0)
.set("f", 1.0f)
.set("i", 1)
.set("l", 10L)
.build())
.build();
Map<String, String> properties = new HashMap<>();
properties.put("prop-key", "prop-value");
Record<GenericObject> genericObjectRecord = new Record<GenericObject>() {
@Override
public Optional<String> getTopicName() {
return Optional.of("data-ks1.table1");
}
@Override
public org.apache.pulsar.client.api.Schema getSchema() {
return valueSchema;
}
@Override
public Optional<String> getKey() {
return Optional.of("message-key");
}
@Override
public GenericObject getValue() {
return valueGenericRecord;
}
@Override
public Map<String, String> getProperties() {
return properties;
}
@Override
public Optional<Long> getEventTime() {
return Optional.of(1648502845803L);
}
};
ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
String json = Utils.serializeRecordToJsonExpandingValue(objectMapper, genericObjectRecord, false);
assertEquals(json, "{\"topicName\":\"data-ks1.table1\",\"key\":\"message-key\",\"payload\":{\"c\":\"1\","
+ "\"d\":1,\"e\":{\"a\":\"a\",\"b\":true,\"d\":1.0,\"f\":1.0,\"i\":1,\"l\":10}},"
+ "\"properties\":{\"prop-key\":\"prop-value\"},\"eventTime\":1648502845803}");
}
@Test(dataProvider = "schemaType")
public void testKeyValueSerializeRecordToJsonExpandingValue(SchemaType schemaType) throws Exception {
RecordSchemaBuilder keySchemaBuilder = org.apache.pulsar.client.api.schema.SchemaBuilder.record("key");
keySchemaBuilder.field("a").type(SchemaType.STRING).optional().defaultValue(null);
keySchemaBuilder.field("b").type(SchemaType.INT32).optional().defaultValue(null);
GenericSchema<GenericRecord> keySchema = Schema.generic(keySchemaBuilder.build(schemaType));
GenericRecord keyGenericRecord = keySchema.newRecordBuilder()
.set("a", "1")
.set("b", 1)
.build();
RecordSchemaBuilder valueSchemaBuilder = org.apache.pulsar.client.api.schema.SchemaBuilder.record("value");
valueSchemaBuilder.field("c").type(SchemaType.STRING).optional().defaultValue(null);
valueSchemaBuilder.field("d").type(SchemaType.INT32).optional().defaultValue(null);
RecordSchemaBuilder udtSchemaBuilder = SchemaBuilder.record("type1");
udtSchemaBuilder.field("a").type(SchemaType.STRING).optional().defaultValue(null);
udtSchemaBuilder.field("b").type(SchemaType.BOOLEAN).optional().defaultValue(null);
udtSchemaBuilder.field("d").type(SchemaType.DOUBLE).optional().defaultValue(null);
udtSchemaBuilder.field("f").type(SchemaType.FLOAT).optional().defaultValue(null);
udtSchemaBuilder.field("i").type(SchemaType.INT32).optional().defaultValue(null);
udtSchemaBuilder.field("l").type(SchemaType.INT64).optional().defaultValue(null);
GenericSchema<GenericRecord> udtGenericSchema = Schema.generic(udtSchemaBuilder.build(schemaType));
valueSchemaBuilder.field("e", udtGenericSchema).type(schemaType).optional().defaultValue(null);
GenericSchema<GenericRecord> valueSchema = Schema.generic(valueSchemaBuilder.build(schemaType));
GenericRecord valueGenericRecord = valueSchema.newRecordBuilder()
.set("c", "1")
.set("d", 1)
.set("e", udtGenericSchema.newRecordBuilder()
.set("a", "a")
.set("b", true)
.set("d", 1.0)
.set("f", 1.0f)
.set("i", 1)
.set("l", 10L)
.build())
.build();
Schema<org.apache.pulsar.common.schema.KeyValue<GenericRecord, GenericRecord>> keyValueSchema =
Schema.KeyValue(keySchema, valueSchema, KeyValueEncodingType.INLINE);
org.apache.pulsar.common.schema.KeyValue<GenericRecord, GenericRecord>
keyValue = new org.apache.pulsar.common.schema.KeyValue<>(keyGenericRecord, valueGenericRecord);
GenericObject genericObject = new GenericObject() {
@Override
public SchemaType getSchemaType() {
return SchemaType.KEY_VALUE;
}
@Override
public Object getNativeObject() {
return keyValue;
}
};
Map<String, String> properties = new HashMap<>();
properties.put("prop-key", "prop-value");
Record<GenericObject> genericObjectRecord = new Record<GenericObject>() {
@Override
public Optional<String> getTopicName() {
return Optional.of("data-ks1.table1");
}
@Override
public org.apache.pulsar.client.api.Schema getSchema() {
return keyValueSchema;
}
@Override
public Optional<String> getKey() {
return Optional.of("message-key");
}
@Override
public GenericObject getValue() {
return genericObject;
}
@Override
public Map<String, String> getProperties() {
return properties;
}
@Override
public Optional<Long> getEventTime() {
return Optional.of(1648502845803L);
}
};
ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
String json = Utils.serializeRecordToJsonExpandingValue(objectMapper, genericObjectRecord, false);
assertEquals(json, "{\"topicName\":\"data-ks1.table1\",\"key\":\"message-key\","
+ "\"payload\":{\"value\":{\"c\":\"1\",\"d\":1,\"e\":{\"a\":\"a\",\"b\":true,\"d\":1.0,\"f\":1.0,"
+ "\"i\":1,\"l\":10}},\"key\":{\"a\":\"1\",\"b\":1}},\"properties\":{\"prop-key\":\"prop-value\"},"
+ "\"eventTime\":1648502845803}");
json = Utils.serializeRecordToJsonExpandingValue(objectMapper, genericObjectRecord, true);
assertEquals(json, "{\"topicName\":\"data-ks1.table1\",\"key\":\"message-key\",\"payload.value.c\":\"1\","
+ "\"payload.value.d\":1,\"payload.value.e.a\":\"a\",\"payload.value.e.b\":true,\"payload.value.e"
+ ".d\":1.0,\"payload.value.e.f\":1.0,\"payload.value.e.i\":1,\"payload.value.e.l\":10,\"payload.key"
+ ".a\":\"1\",\"payload.key.b\":1,\"properties.prop-key\":\"prop-value\",\"eventTime\":1648502845803}");
}
@Test
public void testPrimitiveSerializeRecordToJsonExpandingValue() throws Exception {
GenericObject genericObject = new GenericObject() {
@Override
public SchemaType getSchemaType() {
return SchemaType.STRING;
}
@Override
public Object getNativeObject() {
return "message-value";
}
};
Map<String, String> properties = new HashMap<>();
properties.put("prop-key", "prop-value");
Record<GenericObject> genericObjectRecord = new Record<GenericObject>() {
@Override
public Optional<String> getTopicName() {
return Optional.of("data-ks1.table1");
}
@Override
public org.apache.pulsar.client.api.Schema getSchema() {
return Schema.STRING;
}
@Override
public Optional<String> getKey() {
return Optional.of("message-key");
}
@Override
public GenericObject getValue() {
return genericObject;
}
@Override
public Map<String, String> getProperties() {
return properties;
}
@Override
public Optional<Long> getEventTime() {
return Optional.of(1648502845803L);
}
};
ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
String json = Utils.serializeRecordToJsonExpandingValue(objectMapper, genericObjectRecord, false);
assertEquals(json, "{\"topicName\":\"data-ks1.table1\",\"key\":\"message-key\",\"payload\":\"message-value\","
+ "\"properties\":{\"prop-key\":\"prop-value\"},\"eventTime\":1648502845803}");
}
} | 46.033797 | 120 | 0.623278 |
4dd3caec55df44e56ece5ff184a96eb37c203539 | 2,571 | package com.greedystar.generator.db;
import com.greedystar.generator.entity.ColumnInfo;
import com.greedystar.generator.utils.ConfigUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Author GreedyStar
* Date 2018/4/19
*/
public class ConnectionUtil {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
/**
* 初始化数据库连接
*
* @return
*/
public boolean initConnection() {
try {
Class.forName(DriverFactory.getDriver(ConfigUtil.getConfiguration().getDb().getUrl()));
String url = ConfigUtil.getConfiguration().getDb().getUrl();
String username = ConfigUtil.getConfiguration().getDb().getUsername();
String password = ConfigUtil.getConfiguration().getDb().getPassword();
connection = DriverManager.getConnection(url, username, password);
return true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 获取表结构数据
*
* @param tableName 表名
* @return 包含表结构数据的列表
*/
public List<ColumnInfo> getMetaData(String tableName) throws SQLException {
ResultSet tempResultSet = connection.getMetaData().getPrimaryKeys(null, null, tableName);
String primaryKey = null;
if (tempResultSet.next()) {
primaryKey = tempResultSet.getObject(4).toString();
}
List<ColumnInfo> columnInfos = new ArrayList<>();
statement = connection.createStatement();
String sql = "SELECT * FROM " + tableName + " WHERE 1 != 1";
resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
ColumnInfo info;
if (metaData.getColumnName(i).equals(primaryKey)) {
info = new ColumnInfo(metaData.getColumnName(i), metaData.getColumnType(i), true);
} else {
info = new ColumnInfo(metaData.getColumnName(i), metaData.getColumnType(i), false);
}
columnInfos.add(info);
}
statement.close();
resultSet.close();
return columnInfos;
}
public void close() {
try {
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 30.975904 | 99 | 0.598989 |
9ba83533b49bb81dd05643fd8367d1124c88005a | 2,843 | package entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@NamedQuery(name = "School.deleteAllRows", query = "DELETE from School")
@Table(name = "schools")
public class School implements Serializable{
//Variables
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name", nullable = true, length = 45)
private String name;
@Column(name = "domain", nullable = true, length = 45)
private String domain;
@Column(name = "logo_url", nullable = true, length = 45)
private String logoUrl;
@OneToMany(mappedBy = "school", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
private Collection<Course> courses;
//Constructors
public School() {
}
public School(String name, String domain, String logoUrl){
this.id = -1;
this.name = name;
this.domain = domain;
this.logoUrl = logoUrl;
this.courses = null;
}
public School(long id, String name, String domain, String logoUrl) {
this.id = id;
this.name = name;
this.domain = domain;
this.logoUrl = logoUrl;
}
public School(long id, String name, String domain, String logoUrl,
Collection<Course> courses) {
this.id = id;
this.name = name;
this.domain = domain;
this.logoUrl = logoUrl;
this.courses = courses;
}
//Methods
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public Collection<Course> getCourses() {
return courses;
}
public void setCourses(Collection<Course> courses) {
this.courses = courses;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("School{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", domain='").append(domain).append('\'');
sb.append(", logoUrl='").append(logoUrl).append('\'');
sb.append(", courses=").append(courses);
sb.append('}');
return sb.toString();
}
}
| 22.210938 | 110 | 0.675695 |
de06893e1ebee1ca21e78ba1c2483b839516dab4 | 434 | package com.softicar.platform.workflow.module.workflow.transition;
import com.softicar.platform.emf.source.code.reference.point.EmfSourceCodeReferencePointUuid;
import com.softicar.platform.emf.source.code.reference.point.IEmfSourceCodeReferencePoint;
@EmfSourceCodeReferencePointUuid("9f12772f-a244-4ea7-a441-0762a221b2e4")
public class DummySourceCodeReferencePoint implements IEmfSourceCodeReferencePoint {
// nothing to add
}
| 39.454545 | 93 | 0.861751 |
480a5ccb981b02c85bdfaf640cb7217b01bb0374 | 428 | package com.sparrow.collect.index.searcher;
import com.sparrow.collect.index.searcher.write.EmptyResultWriter;
import org.apache.lucene.document.Document;
import java.io.Closeable;
/**
* author: Yzc
* - Date: 2019/3/6 17:33
*/
public interface ResultWriter extends Closeable {
ResultWriter DEFAULT_WRITER = new EmptyResultWriter();
void writeRow(Document document);
void writePageHeader(PageResult page);
}
| 21.4 | 66 | 0.761682 |
2c955245c13d011924295ce0d0aaff019a063520 | 3,820 | /*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2011, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.vms;
/**
* Historic data about requests and allocation of MIPS for a given VM over the time.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.1.2
*/
public class VmStateHistoryEntry {
/**
* The time.
*/
private double time;
/**
* The allocated mips.
*/
private double allocatedMips;
/**
* The requested mips.
*/
private double requestedMips;
/**
* The is in migration.
*/
private boolean inMigration;
/**
* Instantiates a new VmStateHistoryEntry
*
* @param time the time
* @param allocatedMips the allocated mips
* @param requestedMips the requested mips
* @param inMigration the is in migration
*/
public VmStateHistoryEntry(double time, double allocatedMips, double requestedMips, boolean inMigration) {
setTime(time);
setAllocatedMips(allocatedMips);
setRequestedMips(requestedMips);
setInMigration(inMigration);
}
/**
* Sets the time.
*
* @param time the new time
*/
protected final void setTime(double time) {
this.time = time;
}
/**
* Gets the time.
*
* @return the time
*/
public double getTime() {
return time;
}
/**
* Sets the allocated mips.
*
* @param allocatedMips the new allocated mips
*/
protected final void setAllocatedMips(double allocatedMips) {
this.allocatedMips = allocatedMips;
}
/**
* Gets the allocated mips.
*
* @return the allocated mips
*/
public double getAllocatedMips() {
return allocatedMips;
}
/**
* Sets the requested mips.
*
* @param requestedMips the new requested mips
*/
protected final void setRequestedMips(double requestedMips) {
this.requestedMips = requestedMips;
}
/**
* Gets the requested mips.
*
* @return the requested mips
*/
public double getRequestedMips() {
return requestedMips;
}
/**
* Defines if the Vm is in migration for the current history.
*
* @param inMigration true if the Vm is in migration, false otherwise
*/
protected final void setInMigration(boolean inMigration) {
this.inMigration = inMigration;
}
/**
* Checks if the Vm is in migration for the current history.
*
* @return true if the Vm is in migration, false otherwise
*/
public boolean isInMigration() {
return inMigration;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof VmStateHistoryEntry)) {
return false;
}
final VmStateHistoryEntry entry = (VmStateHistoryEntry)obj;
return entry.time == this.time &&
entry.inMigration == this.inMigration &&
entry.allocatedMips == this.allocatedMips &&
entry.requestedMips == this.requestedMips;
}
@Override
public int hashCode() {
int hash = 7;
hash = hash(hash, toBits(this.time));
hash = hash(hash, toBits(this.allocatedMips));
hash = hash(hash, toBits(this.requestedMips));
hash = hash(hash, this.inMigration ? 1 : 0);
return hash;
}
private int hash(final int hash, final int value) {
return 89 * hash + value;
}
private int toBits(final double value){
return (int) (Double.doubleToLongBits(value) ^ (Double.doubleToLongBits(value) >>> 32));
}
}
| 24.33121 | 110 | 0.604974 |
1516d1440c80b4d58ed7f59ac9c6d1f808625971 | 2,233 | package com.bookstore.entity;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
@Entity
public class Author implements Serializable {
private static final Logger logger = Logger.getLogger(Author.class.getName());
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int age;
private String name;
private String genre;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@PrePersist
private void prePersist() {
logger.info("@PrePersist callback ...");
}
@PreUpdate
private void preUpdate() {
logger.info("@PreUpdate callback ...");
}
@PreRemove
private void preRemove() {
logger.info("@PreRemove callback ...");
}
@PostLoad
private void postLoad() {
logger.info("@PostLoad callback ...");
}
@PostPersist
private void postPersist() {
logger.info("@PostPersist callback ...");
}
@PostUpdate
private void postUpdate() {
logger.info("@PostUpdate callback ...");
}
@PostRemove
private void postRemove() {
logger.info("@PostRemove callback ...");
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", age=" + age
+ ", name=" + name + ", genre=" + genre + '}';
}
}
| 21.471154 | 82 | 0.626064 |
eab533da37659deb1dd7739da175d66d869e8953 | 569 | package com.test.autoModel.defaults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j(topic = "log")
public class A implements ExampleAware {
ExampleBean exampleBean;
public A() {
log.debug("default Constructor");
}
public A(B b, C c) {
log.debug("Constructor from b and c");
}
public A(C c) {
log.debug("Constructor from c");
}
public A(B b) {
log.debug("Constructor from b");
}
@Override
public void setExampleBean(ExampleBean exampleBean) {
this.exampleBean = exampleBean;
}
}
| 16.735294 | 54 | 0.699473 |
be89b5ea274f5cc6ae0d74ae62a1ebcc1dac46c1 | 1,080 | package org.opendatakit.sync.client.test;
import org.opendatakit.sync.client.SyncClient;
public class SuperUserTest extends AbstractPrivTestBase {
private String superUserName;
private String superUserPassword;
private String adminUserName;
private String adminPassword;
SyncClient createNewSyncPrivClient() {
SyncClient superUserClient = new SyncClient();
superUserClient.init(host, superUserName, superUserPassword);
return superUserClient;
}
SyncClient createNewAdminPrivClient() {
SyncClient adminClient = new SyncClient();
adminClient.init(host, adminUserName, adminPassword);
return adminClient;
}
/*
* Perform setup for test if necessary
*/
@Override
protected void setUp() throws Exception {
adminUserName = "tester@mezuricloud.com";
adminPassword = "testingTesting0123";
superUserName = "superpriv@mezuricloud.com";
superUserPassword = "testingTesting0123";
super.setUp();
}
/*
* Perform tear down for tests if necessary
*/
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
}
| 21.176471 | 63 | 0.755556 |
319a25fb2f3a89ead5718fba56d6813b1f5c4e2c | 3,652 | package seedu.address.storage;
import java.time.LocalDateTime;
import java.util.logging.Logger;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.commons.util.LocalDateTimeUtil;
import seedu.address.model.module.Assignment;
import seedu.address.model.module.Description;
import seedu.address.model.tag.Tag;
/**
* Jackson-friendly version of {@link Assignment}.
*/
class JsonAdaptedAssignment {
public static final String MISSING_FIELD_MESSAGE_FORMAT = "Assignment's %s field is missing!";
public static final String MESSAGE_CONSTRAINTS = "Assignment deadline must be formatted "
+ "to a valid DD/MM/YYYY HHmm";
private static final Logger logger = LogsCenter.getLogger(JsonAdaptedAssignment.class);
public final String description;
public final String deadline;
public final String tag;
/**
* Constructs a {@code JsonAdaptedAssignment} with the given {@code description} and {@code deadline}.
*/
@JsonCreator
public JsonAdaptedAssignment(@JsonProperty("description") String description,
@JsonProperty("deadline") String deadline,
@JsonProperty("tag") String tag) {
this.description = description;
this.deadline = deadline;
this.tag = tag;
}
/**
* Converts a given {@code source} into this class for Jackson use.
*/
public JsonAdaptedAssignment(Assignment source) {
if (source != null) {
description = source.description.description;
deadline = source.deadline.format(LocalDateTimeUtil.DATETIME_FORMATTER);
tag = source.getTag().tagName;
} else {
description = "Empty";
deadline = "Empty";
tag = "Empty";
}
}
/**
* Converts this Jackson-friendly adapted assignment object into the model's {@code assignment} object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted assignment.
*/
public Assignment toModelType() throws IllegalValueException {
if (description == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT,
Description.class.getSimpleName()));
}
assert description != null;
final Description modelDescription;
if (!Description.isValidDescription(description)) {
throw new IllegalValueException(Description.MESSAGE_CONSTRAINTS);
} else {
modelDescription = new Description(description);
}
if (deadline == null || !LocalDateTimeUtil.isValidDateTime(deadline)) {
throw new IllegalValueException(String.format(MESSAGE_CONSTRAINTS,
LocalDateTime.class.getSimpleName()));
}
assert deadline != null;
final LocalDateTime modelDeadline = LocalDateTime.parse(deadline,
LocalDateTimeUtil.DATETIME_FORMATTER);
if (tag == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT,
Tag.class.getSimpleName()));
}
assert tag != null;
final Tag modelTag;
if (!Tag.isValidTagName(tag)) {
throw new IllegalValueException(Tag.MESSAGE_CONSTRAINTS);
} else {
modelTag = new Tag(tag);
}
return new Assignment(modelDescription, modelDeadline, modelTag);
}
}
| 36.158416 | 107 | 0.661555 |
87fd2aa22613d5a54599f0eba76062659dfe76f0 | 453 |
public enum YesNo
{
YES("YES"),
NO("NO");
private String text = null;
private YesNo (String text) {
this.text = text;
}
public String toString() {
return this.text;
}
public static YesNo fromString(String text) {
if (text != null) {
for (YesNo b : YesNo.values()) {
if (text.equalsIgnoreCase(b.text)) {
return b;
}
}
}
return null;
}
}
| 15.62069 | 47 | 0.496689 |
4f86cff6f0f141f045db461b92d2ac6892f2f6ff | 4,913 | /*
* 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.syncope.core.provisioning.camel.producer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.syncope.common.lib.request.AnyCR;
import org.apache.syncope.common.lib.request.AnyObjectCR;
import org.apache.syncope.common.lib.request.GroupCR;
import org.apache.syncope.common.lib.request.UserCR;
import org.apache.syncope.common.lib.types.AnyTypeKind;
import org.apache.syncope.core.provisioning.api.WorkflowResult;
import org.apache.syncope.core.provisioning.api.propagation.PropagationReporter;
import org.apache.syncope.core.provisioning.api.propagation.PropagationTaskInfo;
public class CreateProducer extends AbstractProducer {
public CreateProducer(final Endpoint endpoint, final AnyTypeKind anyTypeKind) {
super(endpoint, anyTypeKind);
}
@SuppressWarnings("unchecked")
@Override
public void process(final Exchange exchange) throws Exception {
if ((exchange.getIn().getBody() instanceof WorkflowResult)) {
Object actual = exchange.getProperty("actual");
Set<String> excludedResources = exchange.getProperty("excludedResources", Set.class);
Boolean nullPriorityAsync = exchange.getProperty("nullPriorityAsync", Boolean.class);
if (actual instanceof UserCR) {
WorkflowResult<Pair<String, Boolean>> created =
(WorkflowResult<Pair<String, Boolean>>) exchange.getIn().getBody();
List<PropagationTaskInfo> taskInfos = getPropagationManager().getUserCreateTasks(
created.getResult().getKey(),
((UserCR) actual).getPassword(),
created.getResult().getValue(),
created.getPropByRes(),
((UserCR) actual).getVirAttrs(),
excludedResources);
PropagationReporter reporter = getPropagationTaskExecutor().execute(taskInfos, nullPriorityAsync);
exchange.getOut().setBody(
Pair.of(created.getResult().getKey(), reporter.getStatuses()));
} else if (actual instanceof AnyCR) {
WorkflowResult<String> created = (WorkflowResult<String>) exchange.getIn().getBody();
if (actual instanceof GroupCR && isPull()) {
Map<String, String> groupOwnerMap = exchange.getProperty("groupOwnerMap", Map.class);
((GroupCR) actual).getPlainAttr(StringUtils.EMPTY).ifPresent(groupOwner
-> groupOwnerMap.put(created.getResult(), groupOwner.getValues().iterator().next()));
List<PropagationTaskInfo> taskInfos = getPropagationManager().getCreateTasks(
AnyTypeKind.GROUP,
created.getResult(),
null,
created.getPropByRes(),
((AnyCR) actual).getVirAttrs(),
excludedResources);
getPropagationTaskExecutor().execute(taskInfos, nullPriorityAsync);
exchange.getOut().setBody(Pair.of(created.getResult(), null));
} else {
List<PropagationTaskInfo> taskInfos = getPropagationManager().getCreateTasks(
actual instanceof AnyObjectCR ? AnyTypeKind.ANY_OBJECT : AnyTypeKind.GROUP,
created.getResult(),
null,
created.getPropByRes(),
((AnyCR) actual).getVirAttrs(),
excludedResources);
PropagationReporter reporter = getPropagationTaskExecutor().execute(taskInfos, nullPriorityAsync);
exchange.getOut().setBody(Pair.of(created.getResult(), reporter.getStatuses()));
}
}
}
}
}
| 49.13 | 118 | 0.636475 |
d2d35b7565e8d2bad7939db46b96da49667d0e9c | 9,399 | package com.inmobi.commons.core.configs;
import com.inmobi.commons.core.network.C10677d;
import com.inmobi.commons.core.network.NetworkError;
import com.inmobi.commons.core.network.NetworkError.ErrorCode;
import com.inmobi.commons.core.p222e.C10659b;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONException;
import org.json.JSONObject;
final class ConfigNetworkResponse {
/* access modifiers changed from: private */
/* renamed from: b */
public static final String f32431b = ConfigNetworkResponse.class.getName();
/* renamed from: a */
Map<String, ConfigResponse> f32432a = new HashMap();
/* renamed from: c */
private Map<String, C10639a> f32433c;
/* renamed from: d */
private C10677d f32434d;
/* renamed from: e */
private C10647d f32435e;
/* renamed from: f */
private long f32436f;
public static class ConfigResponse {
/* renamed from: a */
ConfigResponseStatus f32437a;
/* renamed from: b */
C10639a f32438b;
/* renamed from: c */
C10647d f32439c;
public enum ConfigResponseStatus {
SUCCESS(200),
NOT_MODIFIED(304),
PRODUCT_NOT_FOUND(404),
INTERNAL_ERROR(500),
UNKNOWN(-1);
/* renamed from: a */
private int f32440a;
private ConfigResponseStatus(int i) {
this.f32440a = i;
}
public final int getValue() {
return this.f32440a;
}
public static ConfigResponseStatus fromValue(int i) {
ConfigResponseStatus[] values;
for (ConfigResponseStatus configResponseStatus : values()) {
if (configResponseStatus.f32440a == i) {
return configResponseStatus;
}
}
return UNKNOWN;
}
}
public ConfigResponse(JSONObject jSONObject, C10639a aVar) {
String str = " Error message:";
String str2 = " Error code:";
String str3 = "Config type:";
this.f32438b = aVar;
if (jSONObject != null) {
try {
this.f32437a = ConfigResponseStatus.fromValue(jSONObject.getInt("status"));
if (this.f32437a == ConfigResponseStatus.SUCCESS) {
this.f32438b.mo33672a(jSONObject.getJSONObject("content"));
if (!this.f32438b.mo33674c()) {
this.f32439c = new C10647d(2, "The received config has failed validation.");
ConfigNetworkResponse.f32431b;
StringBuilder sb = new StringBuilder(str3);
sb.append(this.f32438b.mo33671a());
sb.append(str2);
sb.append(this.f32439c.f32456a);
sb.append(str);
sb.append(this.f32439c.f32457b);
}
} else if (this.f32437a == ConfigResponseStatus.NOT_MODIFIED) {
ConfigNetworkResponse.f32431b;
StringBuilder sb2 = new StringBuilder(str3);
sb2.append(this.f32438b.mo33671a());
sb2.append(" Config not modified");
} else {
this.f32439c = new C10647d(1, this.f32437a.toString());
ConfigNetworkResponse.f32431b;
StringBuilder sb3 = new StringBuilder(str3);
sb3.append(this.f32438b.mo33671a());
sb3.append(str2);
sb3.append(this.f32439c.f32456a);
sb3.append(str);
sb3.append(this.f32439c.f32457b);
}
} catch (JSONException e) {
this.f32439c = new C10647d(2, e.getLocalizedMessage());
ConfigNetworkResponse.f32431b;
StringBuilder sb4 = new StringBuilder(str3);
sb4.append(this.f32438b.mo33671a());
sb4.append(str2);
sb4.append(this.f32439c.f32456a);
sb4.append(str);
sb4.append(this.f32439c.f32457b);
}
}
}
/* renamed from: a */
public final boolean mo34448a() {
return this.f32439c != null;
}
}
ConfigNetworkResponse(Map<String, C10639a> map, C10677d dVar, long j) {
this.f32433c = map;
this.f32434d = dVar;
this.f32436f = j;
m34907c();
}
/* renamed from: c */
private void m34907c() {
JSONObject jSONObject;
String str = "InvalidConfig";
String str2 = "root";
String str3 = "latency";
String str4 = "reason";
String str5 = "errorCode";
String str6 = "name";
String str7 = ")";
String str8 = "Error in submitting telemetry event : (";
String str9 = " Error message:";
String str10 = "Error code:";
if (!this.f32434d.mo34510a()) {
try {
JSONObject jSONObject2 = new JSONObject(this.f32434d.mo34511b());
Iterator keys = jSONObject2.keys();
while (keys.hasNext()) {
String str11 = (String) keys.next();
JSONObject jSONObject3 = jSONObject2.getJSONObject(str11);
if (this.f32433c.get(str11) != null) {
jSONObject = jSONObject2;
this.f32432a.put(str11, new ConfigResponse(jSONObject3, (C10639a) this.f32433c.get(str11)));
} else {
jSONObject = jSONObject2;
}
jSONObject2 = jSONObject;
}
} catch (JSONException e) {
this.f32435e = new C10647d(2, e.getLocalizedMessage());
StringBuilder sb = new StringBuilder(str10);
sb.append(this.f32435e.f32456a);
sb.append(str9);
sb.append(this.f32435e.f32457b);
try {
HashMap hashMap = new HashMap();
hashMap.put(str6, m34905a(this.f32433c));
hashMap.put(str5, "ParsingError");
hashMap.put(str4, e.getLocalizedMessage());
hashMap.put(str3, Long.valueOf(this.f32436f));
C10659b.m34983a();
C10659b.m34987a(str2, str, hashMap);
} catch (Exception e2) {
StringBuilder sb2 = new StringBuilder(str8);
sb2.append(e2.getMessage());
sb2.append(str7);
}
}
} else {
Iterator it = this.f32433c.entrySet().iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();
ConfigResponse configResponse = new ConfigResponse(null, (C10639a) entry.getValue());
Iterator it2 = it;
configResponse.f32439c = new C10647d(0, "Network error in fetching config.");
this.f32432a.put(entry.getKey(), configResponse);
it = it2;
}
this.f32435e = new C10647d(0, this.f32434d.f32591b.f32553b);
StringBuilder sb3 = new StringBuilder(str10);
sb3.append(this.f32435e.f32456a);
sb3.append(str9);
sb3.append(this.f32435e.f32457b);
try {
HashMap hashMap2 = new HashMap();
hashMap2.put(str6, m34905a(this.f32433c));
hashMap2.put(str5, String.valueOf(this.f32434d.f32591b.f32552a.getValue()));
hashMap2.put(str4, this.f32434d.f32591b.f32553b);
hashMap2.put(str3, Long.valueOf(this.f32436f));
C10659b.m34983a();
C10659b.m34987a(str2, str, hashMap2);
} catch (Exception e3) {
StringBuilder sb4 = new StringBuilder(str8);
sb4.append(e3.getMessage());
sb4.append(str7);
}
}
}
/* renamed from: a */
public final boolean mo34447a() {
C10677d dVar = this.f32434d;
if (dVar != null) {
NetworkError networkError = dVar.f32591b;
if (networkError != null) {
ErrorCode errorCode = networkError.f32552a;
if (errorCode != ErrorCode.BAD_REQUEST) {
int value = errorCode.getValue();
if (500 <= value && value < 600) {
return true;
}
}
return true;
}
}
return false;
}
/* renamed from: a */
private static String m34905a(Map<String, C10639a> map) {
String str = "";
for (String str2 : map.keySet()) {
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.append(str2);
sb.append(",");
str = sb.toString();
}
return str.substring(0, str.length() - 1);
}
}
| 37.899194 | 116 | 0.506224 |
32d5f2cf8ccc11d6cb2e1f3b5e09bda968cc32d8 | 550 | package com.angkorteam.fintech.ddl;
public interface MTaxGroup {
public static final String NAME = "m_tax_group";
public interface Field {
public static final String ID = "id";
public static final String NAME = "name";
public static final String CREATED_BY_ID = "createdby_id";
public static final String CREATED_DATE = "created_date";
public static final String LAST_MODIFIED_BY_ID = "lastmodifiedby_id";
public static final String LAST_MODIFIED_DATE = "lastmodified_date";
}
}
| 22.916667 | 77 | 0.694545 |
d1ba2ae1d3456c23a9af4584616d903c3edcea0b | 6,376 | package tv.lid.cinema.api2.models;
import java.sql.SQLException;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.sql2o.Connection;
// класс модели киносеанса
@JsonIgnoreProperties(value = "movieId", allowSetters = true)
public class ScheduleModel extends CommonModel {
// имя SQL-таблицы с сеансами
private static final String TABLE_SCHEDULES = "api2_schedules";
// идентификатор фильма
@JsonProperty(value = "movieId", required = true)
public final int movieId;
// дата и время начала
@JsonProperty(value = "dateAndTime", required = true)
public final String dateAndTime;
// номер зала
@JsonProperty(value = "auditorium", required = false, defaultValue = "1")
public final byte auditorium;
// конструктор #1 -- используется для создания экземпляра из входящего запроса
@JsonCreator
public ScheduleModel(
@JsonProperty("id") final int id,
@JsonProperty("movieId") final int movieId,
@JsonProperty("dateAndTime") final String dateAndTime,
@JsonProperty("auditorium") final byte auditorium
) {
super(id);
this.movieId = movieId;
this.dateAndTime = dateAndTime;
this.auditorium = auditorium;
}
// конструктор #2 -- используется для создания экземпляра с нуля
public ScheduleModel(
final int movieId,
final String dateAndTime,
final byte auditorium
) {
this(0, movieId, dateAndTime, auditorium);
}
// создание таблицы в БД
public static void createTable() throws SQLException {
CommonModel.sql2o
.open()
.createQuery(
"CREATE TABLE IF NOT EXISTS " + ScheduleModel.TABLE_SCHEDULES + " (" +
"id INT NOT NULL IDENTITY, " +
"movie_id INT NOT NULL, " +
"date_time VARCHAR(50) NOT NULL, " +
"auditorium TINYINT NOT NULL, " +
"FOREIGN KEY(movie_id) REFERENCES " + MovieModel.tableName() + "(id) ON DELETE CASCADE)"
)
.executeUpdate()
.close();
}
// удаление таблицы из БД
public static void dropTable() throws SQLException {
CommonModel.sql2o
.open()
.createQuery("DROP TABLE IF EXISTS " + ScheduleModel.TABLE_SCHEDULES)
.executeUpdate()
.close();
}
// имя таблицы в БД
public static String tableName() {
return ScheduleModel.TABLE_SCHEDULES;
}
// подсчет количества записей в БД по заданному идентификатору фильма
public static int count(final int movieId) throws SQLException {
Connection con = CommonModel.sql2o.open();
Integer cnt = con.createQuery(
"SELECT COUNT(*) FROM " + ScheduleModel.TABLE_SCHEDULES + " WHERE movie_id = :movie_id"
).addParameter("movie_id", movieId).executeScalar(Integer.class);
con.close();
return cnt.intValue();
}
// проверка существования в БД записи с заданным идентификатором
public static boolean exists(final int id) throws SQLException {
Connection con = CommonModel.sql2o.open();
Integer cnt = con.createQuery(
"SELECT COUNT(*) FROM " + ScheduleModel.TABLE_SCHEDULES + " WHERE id = :id"
).addParameter("id", id).executeScalar(Integer.class);
con.close();
return cnt.intValue() != 0;
}
// чтение записи из БД по заданному идентификатору
public static ScheduleModel find(final int id) throws SQLException {
Connection con = CommonModel.sql2o.open();
ScheduleModel result = con.createQuery(
"SELECT id, movie_id AS movieId, date_time AS dateAndTime, auditorium FROM " +
ScheduleModel.TABLE_SCHEDULES + " WHERE id = :id"
).addParameter("id", id).executeAndFetchFirst(ScheduleModel.class);
con.close();
return result;
}
// получить список записей из БД в соответствии с заданными параметрами
public static List<ScheduleModel> list(
final int movieId,
final int page,
final int numb
) throws SQLException {
Connection con = CommonModel.sql2o.open();
List<ScheduleModel> result = con.createQuery(
"SELECT id, movie_id AS movieId, date_time AS dateAndTime, auditorium FROM " +
ScheduleModel.TABLE_SCHEDULES + " WHERE movie_id = :movie_id ORDER BY dateAndTime DESC LIMIT :limit OFFSET :offset"
)
.addParameter("movie_id", movieId)
.addParameter("limit", numb)
.addParameter("offset", (page - 1) * numb)
.executeAndFetch(ScheduleModel.class);
con.close();
return result;
}
// удаление записи из БД по заданному идентификатору
public static void kill(final int id) throws SQLException {
CommonModel.sql2o
.open()
.createQuery("DELETE FROM " + ScheduleModel.TABLE_SCHEDULES + " WHERE id = :id")
.addParameter("id", id)
.executeUpdate()
.close();
}
// сохранение данной записи в БД
public void save() throws SQLException {
Connection con = CommonModel.sql2o.open();
if (this.id == 0) { // создание новой
con.createQuery(
"INSERT INTO " + ScheduleModel.TABLE_SCHEDULES +
" (movie_id, date_time, auditorium) VALUES (:movie_id, :date_time, :auditorium)"
)
.addParameter("movie_id", this.movieId)
.addParameter("date_time", this.dateAndTime)
.addParameter("auditorium", this.auditorium)
.executeUpdate();
} else { // изменение ранее созданной
con.createQuery(
"UPDATE " + ScheduleModel.TABLE_SCHEDULES +
" SET movie_id = :movie_id, date_time = :date_time, auditorium = :auditorium WHERE id = :id"
)
.addParameter("movie_id", this.movieId)
.addParameter("date_time", this.dateAndTime)
.addParameter("auditorium", this.auditorium)
.addParameter("id", id)
.executeUpdate();
};
con.close();
}
}
| 37.505882 | 127 | 0.618256 |
a49b877f601d0c0d2087a0a7f79d08487aa7ced7 | 435 | package fr.bouyguestelecom.tv.bboxiot.events.inter;
import fr.bouyguestelecom.tv.bboxiot.datamodel.SmartProperty;
/**
* Incoming property change event
*
* @author Bertrand Martel
*/
public interface IPropertyIncomingEvent {
/**
* retrieve Smart property object
*
* @return
*/
SmartProperty getProperty();
/**
* retrieve device uid
*
* @return
*/
String getDeviceUid();
}
| 16.730769 | 61 | 0.643678 |
a24a504d1aeb2d09be9fcb2d723be7d1098c433b | 614 | package com.davenonymous.bonsaitrees3.registry.sapling;
import com.davenonymous.libnonymous.helper.BaseRecipeHelper;
import com.davenonymous.bonsaitrees3.setup.Registration;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
public class SaplingRecipeHelper extends BaseRecipeHelper<SaplingInfo> {
public SaplingRecipeHelper() {
super(Registration.RECIPE_TYPE_SAPLING);
}
public SaplingInfo getSaplingInfoForItem(Level level, ItemStack stack) {
return getRecipeStream(level.getRecipeManager()).filter(recipe -> recipe.ingredient.test(stack)).findFirst().orElse(null);
}
} | 38.375 | 124 | 0.825733 |
716e5b1a0e45d86411b91ef3222b1b3e807476a4 | 571 | package org.xmx0632.exportfile.excel.model;
import java.util.List;
public class ExcelSheet {
private String title;
private ExcelDataFormatter edf;
private List content;
public ExcelSheet() {
super();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public ExcelDataFormatter getEdf() {
return edf;
}
public void setEdf(ExcelDataFormatter edf) {
this.edf = edf;
}
public List getContent() {
return content;
}
public void setContent(List content) {
this.content = content;
}
}
| 14.641026 | 45 | 0.705779 |
9ebfb6ecb74eb6c697a0c4045ef0f27dc0d9aeba | 164 | package group144.zaicev;
class WrongBracketSequenceExeption extends Exception {
WrongBracketSequenceExeption(String massege) {
super(massege);
}
}
| 20.5 | 54 | 0.75 |
3a5568347352648369cdeff45cd1f1d21d923490 | 964 | package frontend.views;
import frontend.views.board.boardcomponents.AbstractTileView;
import javafx.scene.image.ImageView;
import javafx.scene.Node;
/**
* Represents the View of an icon piece (player gamepiece)
*
* @author Stephanie
*/
public class IconView {
private ImageView myImageView;
/**
* IconView main constructor
* @param icon
*/
public IconView(ImageView icon){
myImageView = icon;
}
/**
* Gets the internal Node
* @return Node an ImageView
*/
public Node getMyNode() { return myImageView; }
public void setOn(AbstractTileView tileView){
myImageView.setX(tileView.getMyX());
myImageView.setY(tileView.getMyY());
}
/**
* Setters for the height and width of the internal ImageView
* @param v
*/
public void setHeight(double v) { myImageView.setFitHeight(v); }
public void setWidth (double v) { myImageView.setFitWidth(v); }
}
| 22.418605 | 68 | 0.656639 |
53bb18f3a0b8db9cbe6038506cafaf9bca85c36c | 4,585 | /**
* Copyright (c) 2013, 2016 ControlsFX
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of ControlsFX, any associated website, nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package impl.org.controlsfx.skin;
import java.util.Collections;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.collections.ObservableList;
import javafx.scene.control.SkinBase;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import org.controlsfx.control.SegmentedButton;
public class SegmentedButtonSkin extends SkinBase<SegmentedButton> {
private static final String ONLY_BUTTON = "only-button"; //$NON-NLS-1$
private static final String LEFT_PILL = "left-pill"; //$NON-NLS-1$
private static final String CENTER_PILL = "center-pill"; //$NON-NLS-1$
private static final String RIGHT_PILL = "right-pill"; //$NON-NLS-1$
private final HBox container;
public SegmentedButtonSkin(SegmentedButton control) {
super(control);
container = new HBox();
getChildren().add(container);
updateButtons();
getButtons().addListener(new InvalidationListener() {
@Override public void invalidated(Observable observable) {
updateButtons();
}
});
control.toggleGroupProperty().addListener((observable, oldValue, newValue) -> {
getButtons().forEach((button) -> {
button.setToggleGroup(newValue);
});
});
}
private ObservableList<ToggleButton> getButtons() {
return getSkinnable().getButtons();
}
private void updateButtons() {
ObservableList<ToggleButton> buttons = getButtons();
ToggleGroup group = getSkinnable().getToggleGroup();
container.getChildren().clear();
for (int i = 0; i < getButtons().size(); i++) {
ToggleButton t = buttons.get(i);
if (group != null) {
t.setToggleGroup(group);
}
t.getStyleClass().removeAll(ONLY_BUTTON, LEFT_PILL, CENTER_PILL, RIGHT_PILL);
container.getChildren().add(t);
if (i == buttons.size() - 1) {
if (i == 0) {
t.getStyleClass().add(ONLY_BUTTON);
} else {
t.getStyleClass().add(RIGHT_PILL);
}
} else if (i == 0) {
t.getStyleClass().add(LEFT_PILL);
} else {
t.getStyleClass().add(CENTER_PILL);
}
}
}
@Override
protected double computeMaxWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) {
return getSkinnable().prefWidth(height);
}
@Override
protected double computeMaxHeight(double width, double topInset, double rightInset, double bottomInset, double leftInset) {
return getSkinnable().prefHeight(width);
}
}
| 39.869565 | 128 | 0.643621 |
7034416874dbd113f781f4dfbd2cc4a24cb98bf3 | 9,286 | /**
* Copyright 2018-2019 CS Systèmes d'Information
*
* 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 fr.cs.ikats.metadata;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import fr.cs.ikats.common.dao.exception.IkatsDaoConflictException;
import fr.cs.ikats.common.dao.exception.IkatsDaoException;
import fr.cs.ikats.common.dao.exception.IkatsDaoMissingResource;
import fr.cs.ikats.common.junit.CommonTest;
import fr.cs.ikats.metadata.model.FunctionalIdentifier;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
*
*/
public class FunctionalIdentifierTest extends CommonTest {
/**
* Remove all data at the end of the tests
*
* @throws IkatsDaoConflictException
* @throws IkatsDaoException
*/
@AfterClass
public static void tearDown() throws IkatsDaoConflictException, IkatsDaoException {
resetDB();
}
/**
* Remove all data before any test execution
*
* @throws IkatsDaoConflictException
* @throws IkatsDaoException
*/
@Before
public void setUpTest() throws IkatsDaoConflictException, IkatsDaoException {
resetDB();
}
/**
* Remove all funcid data
*
* @throws IkatsDaoConflictException
* @throws IkatsDaoException
*/
protected static void resetDB() throws IkatsDaoConflictException, IkatsDaoException {
MetaDataFacade metaDataFacade = new MetaDataFacade();
List<FunctionalIdentifier> funcIdList = metaDataFacade.getFunctionalIdentifiersList();
// get only the tsuids list to be able to call the remove method
List<String> tsuids = funcIdList.stream().map(FunctionalIdentifier::getTsuid).collect(Collectors.toList());
metaDataFacade.removeFunctionalIdentifier(tsuids);
}
@Test
public void testPersist() throws IkatsDaoConflictException, IkatsDaoException {
MetaDataFacade facade = new MetaDataFacade();
Map<String, String> values = new HashMap<String, String>();
values.put("tsuid1", "mon_id_fonctionel1");
int added = facade.persistFunctionalIdentifier(values);
assertEquals(1, added);
}
@Test(expected = IkatsDaoConflictException.class)
public void testPersist_DG_Doublon() throws IkatsDaoConflictException, IkatsDaoException {
MetaDataFacade facade = new MetaDataFacade();
int added = facade.persistFunctionalIdentifier("tsuid1_dg", "mon_id_fonctionel1");
assertEquals(1, added);
// Will throw the IkatsDaoConflictException
added = facade.persistFunctionalIdentifier("tsuid1_dg", "mon_id_fonctionel1");
}
/**
* Test method for {@link fr.cs.ikats.metadata.MetaDataFacade#removeMetaDataForTS(java.lang.String)} .
* @throws IkatsDaoException
* @throws IkatsDaoConflictException
*/
@Test
public void testRemove() throws IkatsDaoConflictException, IkatsDaoException {
MetaDataFacade facade = new MetaDataFacade();
Map<String, String> values = new HashMap<String, String>();
values.put("tsuid2", "mon_id_fonctionel2");
values.put("tsuid3", "mon_id_fonctionel3");
int added = facade.persistFunctionalIdentifier(values);
assertEquals(2, added);
}
/**
* Test method for {@link fr.cs.ikats.metadata.MetaDataFacade#getMetaDataForTS(java.lang.String)} .
* @throws IkatsDaoException
* @throws IkatsDaoConflictException
*/
@Test
public void testlist() throws IkatsDaoConflictException, IkatsDaoException {
MetaDataFacade facade = new MetaDataFacade();
Map<String, String> values = new HashMap<String, String>();
values.put("tsuid4", "mon_id_fonctionel4");
values.put("tsuid5", "mon_id_fonctionel5");
values.put("tsuid6", "mon_id_fonctionel6");
values.put("tsuid7", "mon_id_fonctionel7");
values.put("tsuid8", "mon_id_fonctionel8");
int added = facade.persistFunctionalIdentifier(values);
assertEquals(5, added);
List<String> tsuids = new ArrayList<String>();
tsuids.add("tsuid4");
tsuids.add("tsuid5");
tsuids.add("tsuid6");
tsuids.add("tsuid7");
tsuids.add("tsuid8");
List<FunctionalIdentifier> result = facade.getFunctionalIdentifierByTsuidList(tsuids);
assertNotNull(result);
assertEquals(5, result.size());
assertEquals("mon_id_fonctionel4", result.get(0).getFuncId());
assertEquals("mon_id_fonctionel5", result.get(1).getFuncId());
tsuids = new ArrayList<String>();
tsuids.add("tsuid9");
result = facade.getFunctionalIdentifierByTsuidList(tsuids);
assertTrue(result.isEmpty());
}
/**
* Test method for {@link fr.cs.ikats.metadata.MetaDataFacade#getMetaDataForTS(java.lang.String)} .
* @throws IkatsDaoException
* @throws IkatsDaoMissingResource
* @throws IkatsDaoConflictException
*/
@Test
public void testGetByFuncIdAndByTsuid() throws IkatsDaoConflictException, IkatsDaoMissingResource, IkatsDaoException {
MetaDataFacade facade = new MetaDataFacade();
Map<String, String> values = new HashMap<String, String>();
values.put("tsuid9", "mon_id_fonctionel9");
values.put("tsuid10", "mon_id_fonctionel10");
values.put("tsuid11", "mon_id_fonctionel11");
values.put("tsuid12", "mon_id_fonctionel12");
int added = facade.persistFunctionalIdentifier(values);
assertEquals(4, added);
FunctionalIdentifier result = facade.getFunctionalIdentifierByFuncId("mon_id_fonctionel9");
assertEquals("tsuid9", result.getTsuid());
result = facade.getFunctionalIdentifierByFuncId("mon_id_fonctionel11");
assertEquals("tsuid11", result.getTsuid());
result = facade.getFunctionalIdentifierByTsuid("tsuid12");
assertEquals("mon_id_fonctionel12", result.getFuncId());
}
@Test(expected = IkatsDaoMissingResource.class)
public void testGetbyFuncIdAndByTsuid_DG() throws IkatsDaoConflictException, IkatsDaoMissingResource, IkatsDaoException {
MetaDataFacade facade = new MetaDataFacade();
Map<String, String> values = new HashMap<String, String>();
values.put("tsuid9", "mon_id_fonctionel9");
values.put("tsuid10", "mon_id_fonctionel10");
values.put("tsuid11", "mon_id_fonctionel11");
values.put("tsuid12", "mon_id_fonctionel12");
int added = facade.persistFunctionalIdentifier(values);
assertEquals(4, added);
FunctionalIdentifier result = facade.getFunctionalIdentifierByFuncId("mon_id_fonctionel14");
assertNull(result);
result = facade.getFunctionalIdentifierByTsuid("tsuid14");
assertNull(result);
}
/**
* Test method for {@link fr.cs.ikats.metadata.MetaDataFacade#getFunctionalIdentifiersList(java.lang.String)} .
* @throws IkatsDaoException
* @throws IkatsDaoConflictException
*/
@Test
public void testGetAllFid() throws IkatsDaoConflictException, IkatsDaoException {
MetaDataFacade facade = new MetaDataFacade();
List<FunctionalIdentifier> result = facade.getFunctionalIdentifiersList();
assertEquals(0, result.size());
Map<String, String> values = new HashMap<String, String>();
values.put("tsuid9", "mon_id_fonctionel9");
values.put("tsuid10", "mon_id_fonctionel10");
values.put("tsuid11", "mon_id_fonctionel11");
values.put("tsuid12", "mon_id_fonctionel12");
int added = facade.persistFunctionalIdentifier(values);
assertEquals(4, added);
result = facade.getFunctionalIdentifiersList();
assertEquals(4, result.size());
}
/**
* Tests that implemented equals, hashcode are exact or/and robust to null values.
*/
@Test
public void testRobustness() {
(new FunctionalIdentifier(null, null)).toString();
(new FunctionalIdentifier(null, null)).hashCode();
assertTrue((new FunctionalIdentifier(null, null)).equals(new FunctionalIdentifier(null, null)));
assertTrue(!(new FunctionalIdentifier(null, null)).equals("string"));
assertNotSame(new FunctionalIdentifier("HI", "HA"), new FunctionalIdentifier("HU", "HA"));
assertFalse((new FunctionalIdentifier("HI", "HA")).equals(new FunctionalIdentifier("HI", "HU")));
}
}
| 38.371901 | 125 | 0.697609 |
1f71d084ef1fb981429a1168bcf427d03fdf3822 | 1,070 | package org.nd4j.imports.TFGraphs;
import lombok.val;
import org.junit.Test;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.nd4j.linalg.factory.Nd4j;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class TestPad {
@Test
public void testPad(){
INDArray in = Nd4j.create(1, 28, 28, 264);
INDArray pad = Nd4j.create(new double[][]{{0,0},{0,1},{0,1},{0,0}});
INDArray out = Nd4j.create(1, 29, 29, 264);
DynamicCustomOp op = DynamicCustomOp.builder("pad")
.addInputs(in, pad)
.addOutputs(out)
.addIntegerArguments(0) //constant mode, with no constant specified
.build();
val outShape = Nd4j.getExecutioner().calculateOutputShape(op);
assertEquals(1, outShape.size());
assertArrayEquals(new long[]{1, 29, 29, 264}, outShape.get(0).getShape());
Nd4j.getExecutioner().exec(op); //Crash here
}
}
| 29.722222 | 83 | 0.646729 |
f977732985ab9963c7077f03e87d41b0d8f70bba | 12,038 | /*
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.miku.r2dbc.mysql.client;
import dev.miku.r2dbc.mysql.util.AddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.util.annotation.Nullable;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.security.auth.x500.X500Principal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static dev.miku.r2dbc.mysql.util.AssertUtils.requireNonNull;
/**
* MySQL hostname verifier, it is NOT an implementation of {@code HostnameVerifier}, because it
* needs to throw detailed exception which behavior not like {@code HostnameVerifier.verity}.
*/
final class MySqlHostVerifier {
private static final Logger logger = LoggerFactory.getLogger(MySqlHostVerifier.class);
private static final String COMMON_NAME = "CN";
private MySqlHostVerifier() {
}
static void accept(String host, SSLSession session) throws SSLException {
requireNonNull(host, "host must not be null");
requireNonNull(session, "session must not be null");
Certificate[] certs = session.getPeerCertificates();
if (certs.length < 1) {
throw new SSLException(String.format("Certificate for '%s' does not exists", host));
}
if (!(certs[0] instanceof X509Certificate)) {
throw new SSLException(String.format("Certificate for '%s' must be X509Certificate (not javax) rather than %s", host, certs[0].getClass()));
}
accepted(host, (X509Certificate) certs[0]);
}
private static void accepted(String host, X509Certificate cert) throws SSLException {
HostType type = determineHostType(host);
List<San> sans = extractSans(cert);
if (!sans.isEmpty()) {
// For self-signed certificate, supports SAN of IP.
switch (type) {
case IP_V4:
matchIpv4(host, sans);
break;
case IP_V6:
matchIpv6(host, sans);
break;
default:
// Or just match DNS name?
matchDns(host, sans);
break;
}
} else {
// RFC 6125, validator must check SAN first, and if SAN exists, then CN should not be checked.
String cn = extractCn(cert);
if (cn == null) {
throw new SSLException(String.format("Certificate for '%s' does not contain the Common Name", host));
}
matchCn(host, cn);
}
}
private static void matchIpv4(String ip, List<San> sans) throws SSLPeerUnverifiedException {
for (San san : sans) {
// IP must be case sensitive.
if (San.IP == san.getType() && ip.equals(san.getValue())) {
if (logger.isDebugEnabled()) {
logger.debug("Certificate for '{}' matched by IPv4 value '{}' of the Subject Alternative Names", ip, san.getValue());
}
return;
}
}
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' does not match any of the Subject Alternative Names: %s", ip, sans));
}
private static void matchIpv6(String ip, List<San> sans) throws SSLPeerUnverifiedException {
String host = normaliseIpv6(ip);
for (San san : sans) {
// IP must be case sensitive.
if (san.getType() == San.IP && host.equals(normaliseIpv6(san.getValue()))) {
if (logger.isDebugEnabled()) {
logger.debug("Certificate for '{}' matched by IPv6 value '{}' of the Subject Alternative Names", ip, san.getValue());
}
return;
}
}
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' does not match any of the Subject Alternative Names: %s", ip, sans));
}
private static void matchDns(String hostname, List<San> sans) throws SSLPeerUnverifiedException {
String host = hostname.toLowerCase(Locale.ROOT);
if (host.isEmpty() || host.charAt(0) == '.' || host.endsWith("..")) {
// Invalid hostname
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' cannot match the Subject Alternative Names because it is invalid name", hostname));
}
for (San san : sans) {
if (san.getType() == San.DNS && matchHost(host, san.getValue().toLowerCase(Locale.ROOT))) {
if (logger.isDebugEnabled()) {
logger.debug("Certificate for '{}' matched by DNS name '{}' of the Subject Alternative Names", host, san.getValue());
}
return;
}
}
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' does not match any of the Subject Alternative Names: %s", hostname, sans));
}
private static void matchCn(String hostname, String commonName) throws SSLPeerUnverifiedException {
String host = hostname.toLowerCase(Locale.ROOT);
String cn = commonName.toLowerCase(Locale.ROOT);
if (host.isEmpty() || host.charAt(0) == '.' || host.endsWith("..") || !matchHost(host, cn)) {
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' does not match the Common Name: %s", hostname, commonName));
}
if (logger.isDebugEnabled()) {
logger.debug("Certificate for '{}' matched by Common Name '{}'", hostname, commonName);
}
}
/**
* @param host must be a string of lower case and it must be validated hostname.
* @param pattern must be a string of lower case.
* @return {@code true} if {@code pattern} matching the {@code host}.
*/
private static boolean matchHost(String host, String pattern) {
if (pattern.isEmpty() || pattern.charAt(0) == '.' || pattern.endsWith("..")) {
return false;
}
// RFC 2818, 3.1. Server Identity
// "...Names may contain the wildcard character * which is considered to match any single domain name component or component fragment..."
// According to this statement, assume that only a single wildcard is legal
int asteriskIndex = pattern.indexOf('*');
if (asteriskIndex < 0) {
// Both are lower case, so no need use equalsIgnoreCase.
return host.equals(pattern);
}
int patternSize = pattern.length();
if (patternSize == 1) {
// No one can signature certificate for "*".
return false;
}
if (asteriskIndex > 0) {
String prefix = pattern.substring(0, asteriskIndex);
if (!host.startsWith(prefix)) {
return false;
}
}
int postfixSize = patternSize - asteriskIndex - 1;
if (postfixSize > 0) {
String postfix = pattern.substring(asteriskIndex + 1);
if (!host.endsWith(postfix)) {
return false;
}
}
int remainderIndex = host.length() - postfixSize;
if (remainderIndex <= asteriskIndex) {
// Asterisk must to match least one character.
// In other words: groups.*.example.com can not match groups..example.com
return false;
}
String remainder = host.substring(asteriskIndex, remainderIndex);
// Asterisk cannot match across domain name labels.
return !remainder.contains(".");
}
@Nullable
private static String extractCn(X509Certificate cert) throws SSLException {
String principal = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
LdapName name;
try {
name = new LdapName(principal);
} catch (InvalidNameException e) {
throw new SSLException(e.getMessage(), e);
}
for (Rdn rdn : name.getRdns()) {
if (rdn.getType().equalsIgnoreCase(COMMON_NAME)) {
return rdn.getValue().toString();
}
}
return null;
}
private static List<San> extractSans(X509Certificate cert) {
try {
Collection<List<?>> pairs = cert.getSubjectAlternativeNames();
if (pairs == null || pairs.isEmpty()) {
return Collections.emptyList();
}
List<San> sans = new ArrayList<>();
for (List<?> pair : pairs) {
// Ignore if it is not a pair.
if (pair == null || pair.size() < 2) {
continue;
}
Integer type = determineSubjectType(pair.get(0));
if (type == null) {
continue;
}
if (San.DNS == type || San.IP == type) {
Object value = pair.get(1);
if (value instanceof String) {
sans.add(new San((String) value, type));
} else if (value instanceof byte[]) {
// TODO: decode ASN.1 DER form.
logger.warn("Certificate contains an ASN.1 DER encoded form in Subject Alternative Names, but DER is unsupported now");
} else if (logger.isWarnEnabled()) {
logger.warn("Certificate contains an unknown value of Subject Alternative Names: {}", value.getClass());
}
} else {
logger.warn("Certificate contains an unknown type of Subject Alternative Names: {}", type);
}
}
return sans;
} catch (CertificateParsingException ignored) {
return Collections.emptyList();
}
}
private static String normaliseIpv6(String ip) {
try {
return InetAddress.getByName(ip).getHostAddress();
} catch (UnknownHostException unexpected) {
return ip;
}
}
private static HostType determineHostType(String hostname) {
if (AddressUtils.isIpv4(hostname)) {
return HostType.IP_V4;
}
int maxIndex = hostname.length() - 1;
String host;
if (hostname.charAt(0) == '[' && hostname.charAt(maxIndex) == ']') {
host = hostname.substring(1, maxIndex);
} else {
host = hostname;
}
if (AddressUtils.isIpv6(host)) {
return HostType.IP_V6;
}
return HostType.DNS;
}
@Nullable
private static Integer determineSubjectType(Object type) {
if (type instanceof Integer) {
return (Integer) type;
} else {
try {
return Integer.parseInt(type.toString());
} catch (NumberFormatException e) {
return null;
}
}
}
private enum HostType {
IP_V6,
IP_V4,
DNS
}
}
| 35.615385 | 168 | 0.588221 |
3dca451821f4b3e1eca97987de7f65fd1697deb4 | 894 | package br.matheusmessora.mbot.discord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
/**
* Created by cin_mmessora on 5/30/17.
*/
@Service
public class DiscordServer {
@Autowired
private IDiscordClient client;
private IGuild guild;
private IChannel channel;
public static long GUILD_ID = 301534962430246922L;
public void mainChannel(IChannel channel) {
this.channel = channel;
}
public IDiscordClient client() {
return client;
}
public IChannel channel() {
return channel;
}
public IGuild guild() {
return guild;
}
public void runGuild() {
this.guild = client.getGuildByID(GUILD_ID);
}
}
| 20.790698 | 62 | 0.694631 |
109cc9043278cf029e181ac46a03be55b0df2a90 | 220 | package com.dotterbear.abztract.factory.pattern.pokemon;
public class Growl implements Move {
@Override
public int getPower() {
return 0;
}
@Override
public String getName() {
return "Growl";
}
}
| 13.75 | 56 | 0.677273 |
1cb19f4f1986ed67ec417583f4f6da5f8ee8af36 | 629 | package com.chmod0.manpages;
import java.io.Serializable;
public class Page implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int section;
public Page(String name, int section) {
super();
this.name = name;
this.section = section;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getSection() {
return this.section;
}
public void setSection(int section) {
this.section = section;
}
@Override
public String toString(){
return this.name + " (" + this.section + ")";
}
}
| 16.128205 | 49 | 0.688394 |
012db2f2ca5171846b3ff814ca6767c8c98e534e | 5,170 | /*
*
* Copyright 2018 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.eva.accession.core.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import uk.ac.ebi.ampt2d.commons.accession.autoconfigure.EnableSpringDataContiguousIdService;
import uk.ac.ebi.ampt2d.commons.accession.generators.monotonic.MonotonicAccessionGenerator;
import uk.ac.ebi.ampt2d.commons.accession.persistence.jpa.monotonic.service.ContiguousIdBlockService;
import uk.ac.ebi.eva.accession.core.IClusteredVariant;
import uk.ac.ebi.eva.accession.core.ClusteredVariantAccessioningService;
import uk.ac.ebi.eva.accession.core.persistence.DbsnpClusteredVariantAccessioningDatabaseService;
import uk.ac.ebi.eva.accession.core.persistence.DbsnpClusteredVariantAccessioningRepository;
import uk.ac.ebi.eva.accession.core.persistence.DbsnpClusteredVariantInactiveEntity;
import uk.ac.ebi.eva.accession.core.persistence.DbsnpClusteredVariantOperationEntity;
import uk.ac.ebi.eva.accession.core.persistence.DbsnpClusteredVariantOperationRepository;
import uk.ac.ebi.eva.accession.core.persistence.DbsnpMonotonicAccessionGenerator;
import uk.ac.ebi.eva.accession.core.service.DbsnpClusteredVariantInactiveService;
@Configuration
@EnableSpringDataContiguousIdService
@Import({ApplicationPropertiesConfiguration.class, MongoConfiguration.class})
/**
* Configuration required to accession and query clustered variants.
*
* TODO Support EVA clustered variants, see {@link SubmittedVariantAccessioningConfiguration} for reference
*/
public class ClusteredVariantAccessioningConfiguration {
private static final Logger logger = LoggerFactory.getLogger(ClusteredVariantAccessioningConfiguration.class);
@Autowired
private DbsnpClusteredVariantAccessioningRepository dbsnpRepository;
@Autowired
private DbsnpClusteredVariantOperationRepository dbsnpOperationRepository;
@Autowired
private DbsnpClusteredVariantInactiveService dbsnpInactiveService;
@Autowired
private ApplicationProperties applicationProperties;
@Autowired
private ContiguousIdBlockService service;
@Value("${accessioning.clustered.categoryId}")
private String categoryId;
@Bean
public Long accessioningMonotonicInitSs() {
return service.getBlockParameters(categoryId).getBlockStartValue();
}
@Bean
public ClusteredVariantAccessioningService ClusteredVariantAccessioningService() {
return new ClusteredVariantAccessioningService(dbsnpClusteredVariantAccessionGenerator(),
dbsnpClusteredVariantAccessioningDatabaseService());
}
@Bean
public MonotonicAccessionGenerator<IClusteredVariant> clusteredVariantAccessionGenerator() {
ApplicationProperties properties = applicationProperties;
logger.debug("Using application properties: " + properties.toString());
return new MonotonicAccessionGenerator<>(
properties.getClustered().getCategoryId(),
properties.getInstanceId(),
service);
}
@Bean
public DbsnpMonotonicAccessionGenerator<IClusteredVariant> dbsnpClusteredVariantAccessionGenerator() {
ApplicationProperties properties = applicationProperties;
return new DbsnpMonotonicAccessionGenerator<>(properties.getClustered().getCategoryId(),
properties.getInstanceId(), service);
}
@Bean
public DbsnpClusteredVariantAccessioningDatabaseService dbsnpClusteredVariantAccessioningDatabaseService() {
return new DbsnpClusteredVariantAccessioningDatabaseService(dbsnpRepository, dbsnpInactiveService);
}
@Bean
public DbsnpClusteredVariantOperationRepository dbsnpClusteredVariantOperationRepository() {
return dbsnpOperationRepository;
}
@Bean
public DbsnpClusteredVariantInactiveService dbsnpClusteredVariantInactiveService() {
return new DbsnpClusteredVariantInactiveService(dbsnpOperationRepository,
DbsnpClusteredVariantInactiveEntity::new,
DbsnpClusteredVariantOperationEntity::new);
}
}
| 43.813559 | 114 | 0.772921 |
b84bf2b95474004108c06779f8f64efb277a2343 | 66 | package net.ugolok.dto;
public enum BarrierState {
ON, OFF
}
| 11 | 26 | 0.69697 |
8d0d7bcb9d2a075109a0ba5da9c5de6172283fbd | 2,136 | package com.moviepilot.sheldon.compactor.util;
import com.moviepilot.sheldon.compactor.config.Defaults;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.map.hash.TObjectLongHashMap;
/**
* Utility class for progress counters
*
*
* @author stefanp
* @since 03.08.12
*/
public class Progressor {
public static TObjectLongMap<String> makeCountMap() {
return new TObjectLongHashMap<String>(Defaults.DEFAULT_NUM_COUNTS);
}
public static TObjectLongMap<String> makeTimeMap() {
return new TObjectLongHashMap<String>(Defaults.DEFAULT_NUM_COUNTS);
}
private final TObjectLongMap<String> counts = makeCountMap();
private final TObjectLongMap<String> times = makeTimeMap();
private final TObjectLongMap<String> mods;
private final long created = System.currentTimeMillis();
public Progressor(TObjectLongMap<String> mods) {
this.mods = mods;
for (String name : mods.keySet())
times.put(name, created);
}
public void tick(String name) {
final long count = counts.adjustOrPutValue(name, 1L, 1L);
if (!mods.containsKey(name))
print(name, count);
else {
if ((count % mods.get(name)) == 0) {
final long now = System.currentTimeMillis();
final long last = times.get(name);
print(name, count, last-now);
times.put(name, now);
}
}
}
public void printAll() {
for (String key : counts.keySet())
print(key);
}
public void print(String name) {
print(name, counts.get(name));
}
private void print(String name, long count) {
print(name, count, (System.currentTimeMillis() - created));
}
private void print(String name, long count, long time) {
if (time < 0)
System.out.println(
(System.currentTimeMillis() - created) + " (since start) "
+ (-time) + " (since last) " + name + ": " + count);
else
System.out.println(time + " (since start) " + name + ": " + count);
}
} | 29.666667 | 79 | 0.600655 |
1e2d048e3ef8b6f8b343faa424aa87a86f040941 | 3,157 | /*******************************************************************************
* Copyright 2012 EMBL-EBI, Hinxton outstation
*
* 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.embl.flatfile.writer.genbank;
import java.io.IOException;
import java.io.StringWriter;
import uk.ac.ebi.embl.api.entry.reference.Publication;
import uk.ac.ebi.embl.api.entry.reference.ReferenceFactory;
public class TitleWriterTest extends GenbankWriterTest {
public void testWrite_ShortTitle() throws IOException {
ReferenceFactory referenceFactory = new ReferenceFactory();
Publication publication = referenceFactory.createPublication();
publication.setTitle(
"NISC Comparative Sequencing Initiative");
StringWriter writer = new StringWriter();
assertTrue(new TitleWriter(entry, publication, wrapType).write(writer));
//System.out.print(writer.toString());
assertEquals(
" TITLE NISC Comparative Sequencing Initiative\n",
writer.toString());
}
public void testWrite_EmptyTitle() throws IOException {
ReferenceFactory referenceFactory = new ReferenceFactory();
Publication publication = referenceFactory.createPublication();
publication.setTitle(
"");
StringWriter writer = new StringWriter();
assertFalse(new TitleWriter(entry, publication, wrapType).write(writer));
assertEquals(
"",
writer.toString());
}
public void testWrite_NullTitle() throws IOException {
ReferenceFactory referenceFactory = new ReferenceFactory();
Publication publication = referenceFactory.createPublication();
StringWriter writer = new StringWriter();
assertFalse(new TitleWriter(entry, publication, wrapType).write(writer));
assertEquals(
"",
writer.toString());
}
public void testWrite_LongTitle() throws IOException {
ReferenceFactory referenceFactory = new ReferenceFactory();
Publication publication = referenceFactory.createPublication();
publication.setTitle(
"NISC Comparative Sequencing Initiative NISC Comparative Sequencing Initiative NISC Comparative Sequencing Initiative");
StringWriter writer = new StringWriter();
assertTrue(new TitleWriter(entry, publication, wrapType).write(writer));
//System.out.print(writer.toString());
assertEquals(
" TITLE NISC Comparative Sequencing Initiative NISC Comparative Sequencing\n"+
" Initiative NISC Comparative Sequencing Initiative\n",
writer.toString());
}
}
| 42.093333 | 127 | 0.688628 |
fe1a7d404c5b65cfe8f943752340cb422873ff34 | 3,719 | package ua.stu.scplib.attribute;
import java.io.*;
/**
* <p>A concrete class specializing {@link com.pixelmed.dicom.Attribute Attribute} for
* Unique Identifier (UI) attributes.</p>
*
* <p>Though an instance of this class may be created
* using its constructors, there is also a factory class, {@link com.pixelmed.dicom.AttributeFactory AttributeFactory}.</p>
*
* @see com.pixelmed.dicom.Attribute
* @see com.pixelmed.dicom.AttributeFactory
* @see com.pixelmed.dicom.AttributeList
*
* @author dclunie
*/
public class UniqueIdentifierAttribute extends StringAttribute {
/**
* <p>Construct an (empty) attribute.</p>
*
* @param t the tag of the attribute
*/
public UniqueIdentifierAttribute(AttributeTag t) {
super(t);
}
/**
* <p>Read an attribute from an input stream.</p>
*
* @param t the tag of the attribute
* @param vl the value length of the attribute
* @param i the input stream
* @exception IOException
* @exception DicomException
*/
public UniqueIdentifierAttribute(AttributeTag t,long vl,DicomInputStream i) throws IOException, DicomException {
super(t,vl,i);
}
/**
* <p>Read an attribute from an input stream.</p>
*
* @param t the tag of the attribute
* @param vl the value length of the attribute
* @param i the input stream
* @exception IOException
* @exception DicomException
*/
public UniqueIdentifierAttribute(AttributeTag t,Long vl,DicomInputStream i) throws IOException, DicomException {
super(t,vl.longValue(),i);
}
/**
* <p>Get the value representation of this attribute (UI).</p>
*
* @return 'U','I' in ASCII as a two byte array; see {@link com.pixelmed.dicom.ValueRepresentation ValueRepresentation}
*/
public byte[] getVR() { return ValueRepresentation.UI; }
/**
* <p>Get the appropriate (0X00) byte for padding UIDS to an even length.</p>
*
* @return the byte pad value appropriate to the VR
*/
protected byte getPadByte() { return 0x00; }
// grep 'VR="UI"' ~/work/dicom3tools/libsrc/standard/elmdict/dicom3.tpl | awk '{print $1 " " $5}' | sed -e 's/Keyword="//' -e 's/"//g' | sort +1 | egrep '(TransferSyntax|SOPClass|Private|CodingScheme)' | awk '{print $2}'
static public boolean isSOPClassRelated(AttributeTag t) {
return t.equals(TagFromName.SOPClassUID)
|| t.equals(TagFromName.AffectedSOPClassUID)
|| t.equals(TagFromName.MediaStorageSOPClassUID)
|| t.equals(TagFromName.OriginalSpecializedSOPClassUID)
|| t.equals(TagFromName.ReferencedRelatedGeneralSOPClassUIDInFile)
|| t.equals(TagFromName.ReferencedSOPClassUID)
|| t.equals(TagFromName.ReferencedSOPClassUIDInFile)
|| t.equals(TagFromName.RelatedGeneralSOPClassUID)
|| t.equals(TagFromName.RequestedSOPClassUID)
|| t.equals(TagFromName.RelatedGeneralSOPClassUID)
|| t.equals(TagFromName.SOPClassesInStudy)
|| t.equals(TagFromName.SOPClassesSupported);
}
static public boolean isTransferSyntaxRelated(AttributeTag t) {
return t.equals(TagFromName.TransferSyntaxUID)
|| t.equals(TagFromName.EncryptedContentTransferSyntaxUID)
|| t.equals(TagFromName.MACCalculationTransferSyntaxUID)
|| t.equals(TagFromName.ReferencedTransferSyntaxUIDInFile);
}
static public boolean isCodingSchemeRelated(AttributeTag t) {
return t.equals(TagFromName.CodingSchemeUID)
|| t.equals(TagFromName.ContextGroupExtensionCreatorUID);
}
static public boolean isPrivateRelated(AttributeTag t) {
return t.equals(TagFromName.PrivateInformationCreatorUID)
|| t.equals(TagFromName.PrivateRecordUID);
}
static public boolean isTransient(AttributeTag t) {
return !isSOPClassRelated(t)
&& !isTransferSyntaxRelated(t)
&& !isCodingSchemeRelated(t)
&& !isPrivateRelated(t);
}
}
| 33.205357 | 221 | 0.732455 |
109172df46720ba702c4d0d56257ea6c38209f8b | 2,991 | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.constructor;
import junit.framework.TestCase;
import org.yaml.snakeyaml.SecClass;
import org.yaml.snakeyaml.Yaml;
public class CustomClassLoaderConstructorTest extends TestCase {
public void testGetClassForNameNull() {
try {
new CustomClassLoaderConstructor(null);
fail();
} catch (Exception e) {
assertEquals("Loader must be provided.", e.getMessage());
}
}
public void testGetClassForName() {
CustomClassLoaderConstructor constr = new CustomClassLoaderConstructor(
CustomClassLoaderConstructorTest.class.getClassLoader());
Yaml yaml = new Yaml(constr);
String s = (String) yaml.load("abc");
assertEquals("abc", s);
}
public void testGetClassForNameWithRoot() throws ClassNotFoundException {
Class<?> clazz = SecClass.forName(
"org.yaml.snakeyaml.constructor.CustomClassLoaderConstructorTest$LoaderBean", true,
CustomClassLoaderConstructorTest.class.getClassLoader());
CustomClassLoaderConstructor constr = new CustomClassLoaderConstructor(clazz,
CustomClassLoaderConstructorTest.class.getClassLoader());
Yaml yaml = new Yaml(constr);
LoaderBean bean = (LoaderBean) yaml.load("{name: Andrey, number: 555}");
assertEquals("Andrey", bean.getName());
assertEquals(555, bean.getNumber());
}
public void testGetClassForNameBean() {
CustomClassLoaderConstructor constr = new CustomClassLoaderConstructor(
CustomClassLoaderConstructorTest.class.getClassLoader());
Yaml yaml = new Yaml(constr);
LoaderBean bean = (LoaderBean) yaml
.load("!!org.yaml.snakeyaml.constructor.CustomClassLoaderConstructorTest$LoaderBean {name: Andrey, number: 555}");
assertEquals("Andrey", bean.getName());
assertEquals(555, bean.getNumber());
}
public static class LoaderBean {
private String name;
private int number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
}
| 35.188235 | 130 | 0.660983 |
007d93f869156d66b2608d4e1b968ebe67bf161a | 6,194 | package ca.cgjennings.apps.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
/**
* Prevents multiple instances of a program from running. On startup, the
* class's {@code makeExclusive} method will be called with any file parameters
* from the command line. This method will attempt to create a server on a
* certain port.
*
* If it fails, it assumes a previous instance has already registered the port.
* In this case, it sends a message to the existing server to identify itself
* and to specify which file(s) to were requested on this instance's command
* line.
*
* This method will return {@code true} if the calling instance should keep
* running after the method returns, or {@code false} if it should stop. A
* {@code false} return value indicates that the program arguments were
* successfully sent to an instance that is already running. A value of
* {@code true} indicates that the current instance is the first, exclusive
* instance, or that the method is unable to verify whether an existing instance
* is running.
*
* @author Chris Jennings <https://cgjennings.ca/contact>
*/
public class InstanceController implements Runnable {
private InstanceController() {
}
public static boolean makeExclusive(String programName, int port, String[] args, InstanceControllerListener listener) {
try {
server = new ServerSocket(port, 50, InetAddress.getLoopbackAddress());
server.setSoTimeout(250);
} catch (BindException b) {
// another instance is probably running; try sending it commands
try {
String response;
try (Socket client = new Socket(InetAddress.getLoopbackAddress(), port)) {
client.setSoTimeout(60 * 1_000);
try (DataOutputStream out = new DataOutputStream(client.getOutputStream()); DataInputStream in = new DataInputStream(client.getInputStream())) {
out.writeUTF(MAGIC);
out.writeUTF(programName);
out.writeInt(args.length);
for (String arg : args) {
out.writeUTF(arg);
}
response = in.readUTF();
}
}
if (OK.equals(response)) {
return false;
}
callListener(listener, true, args);
return true;
} catch (IOException e) {
// we don't know what happened, but something went wrong:
// better run this instance to be sure
return true;
}
} catch (IOException e) {
return true;
}
// we have been able to bind the port, now we will start a server
// thread to listen for messages from other instances
InstanceController.programName = programName;
InstanceController.listener = listener;
callListener(listener, true, args);
thread = new Thread(new InstanceController());
thread.setDaemon(true);
thread.start();
return true;
}
protected static void callListener(InstanceControllerListener l, boolean initial, String[] args) {
try {
l.parseInstanceArguments(initial, args);
} catch (Throwable t) {
System.err.println("InstanceControllerListener: exception while parsing arguments");
t.printStackTrace(System.err);
}
}
public static void stopExclusion() {
if (thread != null) {
thread.interrupt();
while (thread.isAlive()) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
thread = null;
}
}
@Override
public void run() {
Socket socket;
while (true) {
socket = null;
try {
socket = server.accept();
} catch (SocketTimeoutException e) {
} catch (IOException e) {
}
if (thread.isInterrupted()) {
try {
server.close();
thread = null;
} catch (IOException e) {
}
return;
}
if (socket != null) {
DataOutputStream out = null;
DataInputStream in = null;
try {
socket.setSoTimeout(60 * 1_000);
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
if (in.readUTF().equals(MAGIC) && in.readUTF().equals(programName)) {
int arglen = in.readInt();
String[] args = new String[arglen];
for (int i = 0; i < arglen; ++i) {
args[i] = in.readUTF();
}
callListener(listener, false, args);
out.writeUTF(OK);
}
} catch (Exception e) {
// ...
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
out.close();
}
socket.close();
} catch (IOException e) {
}
}
}
}
}
private static Thread thread = null;
private static ServerSocket server;
private static InstanceControllerListener listener;
private static String programName;
private static final String MAGIC = "InstanceController.makeExclusive";
private static final String OK = "OK. Please exit now.";
}
| 36.011628 | 164 | 0.533742 |
68da4c26be24eaab844fa3ddf3459f85e7e1500a | 6,207 | /**
* Copyright (c) 2014, Pablo Lamela Seijas
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Created by: Pablo Lamela on 1/10/2014
*/
package eu.prowessproject.jeb.serialisation;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangException;
import com.ericsson.otp.erlang.OtpErlangInt;
import com.ericsson.otp.erlang.OtpErlangList;
import com.ericsson.otp.erlang.OtpErlangLong;
import com.ericsson.otp.erlang.OtpErlangMap;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangString;
import com.ericsson.otp.erlang.OtpErlangTuple;
import eu.prowessproject.jeb.exceptions.WrongErlangValue;
import eu.prowessproject.jeb.exceptions.WrongTypeOfErlangValue;
/**
* Class that stores common procedures for serialisation and deserialisation
* from and to Erlang terms.
*/
public abstract class ErlSerialisationUtils {
public static OtpErlangObject[] tupleOfSizeToArray(OtpErlangObject object,
int size) {
if (object instanceof OtpErlangTuple) {
OtpErlangTuple tuple = (OtpErlangTuple) object;
if (tuple.arity() == size) {
return tuple.elements();
} else {
throw new WrongErlangValue("Wrong size of tuple, expected " + size
+ ", but found: " + tuple.arity());
}
} else {
throw new WrongTypeOfErlangValue(OtpErlangTuple.class, object.getClass());
}
}
public static void checkIsAtom(OtpErlangObject object, String atomText) {
String atomStr = getStringFromAtom(object);
if (!atomStr.equals(atomText)) {
throw new WrongErlangValue("Wrong atom, expected " + atomText
+ ", but found: " + atomStr);
}
}
public static String getStringFromAtom(OtpErlangObject object) {
if (object instanceof OtpErlangAtom) {
OtpErlangAtom atom = (OtpErlangAtom) object;
return atom.atomValue();
} else {
throw new WrongTypeOfErlangValue(OtpErlangAtom.class, object.getClass());
}
}
public static String getStringFromString(OtpErlangObject object) {
if (object instanceof OtpErlangString) {
OtpErlangString atom = (OtpErlangString) object;
return atom.stringValue();
} else if (object instanceof OtpErlangList) {
OtpErlangList atom = (OtpErlangList) object;
try {
return atom.stringValue();
} catch (OtpErlangException e) {
throw new WrongErlangValue(e); // Should be an OtpErlangString in the first place
}
} else {
throw new WrongTypeOfErlangValue(OtpErlangString.class, object.getClass());
}
}
public static BigInteger getBigIntValue(OtpErlangObject object) {
if (object instanceof OtpErlangLong) {
OtpErlangLong value = (OtpErlangLong) object;
return value.bigIntegerValue();
} else {
throw new WrongTypeOfErlangValue(OtpErlangLong.class, object.getClass());
}
}
public static OtpErlangObject[] getArrayFromList(
OtpErlangObject object) {
if (object instanceof OtpErlangList) {
OtpErlangList value = (OtpErlangList) object;
return value.elements();
} else if (object instanceof OtpErlangString) {
OtpErlangString ostring = (OtpErlangString) object;
String str = ostring.toString();
OtpErlangObject[] ao = new OtpErlangObject[str.toString().length()];
for (int i = 0; i < str.length(); ++i) {
ao[i] = new OtpErlangInt(str.charAt(i));
}
return ao;
} else {
throw new WrongTypeOfErlangValue(OtpErlangList.class, object.getClass());
}
}
public static OtpErlangMap serialiseMap(Map<String, OtpErlangObject> map) {
int i = 0;
OtpErlangObject[] mapKeys = new OtpErlangObject[map.size()];
OtpErlangObject[] mapValues = new OtpErlangObject[map.size()];
for (String key : map.keySet()) {
mapKeys[i] = new OtpErlangAtom(key);
mapValues[i] = map.get(key);
i++;
}
return new OtpErlangMap(mapKeys, mapValues);
}
public static Map<String, OtpErlangObject> deserialiseMap(
OtpErlangObject object) {
if (object instanceof OtpErlangMap) {
OtpErlangMap oriMap = (OtpErlangMap) object;
Map<String, OtpErlangObject> destMap = new HashMap<String, OtpErlangObject>();
OtpErlangObject[] mapKeys = oriMap.keys();
OtpErlangObject[] mapValues = oriMap.values();
for (int i = 0; i < mapValues.length; i++) {
destMap.put(getStringFromAtom(mapKeys[i]), mapValues[i]);
}
return destMap;
} else {
throw new WrongTypeOfErlangValue(OtpErlangMap.class, object.getClass());
}
}
public static OtpErlangObject[] mapSerialise(ErlSerialisable[] paramObjects) {
OtpErlangObject[] objectObjects = new OtpErlangObject[paramObjects.length];
for (int i = 0; i < paramObjects.length; i++) {
objectObjects[i] = paramObjects[i].erlSerialise();
}
return objectObjects;
}
}
| 36.298246 | 85 | 0.741421 |
2ae9447d47be0148df4288ca667210a7e9ab76e0 | 5,462 | /*
* #%L
* Alfresco Records Management Module
* %%
* Copyright (C) 2005 - 2021 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
* -
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* -
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* -
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.module.org_alfresco_module_rm.recordfolder;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.alfresco.api.AlfrescoPublicApi;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
/**
* Record folder service interface
*
* @author Roy Wetherall
* @since 2.1
*/
@AlfrescoPublicApi
public interface RecordFolderService
{
/**
* Sets up the a record folder from a standard folder.
*
* @param nodeRef node reference of the folder to setup
*
* @since 2.2
*/
void setupRecordFolder(NodeRef nodeRef);
/**
* Indicates whether the given node is a record folder or not.
*
* @param nodeRef node reference
* @return boolean true if record folder, false otherwise
*
* @since 2.2
*/
boolean isRecordFolder(NodeRef nodeRef);
/**
* Indicates whether the contents of a record folder are all declared.
*
* @param nodeRef node reference (record folder)
* @return boolean true if record folder contents are declared, false otherwise
*
* @since 2.2
*/
boolean isRecordFolderDeclared(NodeRef nodeRef);
/**
* Indicates whether a record folder is closed or not.
*
* @param nodeRef node reference (record folder)
* @return boolean true if record folder is closed, false otherwise
*
* @since 2.2
*/
boolean isRecordFolderClosed(NodeRef nodeRef);
/**
* Create a record folder in the rm container. The record folder will take the name and type
* provided.
*
* @param rmContainer records management container
* @param name name
* @param type type
* @return NodeRef node reference of record folder
*
* @since 2.2
*/
NodeRef createRecordFolder(NodeRef rmContainer, String name, QName type);
/**
* Create a record folder in the rm container. The record folder will take the name, type and
* properties provided.
*
* @param rmContainer records management container
* @param name name
* @param type type
* @param properties properties
* @return NodeRef node reference of record folder
*
* @since 2.2
*/
NodeRef createRecordFolder(NodeRef rmContainer, String name, QName type, Map<QName, Serializable> properties);
/**
* Create a record folder in the rm container. The record folder will take the name provided.
* Type defaults to rm:recordFolder.
*
* @param rmContainer records management container
* @param name name
* @return NodeRef node reference of record folder
*
* @since 2.2
*/
NodeRef createRecordFolder(NodeRef rmContainer, String name);
/**
* Create a record folder in the rm container. The record folder will take the name and
* properties provided. Type defaults to rm:recordFolder.
*
* @param rmContainer records management container
* @param name name
* @param properties properties
* @return NodeRef node reference of record folder
*
* @since 2.2
*/
NodeRef createRecordFolder(NodeRef rmContainer, String name, Map<QName, Serializable> properties);
/**
* Get all the record folders that a record is filed into.
*
* @param record the record node reference
* @return List list of folder record node references
*
* @since 2.2
*/
// TODO rename to List<NodeRef> getParentRecordFolders(NodeRef record);
List<NodeRef> getRecordFolders(NodeRef record);
// TODO NodeRef getRecordFolderByPath(String path);
// TODO NodeRef getRecordFolderById(String id);
// TODO NodeRef getRecordFolderByName(NodeRef parent, String name);
// TODO void deleteRecordFolder(NodeRef recordFolder);
// TODO List<NodeRef> getParentRecordsManagementContainers(NodeRef container); // also applicable to record folders
// TODO rename to getContainedRecords(NodeRef recordFolder);
/**
* Closes the record folder. If the given node reference is a record the parent will be retrieved and processed.
*
* @param nodeRef the record folder node reference
*
* @since 2.2
*/
void closeRecordFolder(NodeRef nodeRef);
}
| 32.129412 | 119 | 0.670084 |
4d66e878f85abe730329225034ec3de9fb6d038f | 870 | package ru.job4j.ee.store.web.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Represents a servlet filter that sets standart charset (for correct work with non-latin symbols)
*
* @author Alexander Savchenko
* @version 1.0
* @since 2019-11-13
*/
public class CharsetFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(UTF_8.name());
response.setCharacterEncoding(UTF_8.name());
chain.doFilter(request, response);
}
}
| 32.222222 | 143 | 0.775862 |
5acf3bf334391de97f015393afe6f86d0e1d4e6f | 775 | package net.sknv.engine.physics.colliders;
import net.sknv.engine.entities.Collider;
import net.sknv.engine.graph.ShaderProgram;
import net.sknv.engine.graph.WebColor;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import java.util.Optional;
public abstract class BoundingBox { //todo: REFACTOR THIS interface and AABB/OBB
public abstract void translate(Vector3f v);
public abstract void rotate(Quaternionf rot);
public abstract void setRenderColor(Optional<WebColor> color); //todo spaghet
public abstract Collider getCollider();
public abstract EndPoint getMin(); //todo: remove getMin and getMax methods
public abstract EndPoint getMax(); //these methods are aabb specific
public abstract void render(ShaderProgram shaderProgram);
}
| 38.75 | 81 | 0.784516 |
e4bc35231e3e34ca215f0f0d8032cf6eae5a08b6 | 503 |
package org.springframework.boot.actuate.endpoint.invoke;
/**
* A single operation parameter.
*
* @author Phillip Webb
* @since 2.0.0
*/
public interface OperationParameter {
/**
* Returns the parameter name.
* @return the name
*/
String getName();
/**
* Returns the parameter type.
* @return the type
*/
Class<?> getType();
/**
* Return if the parameter is mandatory (does not accept null values).
* @return if the parameter is mandatory
*/
boolean isMandatory();
}
| 15.71875 | 71 | 0.662028 |
0fbbd13b0a93f308a177b7382e44edbb68e597b4 | 2,009 | package com.relaxed.common.risk.model.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.extension.activerecord.Model;
/**
* @author Yakir
* @since 2021-08-29T18:48:19.507
*/
@ApiModel(value = "")
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("engine_abstraction")
public class Abstraction extends Model<Abstraction> {
/**
* 主键
*/
@TableId(value = "ID")
@ApiModelProperty(value = "主键")
private Long id;
/**
* Abstraction 名称
*/
@ApiModelProperty(value = "Abstraction 名称")
private String name;
/**
*
*/
@ApiModelProperty(value = "")
private String label;
/**
* MODEL ID
*/
@ApiModelProperty(value = "MODEL ID")
private Long modelId;
/**
* 统计类型
*/
@ApiModelProperty(value = "统计类型")
private Integer aggregateType;
/**
*
*/
@ApiModelProperty(value = "")
private String searchField;
/**
* 时间段类型
*/
@ApiModelProperty(value = "时间段类型")
private Integer searchIntervalType;
/**
* 时间段具体值
*/
@ApiModelProperty(value = "时间段具体值")
private Integer searchIntervalValue;
/**
*
*/
@ApiModelProperty(value = "")
private String functionField;
/**
* 数据校验
*/
@ApiModelProperty(value = "数据校验")
private String ruleScript;
/**
* 数据校验入口
*/
@ApiModelProperty(value = "数据校验入口")
private String ruleScriptEntry;
/**
*
*/
@ApiModelProperty(value = "")
private String ruleDefinition;
/**
* 状态
*/
@ApiModelProperty(value = "状态")
private Integer status;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String comment;
/**
*
*/
@ApiModelProperty(value = "")
private LocalDateTime createTime;
/**
*
*/
@ApiModelProperty(value = "")
private LocalDateTime updateTime;
}
| 16.333333 | 61 | 0.683922 |
c4af89b86ba5e6fe28a695d0d7cfb698e3fd347c | 2,603 | package com.ykushch.prjalgo2.task1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class TravellingSalesmanPerson {
private static final Logger log = LoggerFactory.getLogger(TravellingSalesmanPerson.class);
/*
These are the steps of the algorithm:
1. start on an arbitrary vertex as current vertex.
2. find out the shortest edge connecting current vertex and an unvisited vertex V.
3. set current vertex to V.
4. mark V as visited.
5. if all the vertices in domain are visited, then terminate.
6. Go to step 2.
*/
public List<Integer> tspNearest(int startingPoint, Integer adjacencyMatrix[][]) {
int verticesCount = adjacencyMatrix[1].length - 1;
boolean[] visited = new boolean[adjacencyMatrix[1].length];
int min = Integer.MAX_VALUE;
List<Integer> finalPath = new ArrayList<>();
Deque<Integer> deque = new ArrayDeque<>();
visited[startingPoint] = true;
deque.push(startingPoint);
log.info("Path: {}", startingPoint);
finalPath.add(startingPoint);
boolean isMinValueFound = false;
int element;
int i;
Integer dst = 0;
while(!deque.isEmpty()) {
element = deque.peek();
i = 0;
while(i <= verticesCount) {
Integer curElem = adjacencyMatrix[element][i];
if(curElem != 0 && !visited[i]) {
if(min > curElem) {
min = curElem;
dst = i;
isMinValueFound = true;
}
}
i++;
}
if (isMinValueFound) {
deque.push(dst);
log.info("Path: {}", dst);
finalPath.add(dst);
visited[dst] = true;
isMinValueFound = false;
continue;
}
deque.pop();
}
addNotVisitedNodes(verticesCount, visited, finalPath);
log.info("Path: {}", startingPoint);
finalPath.add(startingPoint);
return finalPath;
}
private void addNotVisitedNodes(int verticesCount, boolean[] visited, List<Integer> finalPath) {
for(int j = 0; j <= verticesCount; j ++) {
if(!visited[j]) {
visited[j] = true;
log.info("Path: {}", j);
finalPath.add(j);
}
}
}
}
| 31.361446 | 100 | 0.540914 |
0902819b0c3d49f6be8f0de1eede19353d598071 | 1,055 | package br.com.wellingtoncosta.mymovies.validation;
import java.util.ArrayList;
import java.util.List;
import br.com.wellingtoncosta.mymovies.validation.validators.Validator;
/**
* @author Wellington Costa on 01/05/17.
*
* TODO create an annotation-based library
*/
public class Validation {
private List<Validator> validators;
private List<Boolean> results = new ArrayList<>();
public Validation() {
this.validators = new ArrayList<>();
this.results = new ArrayList<>();
}
public void addValidator(Validator validator) {
validators.add(validator);
}
public boolean validate() {
boolean valid = true;
validateFields();
for (Boolean isValid : results) {
if (!isValid) {
valid = isValid;
break;
}
}
return valid;
}
private void validateFields() {
results.clear();
for (Validator validator : validators) {
results.add(validator.validate());
}
}
}
| 21.530612 | 71 | 0.600948 |
644c3524a532aa7a8a4bf37050e5e3ee0ca11973 | 237 | package com.aidijing.order.mapper;
import com.aidijing.order.domain.Order;
import com.baomidou.mybatisplus.mapper.BaseMapper;;
/**
* @author : 披荆斩棘
* @date : 2017/9/8
*/
public interface OrderMapper extends BaseMapper< Order > {
}
| 18.230769 | 58 | 0.734177 |
0a53160fc6c37a7c282badac06e7c26a98aa469c | 139 | class Test {
/**
* @see #perform(String, int)
*/
public void i() {}
public void perform(String s, int a) {}
} | 17.375 | 43 | 0.482014 |
c94d3c0be4a05ea27acf949b19f9ca573bdc2e14 | 21,900 | /*
* $Id$
*
* 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.struts.upload;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
/**
* <p> This class implements the <code>MultipartRequestHandler</code>
* interface by providing a wrapper around the Jakarta Commons FileUpload
* library. </p>
*
* @version $Rev$ $Date$
* @since Struts 1.1
*/
public class CommonsMultipartRequestHandler implements MultipartRequestHandler {
// ----------------------------------------------------- Manifest Constants
/**
* <p> The default value for the maximum allowable size, in bytes, of an
* uploaded file. The value is equivalent to 250MB. </p>
*/
public static final long DEFAULT_SIZE_MAX = 250 * 1024 * 1024;
/**
* <p> The default value for the threshold which determines whether an
* uploaded file will be written to disk or cached in memory. The value is
* equivalent to 250KB. </p>
*/
public static final int DEFAULT_SIZE_THRESHOLD = 256 * 1024;
// ----------------------------------------------------- Instance Variables
/**
* <p> Commons Logging instance. </p>
*/
protected static Log log =
LogFactory.getLog(CommonsMultipartRequestHandler.class);
/**
* <p> The combined text and file request parameters. </p>
*/
private Hashtable elementsAll;
/**
* <p> The file request parameters. </p>
*/
private Hashtable elementsFile;
/**
* <p> The text request parameters. </p>
*/
private Hashtable elementsText;
/**
* <p> The action mapping with which this handler is associated. </p>
*/
private ActionMapping mapping;
/**
* <p> The servlet with which this handler is associated. </p>
*/
private ActionServlet servlet;
// ---------------------------------------- MultipartRequestHandler Methods
/**
* <p> Retrieves the servlet with which this handler is associated. </p>
*
* @return The associated servlet.
*/
public ActionServlet getServlet() {
return this.servlet;
}
/**
* <p> Sets the servlet with which this handler is associated. </p>
*
* @param servlet The associated servlet.
*/
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
}
/**
* <p> Retrieves the action mapping with which this handler is associated.
* </p>
*
* @return The associated action mapping.
*/
public ActionMapping getMapping() {
return this.mapping;
}
/**
* <p> Sets the action mapping with which this handler is associated.
* </p>
*
* @param mapping The associated action mapping.
*/
public void setMapping(ActionMapping mapping) {
this.mapping = mapping;
}
/**
* <p> Parses the input stream and partitions the parsed items into a set
* of form fields and a set of file items. In the process, the parsed
* items are translated from Commons FileUpload <code>FileItem</code>
* instances to Struts <code>FormFile</code> instances. </p>
*
* @param request The multipart request to be processed.
* @throws ServletException if an unrecoverable error occurs.
*/
public void handleRequest(HttpServletRequest request)
throws ServletException {
// Get the app config for the current request.
ModuleConfig ac =
(ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
// Create and configure a DIskFileUpload instance.
DiskFileUpload upload = new DiskFileUpload();
// The following line is to support an "EncodingFilter"
// see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255
upload.setHeaderEncoding(request.getCharacterEncoding());
// Set the maximum size before a FileUploadException will be thrown.
upload.setSizeMax(getSizeMax(ac));
// Set the maximum size that will be stored in memory.
upload.setSizeThreshold((int) getSizeThreshold(ac));
// Set the the location for saving data on disk.
upload.setRepositoryPath(getRepositoryPath(ac));
// Create the hash tables to be populated.
elementsText = new Hashtable();
elementsFile = new Hashtable();
elementsAll = new Hashtable();
// Parse the request into file items.
List items = null;
try {
items = upload.parseRequest(request);
} catch (DiskFileUpload.SizeLimitExceededException e) {
// Special handling for uploads that are too big.
request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED,
Boolean.TRUE);
return;
} catch (FileUploadException e) {
log.error("Failed to parse multipart request", e);
throw new ServletException(e);
}
// Partition the items into form fields and files.
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
addTextParameter(request, item);
} else {
addFileParameter(item);
}
}
}
/**
* <p> Returns a hash table containing the text (that is, non-file)
* request parameters. </p>
*
* @return The text request parameters.
*/
public Hashtable getTextElements() {
return this.elementsText;
}
/**
* <p> Returns a hash table containing the file (that is, non-text)
* request parameters. </p>
*
* @return The file request parameters.
*/
public Hashtable getFileElements() {
return this.elementsFile;
}
/**
* <p> Returns a hash table containing both text and file request
* parameters. </p>
*
* @return The text and file request parameters.
*/
public Hashtable getAllElements() {
return this.elementsAll;
}
/**
* <p> Cleans up when a problem occurs during request processing. </p>
*/
public void rollback() {
Iterator iter = elementsFile.values().iterator();
Object o;
while (iter.hasNext()) {
o = iter.next();
if (o instanceof List) {
for (Iterator i = ((List)o).iterator(); i.hasNext(); ) {
((FormFile)i.next()).destroy();
}
} else {
((FormFile)o).destroy();
}
}
}
/**
* <p> Cleans up at the end of a request. </p>
*/
public void finish() {
rollback();
}
// -------------------------------------------------------- Support Methods
/**
* <p> Returns the maximum allowable size, in bytes, of an uploaded file.
* The value is obtained from the current module's controller
* configuration. </p>
*
* @param mc The current module's configuration.
* @return The maximum allowable file size, in bytes.
*/
protected long getSizeMax(ModuleConfig mc) {
return convertSizeToBytes(mc.getControllerConfig().getMaxFileSize(),
DEFAULT_SIZE_MAX);
}
/**
* <p> Returns the size threshold which determines whether an uploaded
* file will be written to disk or cached in memory. </p>
*
* @param mc The current module's configuration.
* @return The size threshold, in bytes.
*/
protected long getSizeThreshold(ModuleConfig mc) {
return convertSizeToBytes(mc.getControllerConfig().getMemFileSize(),
DEFAULT_SIZE_THRESHOLD);
}
/**
* <p> Converts a size value from a string representation to its numeric
* value. The string must be of the form nnnm, where nnn is an arbitrary
* decimal value, and m is a multiplier. The multiplier must be one of
* 'K', 'M' and 'G', representing kilobytes, megabytes and gigabytes
* respectively. </p><p> If the size value cannot be converted, for
* example due to invalid syntax, the supplied default is returned
* instead. </p>
*
* @param sizeString The string representation of the size to be
* converted.
* @param defaultSize The value to be returned if the string is invalid.
* @return The actual size in bytes.
*/
protected long convertSizeToBytes(String sizeString, long defaultSize) {
int multiplier = 1;
if (sizeString.endsWith("K")) {
multiplier = 1024;
} else if (sizeString.endsWith("M")) {
multiplier = 1024 * 1024;
} else if (sizeString.endsWith("G")) {
multiplier = 1024 * 1024 * 1024;
}
if (multiplier != 1) {
sizeString = sizeString.substring(0, sizeString.length() - 1);
}
long size = 0;
try {
size = Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
log.warn("Invalid format for file size ('" + sizeString
+ "'). Using default.");
size = defaultSize;
multiplier = 1;
}
return (size * multiplier);
}
/**
* <p> Returns the path to the temporary directory to be used for uploaded
* files which are written to disk. The directory used is determined from
* the first of the following to be non-empty. <ol> <li>A temp dir
* explicitly defined either using the <code>tempDir</code> servlet init
* param, or the <code>tempDir</code> attribute of the <controller>
* element in the Struts config file.</li> <li>The container-specified
* temp dir, obtained from the <code>javax.servlet.context.tempdir</code>
* servlet context attribute.</li> <li>The temp dir specified by the
* <code>java.io.tmpdir</code> system property.</li> (/ol> </p>
*
* @param mc The module config instance for which the path should be
* determined.
* @return The path to the directory to be used to store uploaded files.
*/
protected String getRepositoryPath(ModuleConfig mc) {
// First, look for an explicitly defined temp dir.
String tempDir = mc.getControllerConfig().getTempDir();
// If none, look for a container specified temp dir.
if ((tempDir == null) || (tempDir.length() == 0)) {
if (servlet != null) {
ServletContext context = servlet.getServletContext();
File tempDirFile =
(File) context.getAttribute("javax.servlet.context.tempdir");
tempDir = tempDirFile.getAbsolutePath();
}
// If none, pick up the system temp dir.
if ((tempDir == null) || (tempDir.length() == 0)) {
tempDir = System.getProperty("java.io.tmpdir");
}
}
if (log.isTraceEnabled()) {
log.trace("File upload temp dir: " + tempDir);
}
return tempDir;
}
/**
* <p> Adds a regular text parameter to the set of text parameters for
* this request and also to the list of all parameters. Handles the case
* of multiple values for the same parameter by using an array for the
* parameter value. </p>
*
* @param request The request in which the parameter was specified.
* @param item The file item for the parameter to add.
*/
protected void addTextParameter(HttpServletRequest request, FileItem item) {
String name = item.getFieldName();
String value = null;
boolean haveValue = false;
String encoding = null;
if (item instanceof DiskFileItem) {
encoding = ((DiskFileItem)item).getCharSet();
if (log.isDebugEnabled()) {
log.debug("DiskFileItem.getCharSet=[" + encoding + "]");
}
}
if (encoding == null) {
encoding = request.getCharacterEncoding();
if (log.isDebugEnabled()) {
log.debug("request.getCharacterEncoding=[" + encoding + "]");
}
}
if (encoding != null) {
try {
value = item.getString(encoding);
haveValue = true;
} catch (Exception e) {
// Handled below, since haveValue is false.
}
}
if (!haveValue) {
try {
value = item.getString("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
value = item.getString();
}
haveValue = true;
}
if (request instanceof MultipartRequestWrapper) {
MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
wrapper.setParameter(name, value);
}
String[] oldArray = (String[]) elementsText.get(name);
String[] newArray;
if (oldArray != null) {
newArray = new String[oldArray.length + 1];
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
newArray[oldArray.length] = value;
} else {
newArray = new String[] { value };
}
elementsText.put(name, newArray);
elementsAll.put(name, newArray);
}
/**
* <p> Adds a file parameter to the set of file parameters for this
* request and also to the list of all parameters. </p>
*
* @param item The file item for the parameter to add.
*/
protected void addFileParameter(FileItem item) {
FormFile formFile = new CommonsFormFile(item);
String name = item.getFieldName();
if (elementsFile.containsKey(name)) {
Object o = elementsFile.get(name);
if (o instanceof List) {
((List)o).add(formFile);
} else {
List list = new ArrayList();
list.add((FormFile)o);
list.add(formFile);
elementsFile.put(name, list);
elementsAll.put(name, list);
}
} else {
elementsFile.put(name, formFile);
elementsAll.put(name, formFile);
}
}
// ---------------------------------------------------------- Inner Classes
/**
* <p> This class implements the Struts <code>FormFile</code> interface by
* wrapping the Commons FileUpload <code>FileItem</code> interface. This
* implementation is <i>read-only</i>; any attempt to modify an instance
* of this class will result in an <code>UnsupportedOperationException</code>.
* </p>
*/
static class CommonsFormFile implements FormFile, Serializable {
/**
* <p> The <code>FileItem</code> instance wrapped by this object.
* </p>
*/
FileItem fileItem;
/**
* Constructs an instance of this class which wraps the supplied file
* item. </p>
*
* @param fileItem The Commons file item to be wrapped.
*/
public CommonsFormFile(FileItem fileItem) {
this.fileItem = fileItem;
}
/**
* <p> Returns the content type for this file. </p>
*
* @return A String representing content type.
*/
public String getContentType() {
return fileItem.getContentType();
}
/**
* <p> Sets the content type for this file. <p> NOTE: This method is
* not supported in this implementation. </p>
*
* @param contentType A string representing the content type.
*/
public void setContentType(String contentType) {
throw new UnsupportedOperationException(
"The setContentType() method is not supported.");
}
/**
* <p> Returns the size, in bytes, of this file. </p>
*
* @return The size of the file, in bytes.
*/
public int getFileSize() {
return (int) fileItem.getSize();
}
/**
* <p> Sets the size, in bytes, for this file. <p> NOTE: This method
* is not supported in this implementation. </p>
*
* @param filesize The size of the file, in bytes.
*/
public void setFileSize(int filesize) {
throw new UnsupportedOperationException(
"The setFileSize() method is not supported.");
}
/**
* <p> Returns the (client-side) file name for this file. </p>
*
* @return The client-size file name.
*/
public String getFileName() {
return getBaseFileName(fileItem.getName());
}
/**
* <p> Sets the (client-side) file name for this file. <p> NOTE: This
* method is not supported in this implementation. </p>
*
* @param fileName The client-side name for the file.
*/
public void setFileName(String fileName) {
throw new UnsupportedOperationException(
"The setFileName() method is not supported.");
}
/**
* <p> Returns the data for this file as a byte array. Note that this
* may result in excessive memory usage for large uploads. The use of
* the {@link #getInputStream() getInputStream} method is encouraged
* as an alternative. </p>
*
* @return An array of bytes representing the data contained in this
* form file.
* @throws FileNotFoundException If some sort of file representation
* cannot be found for the FormFile
* @throws IOException If there is some sort of IOException
*/
public byte[] getFileData()
throws FileNotFoundException, IOException {
return fileItem.get();
}
/**
* <p> Get an InputStream that represents this file. This is the
* preferred method of getting file data. </p>
*
* @throws FileNotFoundException If some sort of file representation
* cannot be found for the FormFile
* @throws IOException If there is some sort of IOException
*/
public InputStream getInputStream()
throws FileNotFoundException, IOException {
return fileItem.getInputStream();
}
/**
* <p> Destroy all content for this form file. Implementations should
* remove any temporary files or any temporary file data stored
* somewhere </p>
*/
public void destroy() {
fileItem.delete();
}
/**
* <p> Returns the base file name from the supplied file path. On the
* surface, this would appear to be a trivial task. Apparently,
* however, some Linux JDKs do not implement <code>File.getName()</code>
* correctly for Windows paths, so we attempt to take care of that
* here. </p>
*
* @param filePath The full path to the file.
* @return The base file name, from the end of the path.
*/
protected String getBaseFileName(String filePath) {
// First, ask the JDK for the base file name.
String fileName = new File(filePath).getName();
// Now check for a Windows file name parsed incorrectly.
int colonIndex = fileName.indexOf(":");
if (colonIndex == -1) {
// Check for a Windows SMB file path.
colonIndex = fileName.indexOf("\\\\");
}
int backslashIndex = fileName.lastIndexOf("\\");
if ((colonIndex > -1) && (backslashIndex > -1)) {
// Consider this filename to be a full Windows path, and parse it
// accordingly to retrieve just the base file name.
fileName = fileName.substring(backslashIndex + 1);
}
return fileName;
}
/**
* <p> Returns the (client-side) file name for this file. </p>
*
* @return The client-size file name.
*/
public String toString() {
return getFileName();
}
}
}
| 34.006211 | 87 | 0.585662 |
7b91b956055c9a72aeddc75d02154111ffae60b2 | 1,035 | package com.taobao.tddl.executor.handler;
import com.taobao.tddl.common.exception.TddlException;
import com.taobao.tddl.executor.common.ExecutionContext;
import com.taobao.tddl.executor.cursor.ISchematicCursor;
import com.taobao.tddl.optimizer.core.plan.IDataNodeExecutor;
import com.taobao.tddl.optimizer.core.plan.query.IShow;
public abstract class BaseShowHandler extends HandlerCommon {
@Override
public ISchematicCursor handle(IDataNodeExecutor executor, ExecutionContext executionContext) throws TddlException {
IShow show = (IShow) executor;
ISchematicCursor showCursor = doShow(show, executionContext);
if (show.getWhereFilter() != null) {
showCursor = executionContext.getCurrentRepository()
.getCursorFactory()
.valueFilterCursor(executionContext, showCursor, show.getWhereFilter());
}
return showCursor;
}
public abstract ISchematicCursor doShow(IShow show, ExecutionContext executionContext) throws TddlException;
}
| 36.964286 | 120 | 0.751691 |
4f7f55650dc5ea9195eebae38a43447a29351715 | 6,648 | package com.example.awesometic.facetalk;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
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.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
final static String LogTag = "Awe_LoginActivity";
private Singleton single = Singleton.getInstance();
private DBConnect dbConn = new DBConnect(LoginActivity.this, LoginActivity.this);
public static Activity loginActivity;
EditText emailInput, passwordInput;
Button loginButton, signupButton;
CheckBox autoLoginCheckBox;
Boolean autoLoginChecked;
SharedPreferences pref;
SharedPreferences.Editor prefEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginActivity = LoginActivity.this;
emailInput = (EditText) findViewById(R.id.login_emailInput);
passwordInput = (EditText) findViewById(R.id.login_passwordInput);
loginButton = (Button) findViewById(R.id.login_loginButton);
signupButton = (Button) findViewById(R.id.login_signupButton);
autoLoginCheckBox = (CheckBox) findViewById(R.id.autoLoginCheckBox);
pref = getSharedPreferences("autoLogin", Activity.MODE_PRIVATE);
prefEditor = pref.edit();
autoLoginChecked = false;
loginButton.setOnClickListener(mClickListener);
signupButton.setOnClickListener(mClickListener);
autoLoginCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
autoLoginChecked = true;
} else {
autoLoginChecked = false;
prefEditor.putString("email", "");
prefEditor.putString("password", "");
prefEditor.putBoolean("autoLogin", false);
prefEditor.apply();
}
}
});
// If success sign up, auto fill out the email EditText
Intent intent = getIntent();
emailInput.setText(intent.getStringExtra("signup_email"));
if (intent.getBooleanExtra("logout", false)) {
prefEditor.putString("email", "");
prefEditor.putString("password", "");
prefEditor.putBoolean("autoLogin", false);
prefEditor.apply();
autoLoginCheckBox.setChecked(true);
}
// If autoLogin checked, get user login information
if (pref.getBoolean("autoLogin", true)) {
Log.d(LogTag, "email: " + pref.getString("email", "") + "\tpassword: " + pref.getString("password", ""));
emailInput.setText(pref.getString("email", ""));
passwordInput.setText(pref.getString("password", ""));
autoLoginCheckBox.setChecked(true);
if (loginValidate(pref.getString("email", ""), pref.getString("password", ""))) {
gotoMainActivity();
finish();
} else {
passwordInput.setText("");
autoLoginCheckBox.setChecked(false);
}
}
}
Button.OnClickListener mClickListener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_loginButton:
String email = emailInput.getText().toString();
String password = passwordInput.getText().toString();
if (email.length() == 0 || password.length() == 0) {
Toast.makeText(LoginActivity.this, "Type your email or password!", Toast.LENGTH_LONG).show();
break;
} else {
Boolean validation = loginValidate(email, password);
if (validation) {
if (autoLoginChecked) {
// If autoLogin checked, save values
prefEditor.putString("email", email);
prefEditor.putString("password", password);
prefEditor.putBoolean("autoLogin", true);
prefEditor.apply();
}
gotoMainActivity();
finish();
} else {
passwordInput.setText("");
autoLoginCheckBox.setChecked(false);
}
}
break;
case R.id.login_signupButton:
gotoSignupActivity();
break;
}
}
};
private boolean loginValidate(String email, String password) {
int useridx = dbConn.loginValidation(email, password);
single.setCurrentUserIdx(useridx);
single.setCurrentUserEmail(email);
single.setCurrentUserNickname(dbConn.getNickname(useridx));
Log.d(LogTag, "Current useridx: " + single.getCurrentUserIdx() + "\temail: " + single.getCurrentUserEmail() + "\tnickname: " + single.getCurrentUserNickname());
if (useridx == -1) {
Toast.makeText(LoginActivity.this, "Not a member? Sign-up", Toast.LENGTH_LONG).show();
return false;
} else if (useridx == 0) {
Toast.makeText(LoginActivity.this, "Wrong password!", Toast.LENGTH_LONG).show();
return false;
} else if (useridx == -9){
Toast.makeText(LoginActivity.this, "Something wrong...", Toast.LENGTH_LONG).show();
return false;
} else {
Toast.makeText(LoginActivity.this, "Login Success!", Toast.LENGTH_LONG).show();
return true;
}
}
private void gotoMainActivity() {
Log.d(LogTag, "gotoMainActivity()");
Intent intent = new Intent(this.getApplicationContext(), MainActivity.class);
startActivity(intent);
}
private void gotoSignupActivity() {
Log.d(LogTag, "gotoSignupActivity()");
Intent intent = new Intent(this.getApplicationContext(), SignupActivity.class);
startActivity(intent);
}
}
| 38.651163 | 168 | 0.58559 |
b91be68ea8fc003d1b733292246d259b2f68f454 | 2,308 | /*
* Copyright 2019-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.client.value.impl;
import java.util.concurrent.CompletableFuture;
import com.google.common.io.BaseEncoding;
import io.atomix.api.headers.Name;
import io.atomix.client.PrimitiveManagementService;
import io.atomix.client.utils.serializer.Serializer;
import io.atomix.client.value.AsyncAtomicValue;
import io.atomix.client.value.AtomicValue;
import io.atomix.client.value.AtomicValueBuilder;
/**
* Default implementation of AtomicValueBuilder.
*
* @param <V> value type
*/
public class DefaultAtomicValueBuilder<V> extends AtomicValueBuilder<V> {
public DefaultAtomicValueBuilder(Name name, PrimitiveManagementService managementService) {
super(name, managementService);
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<AtomicValue<V>> buildAsync() {
return managementService.getPartitionService().getPartitionGroup(group)
.thenCompose(group -> new DefaultAsyncAtomicValue(
getName(),
group.getPartition(partitioner.partition(getName().getName(), group.getPartitionIds())),
managementService.getThreadFactory().createContext(),
sessionTimeout)
.connect()
.thenApply(rawValue -> {
Serializer serializer = serializer();
return new TranscodingAsyncAtomicValue<V, String>(
rawValue,
value -> BaseEncoding.base16().encode(serializer.encode(value)),
string -> serializer.decode(BaseEncoding.base16().decode(string)));
})
.thenApply(AsyncAtomicValue::sync));
}
}
| 39.793103 | 104 | 0.688908 |
71438eda4b727fdd7e14eca238d5d9dab9ca08c3 | 6,948 | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identityprovider.client;
import com.yahoo.container.core.identity.IdentityConfig;
import com.yahoo.container.jdisc.athenz.AthenzIdentityProviderException;
import com.yahoo.jdisc.Metric;
import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyStoreUtils;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.Pkcs10Csr;
import com.yahoo.security.Pkcs10CsrBuilder;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.test.ManualClock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import javax.security.auth.x500.X500Principal;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author mortent
* @author bjorncs
*/
public class AthenzIdentityProviderImplTest {
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
public static final Duration certificateValidity = Duration.ofDays(30);
private static final IdentityConfig IDENTITY_CONFIG =
new IdentityConfig(new IdentityConfig.Builder()
.service("tenantService")
.domain("tenantDomain")
.nodeIdentityName("vespa.tenant")
.configserverIdentityName("vespa.configserver")
.loadBalancerAddress("cfg")
.ztsUrl("https:localhost:4443/zts/v1")
.athenzDnsSuffix("dev-us-north-1.vespa.cloud"));
private final KeyPair caKeypair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
private Path trustStoreFile;
private X509Certificate caCertificate;
@Before
public void createTrustStoreFile() throws IOException {
caCertificate = X509CertificateBuilder
.fromKeypair(
caKeypair,
new X500Principal("CN=mydummyca"),
Instant.EPOCH,
Instant.EPOCH.plus(10000, ChronoUnit.DAYS),
SignatureAlgorithm.SHA256_WITH_ECDSA,
BigInteger.ONE)
.build();
trustStoreFile = tempDir.newFile().toPath();
KeyStoreUtils.writeKeyStoreToFile(
KeyStoreBuilder.withType(KeyStoreType.JKS)
.withKeyEntry("default", caKeypair.getPrivate(), caCertificate)
.build(),
trustStoreFile);
}
@Test(expected = AthenzIdentityProviderException.class)
public void component_creation_fails_when_credentials_not_found() {
AthenzCredentialsService credentialService = mock(AthenzCredentialsService.class);
when(credentialService.registerInstance())
.thenThrow(new RuntimeException("athenz unavailable"));
new AthenzIdentityProviderImpl(IDENTITY_CONFIG, mock(Metric.class), trustStoreFile ,credentialService, mock(ScheduledExecutorService.class), new ManualClock(Instant.EPOCH));
}
@Test
public void metrics_updated_on_refresh() {
ManualClock clock = new ManualClock(Instant.EPOCH);
Metric metric = mock(Metric.class);
AthenzCredentialsService athenzCredentialsService = mock(AthenzCredentialsService.class);
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
X509Certificate certificate = getCertificate(keyPair, getExpirationSupplier(clock));
when(athenzCredentialsService.registerInstance())
.thenReturn(new AthenzCredentials(certificate, keyPair, null));
when(athenzCredentialsService.updateCredentials(any(), any()))
.thenThrow(new RuntimeException("#1"))
.thenThrow(new RuntimeException("#2"))
.thenReturn(new AthenzCredentials(certificate, keyPair, null));
AthenzIdentityProviderImpl identityProvider =
new AthenzIdentityProviderImpl(IDENTITY_CONFIG, metric, trustStoreFile, athenzCredentialsService, mock(ScheduledExecutorService.class), clock);
identityProvider.reportMetrics();
verify(metric).set(eq(AthenzIdentityProviderImpl.CERTIFICATE_EXPIRY_METRIC_NAME), eq(certificateValidity.getSeconds()), any());
// Advance 1 day, refresh fails, cert is 1 day old
clock.advance(Duration.ofDays(1));
identityProvider.refreshCertificate();
identityProvider.reportMetrics();
verify(metric).set(eq(AthenzIdentityProviderImpl.CERTIFICATE_EXPIRY_METRIC_NAME), eq(certificateValidity.minus(Duration.ofDays(1)).getSeconds()), any());
// Advance 1 more day, refresh fails, cert is 2 days old
clock.advance(Duration.ofDays(1));
identityProvider.refreshCertificate();
identityProvider.reportMetrics();
verify(metric).set(eq(AthenzIdentityProviderImpl.CERTIFICATE_EXPIRY_METRIC_NAME), eq(certificateValidity.minus(Duration.ofDays(2)).getSeconds()), any());
// Advance 1 more day, refresh succeds, cert is new
clock.advance(Duration.ofDays(1));
identityProvider.refreshCertificate();
identityProvider.reportMetrics();
verify(metric).set(eq(AthenzIdentityProviderImpl.CERTIFICATE_EXPIRY_METRIC_NAME), eq(certificateValidity.getSeconds()), any());
}
private Supplier<Date> getExpirationSupplier(ManualClock clock) {
return () -> new Date(clock.instant().plus(certificateValidity).toEpochMilli());
}
private X509Certificate getCertificate(KeyPair keyPair, Supplier<Date> expiry) {
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=dummy"), keyPair, SignatureAlgorithm.SHA256_WITH_ECDSA)
.build();
return X509CertificateBuilder
.fromCsr(csr,
caCertificate.getSubjectX500Principal(),
Instant.EPOCH,
expiry.get().toInstant(),
caKeypair.getPrivate(),
SignatureAlgorithm.SHA256_WITH_ECDSA,
BigInteger.ONE)
.build();
}
}
| 44.254777 | 181 | 0.682355 |
8aa687e5cd14dbd5c32b8ecf540322d8f7dd688b | 1,854 | package net.meisen.dissertation.model.dimensions.templates;
import java.util.Iterator;
import net.meisen.dissertation.model.data.IntervalModel;
import net.meisen.dissertation.model.dimensions.TimeLevelMember;
import net.meisen.general.genmisc.exceptions.ForwardedRuntimeException;
/**
* Interface for a template definition of a {@code TimeLevelTemplate}.
*
* @author pmeisen
*
* @see BaseTimeLevelTemplate
*
*/
public interface ITimeLevelTemplate {
/**
* Gets the identifier of the template, useful to re-use the template.
*
* @return the identifier of the template
*/
public String getId();
/**
* The iterator used to iterate the different {@code TimeMember} instances
* of the level. The iterator must iterate over the sorted members (i.e.
* sorted by the first range returned by the {@code TimeLevelMember}).
*
* @param model
* the {@code IntervalModel} used
* @param timezone
* the time-zone used to create the iterator
*
* @return the created iterator
*
* @throws ForwardedRuntimeException
* if the iterator cannot be created
*/
public Iterator<TimeLevelMember> it(final IntervalModel model,
final String timezone) throws ForwardedRuntimeException;
/**
* Creates an iterator for the specified range.
*
* @param model
* the {@code IntervalModel} used
* @param start
* the start of the range
* @param end
* the end of the range
* @param timezone
* the time-zone used to create the iterator
*
* @return the created iterator
*
* @throws ForwardedRuntimeException
* if the iterator cannot be created
*/
public Iterator<TimeLevelMember> it(final IntervalModel model,
final long start, final long end, final String timezone)
throws ForwardedRuntimeException;
} | 28.96875 | 75 | 0.695254 |
6a47be2178e5a3773de88462d869bbe1768b580d | 4,597 | package uk.org.wolfpuppy.minecraft.chunkchecker;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.apache.logging.log4j.Logger;
import uk.org.wolfpuppy.minecraft.chunkchecker.util.DimChunkPos;
import uk.org.wolfpuppy.minecraft.chunkchecker.util.LimitedMap;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
@Mod(modid = "chunkchecker",
useMetadata = true,
serverSideOnly = true,
acceptableRemoteVersions = "*")
@Mod.EventBusSubscriber
public class ChunkChecker {
private static final int UNLOADED_CHUNK_CACHE = 100;
private static final int RELOAD_COUNT = 3;
private static Logger logger;
private static boolean serverStarted = false;
static class ChunkLoadInfo {
private DimChunkPos pos;
private List<Throwable> loadTraces = new ArrayList<>(RELOAD_COUNT);
public ChunkLoadInfo(DimChunkPos pos) {
this.pos = pos;
}
public boolean addTraceAndCheckLimit(Throwable t) {
loadTraces.add(t);
if (loadTraces.size() >= RELOAD_COUNT) {
logger.warn("Chunk at {} has reloaded too many times, most recent trace: {}",
pos, stackTraceAsString(t));
return true;
}
return false;
}
private static String stackTraceAsString(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
return sw.toString();
}
}
private static Map<DimChunkPos, ChunkLoadInfo> loadedChunks = new HashMap<>();
private static Map<DimChunkPos, ChunkLoadInfo> unloadedChunks = new LimitedMap<>(UNLOADED_CHUNK_CACHE);
private static Set<DimChunkPos> ignoredChunks = new HashSet<>();
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
logger = event.getModLog();
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {}
@Mod.EventHandler
public void serverStarted(FMLServerStartedEvent event) {
serverStarted = true;
}
@SubscribeEvent
public static void chunkLoaded(ChunkEvent.Load event) {
Chunk chunk = event.getChunk();
WorldServer world = (WorldServer) chunk.getWorld();
int dim = world.provider.getDimension();
DimChunkPos pos = new DimChunkPos(dim, chunk.getPos());
if (!serverStarted || chunk.getWorld().isSpawnChunk(pos.x, pos.z) || ignoredChunks.contains(pos)) {
// spawn chunks don't unload, so loading them is boring. ignored chunks are.. ignored.
return;
}
ChunkLoadInfo loadInfo = unloadedChunks.remove(pos);
if (world.getPlayerChunkMap().contains(pos.x, pos.z)) {
// chunk loading because of player presence, so this is okay, but we need to keep the chunk record
// if it already existed, since it may have previously been loaded by a non-player event.
if (loadInfo != null) {
loadedChunks.put(pos, loadInfo);
}
return;
}
// make a new record if it didn't exist.
if (loadInfo == null) {
loadInfo = new ChunkLoadInfo(pos);
}
if (loadInfo.addTraceAndCheckLimit(new Throwable())) {
// limit was hit, stop paying attention to this chunk and let the record drop.
ignoredChunks.add(pos);
} else {
// limit not hit, keep the record around.
loadedChunks.put(pos, loadInfo);
}
}
@SubscribeEvent
public static void chunkUnloaded(ChunkEvent.Unload event) {
Chunk chunk = event.getChunk();
WorldServer world = (WorldServer) chunk.getWorld();
int dim = world.provider.getDimension();
DimChunkPos pos = new DimChunkPos(dim, chunk.getPos());
// just move the record back to the unloaded cache if it exists.
ChunkLoadInfo loadInfo = loadedChunks.remove(pos);
if (loadInfo != null) {
unloadedChunks.put(pos, loadInfo);
}
}
}
| 36.19685 | 110 | 0.655427 |
60497216ae004c1544469e0025e68e7ce6615064 | 779 | package io.realm;
public interface com_news_newsapp_NewRealmProxyInterface {
public int realmGet$id();
public void realmSet$id(int value);
public String realmGet$author();
public void realmSet$author(String value);
public String realmGet$title();
public void realmSet$title(String value);
public String realmGet$description();
public void realmSet$description(String value);
public String realmGet$url();
public void realmSet$url(String value);
public java.util.Date realmGet$publishedTime();
public void realmSet$publishedTime(java.util.Date value);
public String realmGet$urlToImage();
public void realmSet$urlToImage(String value);
public String realmGet$source();
public void realmSet$source(String value);
}
| 35.409091 | 61 | 0.741977 |
0cdcbfa197ab01e5b55b99c39e7f638b068fabd2 | 3,089 | package com.ducetech.framework.support.service;
import com.ducetech.framework.cons.GlobalConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setItem(String key, Object value){
redisTemplate.opsForValue().set(key, value);
}
public Object getItem(String key) {
return redisTemplate.opsForValue().get(key);
}
public void sendMessage(String userId , String noticeType){
redisTemplate.convertAndSend(GlobalConstant.SYS_CHANNEL_MAIN, userId+":"+noticeType);
}
public boolean expire(String key, long l) {
return redisTemplate.expire(key, l, TimeUnit.MINUTES);
}
public void delDic(String key) {
redisTemplate.delete(key);
}
public void clearByDicName(String dicName) {
redisTemplate.delete("*" + dicName + "*");
}
public void loadByDicName(String dicName) {
}
public void delDicKey(String dicName, String key) {
redisTemplate.opsForHash().delete(dicName, key);
}
public Set<String> getKeys(String dicName) {
return redisTemplate.keys(dicName);
}
public String getValueByKey(String dicName, String key) {
return redisTemplate.opsForHash().get(dicName, key).toString();
}
public Map<Object, Object> getAllByDicName(String dicName) {
return redisTemplate.opsForHash().entries(dicName);
}
public boolean hexists(String dicName, String key) {
return redisTemplate.opsForHash().hasKey(dicName, key);
}
public void setValueByKey(String dicName, String key, String value) {
redisTemplate.opsForHash().put(dicName, key, value);
}
public long rpush(String dicName, String value) {
return redisTemplate.opsForList().rightPush(dicName, value);
}
public long lpush(String dicName, String value) {
return redisTemplate.opsForList().leftPush(dicName, value);
}
public String rpop(String dicName) {
return redisTemplate.opsForList().rightPop(dicName).toString();
}
public String lpop(String dicName) {
return redisTemplate.opsForList().leftPop(dicName).toString();
}
public long llen(String dicName) {
return redisTemplate.opsForList().size(dicName);
}
public void hmset(String dicName, Map<String, String> elements) {
redisTemplate.opsForHash().putAll(dicName, elements);
}
public List<Object> hmget(String dicName, Object[] keys) {
return redisTemplate.opsForHash().multiGet(dicName, Arrays.asList(keys));
}
public void publish(String channel, String message) {
redisTemplate.convertAndSend(channel, message);
}
public void setx(String key, Object value, long l) {
redisTemplate.opsForValue().set(key, value, l, TimeUnit.MINUTES);
}
public boolean exists(String key) {
return redisTemplate.hasKey(key);
}
}
| 27.336283 | 88 | 0.729039 |
b658367827c1fbb7f683146e2d6820175846599d | 584 | package io.funraise.dm.blitz.orika;
import io.funraise.dm.blitz.CustomConverter;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.metadata.Type;
public class OffsetDateTimeConverter extends CustomConverter<LocalDateTime, OffsetDateTime> {
@Override
public OffsetDateTime convert(LocalDateTime source, Type<? extends OffsetDateTime> destinationType, MappingContext mappingContext) {
return OffsetDateTime.of(source, ZoneOffset.ofTotalSeconds(0));
}
}
| 34.352941 | 136 | 0.808219 |
09db63c622a69b4d6662a4b78f56b23c778fbbda | 98 | package de.bmoth.parser.ast.nodes;
public interface Node {
boolean equalAst(Node other);
}
| 12.25 | 34 | 0.72449 |
f5d884ecd1c6193997141082be7db70eade12fd5 | 3,554 | package com.palmelf.eoffice.model.hrm;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.palmelf.core.model.BaseModel;
import com.palmelf.eoffice.model.system.Department;
@Entity
@Table(name = "job")
public class Job extends BaseModel {
/**
*
*/
private static final long serialVersionUID = 2809740680937752365L;
public static short DELFLAG_NOT = 0;
public static short DELFLAG_HAD = 1;
private Long jobId;
private String jobName;
private String memo;
private Short delFlag;
private Department department;
private Set<EmpProfile> empProfiles = new HashSet<EmpProfile>();
public Job() {
}
public Job(Long in_jobId) {
this.setJobId(in_jobId);
}
@Transient
public Long getDepId() {
return this.getDepartment() == null ? null : this.getDepartment()
.getDepId();
}
// Property accessors
@Id
@GeneratedValue
@Column(name = "jobId", unique = true, nullable = false)
public Long getJobId() {
return this.jobId;
}
public void setJobId(Long jobId) {
this.jobId = jobId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "depId")
public Department getDepartment() {
return this.department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Column(name = "jobName", nullable = false, length = 128)
public String getJobName() {
return this.jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
@Column(name = "memo", length = 512)
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@Column(name = "delFlag")
public Short getDelFlag() {
return this.delFlag;
}
public void setDelFlag(Short delFlag) {
this.delFlag = delFlag;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "jobId")
public Set<EmpProfile> getEmpProfiles() {
return this.empProfiles;
}
public void setEmpProfiles(Set<EmpProfile> empProfiles) {
this.empProfiles = empProfiles;
}
public void setDepId(Long aValue) {
if (aValue == null) {
this.department = null;
} else if (this.department == null) {
this.department = new Department(aValue);
this.department.setVersion(new Integer(0));
} else {
this.department.setDepId(aValue);
}
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Job)) {
return false;
}
Job rhs = (Job) object;
return new EqualsBuilder().append(this.jobId, rhs.jobId)
.append(this.jobName, rhs.jobName).append(this.memo, rhs.memo)
.append(this.delFlag, rhs.delFlag).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(-82280557, -700257973).append(this.jobId)
.append(this.jobName).append(this.memo).append(this.delFlag)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this).append("jobId", this.jobId)
.append("jobName", this.jobName).append("memo", this.memo)
.append("delFlag", this.delFlag).toString();
}
}
| 23.852349 | 70 | 0.727349 |
f3a3fff8bac1c2e9210e62401e8471b3ce9aa2c6 | 709 | package g1001_1100.s1071_greatest_common_divisor_of_strings;
// #Easy #String #Math #2022_02_27_Time_1_ms_(82.09%)_Space_42.6_MB_(33.55%)
public class Solution {
public String gcdOfStrings(String str1, String str2) {
if (str1 == null || str2 == null) {
return "";
}
if (str1.equals(str2)) {
return str1;
}
int m = str1.length();
int n = str2.length();
if (m > n && str1.substring(0, n).equals(str2)) {
return gcdOfStrings(str1.substring(n), str2);
}
if (n > m && str2.substring(0, m).equals(str1)) {
return gcdOfStrings(str2.substring(m), str1);
}
return "";
}
}
| 29.541667 | 76 | 0.551481 |
2f4046559270b3e5ea19fc90b9668983164d653c | 3,864 | /*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat 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 io.vertx.rxjava.ext.web.handler;
import java.util.Map;
import io.vertx.lang.rxjava.InternalHelper;
import rx.Observable;
import java.util.List;
import java.util.Set;
import io.vertx.rxjava.ext.web.RoutingContext;
import io.vertx.rxjava.ext.auth.AuthProvider;
/**
* An auth handler that provides JWT Authentication support.
*
* <p/>
* NOTE: This class has been automatically generated from the {@link io.vertx.ext.web.handler.JWTAuthHandler original} non RX-ified interface using Vert.x codegen.
*/
public class JWTAuthHandler implements AuthHandler {
final io.vertx.ext.web.handler.JWTAuthHandler delegate;
public JWTAuthHandler(io.vertx.ext.web.handler.JWTAuthHandler delegate) {
this.delegate = delegate;
}
public Object getDelegate() {
return delegate;
}
public void handle(RoutingContext arg0) {
this.delegate.handle((io.vertx.ext.web.RoutingContext) arg0.getDelegate());
}
/**
* Add a required authority for this auth handler
* @param authority the authority
* @return a reference to this, so the API can be used fluently
*/
public AuthHandler addAuthority(String authority) {
this.delegate.addAuthority(authority);
return this;
}
/**
* Add a set of required authorities for this auth handler
* @param authorities the set of authorities
* @return a reference to this, so the API can be used fluently
*/
public AuthHandler addAuthorities(Set<String> authorities) {
this.delegate.addAuthorities(authorities);
return this;
}
/**
* Create a JWT auth handler
* @param authProvider the auth provider to use
* @return the auth handler
*/
public static JWTAuthHandler create(AuthProvider authProvider) {
JWTAuthHandler ret= JWTAuthHandler.newInstance(io.vertx.ext.web.handler.JWTAuthHandler.create((io.vertx.ext.auth.AuthProvider) authProvider.getDelegate()));
return ret;
}
/**
* Create a JWT auth handler
* @param authProvider the auth provider to use.
* @param skip
* @return the auth handler
*/
public static JWTAuthHandler create(AuthProvider authProvider, String skip) {
JWTAuthHandler ret= JWTAuthHandler.newInstance(io.vertx.ext.web.handler.JWTAuthHandler.create((io.vertx.ext.auth.AuthProvider) authProvider.getDelegate(), skip));
return ret;
}
/**
* Set the audience list
* @param audience the audience list
* @return a reference to this for fluency
*/
public JWTAuthHandler setAudience(List<String> audience) {
this.delegate.setAudience(audience);
return this;
}
/**
* Set the issuer
* @param issuer the issuer
* @return a reference to this for fluency
*/
public JWTAuthHandler setIssuer(String issuer) {
this.delegate.setIssuer(issuer);
return this;
}
/**
* Set whether expiration is ignored
* @param ignoreExpiration whether expiration is ignored
* @return a reference to this for fluency
*/
public JWTAuthHandler setIgnoreExpiration(boolean ignoreExpiration) {
this.delegate.setIgnoreExpiration(ignoreExpiration);
return this;
}
public static JWTAuthHandler newInstance(io.vertx.ext.web.handler.JWTAuthHandler arg) {
return arg != null ? new JWTAuthHandler(arg) : null;
}
}
| 30.666667 | 166 | 0.725932 |
c777793ee8e74b6a3fe266cfc57024b02e17a3bc | 409 | package net.zestyblaze.malusphaethusa.client;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.zestyblaze.malusphaethusa.init.ClientInit;
@Environment(EnvType.CLIENT)
public class MalusPhaethusaClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
ClientInit.register();
}
}
| 24.058824 | 67 | 0.792176 |
52c94563dbb308f9788dd3a2eaf6b7f80031af5a | 3,744 |
package com.sosv.breweryDB.connector.entity;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Locations{
private Country country;
private String countryIsoCode;
private String createDate;
private String id;
private String inPlanning;
private String isClosed;
private String isPrimary;
private Number latitude;
private String locality;
private String locationType;
private String locationTypeDisplay;
private Number longitude;
private String name;
private String openToPublic;
private String postalCode;
private String region;
private String status;
private String statusDisplay;
private String updateDate;
private String website;
private String yearOpened;
public Country getCountry(){
return this.country;
}
public void setCountry(Country country){
this.country = country;
}
public String getCountryIsoCode(){
return this.countryIsoCode;
}
public void setCountryIsoCode(String countryIsoCode){
this.countryIsoCode = countryIsoCode;
}
public String getCreateDate(){
return this.createDate;
}
public void setCreateDate(String createDate){
this.createDate = createDate;
}
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
}
public String getInPlanning(){
return this.inPlanning;
}
public void setInPlanning(String inPlanning){
this.inPlanning = inPlanning;
}
public String getIsClosed(){
return this.isClosed;
}
public void setIsClosed(String isClosed){
this.isClosed = isClosed;
}
public String getIsPrimary(){
return this.isPrimary;
}
public void setIsPrimary(String isPrimary){
this.isPrimary = isPrimary;
}
public Number getLatitude(){
return this.latitude;
}
public void setLatitude(Number latitude){
this.latitude = latitude;
}
public String getLocality(){
return this.locality;
}
public void setLocality(String locality){
this.locality = locality;
}
public String getLocationType(){
return this.locationType;
}
public void setLocationType(String locationType){
this.locationType = locationType;
}
public String getLocationTypeDisplay(){
return this.locationTypeDisplay;
}
public void setLocationTypeDisplay(String locationTypeDisplay){
this.locationTypeDisplay = locationTypeDisplay;
}
public Number getLongitude(){
return this.longitude;
}
public void setLongitude(Number longitude){
this.longitude = longitude;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getOpenToPublic(){
return this.openToPublic;
}
public void setOpenToPublic(String openToPublic){
this.openToPublic = openToPublic;
}
public String getPostalCode(){
return this.postalCode;
}
public void setPostalCode(String postalCode){
this.postalCode = postalCode;
}
public String getRegion(){
return this.region;
}
public void setRegion(String region){
this.region = region;
}
public String getStatus(){
return this.status;
}
public void setStatus(String status){
this.status = status;
}
public String getStatusDisplay(){
return this.statusDisplay;
}
public void setStatusDisplay(String statusDisplay){
this.statusDisplay = statusDisplay;
}
public String getUpdateDate(){
return this.updateDate;
}
public void setUpdateDate(String updateDate){
this.updateDate = updateDate;
}
public String getWebsite(){
return this.website;
}
public void setWebsite(String website){
this.website = website;
}
public String getYearOpened(){
return this.yearOpened;
}
public void setYearOpened(String yearOpened){
this.yearOpened = yearOpened;
}
}
| 23.847134 | 64 | 0.744925 |
b770e3800d04d770175a07166f41e731606fe036 | 870 | package org.gridsphere.provider.portletui.beans;
/**
* The <code>TextBean</code> represents text to be displayed
*/
public class ValidatorBean extends BaseComponentBean implements TagBean {
protected String type = "";
/**
* Constructs a default text bean
*/
public ValidatorBean() {
}
/**
* Constructs a text bean using a supplied bean identifier
*
* @param beanId the bean identifier
*/
public ValidatorBean(String beanId) {
this.beanId = beanId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toStartString() {
return "<input type=\"hidden\" name=\"" + "val#" + name + "#" + type + "\" value=\"" + value + "\"/>";
}
public String toEndString() {
return "";
}
}
| 20.232558 | 110 | 0.582759 |
2e1d1266f8db5fce0c5406cd34c0bbeba9f3a200 | 5,645 | package fr.openwide.core.wicket.more.link.descriptor.builder.impl.main;
import org.apache.wicket.Page;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.resource.ResourceReference;
import org.bindgen.BindingRoot;
import org.bindgen.binding.AbstractBinding;
import org.javatuples.Unit;
import com.google.common.base.Predicate;
import fr.openwide.core.wicket.more.condition.Condition;
import fr.openwide.core.wicket.more.link.descriptor.builder.impl.parameter.LinkParameterTypeInformation;
import fr.openwide.core.wicket.more.link.descriptor.builder.state.main.common.IMainState;
import fr.openwide.core.wicket.more.link.descriptor.builder.state.main.generic.IGenericOneMappableParameterMainState;
import fr.openwide.core.wicket.more.link.descriptor.builder.state.parameter.chosen.common.IOneChosenParameterState;
import fr.openwide.core.wicket.more.link.descriptor.builder.state.parameter.mapping.IAddedParameterMappingState;
import fr.openwide.core.wicket.more.link.descriptor.parameter.mapping.factory.ILinkParameterMappingEntryFactory;
import fr.openwide.core.wicket.more.link.descriptor.parameter.validator.factory.ILinkParameterValidatorFactory;
import fr.openwide.core.wicket.more.markup.html.factory.IDetachableFactory;
/**
* This class exists mainly to avoid having to repeatedly write down TSelf in its expanded form
* (see {@link OneMappableParameterMainStateImpl}), which would be really verbose.
*
* @see OneMappableParameterMainStateImpl
* @see IGenericOneMappableParameterMainState
*/
abstract class AbstractGenericOneMappableParameterMainStateImpl
<
TSelf extends IMainState<TSelf>,
TParam1,
TEarlyTargetDefinitionLinkDescriptor,
TLateTargetDefinitionPageLinkDescriptor,
TLateTargetDefinitionResourceLinkDescriptor,
TLateTargetDefinitionImageResourceLinkDescriptor,
TEarlyTargetDefinitionResult,
TLateTargetDefinitionPageResult,
TLateTargetDefinitionResourceResult,
TLateTargetDefinitionImageResourceResult
>
extends AbstractOneOrMoreMappableParameterMainStateImpl
<
TSelf,
TEarlyTargetDefinitionLinkDescriptor,
TLateTargetDefinitionPageLinkDescriptor,
TLateTargetDefinitionResourceLinkDescriptor,
TLateTargetDefinitionImageResourceLinkDescriptor
>
implements IGenericOneMappableParameterMainState
<
TSelf,
TParam1,
TEarlyTargetDefinitionResult,
TLateTargetDefinitionPageResult,
TLateTargetDefinitionResourceResult,
TLateTargetDefinitionImageResourceResult
> {
AbstractGenericOneMappableParameterMainStateImpl(
NoMappableParameterMainStateImpl<
TEarlyTargetDefinitionLinkDescriptor,
TLateTargetDefinitionPageLinkDescriptor,
TLateTargetDefinitionResourceLinkDescriptor,
TLateTargetDefinitionImageResourceLinkDescriptor
> previousState,
LinkParameterTypeInformation<?> addedParameterType) {
super(previousState, addedParameterType);
}
protected abstract IOneChosenParameterState<
TSelf,
TParam1,
TLateTargetDefinitionPageResult,
TLateTargetDefinitionResourceResult,
TLateTargetDefinitionImageResourceResult
> pickLast();
@Override
public IAddedParameterMappingState<TSelf> map(String parameterName) {
return pickLast().map(parameterName);
}
@Override
public IAddedParameterMappingState<TSelf> map(
ILinkParameterMappingEntryFactory<? super Unit<IModel<TParam1>>> parameterMappingEntryFactory) {
return pickLast().map(parameterMappingEntryFactory);
}
@Override
public IAddedParameterMappingState<TSelf> renderInUrl(String parameterName) {
return pickLast().renderInUrl(parameterName);
}
@Override
public IAddedParameterMappingState<TSelf> renderInUrl(String parameterName,
AbstractBinding<? super TParam1, ?> binding) {
return pickLast().renderInUrl(parameterName, binding);
}
@Override
public TSelf validator(
ILinkParameterValidatorFactory<? super Unit<IModel<TParam1>>> parameterValidatorFactory) {
return pickLast().validator(parameterValidatorFactory);
}
@Override
public TSelf validator(IDetachableFactory<? super Unit<IModel<TParam1>>, ? extends Condition> conditionFactory) {
return pickLast().validator(conditionFactory);
}
@Override
public TSelf validator(Predicate<? super TParam1> predicate) {
return pickLast().validator(predicate);
}
@Override
public TSelf permission(String permissionName) {
return pickLast().permission(permissionName);
}
@Override
public TSelf permission(String firstPermissionName, String... otherPermissionNames) {
return pickLast().permission(firstPermissionName, otherPermissionNames);
}
@Override
public TSelf permission(BindingRoot<? super TParam1, ?> binding,
String firstPermissionName, String... otherPermissionNames) {
return pickLast().permission(binding, firstPermissionName, otherPermissionNames);
}
@Override
public TLateTargetDefinitionPageResult page(
IDetachableFactory<
? super Unit<IModel<TParam1>>,
? extends IModel<? extends Class<? extends Page>>
> pageClassFactory) {
return pickLast().page(pageClassFactory);
}
@Override
public TLateTargetDefinitionResourceResult resource(
IDetachableFactory<
? super Unit<IModel<TParam1>>,
? extends IModel<? extends ResourceReference>
> resourceReferenceFactory) {
return pickLast().resource(resourceReferenceFactory);
}
@Override
public TLateTargetDefinitionImageResourceResult imageResource(
IDetachableFactory<
? super Unit<IModel<TParam1>>,
? extends IModel<? extends ResourceReference>
> resourceReferenceFactory) {
return pickLast().imageResource(resourceReferenceFactory);
}
}
| 35.062112 | 117 | 0.805846 |
ea33ee75fb961a9776e87aa935b47055fe00e410 | 1,086 | package zmq;
class Pull extends SocketBase
{
public static class PullSession extends SessionBase
{
public PullSession(IOThread ioThread, boolean connect,
SocketBase socket, final Options options,
final Address addr)
{
super(ioThread, connect, socket, options, addr);
}
}
// Fair queueing object for inbound pipes.
private final FQ fq;
public Pull(Ctx parent, int tid, int sid)
{
super(parent, tid, sid);
options.type = ZMQ.ZMQ_PULL;
fq = new FQ();
}
@Override
protected void xattachPipe(Pipe pipe, boolean icanhasall)
{
assert (pipe != null);
fq.attach(pipe);
}
@Override
protected void xreadActivated(Pipe pipe)
{
fq.activated(pipe);
}
@Override
protected void xpipeTerminated(Pipe pipe)
{
fq.terminated(pipe);
}
@Override
public Msg xrecv()
{
return fq.recv(errno);
}
@Override
protected boolean xhasIn()
{
return fq.hasIn();
}
}
| 19.052632 | 62 | 0.576427 |
1da267e8e7fbaba570ab2b54dd9aa218231c0872 | 570 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.kafka;
import io.opentelemetry.context.propagation.TextMapSetter;
import java.nio.charset.StandardCharsets;
import org.apache.kafka.clients.producer.ProducerRecord;
public final class KafkaHeadersSetter implements TextMapSetter<ProducerRecord<?, ?>> {
@Override
public void set(ProducerRecord<?, ?> carrier, String key, String value) {
carrier.headers().remove(key).add(key, value.getBytes(StandardCharsets.UTF_8));
}
}
| 30 | 86 | 0.780702 |
ebe2fcc21123e629cbe939ae58761ca8afc0928f | 1,017 | package ode.vertex.impl.helper.backward;
import ode.solve.api.FirstOrderSolver;
import ode.vertex.impl.helper.backward.timegrad.NoMultiStepTimeGrad;
import ode.vertex.impl.helper.backward.timegrad.NoTimeGrad;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.nd4j.linalg.api.ndarray.INDArray;
/**
* {@link OdeHelperBackward} with a fixed given sequence of time steps to evaluate the ODE for.
*
* @author Christian Skarby
*/
public class FixedStepAdjoint implements OdeHelperBackward {
private final OdeHelperBackward helper;
public FixedStepAdjoint(FirstOrderSolver solver, INDArray time) {
if(time.length() > 2) {
helper = new MultiStepAdjoint(solver, time, NoMultiStepTimeGrad.factory);
} else {
helper = new SingleStepAdjoint(solver, time, NoTimeGrad.factory);
}
}
@Override
public INDArray[] solve(ComputationGraph graph, InputArrays input, MiscPar miscPars) {
return helper.solve(graph, input, miscPars);
}
}
| 32.806452 | 95 | 0.73353 |
de351458b96fe623f67cdde197e9032fe5284c91 | 928 | package br.copacabana.marshllers;
import java.lang.reflect.Type;
import br.com.copacabana.cb.KeyWrapper;
import br.com.copacabana.cb.entities.mgr.JPAManager;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class KeyWrapperSerializerWithValue implements JsonSerializer<KeyWrapper> {
private JPAManager man;
public KeyWrapperSerializerWithValue(JPAManager man){
this.man=man;
}
@Override
public JsonElement serialize(KeyWrapper kw, Type arg1, JsonSerializationContext arg2) {
if(kw==null || kw.getK()==null){
return new JsonNull();
}
if(kw.getValue()==null){
man.find(kw, kw.getK().getClass());
}
return new JsonPrimitive(KeyFactory.keyToString(kw.getK()));
}
}
| 29 | 89 | 0.753233 |
a83b919b6dadc9d3e25cf89d8bf2162491bf53c0 | 398 | package com.xxdb.data;
/**
*
* Interface for DolphinDB data form: ARRAY, BIGARRAY
*
*/
public interface Vector extends Entity{
final int DISPLAY_ROWS = 10;
Vector combine(Vector vector);
boolean isNull(int index);
void setNull(int index);
int hashBucket(int index, int buckets);
Scalar get(int index);
void set(int index, Scalar value) throws Exception;
Class<?> getElementClass();
}
| 22.111111 | 53 | 0.728643 |
06856d421643784d5b95d7da8d463fdc004b35ac | 6,514 | package uk.gov.hmcts.reform.finrem.caseorchestration.service.bulkscan.validation;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import uk.gov.hmcts.reform.bsp.common.error.InvalidDataException;
import uk.gov.hmcts.reform.bsp.common.error.UnsupportedFormTypeException;
import uk.gov.hmcts.reform.bsp.common.model.shared.in.ExceptionRecord;
import uk.gov.hmcts.reform.bsp.common.model.shared.in.OcrDataField;
import uk.gov.hmcts.reform.bsp.common.model.validation.out.OcrValidationResult;
import uk.gov.hmcts.reform.bsp.common.service.BulkScanFormValidator;
import uk.gov.hmcts.reform.bsp.common.service.transformation.BulkScanFormTransformer;
import uk.gov.hmcts.reform.finrem.caseorchestration.service.BulkScanService;
import uk.gov.hmcts.reform.finrem.caseorchestration.service.bulkscan.transformation.FinRemBulkScanFormTransformerFactory;
import java.util.List;
import java.util.Map;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.rules.ExpectedException.none;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static uk.gov.hmcts.reform.finrem.caseorchestration.TestConstants.TEST_BULK_UNSUPPORTED_FORM_TYPE;
import static uk.gov.hmcts.reform.finrem.caseorchestration.TestConstants.TEST_FORM;
import static uk.gov.hmcts.reform.finrem.caseorchestration.TestConstants.TEST_FORM_TYPE;
import static uk.gov.hmcts.reform.finrem.caseorchestration.TestConstants.TEST_KEY;
import static uk.gov.hmcts.reform.finrem.caseorchestration.TestConstants.TEST_VALUE;
@RunWith(MockitoJUnitRunner.class)
public class BulkScanServiceTest {
@Rule
public ExpectedException expectedException = none();
@Mock
private FinRemBulkScanFormTransformerFactory finRemBulkScanFormTransformerFactory;
@Mock
private BulkScanFormTransformer bulkScanFormTransformer;
@Mock
private BulkScanFormValidator bulkScanFormValidator;
@Mock
private FormAValidator formAValidator;
@Mock
private FinRemBulkScanFormValidatorFactory finRemBulkScanFormValidatorFactory;
@InjectMocks
private BulkScanService bulkScanService;
@Test
public void shouldCallReturnedValidator() throws UnsupportedFormTypeException {
OcrValidationResult resultFromValidator = OcrValidationResult.builder().build();
List<OcrDataField> ocrDataFields = singletonList(new OcrDataField(TEST_KEY, TEST_VALUE));
when(finRemBulkScanFormValidatorFactory.getValidator(TEST_FORM)).thenReturn(bulkScanFormValidator);
when(bulkScanFormValidator.validateBulkScanForm(ocrDataFields)).thenReturn(resultFromValidator);
OcrValidationResult returnedResult = bulkScanService.validateBulkScanForm(TEST_FORM, ocrDataFields);
verify(bulkScanFormValidator).validateBulkScanForm(ocrDataFields);
assertThat(returnedResult, equalTo(resultFromValidator));
}
@Test
public void shouldRethrowUnsupportedFormTypeExceptionFromFactory() {
expectedException.expect(UnsupportedFormTypeException.class);
List<OcrDataField> ocrDataFields = singletonList(new OcrDataField(TEST_KEY, TEST_VALUE));
when(finRemBulkScanFormValidatorFactory.getValidator(TEST_BULK_UNSUPPORTED_FORM_TYPE)).thenThrow(UnsupportedFormTypeException.class);
bulkScanService.validateBulkScanForm(TEST_BULK_UNSUPPORTED_FORM_TYPE, ocrDataFields);
}
@Test
public void shouldCallReturnedTransformer() throws UnsupportedFormTypeException {
ExceptionRecord exceptionRecord = ExceptionRecord.builder()
.formType(TEST_FORM_TYPE)
.ocrDataFields(singletonList(new OcrDataField(TEST_KEY, TEST_VALUE)))
.build();
OcrValidationResult resultFromValidator = OcrValidationResult.builder().build();
when(finRemBulkScanFormValidatorFactory.getValidator(TEST_FORM_TYPE)).thenReturn(bulkScanFormValidator);
when(bulkScanFormValidator.validateBulkScanForm(any())).thenReturn(resultFromValidator);
when(formAValidator.validateFormAScannedDocuments(any())).thenReturn(resultFromValidator);
when(finRemBulkScanFormTransformerFactory.getTransformer(TEST_FORM_TYPE)).thenReturn(bulkScanFormTransformer);
when(bulkScanFormTransformer.transformIntoCaseData(exceptionRecord)).thenReturn(singletonMap(TEST_KEY, TEST_VALUE));
Map<String, Object> returnedResult = bulkScanService.transformBulkScanForm(exceptionRecord);
verify(finRemBulkScanFormTransformerFactory).getTransformer(TEST_FORM_TYPE);
verify(bulkScanFormTransformer).transformIntoCaseData(exceptionRecord);
assertThat(returnedResult, hasEntry(TEST_KEY, TEST_VALUE));
}
@Test
public void shouldRethrowUnsupportedFormTypeExceptionFromFormTransformerFactory() {
expectedException.expect(UnsupportedFormTypeException.class);
ExceptionRecord exceptionRecord = ExceptionRecord.builder().formType(TEST_BULK_UNSUPPORTED_FORM_TYPE).build();
when(finRemBulkScanFormValidatorFactory.getValidator(TEST_BULK_UNSUPPORTED_FORM_TYPE)).thenThrow(UnsupportedFormTypeException.class);
bulkScanService.transformBulkScanForm(exceptionRecord);
}
@Test(expected = InvalidDataException.class)
public void shouldThrowInvalidDataExceptionForTransformer() {
ExceptionRecord exceptionRecord = ExceptionRecord.builder()
.formType(TEST_FORM_TYPE)
.ocrDataFields(singletonList(new OcrDataField(TEST_KEY, TEST_VALUE)))
.build();
OcrValidationResult validatedWithWarn = OcrValidationResult.builder().addWarning("warning").build();
when(finRemBulkScanFormValidatorFactory.getValidator(TEST_FORM_TYPE)).thenReturn(bulkScanFormValidator);
when(bulkScanFormValidator.validateBulkScanForm(any())).thenReturn(validatedWithWarn);
bulkScanService.transformBulkScanForm(exceptionRecord);
verify(finRemBulkScanFormTransformerFactory, never()).getTransformer(TEST_FORM_TYPE);
verify(bulkScanFormTransformer, never()).transformIntoCaseData(exceptionRecord);
}
}
| 48.977444 | 141 | 0.805803 |
8422d9c0ac00565c47bf1861c3376a9868419c9c | 1,442 | package com.newer.deal.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.newer.deal.entiry.Freeze;
import com.newer.deal.entiry.Legalcurrency;
import com.newer.deal.repository.FreezeMapper;
import com.newer.deal.repository.LegalcurrencyMapper;
@RestController
@RequestMapping("/legal")
public class LegalcurrencyController {
@Autowired
LegalcurrencyMapper mapper;
@Autowired
FreezeMapper map;
/**
* 根据登录用户ID获取该用户的所有法币库存
* @param id
* @return
*/
@GetMapping("/{id}")
public List<Legalcurrency> a(@PathVariable int id) {
return mapper.loadByUserId(id);
}
// @DeleteMapping("/freeze")
// public boolean c(@RequestBody Freeze freeze) {
// boolean b = false;
// b = map.removeFreeze(freeze);
// return b;
//
// }
// @PostMapping
// public Legalcurrency b(@RequestBody Legalcurrency legalcurrency) {
// mapper.create(legalcurrency);
// return legalcurrency;
// }
}
| 26.218182 | 70 | 0.745492 |
f64a6b8f5e2b6f7429aaddd3b3b773571986c0c5 | 510 | package org.javamaster.b2c.core.exception;
import org.javamaster.b2c.core.enums.BizExceptionEnum;
/**
* @author yudong
* @date 2019/6/10
*/
public class BizException extends RuntimeException {
private final BizExceptionEnum bizExceptionEnum;
public BizException(BizExceptionEnum bizExceptionEnum) {
super(bizExceptionEnum.getErrorMsg());
this.bizExceptionEnum = bizExceptionEnum;
}
public BizExceptionEnum getBizExceptionEnum() {
return bizExceptionEnum;
}
}
| 24.285714 | 60 | 0.739216 |
0e00ac52c173bc46f25f82697e9ea790032c5c1f | 946 | package com.bxl.bpm.dao;
import com.bxl.bpm.model.SysButton;
import com.bxl.bpm.model.SysButtonExample;
import java.util.List;
import com.bxl.common.generic.GenericDao;
import org.apache.ibatis.annotations.Param;
public interface SysButtonMapper extends GenericDao<SysButton, Integer> {
int countByExample(SysButtonExample example);
int deleteByExample(SysButtonExample example);
int deleteByPrimaryKey(Integer id);
int insert(SysButton record);
int insertSelective(SysButton record);
List<SysButton> selectByExample(SysButtonExample example);
SysButton selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") SysButton record, @Param("example") SysButtonExample example);
int updateByExample(@Param("record") SysButton record, @Param("example") SysButtonExample example);
int updateByPrimaryKeySelective(SysButton record);
int updateByPrimaryKey(SysButton record);
} | 29.5625 | 112 | 0.782241 |
c067fac89284e7cde4629e256bbacca8ea98ebbe | 863 | package seedu.docit.testutil.stubs;
import static java.util.Objects.requireNonNull;
import java.util.ArrayList;
import seedu.docit.model.AddressBook;
import seedu.docit.model.ReadOnlyAddressBook;
import seedu.docit.model.patient.Patient;
/**
* A Model stub that always accept the patient being added.
*/
public class ModelStubAcceptingPatientAdded extends ModelStub {
public final ArrayList<Patient> patientsAdded = new ArrayList<>();
@Override
public boolean hasPatient(Patient patient) {
requireNonNull(patient);
return patientsAdded.stream().anyMatch(patient::isSamePatient);
}
@Override
public void addPatient(Patient patient) {
requireNonNull(patient);
patientsAdded.add(patient);
}
@Override
public ReadOnlyAddressBook getAddressBook() {
return new AddressBook();
}
}
| 25.382353 | 71 | 0.727694 |
6c8a88c1042fea456f3c28865eb787d41a778f94 | 1,786 | package com.example.app;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DomParserApp {
private static final Map<String, Long> continentCountryNumbers = new HashMap<>();
public static void main(String[] args) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("resources", "countries.xml"));
Node countryList = document.getDocumentElement();
if (countryList.getNodeType() == Node.ELEMENT_NODE) {
NodeList countries = countryList.getChildNodes();
for (int i = 0; i < countries.getLength(); i++) {
if (countries.item(i).getNodeType() == Node.ELEMENT_NODE) {
NodeList country = countries.item(i).getChildNodes();
for (int j = 0; j < country.getLength(); j++) {
if (country.item(j).getNodeName().compareTo("continent") == 0) {
NodeList countryContinent = country.item(j).getChildNodes();
for (int k = 0; k < countryContinent.getLength(); k++) {
if (countryContinent.item(k).getNodeType() == Node.TEXT_NODE) {
String continent = countryContinent.item(k).getNodeValue();
Long count = continentCountryNumbers.get(continent);
if (count == null)
count = 0L;
count = count + 1;
continentCountryNumbers.put(continent, count);
}
}
}
}
}
}
}
continentCountryNumbers.forEach((continent, count) -> System.out.println(continent + ": " + count));
}
}
| 35.72 | 102 | 0.68981 |
d8be92aeb0fa0dad22a778f3058eb2c483a7ae37 | 952 | /*
* 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 cn.hanbell.oa.ejb;
import cn.hanbell.oa.comm.SuperEJBForEFGP;
import cn.hanbell.oa.entity.HZCW033reDetail;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.Query;
/**
*
* @author C0160
*/
@Stateless
@LocalBean
public class HZCW033reDetailBean extends SuperEJBForEFGP<HZCW033reDetail> {
public HZCW033reDetailBean() {
super(HZCW033reDetail.class);
}
public List<HZCW033reDetail> findByLoanNo(String loanNo) {
Query query = getEntityManager().createNamedQuery("HZCW033reDetail.findByLoanNo");
query.setParameter("loanNo", loanNo);
try {
return query.getResultList();
} catch (Exception ex) {
return null;
}
}
}
| 25.72973 | 90 | 0.702731 |
df7bc9ba49e8237fb553707501516378cb0a218b | 1,525 | package chess.parser;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Stanisław Kabaciński.
*/
public class MovesFilter {
public static List<Move> filter(List<Entity> entities, int toPosition) {
if (entities.size() <= 1) {
return new ArrayList<>();
}
List<Move> out = new ArrayList<>();
List<RevertedMove> reverted = new ArrayList<>();
for (int i = 0; i <= toPosition; i++) {
Entity e = entities.get(i);
if (e instanceof Move) {
Move m = (Move) e;
out.add(m);
} else if (e instanceof VariantBegin) {
int pos = out.size() - 1;
Move prev = out.remove(pos);
reverted.add(new RevertedMove(prev, pos));
} else if (e instanceof VariantEnd) {
RevertedMove rMove = reverted.remove(reverted.size() - 1);
out.add(rMove.position, rMove.move);
for (int j = out.size() - 1; j > rMove.position; j--) {
out.remove(j);
}
}
}
return out;
}
public static List<Move> filter(List<Entity> entities) {
return filter(entities, entities.size() - 1);
}
public static class RevertedMove {
public final Move move;
public final int position;
public RevertedMove(Move move, int position) {
this.move = move;
this.position = position;
}
}
}
| 26.754386 | 76 | 0.518689 |
a96eb97b0d2ab68d33c894f57919903bf80fa459 | 3,569 | /*
* The MIT License
*
* Copyright 2014 Lukas Plechinger.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package at.plechinger.spring.security.scribe;
import java.util.Collection;
import java.util.Map;
import org.scribe.model.Token;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import at.plechinger.spring.security.scribe.provider.ProviderConfiguration;
/**
* The implementation of
* <code>AuthenticationToken</code> for ScribeAuthentication.
*
* @author Lukas Plechinger, www.plechinger.at
*/
public class ScribeAuthentication extends AbstractAuthenticationToken {
private static final long serialVersionUID = 1L;
private UserDetails userDetails;
private Token scribeToken;
private Map<String, Object> scribeDetails;
private String redirectUrl;
private ProviderConfiguration providerConfiguration;
public ScribeAuthentication(Collection<? extends GrantedAuthority> authorities) {
super(authorities);
}
public ScribeAuthentication(Token scribeToken, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.scribeToken = scribeToken;
super.setAuthenticated(true);
}
public ScribeAuthentication() {
super(null);
}
public Object getCredentials() {
return scribeToken;
}
public Object getPrincipal() {
return userDetails;
}
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
public UserDetails getUserDetails() {
return userDetails;
}
public Token getScribeToken() {
return scribeToken;
}
public void setScribeToken(Token scribeToken) {
this.scribeToken = scribeToken;
}
public Map<String, Object> getScribeDetails() {
return scribeDetails;
}
public void setScribeDetails(Map<String, Object> scribeDetails) {
this.scribeDetails = scribeDetails;
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public ProviderConfiguration getProviderConfiguration() {
return providerConfiguration;
}
public void setProviderConfiguration(ProviderConfiguration providerConfiguration) {
this.providerConfiguration = providerConfiguration;
}
}
| 32.153153 | 104 | 0.736341 |
fcd649b11c1102d90eb338131a5dcbe5ef5c4cf6 | 1,450 | package com.example.superapp30.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.superapp30.R;
import com.example.superapp30.model.Tarefa;
import java.util.List;
public class AdapterTarefas extends RecyclerView.Adapter<AdapterTarefas.MyViewHolder> {
private List<Tarefa> listaTarefas;
public AdapterTarefas(List<Tarefa> listaTarefas) {
this.listaTarefas = listaTarefas;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_lista_simples, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Tarefa tarefa = listaTarefas.get(position);
holder.textTarefa.setText(tarefa.getTarefa());
}
@Override
public int getItemCount() {
return listaTarefas.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView textTarefa;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textTarefa = itemView.findViewById(R.id.textItemSimples);
}
}
}
| 26.851852 | 87 | 0.713793 |
72ae21e5dff9f5579cf292d3e390c5663f8fb4aa | 1,664 | package com.devom.cndb_example.app;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.devom.cndb_example.di.component.ApplicationComponent;
import com.devom.cndb_example.di.component.DaggerApplicationComponent;
import com.devom.cndb_example.di.module.ApplicationContextModule;
public class BaseApplication extends Application {
public static final String TAG = BaseApplication.class.getSimpleName();
private static BaseApplication mInstance;
private static ConnectivityManager connManager;
private static NetworkInfo mWifi;
private ApplicationComponent applicationComponent;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
setupGraphApplicationComponent();
}
//Request Instance
public static BaseApplication getInstance() {
return mInstance;
}
//Connection to Network
public static boolean getConnectionToNetwork() {
connManager = (ConnectivityManager) mInstance.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
//Application
private void setupGraphApplicationComponent() {
applicationComponent = DaggerApplicationComponent
.builder()
.applicationContextModule(new ApplicationContextModule(this))
.build();
}
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
}
| 30.814815 | 101 | 0.738582 |
1672c74504b2bb0546fb7cd0a38377c11ff434ca | 1,962 | package uk.gov.ons.ctp.integration.rhcucumber.selenium.pageobject;
import lombok.Getter;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import uk.gov.ons.ctp.integration.rhcucumber.selenium.pages.Country;
import uk.gov.ons.ctp.integration.rhcucumber.selenium.pages.PageTracker.PageId;
import uk.gov.ons.ctp.integration.rhcucumber.selenium.pages.Translations.KEYS;
@Getter
public class IsThisMobileNumCorrect extends PageObjectBase {
private String expectedText = "Is this mobile number correct?";
public IsThisMobileNumCorrect(WebDriver driver, Country country) {
super(PageId.IS_THIS_MOBILE_NUM_CORRECT, driver, country);
expectedText = translate(KEYS.IS_THIS_MOBILE_NUM_CORRECT_EXPECTED_TEXT);
}
@FindBy(xpath = WebPageConstants.XPATH_LOGO)
private WebElement onsLogo;
@FindBy(xpath = WebPageConstants.XPATH_PAGE_CONTENT_TITLE)
private WebElement isMobileCorrectTitle;
@FindBy(xpath = WebPageConstants.XPATH_RADIO_MOBILE_YES)
private WebElement optionYes;
@FindBy(xpath = WebPageConstants.XPATH_RADIO_MOBILE_NO)
private WebElement optionNo;
@FindBy(xpath = WebPageConstants.XPATH_CONTINUE_BUTTON)
private WebElement continueButton;
@FindBy(xpath = WebPageConstants.XPATH_DISPLAYED_MOBILE_NUMBER)
private WebElement displayedMobileNumber;
public String getIsMobileCorrectTitleText() {
waitForElement(isMobileCorrectTitle, classPrefix + "isMobileCorrectTitle");
return isMobileCorrectTitle.getText();
}
public void clickContinueButton() {
waitForElement(continueButton, "continueButton");
continueButton.click();
}
public void clickOptionYes() {
waitForElement(optionYes, "optionYes");
optionYes.click();
}
public void clickOptionNo() {
waitForElement(optionNo, "optionNo");
optionNo.click();
}
public String displayedMobileNumber() {
return displayedMobileNumber.getText();
}
}
| 30.65625 | 79 | 0.79052 |
791aada9bb16a9776e9eabd1f667ef82c99a219d | 2,713 | package com.onesignal;
import android.content.Context;
import com.onesignal.OneSignalDbContract;
import com.onesignal.influence.model.OSInfluenceChannel;
import com.onesignal.outcomes.OSOutcomeTableProvider;
class OneSignalCacheCleaner {
private static final long NOTIFICATION_CACHE_DATA_LIFETIME = 604800;
private static final String OS_DELETE_CACHED_NOTIFICATIONS_THREAD = "OS_DELETE_CACHED_NOTIFICATIONS_THREAD";
private static final String OS_DELETE_CACHED_REDISPLAYED_IAMS_THREAD = "OS_DELETE_CACHED_REDISPLAYED_IAMS_THREAD";
OneSignalCacheCleaner() {
}
static void cleanOldCachedData(Context context) {
OneSignalDbHelper instance = OneSignalDbHelper.getInstance(context);
cleanNotificationCache(instance);
cleanCachedInAppMessages(instance);
}
static synchronized void cleanNotificationCache(final OneSignalDbHelper oneSignalDbHelper) {
synchronized (OneSignalCacheCleaner.class) {
new Thread(new Runnable() {
public void run() {
Thread.currentThread().setPriority(10);
OneSignalCacheCleaner.cleanCachedNotifications(OneSignalDbHelper.this);
OneSignalCacheCleaner.cleanCachedUniqueOutcomeEventNotifications(OneSignalDbHelper.this);
}
}, OS_DELETE_CACHED_NOTIFICATIONS_THREAD).start();
}
}
static synchronized void cleanCachedInAppMessages(final OneSignalDbHelper oneSignalDbHelper) {
synchronized (OneSignalCacheCleaner.class) {
new Thread(new Runnable() {
public void run() {
Thread.currentThread().setPriority(10);
OneSignal.getInAppMessageController().getInAppMessageRepository(OneSignalDbHelper.this).cleanCachedInAppMessages();
}
}, OS_DELETE_CACHED_REDISPLAYED_IAMS_THREAD).start();
}
}
/* access modifiers changed from: private */
public static void cleanCachedNotifications(OneSignalDbHelper oneSignalDbHelper) {
oneSignalDbHelper.delete(OneSignalDbContract.NotificationTable.TABLE_NAME, "created_time < ?", new String[]{String.valueOf((System.currentTimeMillis() / 1000) - NOTIFICATION_CACHE_DATA_LIFETIME)});
}
/* access modifiers changed from: private */
public static void cleanCachedUniqueOutcomeEventNotifications(OneSignalDbHelper oneSignalDbHelper) {
oneSignalDbHelper.delete(OSOutcomeTableProvider.CACHE_UNIQUE_OUTCOME_TABLE, "NOT EXISTS(SELECT NULL FROM notification n WHERE n.notification_id = channel_influence_id AND channel_type = \"" + OSInfluenceChannel.NOTIFICATION.toString().toLowerCase() + "\")", (String[]) null);
}
}
| 49.327273 | 283 | 0.731662 |
af6251d96d9d216715d1c596185e8ea8bfdee03d | 2,315 | package com.manning.hsia.dvdstore.action;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.SearchException;
import com.manning.hsia.dvdstore.model.Item;
import com.manning.hsia.dvdstore.util.SessionHolder;
/**
* Example 5.13
*/
public class StemmerIndexerImpl implements StemmerIndexer {
public String checkStemmingIndex() {
FullTextSession ftSession = SessionHolder.getFullTextSession();
try {
//build the Lucene query
final Analyzer entityScopedAnalyzer = ftSession.getSearchFactory().getAnalyzer(Item.class);
QueryParser parser = new QueryParser("id", entityScopedAnalyzer ); //use Item analyzer
//search on the exact field
Query query = parser.parse("title:saving"); //build Lucene query
//the query is not altered
if ( ! "title:saving".equals( query.toString() ) ) {
return "searching the exact field should not alter the query";
}
//return matching results
org.hibernate.search.FullTextQuery hibQuery =
ftSession.createFullTextQuery(query, Item.class); //return matching results
@SuppressWarnings("unchecked")
List<Item> results = hibQuery.list();
//we find a single matching result
int exactResultSize = results.size();
if ( exactResultSize != 1 ) {
return "exact match should only return 1 result";
}
//search on the stemmed field
query = parser.parse("title_stemmer:saving"); //search same word on the stemmed field
//the query search the stem version of each word
if ( ! "title_stemmer:save".equals( query.toString() ) ) { //search the stem version of each word
return "searching the stemmer field should search the stem";
}
//return matching results
hibQuery = ftSession.createFullTextQuery(query);
results = (List<Item>) hibQuery.list();
//we should find more matches than the exact query
if ( results.size() <= exactResultSize ) { //more matching results are found
return "stemming should return more matches";
}
return null; //no error
}
catch (ParseException e) {
throw new SearchException(e);
}
}
}
| 33.071429 | 101 | 0.722246 |
876edcfc544ff45eb6eab9830b238fcea9fd08a4 | 2,607 | package com.atguigu.gmall.organization.controller;
import java.util.Arrays;
import java.util.Map;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.QueryCondition;
import com.atguigu.core.bean.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.atguigu.gmall.organization.entity.UserGroupRelationEntity;
import com.atguigu.gmall.organization.service.UserGroupRelationService;
/**
* 用户和组关系表
*
* @author stanley.yu
* @email 363825455@qq.com
* @date 2020-01-22 21:56:30
*/
@Api(tags = "用户和组关系表 管理")
@RestController
@RequestMapping("organization/usergrouprelation")
public class UserGroupRelationController {
@Autowired
private UserGroupRelationService userGroupRelationService;
/**
* 列表
*/
@ApiOperation("分页查询(排序)")
@GetMapping("/list")
@PreAuthorize("hasAuthority('organization:usergrouprelation:list')")
public Resp<PageVo> list(QueryCondition queryCondition) {
PageVo page = userGroupRelationService.queryPage(queryCondition);
return Resp.ok(page);
}
/**
* 信息
*/
@ApiOperation("详情查询")
@GetMapping("/info/{id}")
@PreAuthorize("hasAuthority('organization:usergrouprelation:info')")
public Resp<UserGroupRelationEntity> info(@PathVariable("id") String id){
UserGroupRelationEntity userGroupRelation = userGroupRelationService.getById(id);
return Resp.ok(userGroupRelation);
}
/**
* 保存
*/
@ApiOperation("保存")
@PostMapping("/save")
@PreAuthorize("hasAuthority('organization:usergrouprelation:save')")
public Resp<Object> save(@RequestBody UserGroupRelationEntity userGroupRelation){
userGroupRelationService.save(userGroupRelation);
return Resp.ok(null);
}
/**
* 修改
*/
@ApiOperation("修改")
@PostMapping("/update")
@PreAuthorize("hasAuthority('organization:usergrouprelation:update')")
public Resp<Object> update(@RequestBody UserGroupRelationEntity userGroupRelation){
userGroupRelationService.updateById(userGroupRelation);
return Resp.ok(null);
}
/**
* 删除
*/
@ApiOperation("删除")
@PostMapping("/delete")
@PreAuthorize("hasAuthority('organization:usergrouprelation:delete')")
public Resp<Object> delete(@RequestBody String[] ids){
userGroupRelationService.removeByIds(Arrays.asList(ids));
return Resp.ok(null);
}
}
| 26.602041 | 87 | 0.71845 |
80937439db05531861facce1a000d6800633cd0a | 2,456 | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("16")
class Record_1907 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 1907: FirstName is Geoffrey")
void FirstNameOfRecord1907() {
assertEquals("Geoffrey", customers.get(1906).getFirstName());
}
@Test
@DisplayName("Record 1907: LastName is Quelette")
void LastNameOfRecord1907() {
assertEquals("Quelette", customers.get(1906).getLastName());
}
@Test
@DisplayName("Record 1907: Company is Control Associates Inc")
void CompanyOfRecord1907() {
assertEquals("Control Associates Inc", customers.get(1906).getCompany());
}
@Test
@DisplayName("Record 1907: Address is 255 E 2nd St")
void AddressOfRecord1907() {
assertEquals("255 E 2nd St", customers.get(1906).getAddress());
}
@Test
@DisplayName("Record 1907: City is Mineola")
void CityOfRecord1907() {
assertEquals("Mineola", customers.get(1906).getCity());
}
@Test
@DisplayName("Record 1907: County is Nassau")
void CountyOfRecord1907() {
assertEquals("Nassau", customers.get(1906).getCounty());
}
@Test
@DisplayName("Record 1907: State is NY")
void StateOfRecord1907() {
assertEquals("NY", customers.get(1906).getState());
}
@Test
@DisplayName("Record 1907: ZIP is 11501")
void ZIPOfRecord1907() {
assertEquals("11501", customers.get(1906).getZIP());
}
@Test
@DisplayName("Record 1907: Phone is 516-747-2926")
void PhoneOfRecord1907() {
assertEquals("516-747-2926", customers.get(1906).getPhone());
}
@Test
@DisplayName("Record 1907: Fax is 516-747-6771")
void FaxOfRecord1907() {
assertEquals("516-747-6771", customers.get(1906).getFax());
}
@Test
@DisplayName("Record 1907: Email is geoffrey@quelette.com")
void EmailOfRecord1907() {
assertEquals("geoffrey@quelette.com", customers.get(1906).getEmail());
}
@Test
@DisplayName("Record 1907: Web is http://www.geoffreyquelette.com")
void WebOfRecord1907() {
assertEquals("http://www.geoffreyquelette.com", customers.get(1906).getWeb());
}
}
| 25.583333 | 80 | 0.734528 |
b28f49c10787c77399262d9009dc34f040945c84 | 714 | package de.rnd7.calexport.renderer;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import j2html.tags.DomContent;
public final class MarkdownUtil {
private MarkdownUtil() {
}
public static DomContent convertMarkdown(final String text) {
final Parser parser = Parser.builder().build();
final Node document = parser.parse(text);
final HtmlRenderer renderer = HtmlRenderer.builder().build();
final String rendered = renderer.render(document).trim();
final String withoutP = rendered.substring(3, rendered.length()-4);
return new DomContent() {
@Override
public String render() {
return withoutP;
}
};
}
}
| 23.032258 | 69 | 0.739496 |
b7b43381bfd1430be3da2bd63356c57f4f1770c4 | 2,410 | /*
* 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.flink.table.functions.tablefunctions;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;
import static org.apache.flink.util.Preconditions.checkArgument;
/**
* Replicate the row N times. N is specified as the first argument to the function.
* This is an internal function solely used by optimizer to rewrite EXCEPT ALL AND
* INTERSECT ALL queries.
*/
public class ReplicateRows extends TableFunction<Row> {
private static final long serialVersionUID = 1L;
private final TypeInformation[] fieldTypes;
private transient Row reuseRow;
public ReplicateRows(TypeInformation[] fieldTypes) {
this.fieldTypes = fieldTypes;
}
public void eval(Object... inputs) {
checkArgument(inputs.length == fieldTypes.length + 1);
long numRows = (long) inputs[0];
if (reuseRow == null) {
reuseRow = new Row(fieldTypes.length);
}
for (int i = 0; i < fieldTypes.length; i++) {
reuseRow.setField(i, inputs[i + 1]);
}
for (int i = 0; i < numRows; i++) {
collect(reuseRow);
}
}
@Override
public TypeInformation<Row> getResultType() {
return new RowTypeInfo(fieldTypes);
}
@Override
public TypeInformation<?>[] getParameterTypes(Class<?>[] signature) {
TypeInformation[] paraTypes = new TypeInformation[1 + fieldTypes.length];
paraTypes[0] = Types.LONG;
System.arraycopy(fieldTypes, 0, paraTypes, 1, fieldTypes.length);
return paraTypes;
}
}
| 33.472222 | 83 | 0.743983 |
e5d346ec88d0952c5a67593ed3d63e3bff400a17 | 311 | package terrails.terracore.block.tile.fluid;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fluids.FluidTank;
public class FluidTankCustom extends FluidTank {
public FluidTankCustom(TileEntity tileEntity, int capacity) {
super(capacity);
tile = tileEntity;
}
}
| 23.923077 | 65 | 0.755627 |
dcb9289bef431c892a1524fbea0024b34b5262a6 | 2,055 | package com.hfad.companysyearendparty.views;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import com.hfad.companysyearendparty.R;
import com.hfad.companysyearendparty.constant.EndYearConstants;
import com.hfad.companysyearendparty.data.SecurityPreferences;
public class DetailsActivite extends AppCompatActivity implements View.OnClickListener {
private ViewHolder mViewHolder = new ViewHolder();
private SecurityPreferences mSecurityPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_activite);
this.mSecurityPreferences = new SecurityPreferences(this);
this.mViewHolder.checkParticipate = findViewById(R.id.check_participate);
this.mViewHolder.checkParticipate.setOnClickListener(this);
this.loadDataFromActivity();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.check_participate){
if(this.mViewHolder.checkParticipate.isChecked()){
//confirmed
this.mSecurityPreferences.storeString(EndYearConstants.PRESENCE_KEY, EndYearConstants.CONFIRMATION_YES);
}else{
//not confirmed
this.mSecurityPreferences.storeString(EndYearConstants.PRESENCE_KEY, EndYearConstants.CONFIRMATION_NO);
}
}
}
private static class ViewHolder{
CheckBox checkParticipate;
}
private void loadDataFromActivity(){
Bundle extras = getIntent().getExtras();
if (extras != null){
String presence = extras.getString(EndYearConstants.PRESENCE_KEY);
if (presence != null && presence.equals(EndYearConstants.CONFIRMATION_YES)) {
this.mViewHolder.checkParticipate.setChecked(true);
}else{
this.mViewHolder.checkParticipate.setChecked(false);
}
}
}
}
| 34.25 | 120 | 0.698297 |
0eaa8518dcf4f57664d1ae3660ff41759a79fce8 | 592 | package lsieun.bytecode.gen.opcode;
import java.io.DataOutputStream;
import java.io.IOException;
import lsieun.bytecode.core.cst.OpcodeConst;
import lsieun.bytecode.gen.opcode.facet.GotoInstruction;
/**
* GOTO_W - Branch always (to relative offset, not absolute address)
*/
public final class GOTO_W extends GotoInstruction {
public GOTO_W(final int branch) {
super(OpcodeConst.GOTO_W, 5);
this.branch = branch;
}
@Override
public void dump(DataOutputStream out) throws IOException {
out.writeByte(opcode);
out.writeInt(branch);
}
}
| 23.68 | 68 | 0.712838 |
4448d55d87f2c2a2d6ec7a504735ec7d39b7384b | 4,102 | package com.sample.business.content.entity;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.castle.repo.jpa.DataEntity;
import com.sample.business.member.entity.AdminEntity;
@Entity
@Table(name = "tbl_article")
public class ArticleEntity extends DataEntity<AdminEntity, Long> {
private static final long serialVersionUID = 2592900939574931917L;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "article_category", nullable = false)
private ArticleCategoryEntity category;
@NotNull
@Size(max = 100)
@Column(nullable = false, length = 200)
private String title;
@NotNull
@Size(max = 50)
@Column(nullable = false, length = 100)
private String author;
@NotNull
@Lob
private String content;
@Size(max = 500)
@Column(length = 1000)
private String summary;
@Size(max = 200)
@Column(length = 200)
private String linkTo;
@Size(max = 200)
@Column(length = 200)
private String thumbnail;
@Column(nullable = false)
private boolean published = false;
@Temporal(TemporalType.TIMESTAMP)
@Column
private Date publishedDate;
@Column(nullable = false)
private boolean stick = false;
@Column(nullable = false)
private long hits = 0l;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "tbl_article_to_tag")
@OrderBy("sortNo asc")
private Set<ArticleTagEntity> tags = new HashSet<>();
/** 页面标题 */
@Size(max = 200)
@Column(length = 200)
private String seoTitle;
/** 页面关键词 */
@Size(max = 200)
@Column(length = 200)
private String seoKeywords;
/** 页面描述 */
@Size(max = 200)
@Column(length = 200)
private String seoDescription;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getLinkTo() {
return linkTo;
}
public void setLinkTo(String linkTo) {
this.linkTo = linkTo;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public boolean isPublished() {
return published;
}
public void setPublished(boolean published) {
this.published = published;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public ArticleCategoryEntity getCategory() {
return category;
}
public void setCategory(ArticleCategoryEntity category) {
this.category = category;
}
public boolean isStick() {
return stick;
}
public void setStick(boolean stick) {
this.stick = stick;
}
public long getHits() {
return hits;
}
public void setHits(long hits) {
this.hits = hits;
}
public Set<ArticleTagEntity> getTags() {
return tags;
}
public void setTags(Set<ArticleTagEntity> tags) {
this.tags = tags;
}
public String getSeoTitle() {
return seoTitle;
}
public void setSeoTitle(String seoTitle) {
this.seoTitle = seoTitle;
}
public String getSeoKeywords() {
return seoKeywords;
}
public void setSeoKeywords(String seoKeywords) {
this.seoKeywords = seoKeywords;
}
public String getSeoDescription() {
return seoDescription;
}
public void setSeoDescription(String seoDescription) {
this.seoDescription = seoDescription;
}
}
| 19.07907 | 67 | 0.733545 |
7ebc7b9481301601635f4e9a1df138ea6e153c3f | 619 | package io.github.lonamiwebs.klooni;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
final AndroidShareChallenge shareChallenge = new AndroidShareChallenge(this);
initialize(new Klooni(shareChallenge), config);
}
}
| 36.411765 | 93 | 0.789984 |
8fd1d02e6d85a9c3e2aa42a7a76db1e908c95d86 | 179 | public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for(int i = 0;i<nums.length;i++)
result = result ^ nums[i];
return result;
}
}
| 19.888889 | 41 | 0.592179 |
e771a8f44c7f869d35f8e4bf4428d5bbd3076b35 | 1,768 | package com.github.dodii.finalreality.model.weapon;
import com.github.dodii.finalreality.model.character.playablecharacters.common.EngineerCharacter;
import com.github.dodii.finalreality.model.character.playablecharacters.common.KnightCharacter;
import com.github.dodii.finalreality.model.character.playablecharacters.common.ThiefCharacter;
import com.github.dodii.finalreality.model.character.playablecharacters.mage.IMageCharacter;
/**
* An interface that represents a weapon.
* Holds all the available methods for generic weapons.
*
* @author Rodrigo Oportot.
*/
public interface IWeapon {
/**
* @return the name of the weapon.
*/
String getName();
/**
* @return the damage of the weapon.
*/
int getDmg();
/**
* @return the weight of the weapon.
*/
int getWeight();
/**
* Aux method for the double dispatch equip implementation.
* @param engineer character to equip weapon
*/
void equipToEngineer(EngineerCharacter engineer);
/**
* Aux method for the double dispatch equip implementation
* @param knight character to equip weapon
*/
void equipToKnight(KnightCharacter knight);
/**
* Aux method for the double dispatch equip implementation
* @param thief character to equip weapon
*/
void equipToThief(ThiefCharacter thief);
/**
* Aux method for the double dispatch equip implementation
* @param mage character to equip weapon
*/
void equipToMage(IMageCharacter mage);
/**
* @return the hashcode
*/
int hashCode();
/**
* @param o the object (usually an IWeapon instance of a weapon).
* @return true if both objects are equal.
*/
boolean equals(final Object o);
}
| 26.787879 | 97 | 0.687217 |
9b6b617b618661bc47ce6c3659be6a615165aa65 | 1,374 | /*
* 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 ar.com.scvst.server.bean;
import java.time.LocalDateTime;
/**
*
* @author tserra
*/
public class Commit {
private String id;
private LocalDateTime fecha;
private String autor;
private String mensaje;
public Commit() {
}
public Commit(String id, LocalDateTime fecha, String autor, String mensaje) {
this.id = id;
this.fecha = fecha;
this.autor = autor;
this.mensaje = mensaje;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public LocalDateTime getFecha() {
return fecha;
}
public void setFecha(LocalDateTime fecha) {
this.fecha = fecha;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
@Override
public String toString() {
return "Commit{" + "id=" + id + ", fecha=" + fecha + ", autor=" + autor + ", mensaje=" + mensaje + '}';
}
}
| 19.913043 | 111 | 0.588064 |
f69be1b8b32e1bedf54dc29cd03e26196b78944d | 3,162 | /**
* DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND
* SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY.
* <p>
* Samsung expressly disclaims any and all warranties of any kind,
* whether express or implied, including but not limited to the implied warranties and conditions
* of merchantability, fitness for com.samsung.knoxsdksample particular purpose and non-infringement.
* Further, Samsung does not represent or warrant that any portion of the sample application and
* source code is free of inaccuracies, errors, bugs or interruptions, or is reliable,
* accurate, complete, or otherwise valid. The sample application and source code is provided
* "as is" and "as available", without any warranty of any kind from Samsung.
* <p>
* Your use of the sample application and source code is at its own discretion and risk,
* and licensee will be solely responsible for any damage that results from the use of the sample
* application and source code including, but not limited to, any damage to your computer system or
* platform. For the purpose of clarity, the sample code is licensed “as is” and
* licenses bears the risk of using it.
* <p>
* Samsung shall not be liable for any direct, indirect or consequential damages or
* costs of any type arising out of any action taken by you or others related to the sample application
* and source code.
*/
package com.samsung.knox.example.gettingstarted;
/**
* Provide a valid Knox Platform for Enterprise (KPE) license as a constant. This technique is used for demonstration purposes
* only.
* Consider using more secure approach for passing your license key in a commercial scenario.
* Visit https://docs.samsungknox.com/dev/common/knox-licenses.htm for details
*/
public interface Constants {
/**
* NOTE:
* There are three types of license keys available:
* - KPE Development Key
* - KPE Commercial Key - Standard
* - KPE Commercial Key - Premium
*
* The KPE Development and KPE Commercial Key - Standard can be generated from KPP while a KPE
* Commercial Key can be bought from a reseller.
*
* You can read more about how to get a licenses at:
* https://docs.samsungknox.com/dev/common/tutorial-get-a-license.htm
*
* Do not hardcode license keys in an actual commercial scenario
* TODO Implement a secure mechanism to pass KPE key to your application
*
*/
// TODO Enter the KPE Development, KPE Standard license key or KPE Premium license key
String KPE_LICENSE_KEY = "";
// TODO: Enter a backwards-compatible key
/**
* Find more information about how to use the backward-compatibility key here:
* https://docs.samsungknox.com/dev/knox-sdk/faqs/licensing/what-backwards-compatible-key.htm
*
* The button to activate the backwards compatibility key will only appear if the
* device is between Knox version 2.5 and 2.7.1 / Knox API 17 to 21
*
* For more details see:
* https://docs.samsungknox.com/dev/knox-sdk/faqs/licensing/what-backwards-compatible-key.htm
*/
String BACKWARDS_COMPATIBLE_KEY = "";
}
| 45.826087 | 126 | 0.729918 |
9e8d631de365ba0668003d19fe2233f6a3c73e5a | 1,006 | package polimorfismo;
public class ClasseDeDados {
public int ard;
public byte ord;
public long ddn;
public String variaveis;
public String getVariaveis() {
return variaveis;
}
public void setVariaveis(String variaveis){
//polimorfismo é isso um metodo que pode ter varios metodos dentro dele
if(variaveis.isEmpty()||variaveis==null||variaveis.length()<0){
this.variaveis="sem dados";
}else{
this.variaveis = variaveis;
}
}
public int getArd() {
return ard;
}
public void setArd(int ard) {
if(ard<=0){
throw new RuntimeException("a variavel não pode ser menor ou igual a 0");
}
this.ard = ard;
}
public byte getOrd() {
return ord;
}
public void setOrd(byte ord) {
this.ord = ord;
}
public long getDdn() {
return ddn;
}
public void setDdn(long ddn) {
this.ddn = ddn;
}
}
| 20.12 | 85 | 0.56163 |
8169d9538daebc33b96443a0da97f114d98ab36a | 4,967 | package fr.niware.uhcrun.world.populators;
import net.minecraft.server.v1_8_R3.ChunkSnapshot;
import net.minecraft.server.v1_8_R3.WorldGenCanyon;
import net.minecraft.server.v1_8_R3.WorldGenCaves;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.generator.BlockPopulator;
import java.util.ArrayList;
import java.util.Random;
public class OrePopulator extends BlockPopulator {
private final ArrayList<Rule> rules;
public OrePopulator() {
this.rules = new ArrayList<>();
}
private int randInt(Random rand, int min, int max) {
return rand.nextInt((max - min) + 1) + min;
}
public void addRule(Rule rule) {
if (!this.rules.contains(rule))
this.rules.add(rule);
}
@Override
public void populate(World world, Random random, Chunk chunk) {
if (chunk == null)
return;
CraftWorld handle = (CraftWorld) world;
int xr = this.randInt(random, -200, 200);
if (xr >= 50)
new WorldGenCaves().a(handle.getHandle().chunkProviderServer, handle.getHandle(), chunk.getX(), chunk.getZ(), new ChunkSnapshot());
else if (xr <= -50)
new WorldGenCanyon().a(handle.getHandle().chunkProviderServer, handle.getHandle(), chunk.getX(), chunk.getZ(), new ChunkSnapshot());
for (Rule block : this.rules) {
for (int i = 0; i < block.round; i++) {
int x = chunk.getX() * 16 + random.nextInt(16);
int y = block.minY + random.nextInt(block.maxY - block.minY);
int z = chunk.getZ() * 16 + random.nextInt(16);
this.generate(world, random, x, y, z, block.size, block);
}
}
}
private void generate(World world, Random rand, int x, int y, int z, int size, Rule material) {
double rpi = rand.nextDouble() * Math.PI;
double x1 = x + 8 + Math.sin(rpi) * size / 8.0F;
double x2 = x + 8 - Math.sin(rpi) * size / 8.0F;
double z1 = z + 8 + Math.cos(rpi) * size / 8.0F;
double z2 = z + 8 - Math.cos(rpi) * size / 8.0F;
double y1 = y + rand.nextInt(3) + 2;
double y2 = y + rand.nextInt(3) + 2;
for (int i = 0; i <= size; i++) {
double xPos = x1 + (x2 - x1) * i / size;
double yPos = y1 + (y2 - y1) * i / size;
double zPos = z1 + (z2 - z1) * i / size;
double fuzz = rand.nextDouble() * size / 16.0D;
double fuzzXZ = (Math.sin((float) (i * Math.PI / size)) + 1.0F) * fuzz + 1.0D;
double fuzzY = (Math.sin((float) (i * Math.PI / size)) + 1.0F) * fuzz + 1.0D;
int xStart = (int) Math.floor(xPos - fuzzXZ / 2.0D);
int yStart = (int) Math.floor(yPos - fuzzY / 2.0D);
int zStart = (int) Math.floor(zPos - fuzzXZ / 2.0D);
int xEnd = (int) Math.floor(xPos + fuzzXZ / 2.0D);
int yEnd = (int) Math.floor(yPos + fuzzY / 2.0D);
int zEnd = (int) Math.floor(zPos + fuzzXZ / 2.0D);
for (int ix = xStart; ix <= xEnd; ix++) {
double xThresh = (ix + 0.5D - xPos) / (fuzzXZ / 2.0D);
if (xThresh * xThresh < 1.0D) {
for (int iy = yStart; iy <= yEnd; iy++) {
double yThresh = (iy + 0.5D - yPos) / (fuzzY / 2.0D);
if (xThresh * xThresh + yThresh * yThresh < 1.0D) {
for (int iz = zStart; iz <= zEnd; iz++) {
double zThresh = (iz + 0.5D - zPos) / (fuzzXZ / 2.0D);
if (xThresh * xThresh + yThresh * yThresh + zThresh * zThresh < 1.0D) {
Block block = getBlock(world, ix, iy, iz);
if (block != null && block.getType() == Material.STONE)
block.setType(material.id);
}
}
}
}
}
}
}
}
private Block getBlock(World world, int x, int y, int z) {
int cx = x >> 4;
int cz = z >> 4;
if ((!world.isChunkLoaded(cx, cz)) && (!world.loadChunk(cx, cz, false)))
return null;
Chunk chunk = world.getChunkAt(cx, cz);
if (chunk == null)
return null;
return chunk.getBlock(x & 0xF, y, z & 0xF);
}
public static class Rule {
public Material id;
public int round;
public int minY;
public int maxY;
public int size;
public Rule(Material type, int round, int minY, int maxY, int size) {
this.id = type;
this.round = round;
this.minY = minY;
this.maxY = maxY;
this.size = size;
}
}
} | 37.067164 | 144 | 0.511576 |
bbf9713951cd424656da3945f342d256dbcf14fa | 2,002 | package com.softserveinc.ita.homeproject.api.tests.query;
import com.softserveinc.ita.homeproject.client.ApiException;
import com.softserveinc.ita.homeproject.client.api.PollQuestionApi;
import com.softserveinc.ita.homeproject.client.model.QuestionType;
import com.softserveinc.ita.homeproject.client.model.ReadQuestion;
import java.util.List;
public class PollQuestionQuery extends BaseQuery {
private Long pollId;
private PollQuestionApi pollQuestionApi;
private QuestionType type;
private Long id;
public void setType(QuestionType type){
this.type = type;
}
public void setPollQuestionApi(PollQuestionApi pollQuestionApi) {
this.pollQuestionApi = pollQuestionApi;
}
public void setId(Long id) {
this.id = id;
}
public void setPollId(Long pollId) {
this.pollId = pollId;
}
public List<ReadQuestion> perform() throws ApiException {
return pollQuestionApi
.queryQuestion(pollId, this.getPageNumber(),
this.getPageSize(),
this.getSort(),
this.getFilter(),
id,
type);
}
public static class Builder extends BaseQuery.BaseBuilder<PollQuestionQuery, PollQuestionQuery.Builder> {
public Builder(PollQuestionApi pollQuestionApi) {
queryClass.setPollQuestionApi(pollQuestionApi);
}
public PollQuestionQuery.Builder pollId(Long pollId) {
queryClass.setPollId(pollId);
return this;
}
public PollQuestionQuery.Builder type(QuestionType questionType) {
queryClass.setType(questionType);
return this;
}
@Override
protected PollQuestionQuery getActual() {
return new PollQuestionQuery();
}
@Override
protected PollQuestionQuery.Builder getActualBuilder() {
return this;
}
}
}
| 26.693333 | 109 | 0.63986 |
8bdb87ca19d8c8756aa2c92ed1cb1bd57cca7b18 | 77 | package com.api.client.auth;
public enum AuthType {
NONE, BASIC, CERT
}
| 12.833333 | 28 | 0.701299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.