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 ...
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.UnsupportedEncodingExceptio...
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...
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 < ve...
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...
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 = conte...
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)...
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.getParameterTyp...
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! """; } ...
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(en...
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; } ...
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 (Exc...
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,...
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 Memb...
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 fil...
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 -> generateC...
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.inf...
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 = ...
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,...
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 up...
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...
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(g...
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...
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) ...
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...
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 ...
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: resolvedHostna...
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: brea...
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 ...
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() || EventT...
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> rootPr...
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[] insertRowD...
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))) .co...
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")) { ...
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 LinkedHa...
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 = pa...
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", AttributeVa...
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(libraBalan...
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/jwt...
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.obs...
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...
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; Stri...
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.getFi...
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 conversi...
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.getDesiredRe...
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); ...
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");...
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())) { ...
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); }