id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
202361279_89 | public static void parse(Prefix prefix, QueryParameterValue parameterValue, String v) throws FHIRSearchException {
TemporalAccessor value = parse(v);
parameterValue.setValueDateLowerBound(generateLowerBound(prefix, value, v));
parameterValue.setValueDateUpperBound(generateUpperBound(prefix, value, v));
} |
202455971_4 | @Override
public void authorizeCiData(int ciTypeId, Object ciData, String action) {
if (!securityProperties.isEnabled()) {
log.warn("Security authorization is disabled.");
return;
}
String username = getCurrentUsername();
if (!isCiDataPermitted(ciTypeId, ciData, action)) {
throw new CmdbAccessDeniedException(String.format("Access denied. No %s permission on ci-type[%d] found for %s", action, ciTypeId, username));
} else {
log.info(String.format("Access granted. %s on ci-type[%d] permitted for %s", action, ciTypeId, username));
}
} |
202482196_66 | public static <T> T loadClass(String name, Class<?> clazz) {
final InputStream is = getResourceAsStream(getContextClassLoader(), name);
BufferedReader reader;
try {
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (java.io.UnsupportedEncodingException e) {
reader = new BufferedReader(new InputStreamReader(is));
}
String serviceName = reader.readLine();
reader.close();
if (serviceName != null && !"".equals(serviceName)) {
return initService(getContextClassLoader(), serviceName, clazz);
} else {
LOG.warn("ServiceName is empty!");
return null;
}
} catch (Exception e) {
LOG.error("Error occured when looking for resource file " + name, e);
}
return null;
} |
202672490_1031 | public void destroy() {
synchronized (factoryLock) {
isDestroyed = true;
MemorySegment segment;
while ((segment = availableMemorySegments.poll()) != null) {
segment.free();
}
}
} |
202839292_117 | @Override
public UpdateSchema addColumn(String name, Type type, String doc) {
Preconditions.checkArgument(!name.contains("."),
"Cannot add column with ambiguous name: %s, use addColumn(parent, name, type)", name);
return addColumn(null, name, type, doc);
} |
203282691_5 | @DeleteMapping("/{id:\\d+}") //非Get方法,会生成到GraphQL Schema的Mutation内,如果有需要写操作后也可以返回需要的字段
public Article articleDelete(@PathVariable int id) {
return articleService.delete(id, SelectionHandler.getSelections());
} |
203381991_31 | public void setSize(final int size) {
if (DEBUG >= LOG_TRACE) {
log.trace("Writing packet size field @ 0x{} + {}.", leftPad(virtualAddress), PKT_OFFSET);
}
mmanager.putIntVolatile(virtualAddress + PKT_OFFSET, size);
} |
203595784_93 | @Override
public ChangeScope<Change> getChangeScope(RevisionScope<ObjectId> revisionScope) throws SourceControlException {
final ChangeScope<Change> scope = new ChangeScopeImpl();
List<Diff> diffs = GitDiffRunner.diff(repository, revisionScope);
ObjectId toRevision = revisionScope.getTo();
diffs.forEach(throwingConsumerWrapper(d -> getChangesForDiff(d, scope, toRevision)));
return scope;
} |
203830892_17 | @Override
public boolean isEqual(T object1, T object2) {
float value1 = valueExtractor.applyAsFloat(object1);
float value2 = valueExtractor.applyAsFloat(object2);
return floatToIntBits(value1) == floatToIntBits(value2);
} |
203954530_0 | public <R> Result<R> ifSuccess(Function<T, ? extends Result<R>> function) {
if (success()) {
return function.apply(data);
}
return Result.fail(BaseResultCode.SYSTEM_ERROR);
} |
203966607_9 | public String compareTo(VersionNumber latestVersion) {
if (versionNumberArray != null) {
// Calculate max length of version number
int maxLength = Math.max(versionNumberArray.length, latestVersion.versionNumberArray.length);
for (int i = 0; i < maxLength; i++) {
int left = i < versionNumberArray.length ? versionNumberArray[i] : 0;
int right = i < latestVersion.versionNumberArray.length ? latestVersion.versionNumberArray[i] : 0;
// Compare current version & latest version
if (left != right) {
return left < right ? VersionStatus.OUTDATED.toString() : VersionStatus.AHEAD.toString();
}
}
return VersionStatus.UP_TO_DATE.toString();
}
else {
return "Nothing to compare";
}
} |
203975385_3 | public void listFile(MinioClient minioClient, String bucketName) throws XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, IOException {
try {
Iterable<Result<Item>> results = minioClient.listObjects(bucketName);
Iterator<Result<Item>> iterator = results.iterator();
while (iterator.hasNext()) {
Item item = iterator.next().get();
System.out.println(item.objectName() + ", " + item.objectSize() + "B");
}
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
}
} |
204463745_46 | @Around("execution(@org.apache.servicecomb.saga.omega.transaction.annotations.Compensable * *(..)) && @annotation(compensable)")
Object advise(ProceedingJoinPoint joinPoint, Compensable compensable) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
String localTxId = context.localTxId();
context.newLocalTxId();
LOG.debug("Updated context {} for compensable method {} ", context, method.toString());
int retries = compensable.retries();
RecoveryPolicy recoveryPolicy = RecoveryPolicyFactory.getRecoveryPolicy(retries);
try {
return recoveryPolicy.apply(joinPoint, compensable, interceptor, context, localTxId, retries);
} catch (Exception e) {
throw e;
} finally {
context.setLocalTxId(localTxId);
LOG.debug("Restored context back to {}", context);
}
} |
204591382_0 | @Override
public String exportMarkdown(String dbName, List<String> tableList) {
StringBuilder markdownBuilder = new StringBuilder();
for (String table : tableList) {
TableInfo tableInfo = treeService.oneTable(dbName, table);
List<ColumnInfo> columnInfoList = treeService.columnList(dbName, table);
markdownBuilder.append("\n\n").append("## ").append(table).append(": ").append(tableInfo.getDescription()).append("\n");
markdownBuilder.append("序号|字段名|类型|自增|可空|主键|默认值|注释").append("\n")
.append("---|---|---|---|---|---|---|---");
for (int i = 0; i < columnInfoList.size(); i++) {
ColumnInfo columnInfo = columnInfoList.get(i);
markdownBuilder.append("\n").append(i).append("|")
.append(columnInfo.getColumnName()).append("|")
.append(columnInfo.getColumnType()).append("|")
.append(columnInfo.getAutoIncrement()).append("|")
.append(columnInfo.getNullable()).append("|")
.append(columnInfo.getPrimaryKey()).append("|")
.append(columnInfo.getColumnDefault() == null ? "" : columnInfo.getColumnDefault()).append("|")
.append(columnInfo.getColumnComment());
}
}
return markdownBuilder.toString();
} |
204709060_0 | @RequestMapping("/")
public String home(){
return "Hell World!";
} |
205042001_2 | @Override
public ReturnT<String> beat() {
return ReturnT.SUCCESS;
} |
205116498_415 | protected void appendAnnotation(Class<?> annotationClass, Object annotation) {
Method[] methods = annotationClass.getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() != Object.class
&& method.getReturnType() != void.class
&& method.getParameterTypes().length == 0
&& Modifier.isPublic(method.getModifiers())
&& !Modifier.isStatic(method.getModifiers())) {
try {
String property = method.getName();
if ("interfaceClass".equals(property) || "interfaceName".equals(property)) {
property = "interface";
}
String setter = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
Object value = method.invoke(annotation);
if (value != null && !value.equals(method.getDefaultValue())) {
Class<?> parameterType = ReflectUtils.getBoxedClass(method.getReturnType());
if ("filter".equals(property) || "listener".equals(property)) {
parameterType = String.class;
value = StringUtils.join((String[]) value, ",");
} else if ("parameters".equals(property)) {
parameterType = Map.class;
value = CollectionUtils.toStringMap((String[]) value);
}
try {
Method setterMethod = getClass().getMethod(setter, parameterType);
setterMethod.invoke(this, value);
} catch (NoSuchMethodException e) {
// ignore
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
}
} |
205517727_0 | public String run(String[] args) {
// Switch Expressions
// https://openjdk.java.net/jeps/325
var result = switch (args.length) {
case 1 -> {
yield """
one...
yet pretty long!
""";
}
case 2, 3 -> "two or three";
default -> new JabelExample().new Inner().innerPublic();
};
return result;
}
// Project Coin: Allow @SafeVarargs on private methods
// https://bugs.openjdk.java.net/browse/JDK-7196160
@SafeVarargs
private String outerPrivate(List<String>... args) {
// Look, Ma! No explicit diamond parameter
var callable = new Callable<>() {
@Override
public String call() {
// Var in lambda parameter
Function<Object, String> function = (var prefix) -> {
// Pattern Matching in instanceof
// https://openjdk.java.net/jeps/305
if (prefix instanceof String s) {
return s + Integer.toString(0);
} else {
throw new IllegalArgumentException("Expected string!");
}
};
// Test indy strings
return function.apply("idk ");
}
};
var closeable = new AutoCloseable() {
@Override
public void close() {
}
};
// Project Coin: Allow final or effectively final variables to be used as resources in try-with-resources
// https://bugs.openjdk.java.net/browse/JDK-7196163
try (closeable) {
return callable.call();
}
}
class Inner {
public String innerPublic() {
// Test nest-mate
return outerPrivate();
}
}
} |
205635067_6 | public Set<String> hint(String prefix, long count) {
String key = "auto_complete:" + prefix;
return client.zrevrange(key, 0, count - 1);
} |
205733669_7 | public static float asin(float fValue) {
if (-1.0f < fValue) {
if (fValue < 1.0f) {
return (float) Math.asin(fValue);
}
return HALF_PI;
}
return -HALF_PI;
} |
205759200_0 | static String getRandomAlphanumericString(int length) {
if (length <= 0) {
return "";
}
// TODO request fewer bytes
byte[] bytes = getRandomBytes(length);
// Generate unique name from alphabet [-_a-zA-Z0-9]
byte[] encodedBytes = Base64.getUrlEncoder().withoutPadding().encode(bytes);
return new String(encodedBytes, 0, length);
} |
205782720_943 | public static Object getWritableObject(Integer type, Serializable value) {
if (value == null) {
return null;
}
if (type == null) {
if (value instanceof byte[]) {
return new String((byte[]) value);
} else if (value instanceof Number) {
return value;
}
} else if (value instanceof Number) {
return value;
} else {
if (value instanceof byte[]) {
return new String((byte[]) value);
} else {
return value.toString();
}
}
return null;
} |
205815601_211 | public byte[] getAllTopicList() {
TopicList topicList = new TopicList();
try {
try {
this.lock.readLock().lockInterruptibly();
topicList.getTopicList().addAll(this.topicQueueTable.keySet());
} finally {
this.lock.readLock().unlock();
}
} catch (Exception e) {
log.error("getAllTopicList Exception", e);
}
return topicList.encode();
} |
205819560_2 | public static Scheduler from(Looper looper) {
return from(looper, false);
} |
205889879_2 | public static boolean hasIllegalChar(CharSequence fileName) {
Pattern pattern = Pattern.compile("[^a-zA-Z0-9.\\- ]");
Matcher matcher = pattern.matcher(fileName);
return matcher.find();
} |
206005266_15 | public static LogSequenceNumber valueOf(long value) {
return new LogSequenceNumber(value);
} |
206101640_11 | public ResponseEntity<IResponse> getAddresses(GetHistoryAddressesRequest getHistoryAddressesRequest) {
try {
if (!getHistoryAddressesRequestCrypto.verifySignature(getHistoryAddressesRequest)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new SerializableResponse(INVALID_SIGNATURE, STATUS_ERROR));
}
List<Hash> addressesHashesToGetFromStorage = new ArrayList<>(getHistoryAddressesRequest.getAddressHashes());
HashMap<Hash, AddressData> addressToAddressDataFromDB = populateAndRemoveFoundAddresses(addressesHashesToGetFromStorage);
Map<Hash, AddressData> getHistoryAddressesResponseMap;
if (!addressesHashesToGetFromStorage.isEmpty()) {
GetHistoryAddressesResponse getHistoryAddressesResponseFromStorageNode = getAddressesFromStorage(addressesHashesToGetFromStorage);
Optional<ResponseEntity<IResponse>> responseValidationResult = validateStorageResponse(getHistoryAddressesResponseFromStorageNode);
if (responseValidationResult.isPresent()) {
return responseValidationResult.get()
getHistoryAddressesResponseMap = addressToAddressDataFromDB;
} else {
Map<Hash, AddressData> addressHashesToAddressesFromStorage = getHistoryAddressesResponseFromStorageNode.getAddressHashesToAddresses();
getHistoryAddressesResponseMap = reorderHashResponses(getHistoryAddressesRequest.getAddressHashes(), addressToAddressDataFromDB, addressHashesToAddressesFromStorage);
}
} else {
getHistoryAddressesResponseMap = addressToAddressDataFromDB;
}
GetHistoryAddressesResponse getHistoryAddressesResponseToFullNode = new GetHistoryAddressesResponse(getHistoryAddressesResponseMap);
getHistoryAddressesResponseCrypto.signMessage(getHistoryAddressesResponseToFullNode);
return ResponseEntity.
status(HttpStatus.OK).
body(getHistoryAddressesResponseToFullNode);
} catch (HttpClientErrorException | HttpServerErrorException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new SerializableResponse(String.format(STORAGE_ADDRESS_ERROR, ((SerializableResponse) jacksonSerializer.deserialize(e.getResponseBodyAsByteArray())).getMessage()), STATUS_ERROR));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new SerializableResponse(e.getMessage(), STATUS_ERROR));
}
} |
206137428_4 | public Iterable<Member> successors(HashKey location, Predicate<Member> predicate) {
Iterator<Member> tail = ring.tailMap(location, false).values().iterator();
Iterator<Member> head = ring.headMap(location, false).values().iterator();
Iterator<Member> iterator = new Iterator<Member>() {
private Member next = nextMember();
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Member next() {
if (next == null) {
throw new NoSuchElementException();
}
Member current = next;
next = nextMember();
return current;
}
private Member nextMember() {
while (tail.hasNext()) {
Member next = tail.next();
return predicate.test(next) ? null : next;
}
while (head.hasNext()) {
Member next = head.next();
return predicate.test(next) ? null : next;
}
return null;
}
};
return new Iterable<Member>() {
@Override
public Iterator<Member> iterator() {
return iterator;
}
};
} |
206303197_1 | @Override
public String resolve(String parameter) {
return resolvers.stream()
.map(benchConfigurationResolver -> benchConfigurationResolver.resolve(parameter))
.filter(Objects::nonNull)
.findFirst().orElse(null);
} |
206414745_690 | public static Set<EnodeURL> fromPath(
final Path path, final EnodeDnsConfiguration enodeDnsConfiguration)
throws IOException, IllegalArgumentException {
try {
return readEnodesFromPath(path, enodeDnsConfiguration);
} catch (FileNotFoundException | NoSuchFileException ex) {
LOG.info("StaticNodes file {} does not exist, no static connections will be created.", path);
return emptySet();
} catch (IOException ex) {
LOG.info("Unable to parse static nodes file ({})", path);
throw ex;
} catch (DecodeException ex) {
LOG.info("Content of ({}} was invalid json, and could not be decoded.", path);
throw ex;
} catch (IllegalArgumentException ex) {
LOG.info("Parsing ({}) has failed due incorrectly formatted enode element.", path);
throw ex;
}
} |
206574671_3 | public static boolean percentage(double percent) {
return Math.random() <= percent * 0.01;
} |
206662517_4 | public String[] generateCodes(int amount) {
// Must generate at least one code
if (amount < 1) {
throw new InvalidParameterException("Amount must be at least 1.");
}
// Create an array and fill with generated codes
String[] codes = new String[amount];
Arrays.setAll(codes, i -> generateCode());
return codes;
} |
206738246_0 | @Transactional(REQUIRED)
Hero add(final String legumeItem) {
log.info("Legume received: {}", legumeItem);
final Hero hero = Hero.builder()
.name("SUPER-" + legumeItem)
.capeType(CapeType.SUPERMAN)
.build();
final Hero createdHero = entityManager.merge(hero);
log.info("hero created: {}", createdHero);
return createdHero;
} |
206873260_1 | @NonNull
public TextMarkdown parse(@NonNull final String string) {
List<Element> parents = new ArrayList<>();
Pattern quotePattern = Pattern.compile(QUOTE_REGEX);
Pattern pattern = Pattern.compile(BULLET_POINT_CODE_BLOCK_REGEX);
Matcher matcher = quotePattern.matcher(string);
int lastStartIndex = 0;
while (matcher.find(lastStartIndex)) {
int startIndex = matcher.start();
int endIndex = matcher.end();
// we found a quote
if (lastStartIndex < startIndex) {
// check what was before the quote
String text = string.substring(lastStartIndex, startIndex);
parents.addAll(findElements(text, pattern));
}
// a quote can only be a paragraph long, so look for end of line
int endOfQuote = getEndOfParagraph(string, endIndex);
lastStartIndex = endOfQuote;
String quotedText = string.substring(endIndex, endOfQuote);
parents.add(new Element(Type.QUOTE, quotedText, Collections.<Element>emptyList()));
}
// check if there are any other element after the quote
if (lastStartIndex < string.length()) {
String text = string.substring(lastStartIndex, string.length());
parents.addAll(findElements(text, pattern));
}
return new TextMarkdown(parents);
} |
207067400_0 | @GetMapping("/restaurants")
public List<Restaurant> list(
@RequestParam("region") String region,
@RequestParam("category") Long categoryId
) {
List<Restaurant> restaurants =
restaurantService.getRestaurants(region, categoryId);
return restaurants;
} |
207384523_56 | private static void setAttrShape(TF_OperationDescription handle, String name, long[] shape, int numDims) {
requireHandle(handle);
// num_dims and env->GetArrayLength(shape) are assumed to be consistent.
// i.e., either num_dims < 0 or num_dims == env->GetArrayLength(shape).
TF_SetAttrShape(handle, name, shape, numDims);
} |
207457953_1127 | @Override
public void heartbeatFromTaskManager(final ResourceID resourceID, AccumulatorReport accumulatorReport) {
taskManagerHeartbeatManager.receiveHeartbeat(resourceID, accumulatorReport);
} |
207497806_29 | public UpdateResult updateFields(String originalJsonObject, JsonNode jsonToUpdate, String attrId)
throws Exception, ResponseException {
logger.trace("updateFields() :: started");
String now = SerializationTools.formatter.format(Instant.now());
JsonNode resultJson = objectMapper.createObjectNode();
UpdateResult updateResult = new UpdateResult(jsonToUpdate, resultJson);
JsonNode node = objectMapper.readTree(originalJsonObject);
ObjectNode objectNode = (ObjectNode) node;
if (attrId != null) {
if (objectNode.get(attrId) == null) {
throw new ResponseException(ErrorType.NotFound, "Provided attribute is not present");
}
JsonNode originalNode = ((ArrayNode) objectNode.get(attrId)).get(0);
if (((ObjectNode) originalNode).has(NGSIConstants.NGSI_LD_INSTANCE_ID)) {
((ObjectNode) originalNode).remove(NGSIConstants.NGSI_LD_INSTANCE_ID);
}
JsonNode innerNode = ((ArrayNode) objectNode.get(attrId));
ArrayNode myArray = (ArrayNode) innerNode;
String availableDatasetId = null;
for (int i = 0; i < myArray.size(); i++) {
if (myArray.get(i).has(NGSIConstants.NGSI_LD_DATA_SET_ID)) {
String payloadDatasetId = myArray.get(i).get(NGSIConstants.NGSI_LD_DATA_SET_ID).get(0)
.get(NGSIConstants.JSON_LD_ID).asText();
if (jsonToUpdate.has(NGSIConstants.NGSI_LD_DATA_SET_ID)) {
String datasetId = jsonToUpdate.get(NGSIConstants.NGSI_LD_DATA_SET_ID).get(0)
.get(NGSIConstants.JSON_LD_ID).asText();
if (payloadDatasetId.equalsIgnoreCase(datasetId)) {
availableDatasetId = "available";
setFieldValue(jsonToUpdate.fieldNames(), ((ArrayNode) objectNode.get(attrId)), jsonToUpdate,
updateResult, i);
}
} else {
if (payloadDatasetId.equals(NGSIConstants.DEFAULT_DATA_SET_ID)) {
setFieldValue(jsonToUpdate.fieldNames(), ((ArrayNode) objectNode.get(attrId)), jsonToUpdate,
updateResult, i);
}
}
} else {
if (jsonToUpdate.has(NGSIConstants.NGSI_LD_DATA_SET_ID)) {
((ObjectNode) innerNode.get(i)).putArray(NGSIConstants.NGSI_LD_DATA_SET_ID).addObject()
.put(NGSIConstants.JSON_LD_ID, NGSIConstants.DEFAULT_DATA_SET_ID);
} else {
((ObjectNode) innerNode.get(i)).putArray(NGSIConstants.NGSI_LD_DATA_SET_ID).addObject()
.put(NGSIConstants.JSON_LD_ID, NGSIConstants.DEFAULT_DATA_SET_ID);
setFieldValue(jsonToUpdate.fieldNames(), ((ArrayNode) objectNode.get(attrId)), jsonToUpdate,
updateResult, i);
}
}
}
if (jsonToUpdate.has(NGSIConstants.NGSI_LD_DATA_SET_ID)) {
if ((availableDatasetId == null) || (availableDatasetId.isEmpty())) {
throw new ResponseException(ErrorType.NotFound, "Provided datasetId is not present");
}
}
} else {
Iterator<String> it = jsonToUpdate.fieldNames();
while (it.hasNext()) {
String field = it.next();
// TOP level updates of context id or type are ignored
if (field.equalsIgnoreCase(NGSIConstants.JSON_LD_CONTEXT)
|| field.equalsIgnoreCase(NGSIConstants.JSON_LD_ID)
|| field.equalsIgnoreCase(NGSIConstants.JSON_LD_TYPE)) {
continue;
}
logger.trace("field: " + field);
if (node.has(field)) {
JsonNode originalNode = ((ArrayNode) objectNode.get(field)).get(0);
JsonNode attrNode = jsonToUpdate.get(field).get(0);
String createdAt = now;
// keep original createdAt value if present in the original json
if ((originalNode instanceof ObjectNode)
&& ((ObjectNode) originalNode).has(NGSIConstants.NGSI_LD_CREATED_AT)
&& ((ObjectNode) originalNode).get(NGSIConstants.NGSI_LD_CREATED_AT).isArray()) {
createdAt = ((ObjectNode) ((ObjectNode) originalNode).get(NGSIConstants.NGSI_LD_CREATED_AT)
.get(0)).get(NGSIConstants.JSON_LD_VALUE).asText();
}
setTemporalProperties(attrNode, createdAt, now, true);
// TODO check if this should ever happen. 5.6.4.4 says BadRequest if AttrId is
// present ...
objectNode.replace(field, jsonToUpdate.get(field));
((ObjectNode) updateResult.getAppendedJsonFields()).set(field, jsonToUpdate.get(field));
logger.trace("appended json fields: " + updateResult.getAppendedJsonFields().toString());
updateResult.setStatus(true);
} else {
// throw new ResponseException(ErrorType.NotFound);
}
}
}
setTemporalProperties(node, "", now, true); // root only, modifiedAt only
updateResult.setJson(node.toString().getBytes(NGSIConstants.ENCODE_FORMAT));
updateResult.setFinalNode(node);
removeTemporalProperties(node);
updateResult.setJsonWithoutSysAttrs(node.toString().getBytes(NGSIConstants.ENCODE_FORMAT));
logger.trace("updateFields() :: completed");
return updateResult;
} |
207567112_5 | @RequestMapping(value = {"/greeting/{name}", "/greeting"})
Greeting greeting(@PathVariable(required = false) String name) {
String object = name != null ? name : "world";
/* Jack Griffin is the name of the "Invisible Man." */
if (object.equalsIgnoreCase("jack griffin")) {
return new Greeting("I don't know who you are.");
} else {
return new Greeting("Hello, " + object + "!");
}
} |
207726223_11 | @Override
protected Object encode(ChannelHandlerContext ctx,
Channel channel, Object msg) throws Exception {
RpcDataPack dataPack = (RpcDataPack) msg;
List<ByteBuffer> origs = dataPack.getDataLst();
List<ByteBuffer> bbs = new ArrayList<ByteBuffer>(origs.size() * 2 + 1);
bbs.add(getPackHeader(dataPack));
for (ByteBuffer b : origs) {
bbs.add(getLengthHeader(b));
bbs.add(b);
}
return ChannelBuffers.wrappedBuffer(bbs.toArray(new ByteBuffer[bbs.size()]));
} |
207792901_0 | @Override
public Map<String, ? extends DataCollection> initialize(Map<String, ? extends CollectionModel> models, Map<String, ? extends DataCollection> collections) throws Exception {
Map<Class<?>, Type<?>> types = new HashMap<>();
types.put(UUID.class, UUIDType.UUID_TYPE);
types.put(String.class, StringType.STRING_TYPE);
types.put(Integer.class, IntType.INT_TYPE);
types.put(int.class, IntType.INT_TYPE);
EntityTableLoader entityTableLoader = new EntityTableLoader(this, types);
Map<String, Table> entityTables = entityTableLoader.loadModels(models, collections);
RemoteTableLoader remoteTableLoader = new RemoteTableLoader();
Map<String, Table> remoteTables = remoteTableLoader.loadTables();
System.out.println("Generated handlers for tables: ");
entityTables.forEach((name, table) -> tables.put(name, new TableHandler<>(this, table)));
tables.values().forEach(System.out::println);
try (Connection connection = dataSource.getConnection()) {
compare(entityTables, remoteTables, connection);
SqlUtils.consume(connection, "SHOW TABLES;", result -> System.out.println("Remote table: " + result.getString("table_name")));
}
return collections;
} |
207822084_5 | @Override
public final TreeMap<String, String> getParameters() {
TreeMap<String, String> parameters = new TreeMap<>();
if (requestType.equals(PDGuardRequestType.ENCRYPTION)) {
if (authBundle instanceof EncryptionBundle) {
parameters.put("data_provenance", ((EncryptionBundle)
authBundle).getDataProvenance().toString());
parameters.put("update", String.valueOf(((EncryptionBundle)
authBundle).isUpdate()));
} else
throw new RuntimeException();
} else {
if (authBundle instanceof DecryptionBundle) {
parameters.put("data_use", ((DecryptionBundle) authBundle)
.getDataUse().toString());
parameters.put("interaction_purpose", ((DecryptionBundle)
authBundle).getInteractionPurpose().toString());
} else
throw new RuntimeException();
}
parameters.put("client_id", clientCredentials.getClientId());
parameters.put("timestamp", String.valueOf(getTimeStamp()));
parameters.put("nonce", getNonce());
parameters.put("request_token", requestToken.getRequestToken());
parameters.put("data_type", authBundle.getDataType().toString());
parameters.put("request_type", requestType.toString());
return parameters;
} |
208015762_1 | public static <T, M> T getOrLoadExtension(final Class<T> extensible, final M name) {
ExtensionPoint<T, M> spi = SNAPSHOT.getOrLoadExtensionPoint(extensible, null, AscendingComparator.INSTANCE, null);
return spi == null ? null : spi.get(name);
} |
208221849_0 | @Transactional
@DeleteMapping("/{id}")
@PreAuthorize("@securityService.hasAnyRole('ROLE_ADMINISTRATOR,ROLE_DEVELOPER')")
public String delete(Model model, @PathVariable("id") String id, RedirectAttributes redirect) {
final Ontology ontology = ontologyConfigService.getOntologyById(id, utils.getUserId());
if (ontology != null) {
try {
if (ontology.getOntologyKPI() != null) {
ontologyKPIService.unscheduleKpi(ontology.getOntologyKPI());
}
ontologyBusinessService.deleteOntology(id, utils.getUserId());
} catch (final Exception e) {
if (e.getCause() instanceof ConstraintViolationException) {
String apis = "";
String iotClients = "";
for (final Api api : apiRepository.findByOntology(ontology)) {
apis = apis + api.getIdentification() + " ";
}
for (final ClientPlatformOntology cpo : clientPlatformOntologyRepository.findByOntology(ontology)) {
iotClients = iotClients + cpo.getClientPlatform().getIdentification() + " ";
}
if (apis.equals("") && iotClients.equals(""))
utils.addRedirectMessageWithParam(ONT_DEL_ERROR,
"Cannot delete an ontology with attached elements", redirect);
else
utils.addRedirectMessageWithParam(ONT_DEL_ERROR,
"Cannot delete an ontology with attached elements:\n -API: " + apis + "\n"
+ "-IoTClient: " + iotClients,
redirect);
} else {
utils.addRedirectMessageWithParam(ONT_DEL_ERROR, e.getMessage(), redirect);
}
log.error("Error deleting ontology. ", e);
return "redirect:/ontologies/update/" + id;
}
return REDIRECT_ONTOLOGIES_LIST;
} else {
return REDIRECT_ONTOLOGIES_LIST;
}
} |
208317627_38 | protected List<JarEntry> extractEntries(final JarFile jarFile) {
final List<JarEntry> result = new ArrayList<>();
if (jarFile != null) {
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry e = entries.nextElement();
if (!e.isDirectory() && e.getName().endsWith(".class")) {
result.add(e);
}
}
}
return result;
} |
208319207_11 | static void writeHostPrefix(GenerationContext context, OperationShape operation) {
TypeScriptWriter writer = context.getWriter();
SymbolProvider symbolProvider = context.getSymbolProvider();
EndpointTrait trait = operation.getTrait(EndpointTrait.class).get();
writer.write("let { hostname: resolvedHostname } = await context.endpoint();");
// Check if disableHostPrefixInjection has been set to true at runtime
writer.openBlock("if (context.disableHostPrefix !== true) {", "}", () -> {
writer.addImport("isValidHostname", "__isValidHostname",
TypeScriptDependency.AWS_SDK_PROTOCOL_HTTP.packageName);
writer.write("resolvedHostname = $S + resolvedHostname;", trait.getHostPrefix().toString());
List<SmithyPattern.Segment> prefixLabels = trait.getHostPrefix().getLabels();
StructureShape inputShape = context.getModel().expectShape(operation.getInput()
.get(), StructureShape.class);
for (SmithyPattern.Segment label : prefixLabels) {
MemberShape member = inputShape.getMember(label.getContent()).get();
String memberName = symbolProvider.toMemberName(member);
writer.openBlock("if (input.$L === undefined) {", "}", memberName, () -> {
writer.write("throw new Error('Empty value provided for input host prefix: $L.');", memberName);
});
writer.write("resolvedHostname = resolvedHostname.replace(\"{$L}\", input.$L!)",
label.getContent(), memberName);
}
writer.openBlock("if (!__isValidHostname(resolvedHostname)) {", "}", () -> {
writer.write("throw new Error(\"ValidationError: prefixed hostname must be hostname compatible.\");");
});
});
} |
208556644_10 | public RuntimeException unwrapped() {
Throwable cause = exception.getCause();
if (cause instanceof RuntimeException) {
return (RuntimeException) cause;
}
if (cause == null) {
return new IllegalStateException(exception.getMessage());
}
return new IllegalStateException(cause);
} |
208698479_12 | @Override
public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws Exception {
switch (request.getCode()) {
case DeFiBusRequestCode.GET_CONSUMER_LIST_BY_GROUP_AND_TOPIC:
return getConsumerListByGroupAndTopic(ctx, request);
default:
break;
}
return null;
} |
209012030_0 | @Override
public DockerCatalogResp catalog(String registry, Integer number) {
return DockerImageHubClient.getInstance(registry).catalog(number);
} |
209076507_85 | public static SchemaVersionRange parse(String versionStr) {
versionStr = StringUtils.stripToNull(versionStr);
Validate.notNull(versionStr, "Version string is blank");
if (isVersionStr(versionStr)) {
return parseVersionStr(versionStr);
} else if (isVersionRangeStr(versionStr)) {
return parseVersionRangeStr(versionStr);
} else {
throw new IllegalArgumentException(String.format("Invalid version string %s", versionStr));
}
} |
209204932_7 | public void parsePayload(final BinlogContext binlogContext, final ByteBuf in) {
int columnsLength = (int) DataTypesCodec.readLengthCodedIntLE(in);
columnsPresentBitmap = DataTypesCodec.readBitmap(columnsLength, in);
if (EventTypes.UPDATE_ROWS_EVENT_V1 == binlogEventHeader.getTypeCode()
|| EventTypes.UPDATE_ROWS_EVENT_V2 == binlogEventHeader.getTypeCode()) {
columnsPresentBitmap2 = DataTypesCodec.readBitmap(columnsLength, in);
}
ColumnDef[] columnDefs = binlogContext.getColumnDefs(tableId);
while (in.isReadable()) {
//TODO support minimal binlog row image
BitSet nullBitmap = DataTypesCodec.readBitmap(columnsLength, in);
Serializable[] columnValues = new Serializable[columnsLength];
for (int i = 0; i < columnsLength; i++) {
if (!nullBitmap.get(i)) {
columnValues[i] = decodeValue(columnDefs[i], in);
} else {
columnValues[i] = null;
}
}
columnValues1.add(columnValues);
if (EventTypes.UPDATE_ROWS_EVENT_V1 == binlogEventHeader.getTypeCode()
|| EventTypes.UPDATE_ROWS_EVENT_V2 == binlogEventHeader.getTypeCode()) {
nullBitmap = DataTypesCodec.readBitmap(columnsLength, in);
columnValues = new Serializable[columnsLength];
for (int i = 0; i < columnsLength; i++) {
if (!nullBitmap.get(i)) {
columnValues[i] = decodeValue(columnDefs[i], in);
} else {
columnValues[i] = null;
}
}
columnValues2.add(columnValues);
}
}
} |
209392510_23 | public void init() {
try {
this.createSubscriptions();
} catch (Exception e) {
LOG.error("Error on try to create subscription", e);
throw e;
}
} |
209484041_160 | public void dataChanged(@UserIdInt int userId, String packageName) {
UserBackupManagerService userBackupManagerService =
getServiceForUserIfCallerHasPermission(userId, "dataChanged()");
if (userBackupManagerService != null) {
userBackupManagerService.dataChanged(packageName);
}
} |
209677008_4 | public String getGreeting() {
return "[SMTP Client] Welcome to SMTP Client.";
} |
209731679_7 | @Nonnull
@Override
public Set<ImmutableGroup> getChildren() {
return children;
} |
209775117_0 | public void setType(String type) {
this.type = type;
} |
209813646_10 | @NotNull
public static <T> ReferencedOptional<T> filterToReference(@NotNull Collection<T> in, @NotNull Predicate<T> predicate) {
return ReferencedOptional.build(filter(in, predicate));
} |
209854470_7 | @GetMapping(value = "/list")
public String list(Model model) {
logger.info("Populating model with list...");
List<Person> persons = personService.findAll();
persons.sort(COMPARATOR_BY_ID);
model.addAttribute("persons", persons);
return "persons/list";
} |
210029529_0 | static <K> Comparator<K> create0(DependencyGraph<K> dependencyGraph,
Map<String, AtomicLong> historicalServiceTimes,
Function<K, String> toKey) {
final long defaultServiceTime = average(historicalServiceTimes.values());
final Map<K, Long> serviceTimes = new HashMap<>();
final Set<K> rootProjects = new HashSet<>();
dependencyGraph.getProjects().forEach(project -> {
long serviceTime = getServiceTime(historicalServiceTimes, project, defaultServiceTime, toKey);
serviceTimes.put(project, serviceTime);
if (dependencyGraph.isRoot(project)) {
rootProjects.add(project);
}
});
final Map<K, Long> projectWeights = calculateWeights(dependencyGraph, serviceTimes, rootProjects);
return Comparator.comparingLong((ToLongFunction<K>) projectWeights::get)
.thenComparing(toKey, String::compareTo)
.reversed();
} |
210288653_100 | public static String normalizePath(final String path) {
return path.replace('\\', SEPARATORCHAR);
} |
210292685_59 | @Override
public double calculate(TimeSeries series, TradingRecord tradingRecord) {
int nTicks = 0;
for (Trade trade : tradingRecord.getTrades()) {
nTicks += calculate(series, trade);
}
return nTicks;
} |
210568703_68 | @Override
public int compare(final MemoryResultSetRow o1, final MemoryResultSetRow o2) {
if (!selectStatement.getOrderByItems().isEmpty()) {
return compare(o1, o2, selectStatement.getOrderByItems());
}
return compare(o1, o2, selectStatement.getGroupByItems());
} |
210579021_291 | protected Object[] writeToTable( IRowMeta rowMeta, Object[] r ) throws HopException {
if ( r == null ) { // Stop: last line or error encountered
if ( log.isDetailed() ) {
logDetailed( "Last line inserted: stop" );
}
return null;
}
PreparedStatement insertStatement = null;
Object[] insertRowData;
Object[] outputRowData = r;
String tableName = null;
boolean sendToErrorRow = false;
String errorMessage = null;
boolean rowIsSafe = false;
int[] updateCounts = null;
List<Exception> exceptionsList = null;
boolean batchProblem = false;
Object generatedKey = null;
if ( meta.isTableNameInField() ) {
// Cache the position of the table name field
if ( data.indexOfTableNameField < 0 ) {
String realTablename = environmentSubstitute( meta.getTableNameField() );
data.indexOfTableNameField = rowMeta.indexOfValue( realTablename );
if ( data.indexOfTableNameField < 0 ) {
String message = "Unable to find table name field [" + realTablename + "] in input row";
logError( message );
throw new HopTransformException( message );
}
if ( !meta.isTableNameInTable() && !meta.specifyFields() ) {
data.insertRowMeta.removeValueMeta( data.indexOfTableNameField );
}
}
tableName = rowMeta.getString( r, data.indexOfTableNameField );
if ( !meta.isTableNameInTable() && !meta.specifyFields() ) {
// If the name of the table should not be inserted itself, remove the table name
// from the input row data as well. This forcibly creates a copy of r
//
insertRowData = RowDataUtil.removeItem( rowMeta.cloneRow( r ), data.indexOfTableNameField );
} else {
insertRowData = r;
}
} else if ( meta.isPartitioningEnabled()
&& ( meta.isPartitioningDaily() || meta.isPartitioningMonthly() )
&& ( meta.getPartitioningField() != null && meta.getPartitioningField().length() > 0 ) ) {
// Initialize some stuff!
if ( data.indexOfPartitioningField < 0 ) {
data.indexOfPartitioningField =
rowMeta.indexOfValue( environmentSubstitute( meta.getPartitioningField() ) );
if ( data.indexOfPartitioningField < 0 ) {
throw new HopTransformException( "Unable to find field ["
+ meta.getPartitioningField() + "] in the input row!" );
}
if ( meta.isPartitioningDaily() ) {
data.dateFormater = new SimpleDateFormat( "yyyyMMdd" );
} else {
data.dateFormater = new SimpleDateFormat( "yyyyMM" );
}
}
IValueMeta partitioningValue = rowMeta.getValueMeta( data.indexOfPartitioningField );
if ( !partitioningValue.isDate() || r[ data.indexOfPartitioningField ] == null ) {
throw new HopTransformException(
"Sorry, the partitioning field needs to contain a data value and can't be empty!" );
}
Object partitioningValueData = rowMeta.getDate( r, data.indexOfPartitioningField );
tableName =
environmentSubstitute( meta.getTableName() )
+ "_" + data.dateFormater.format( (Date) partitioningValueData );
insertRowData = r;
} else {
tableName = data.tableName;
insertRowData = r;
}
if ( meta.specifyFields() ) {
//
// The values to insert are those in the fields sections
//
insertRowData = new Object[ data.valuenrs.length ];
for ( int idx = 0; idx < data.valuenrs.length; idx++ ) {
insertRowData[ idx ] = r[ data.valuenrs[ idx ] ];
}
}
if ( Utils.isEmpty( tableName ) ) {
throw new HopTransformException( "The tablename is not defined (empty)" );
}
insertStatement = data.preparedStatements.get( tableName );
if ( insertStatement == null ) {
String sql =
data.db
.getInsertStatement( environmentSubstitute( meta.getSchemaName() ), tableName, data.insertRowMeta );
if ( log.isDetailed() ) {
logDetailed( "Prepared statement : " + sql );
}
insertStatement = data.db.prepareSql( sql, meta.isReturningGeneratedKeys() );
data.preparedStatements.put( tableName, insertStatement );
}
try {
// For PG & GP, we add a savepoint before the row.
// Then revert to the savepoint afterwards... (not a transaction, so hopefully still fast)
//
if ( data.useSafePoints ) {
data.savepoint = data.db.setSavepoint();
}
data.db.setValues( data.insertRowMeta, insertRowData, insertStatement );
data.db.insertRow( insertStatement, data.batchMode, false ); // false: no commit, it is handled in this transform differently
if ( isRowLevel() ) {
logRowlevel( "Written row: " + data.insertRowMeta.getString( insertRowData ) );
}
// Get a commit counter per prepared statement to keep track of separate tables, etc.
//
Integer commitCounter = data.commitCounterMap.get( tableName );
if ( commitCounter == null ) {
commitCounter = Integer.valueOf( 1 );
} else {
commitCounter++;
}
data.commitCounterMap.put( tableName, Integer.valueOf( commitCounter.intValue() ) );
// Release the savepoint if needed
//
if ( data.useSafePoints ) {
if ( data.releaseSavepoint ) {
data.db.releaseSavepoint( data.savepoint );
}
}
// Perform a commit if needed
//
if ( ( data.commitSize > 0 ) && ( ( commitCounter % data.commitSize ) == 0 ) ) {
if ( data.db.getUseBatchInsert( data.batchMode ) ) {
try {
insertStatement.executeBatch();
data.db.commit();
insertStatement.clearBatch();
} catch ( SQLException ex ) {
throw Database.createHopDatabaseBatchException( "Error updating batch", ex );
} catch ( Exception ex ) {
throw new HopDatabaseException( "Unexpected error inserting row", ex );
}
} else {
// insertRow normal commit
data.db.commit();
}
// Clear the batch/commit counter...
//
data.commitCounterMap.put( tableName, Integer.valueOf( 0 ) );
rowIsSafe = true;
} else {
rowIsSafe = false;
}
// See if we need to get back the keys as well...
if ( meta.isReturningGeneratedKeys() ) {
RowMetaAndData extraKeys = data.db.getGeneratedKeys( insertStatement );
if ( extraKeys.getRowMeta().size() > 0 ) {
// Send out the good word!
// Only 1 key at the moment. (should be enough for now :-)
generatedKey = extraKeys.getRowMeta().getInteger( extraKeys.getData(), 0 );
} else {
// we have to throw something here, else we don't know what the
// type is of the returned key(s) and we would violate our own rule
// that a hop should always contain rows of the same type.
throw new HopTransformException( "No generated keys while \"return generated keys\" is active!" );
}
}
} catch ( HopDatabaseBatchException be ) {
errorMessage = be.toString();
batchProblem = true;
sendToErrorRow = true;
updateCounts = be.getUpdateCounts();
exceptionsList = be.getExceptionsList();
if ( getTransformMeta().isDoingErrorHandling() ) {
data.db.clearBatch( insertStatement );
data.db.commit( true );
} else {
data.db.clearBatch( insertStatement );
data.db.rollback();
StringBuilder msg = new StringBuilder( "Error batch inserting rows into table [" + tableName + "]." );
msg.append( Const.CR );
msg.append( "Errors encountered (first 10):" ).append( Const.CR );
for ( int x = 0; x < be.getExceptionsList().size() && x < 10; x++ ) {
Exception exception = be.getExceptionsList().get( x );
if ( exception.getMessage() != null ) {
msg.append( exception.getMessage() ).append( Const.CR );
}
}
throw new HopException( msg.toString(), be );
}
} catch ( HopDatabaseException dbe ) {
if ( getTransformMeta().isDoingErrorHandling() ) {
if ( isRowLevel() ) {
logRowlevel( "Written row to error handling : " + getInputRowMeta().getString( r ) );
}
if ( data.useSafePoints ) {
data.db.rollback( data.savepoint );
if ( data.releaseSavepoint ) {
data.db.releaseSavepoint( data.savepoint );
}
// data.db.commit(true); // force a commit on the connection too.
}
sendToErrorRow = true;
errorMessage = dbe.toString();
} else {
if ( meta.ignoreErrors() ) {
if ( data.warnings < 20 ) {
if ( log.isBasic() ) {
logBasic( "WARNING: Couldn't insert row into table: "
+ rowMeta.getString( r ) + Const.CR + dbe.getMessage() );
}
} else if ( data.warnings == 20 ) {
if ( log.isBasic() ) {
logBasic( "FINAL WARNING (no more then 20 displayed): Couldn't insert row into table: "
+ rowMeta.getString( r ) + Const.CR + dbe.getMessage() );
}
}
data.warnings++;
} else {
setErrors( getErrors() + 1 );
data.db.rollback();
throw new HopException( "Error inserting row into table ["
+ tableName + "] with values: " + rowMeta.getString( r ), dbe );
}
}
}
// We need to add a key
if ( generatedKey != null ) {
outputRowData = RowDataUtil.addValueData( outputRowData, rowMeta.size(), generatedKey );
}
if ( data.batchMode ) {
if ( sendToErrorRow ) {
if ( batchProblem ) {
data.batchBuffer.add( outputRowData );
outputRowData = null;
processBatchException( errorMessage, updateCounts, exceptionsList );
} else {
// Simply add this row to the error row
putError( rowMeta, r, 1L, errorMessage, null, "TOP001" );
outputRowData = null;
}
} else {
data.batchBuffer.add( outputRowData );
outputRowData = null;
if ( rowIsSafe ) { // A commit was done and the rows are all safe (no error)
for ( int i = 0; i < data.batchBuffer.size(); i++ ) {
Object[] row = data.batchBuffer.get( i );
putRow( data.outputRowMeta, row );
incrementLinesOutput();
}
// Clear the buffer
data.batchBuffer.clear();
}
}
} else {
if ( sendToErrorRow ) {
putError( rowMeta, r, 1, errorMessage, null, "TOP001" );
outputRowData = null;
}
}
return outputRowData;
} |
210933087_17 | public String getName() {
return slf4jLogger.getName();
} |
210939728_0 | public List<T> absent() {
if (this.configured.isEmpty()) {
return Collections.emptyList();
}
Collection<T> existing = this.existing.get();
return Collections.unmodifiableList(
this.configured
.stream()
.filter(c -> existing.stream().noneMatch(e -> isEqual.test(c, e)))
.collect(Collectors.toList())
);
} |
211090195_79 | public Caption deserialize(JSONObject response) throws JSONException {
Caption caption = new Caption();
if (response.has("uri")) {
caption.setUri(response.getString("uri"));
}
if (response.has("src")) {
caption.setSrc(response.getString("src"));
}
if (response.has("srclang")) {
caption.setSrclang(response.getString("srclang"));
}
if (response.has("default")) {
caption.setDefaut(response.getBoolean("default"));
}
return caption;
} |
211099032_1 | public static Result calculate(Graph graph) {
TraceTraversal<Vertex, Vertex> leafs = graph.traversal(TraceTraversalSource.class).leafSpans();
// service to its dependencies
Map<String, Set<String>> dependencies = new LinkedHashMap<>();
// service to its parents
Map<String, Set<String>> parents = new LinkedHashMap<>();
while (leafs.hasNext()) {
Vertex node = leafs.next();
Vertex parent = Util.parent(node);
Span nodeSpan = GraphCreator.toSpan(node);
while (parent != null) {
Span parentSpan = GraphCreator.toSpan(parent);
if (!nodeSpan.serviceName.equals(parentSpan.serviceName)) {
Set<String> d = dependencies.get(parentSpan.serviceName);
if (d == null) {
d = new LinkedHashSet<>();
dependencies.put(parentSpan.serviceName, d);
}
d.add(nodeSpan.serviceName);
Set<String> p = parents.get(nodeSpan.serviceName);
if (p == null) {
p = new LinkedHashSet<>();
parents.put(nodeSpan.serviceName, p);
}
p.add(parentSpan.serviceName);
}
node = parent;
nodeSpan = GraphCreator.toSpan(node);
parent = Util.parent(parent);
}
}
return new Result(Collections.unmodifiableMap(dependencies), Collections.unmodifiableMap(parents));
} |
211175076_2 | public String name(final TokenMatcher.State state) {
// See: https://wiki.alpinelinux.org/wiki/APKBUILD_Reference#pkgver
Pattern pattern = Pattern.compile("(.*)-([.0-9]+[a-zA-Z]?)(_?(alpha|beta|pre|rc|cvs|svn|git|hg|p)?([0-9]+)?)?-r([0-9]+)");
String filename = match(state, "filename");
Matcher matcher = pattern.matcher(filename);
if (matcher.find()) {
MatchResult matchResult = matcher.toMatchResult();
return matchResult.group(1);
}
return "";
} |
211330796_63 | public String parent() {
int indexOf = loc.lastIndexOf('/');
if (indexOf == -1) {
return "";
}
return loc.substring(0, indexOf);
} |
211971342_16 | @Override
public void deleteApplication(final String applicationId) {
log.info("Deleting application {}", applicationId);
ApplicationRecord applicationRecord = loadApplication(applicationId);
Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
expressionAttributeValues.put(":v", AttributeValue.builder()
.n(applicationRecord.getVersion().toString())
.build());
dynamodb.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(toKeyRecord(applicationId))
.conditionExpression(String.format("%s = :v", ApplicationRecord.VERSION_ATTRIBUTE_NAME))
.expressionAttributeValues(expressionAttributeValues)
.build());
} |
212300461_2 | @Override
public ClusterEntity selectByCluster(String cluster) {
return transferEntity(clusterJpaRepository.findFirstByAndCluster(cluster));
} |
212338967_8 | void create(User user) {
entityManager.persist(user);
} |
212382406_249 | @Override
public ArrayList<Table> listTables() {
ArrayList<Table> returnList = new ArrayList<>();
for (ColumnFamilyHandle handle : handleTable.values()) {
returnList.add(new RDBTable(db, handle, writeOptions, rdbMetrics));
}
return returnList;
} |
212625733_13 | public boolean matches(String toMatch) {
return matches(new Path(toMatch));
} |
212816799_1 | public static int getProperty(Map<String, String> props, String propertyName, int defaultValue) {
if (props != null) {
String propertyValue = props.get(propertyName);
if (StringUtils.isNotBlank(propertyValue)) {
return Integer.parseInt(propertyValue);
}
}
return defaultValue;
} |
212938936_3 | public LibraBalance getBalance(String libraAddress) {
LibraBalance libraBalance = new LibraBalance();
Long balance = jLibraUtil.findBalance(libraAddress);
libraBalance.setLibra(balance/1000000);
libraBalance.setLibraMicro(balance);
libraBalance.setLibraAddress(libraAddress);
log.info(libraBalance.toString());
return libraBalance;
} |
213330914_0 | @Nonnull
String getToken(@Nonnull final TokenConfig tokenConfig, @Nonnull final String issuer) {
JwtBuilder builder =
Jwts.builder()
.setHeaderParam("kid", KEY_ID)
// since the specification allows for more than one audience, but JJWT only accepts
// one (see https://github.com/jwtk/jjwt/issues/77), use a workaround here
.claim("aud", tokenConfig.getAudience())
.setIssuedAt(new Date(tokenConfig.getIssuedAt().toEpochMilli()))
.claim("auth_time", tokenConfig.getAuthenticationTime().getEpochSecond())
.setExpiration(new Date(tokenConfig.getExpiration().toEpochMilli()))
.setIssuer(Objects.requireNonNull(issuer))
.setSubject(tokenConfig.getSubject())
.claim("scope", tokenConfig.getScope())
.claim("typ", "Bearer")
.claim("azp", tokenConfig.getAuthorizedParty());
setClaimIfPresent(builder, "nbf", tokenConfig.getNotBefore());
setClaimIfPresent(builder, "name", tokenConfig.getName());
setClaimIfPresent(builder, "given_name", tokenConfig.getGivenName());
setClaimIfPresent(builder, "family_name", tokenConfig.getFamilyName());
setClaimIfPresent(builder, "email", tokenConfig.getEmail());
setClaimIfPresent(builder, "preferred_username", tokenConfig.getPreferredUsername());
return builder
.claim("realm_access", tokenConfig.getRealmAccess())
.claim("resource_access", tokenConfig.getResourceAccess())
.addClaims(tokenConfig.getClaims())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
} |
213344827_96 | public Observable<Optional<T>> observer() throws ConsumedThingException {
try {
Pair<ProtocolClient, Form> clientAndForm = thing.getClientFor(getForms(), Operation.OBSERVE_PROPERTY);
ProtocolClient client = clientAndForm.first();
Form form = clientAndForm.second();
return client.observeResource(form)
.map(content -> Optional.ofNullable(ContentManager.contentToValue(content, this)));
}
catch (ProtocolClientException e) {
throw new ConsumedThingException(e);
}
} |
213353848_15 | public static Entry doParseDir(String path) {
return new DirEntry(path);
} |
213594368_20 | public boolean isPartialAqlDataValuePath(){
return getSuffix().matches(jsonPathQualifierMatcher);
} |
213687575_123 | public int getFillColor() {
return fillColor;
} |
213770342_10 | public static Integer determinePriceCatForCPD(double price)
{
if (price >= 0 && price <= 3)
{
return 1;
}
if (price > 3 && price <= 5)
{
return 2;
}
if (price > 5)
{
return 3;
}
return 3;
} |
213777474_6 | public Set<ContextItem> contextItems() {
HashSet<ContextItem> contextItems = new HashSet<>(context.size());
for (Map.Entry<String, AttributeValue> entry : context.entrySet()) {
contextItems.add(ContextItem.fromContext(entry.getKey(), partitionKey));
}
return contextItems;
} |
213825606_2 | @VisibleForTesting
String[] findClassNames(AbstractConfiguration config) {
// Find individually-specified filter classes.
String[] filterClassNamesStrArray = config.getStringArray("zuul.filters.classes");
Stream<String> classNameStream = Arrays.stream(filterClassNamesStrArray)
.map(String::trim)
.filter(blank.negate());
// Find filter classes in specified packages.
String[] packageNamesStrArray = config.getStringArray("zuul.filters.packages");
ClassPath cp;
try {
cp = ClassPath.from(this.getClass().getClassLoader());
}
catch (IOException e) {
throw new RuntimeException("Error attempting to read classpath to find filters!", e);
}
Stream<String> packageStream = Arrays.stream(packageNamesStrArray)
.map(String::trim)
.filter(blank.negate())
.flatMap(packageName -> cp.getTopLevelClasses(packageName).stream())
.map(ClassPath.ClassInfo::load)
.filter(ZuulFilter.class::isAssignableFrom)
.map(Class::getCanonicalName);
String[] filterClassNames = Stream.concat(classNameStream, packageStream).toArray(String[]::new);
if (filterClassNames.length != 0) {
LOG.info("Using filter classnames: ");
for (String location : filterClassNames) {
LOG.info(" " + location);
}
}
return filterClassNames;
} |
213896494_10 | public Object klineGet(String symbol, String interval, BigDecimal from, String limit) throws ApiException {
ApiResponse<Object> resp = klineGetWithHttpInfo(symbol, interval, from, limit);
return resp.getData();
} |
213981789_184 | @Override
public <T> Mono<T> invokeActorMethod(String methodName, Object data, TypeRef<T> type) {
return this.daprClient.invokeActorMethod(actorType, actorId.toString(), methodName, this.serialize(data))
.filter(s -> s.length > 0)
.map(s -> deserialize(s, type));
} |
214200976_3 | @Override
public Optional<N> getNode(String nodeId) {
return strategy.getNode(nodeId, ring, hashFunction);
} |
214396571_4 | public static String[] getRowData(DeploymentStatus deploymentStatus) {
if (deploymentStatus == null) {
return null;
}
String age = getAge(deploymentStatus.getAge());
String statusMsg = deploymentStatus.getServiceStatus() != null ? deploymentStatus.getServiceStatus().getMessage() : null;
String[] rowData = new String[]{deploymentStatus.getServiceName(), statusMsg, age, deploymentStatus.getServiceAddress(),
deploymentStatus.getMessage()};
return rowData;
} |
214418380_15 | public PropertyBags getTerminals() {
LOG.info("Querying triple store for terminals");
return queryTripleStore(TERMINALS_QUERY_KEY);
} |
215203638_16 | PushNotification handleMessage(@NonNull RemoteMessage message)
throws InvalidNotificationException {
return this.handleMessage(message.getData().get(MESSAGE_ID), message.getData().get(MESSAGE));
} |
215257930_1 | public static com.alibaba.fastjson.JSONObject of() {
return new com.alibaba.fastjson.JSONObject();
} |
215394390_112 | public static boolean isNullRow(Block block, int row)
{
if (row > block.getRowCount() - 1) {
throw new RuntimeException("block has " + block.getRowCount()
+ " rows but requested to check " + row);
}
//If any column is non-null then return false
for (FieldReader src : block.getFieldReaders()) {
src.setPosition(row);
if (src.isSet()) {
return false;
}
}
return true;
} |
215496017_7 | public static void insertBytesIntoPythonVariables(Data ret, PythonVariables outputs, String variable, PythonConfig pythonConfig) throws IOException {
PythonIO pythonIO = pythonConfig.getIoOutputs().get(variable);
Preconditions.checkState(pythonConfig.getIoOutputs().containsKey(variable),"No output type conversion found for " + variable + " please ensure a type exists for converting bytes to an appropriate data type.");
ValueType byteOutputValueType = pythonIO.type();
Preconditions.checkNotNull(byteOutputValueType,"No byte value output type specified!");
Preconditions.checkState(outputs.get("len_" + variable) != null,"Please ensure a len_" + variable + " is defined for your python script output to get a consistent length from python.");
Long length = getWithType(outputs,"len_" + variable,Long.class);
Preconditions.checkNotNull(length,"No byte pointer length found for variable");
Preconditions.checkNotNull("No byte pointer length found for variable",variable);
BytePointer bytesValue = new BytePointer(getWithType(outputs,variable,byte[].class));
Preconditions.checkNotNull("No byte pointer found for variable",variable);
//ensure length matches what's found in python
Long capacity = length;
bytesValue.capacity(capacity);
switch(byteOutputValueType) {
case IMAGE:
ByteBuffer byteBuffer1 = bytesValue.asBuffer();
if(byteBuffer1.hasArray()) {
byte[] bytesContent = byteBuffer1.array();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytesContent);
BufferedImage bufferedImage = ImageIO.read(byteArrayInputStream);
ret.put(variable, Image.create(bufferedImage));
}
else {
byte[] bytes = new byte[capacity.intValue()];
byteBuffer1.get(bytes);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
BufferedImage bufferedImage = ImageIO.read(byteArrayInputStream);
Preconditions.checkNotNull(bufferedImage,"Buffered image was not returned. Invalid image bytes passed in.");
ret.put(variable,Image.create(bufferedImage));
}
break;
case BYTES:
ByteBuffer byteBuffer = bytesValue.asByteBuffer();
byte[] bytes = new byte[byteBuffer.capacity()];
byteBuffer.get(bytes);
ret.put(variable,bytes);
break;
case BYTEBUFFER:
ByteBuffer byteBuffer2 = bytesValue.asByteBuffer();
ret.put(variable,byteBuffer2);
break;
case STRING:
ret.put(variable,bytesValue.getStringBytes());
break;
default:
throw new IllegalArgumentException("Illegal type found for output type conversion " + byteOutputValueType);
}
} |
215605392_4 | @Override
public ProgressEvent<ResourceModel, CallbackContext> handleRequest(
final AmazonWebServicesClientProxy proxy,
final ResourceHandlerRequest<ResourceModel> request,
final CallbackContext callbackContext,
final Logger logger) {
final ResourceModel model = request.getDesiredResourceState();
final String apiKey = model.getApiKey();
final int policyId = model.getPolicyId();
OperationStatus status = OperationStatus.SUCCESS;
NrqlCondition modelNrqlCondition = model.getNrqlCondition();
// convert to our New Relic-specific class
NewRelicNrqlCondition newRelicNrqlCondition = new NewRelicNrqlCondition(modelNrqlCondition);
try {
logger.log(
String.format(
"Attempting to create alert condition for policy ID: %d", policyId));
JSONObject nrqlConditionJson =
alertApiClient.create(newRelicNrqlCondition, apiKey, policyId);
int id = nrqlConditionJson.getInt("id");
model.getNrqlCondition().setId(id);
model.getNrqlCondition().setType(nrqlConditionJson.getString("type"));
logger.log(
String.format("Created alert condition with ID %d in policy %d", id, policyId));
} catch (IOException | AlertApiException e) {
status = OperationStatus.FAILED;
logger.log(ExceptionUtils.getStackTrace(e));
}
return ProgressEvent.<ResourceModel, CallbackContext>builder()
.resourceModel(model)
.status(status)
.build();
} |
215680638_2 | @Action(method = HttpMethod.GET)
public ActionResult refresh_provider(HttpContext context) {
String path = context.Request.getParams().get("path");
logger.info("path:" + path);
JsonResult jsonResult = cynosureService.queryProviderOrConsumerList(path);
String result = JacksonUtils.toJson(jsonResult);
logger.info("jsonResult:" + result);
ActionResult actionResult = null;
try {
actionResult = new ActionResult(HttpDataType.JSON, result.getBytes(Constants.DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
actionResult = new ActionResult(HttpDataType.JSON, result.getBytes());
logger.error(e);
}
return actionResult;
} |
215805400_0 | public static String newCeptaID() {
return String.format("CPTA-%s", UUID.randomUUID().toString());
} |
215881965_0 | public Map<String, List<String>> extractEntities(final String text, final String entityTypes) throws RuntimeException {
final String[] entityTypeList = entityTypes.split((","));
boolean extractLocations = false;
final List<String> locationNerTagList = new ArrayList<String>();
locationNerTagList.add("LOCATION");
locationNerTagList.add("CITY");
locationNerTagList.add("COUNTRY");
locationNerTagList.add("STATE_OR_PROVINCE");
final List<String> nerTagList = new ArrayList<String>();
final Map<String, List<String>> output = new HashMap<String, List<String>>();
for (final String tag : entityTypeList) {
output.put(tag, new ArrayList<String>());
if (tag.equals("location")) {
extractLocations = true;
} else {
nerTagList.add(tag.toUpperCase());
}
}
final Annotation annotation = new Annotation(text);
pipeline.annotate(annotation);
if (annotation.containsKey(CoreAnnotations.ExceptionAnnotation.class)) {
final Throwable t = annotation.get(CoreAnnotations.ExceptionAnnotation.class);
throw new RuntimeException(t);
}
final CoreDocument document = new CoreDocument(annotation);
List<CoreEntityMention> mentions = document.entityMentions();
if (document.entityMentions() == null) {
mentions = new ArrayList<CoreEntityMention>();
}
for (final CoreEntityMention entityMention : mentions) {
final String eType = entityMention.entityType();
if (extractLocations && locationNerTagList.contains(eType)) {
final List<String> locs = output.get("location");
locs.add(entityMention.text());
output.put("location", locs);
continue;
}
if (nerTagList.contains(eType)) {
final List<String> e = output.get(eType.toLowerCase());
e.add(entityMention.text());
output.put(eType.toLowerCase(), e);
}
}
return output;
} |
215941972_171 | @Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
if (inv.getMethodName().equals(Constants.$INVOKE)
&& inv.getArguments() != null
&& inv.getArguments().length == 3
&& !GenericService.class.isAssignableFrom(invoker.getInterface())) {
String name = ((String) inv.getArguments()[0]).trim();
String[] types = (String[]) inv.getArguments()[1];
Object[] args = (Object[]) inv.getArguments()[2];
try {
Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types);
Class<?>[] params = method.getParameterTypes();
if (args == null) {
args = new Object[params.length];
}
String generic = inv.getAttachment(Constants.GENERIC_KEY);
if (StringUtils.isBlank(generic)) {
generic = RpcContext.getContext().getAttachment(Constants.GENERIC_KEY);
}
if (StringUtils.isEmpty(generic)
|| ProtocolUtils.isDefaultGenericSerialization(generic)) {
args = PojoUtils.realize(args, params, method.getGenericParameterTypes());
} else if (ProtocolUtils.isJavaGenericSerialization(generic)) {
for (int i = 0; i < args.length; i++) {
if (byte[].class == args[i].getClass()) {
try {
UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i]);
args[i] = ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
.deserialize(null, is).readObject();
} catch (Exception e) {
throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e);
}
} else {
throw new RpcException(
"Generic serialization [" +
Constants.GENERIC_SERIALIZATION_NATIVE_JAVA +
"] only support message type " +
byte[].class +
" and your message type is " +
args[i].getClass());
}
}
} else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof JavaBeanDescriptor) {
args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]);
} else {
throw new RpcException(
"Generic serialization [" +
Constants.GENERIC_SERIALIZATION_BEAN +
"] only support message type " +
JavaBeanDescriptor.class.getName() +
" and your message type is " +
args[i].getClass().getName());
}
}
}
Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments()));
if (result.hasException()
&& !(result.getException() instanceof GenericException)) {
return new RpcResult(new GenericException(result.getException()));
}
if (ProtocolUtils.isJavaGenericSerialization(generic)) {
try {
UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
.serialize(null, os).writeObject(result.getValue());
return new RpcResult(os.toByteArray());
} catch (IOException e) {
throw new RpcException("Serialize result failed.", e);
}
} else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD));
} else {
return new RpcResult(PojoUtils.generalize(result.getValue()));
}
} catch (NoSuchMethodException e) {
throw new RpcException(e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new RpcException(e.getMessage(), e);
}
}
return invoker.invoke(inv);
} |
215950115_181 | public Map<String, ConsumerGroupVo> getConfig() {
try {
InputStream inputStream = getConfigFileStream();
return getConfig(inputStream);
} catch (Exception ex) {
log.error("加载配置文件异常,异常信息:" + ex.getMessage(), ex);
throw new RuntimeException(ex);
}
} |
216000802_8 | public String getProcessingQueueChannelName(String queueName) {
if (dbVersion == 1) {
return "rqueue-processing-channel::" + queueName;
}
return prefix + getProcessingQueueChannelSuffix() + getTaggedName(queueName);
} |
Subsets and Splits