id
stringlengths
7
14
text
stringlengths
1
37.2k
121473558_6
public Iterable<String> toIterable(CSVRecord record) { return () -> new Iterator<String>() { int index = 0; @Override public boolean hasNext() { return index <= lastColumnIndex; } @Override public String next() { Header header = headers.get(i...
121507913_47
public void addNewBasket(Basket basket) { checkNotNull(basket, "Basket must not be null"); checkNotEmpty(basket.getBasketItems(), "At least one basket item must be set"); if (basket.getTotalBasketValue() < 0) { throw new IllegalArgumentException("Total basket value must be greater than or equal zero...
121514433_0
@Override public void methodRemoved(final ValidationContext ctx, final MethodDescriptor current) { // TODO(staffan): Take things like lifecycle into account here. Removing methods from a GA // service is a no-no but removing it from a experimental service is probably okay. // Would be very cool if we could get th...
121651800_2
public static String resolveFile(String fileName, String topDir) { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(topDir, fileName); } if (!file.exists()) { // Trying to resolve file using glob pattern List<File> files = getDirectoryList(file.getParentF...
121984024_10
void search(String word) { boolean isLatinAlphabet; if (word.isEmpty()) { return; } word = word.toLowerCase(Locale.ROOT); if (SpellChecker.ALPHABET_LATIN.indexOf(word.charAt(0)) >= 0) { isLatinAlphabet = true; } else if (SpellChecker.ALPHABET_CYRILLIC.indexOf(word.charAt(0)) >...
122078259_12
public static <T> T notNull(T value, String fieldName) { if (value == null) { throw new IllegalArgumentException("Argument " + fieldName + " cannot be null."); } return value; }
122105687_1
Optional<String> fetch(final String assetName) { log.fine(() -> String.format("Fetching asset '%s'", assetName)); Optional<String> rv; try { final Map<String, String> values = getValues(); rv = Optional.ofNullable(values.get(assetName)).map(a -> a.replaceFirst("^/", "")); } catch (IOExc...
122146857_2
public static FieldFeatureExtractorFactory loadFactory(FeaturesConfigReader.FeatureDesc featureDesc){ ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Class<? extends FieldFeatureExtractorFactory> cls = (Class<? extends FieldFeatureExtractorFactory>) loader.loadClass(featureDesc.klass)...
122194961_3
@Bean @ConditionalOnMissingBean public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager, TransactionSynchronizationRegistry transactionSynchronizationRegistry) { JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(use...
122369264_51
@Nonnull @Override public Response handle(@Nonnull final Context context) throws Exception { Response response = context.proceed(); if (!Boolean.parseBoolean(context.getRequest().getAttributes().get(DO_NOT_REWRITE, String.class))) { if (response.getStatus().getCode() == HttpStatus.OK && response.getPayload() !=...
122426223_23
@Override public List<String> getPendingTransactionList(String branchId) { return branchGroup.getUnconfirmedTxs(BranchId.of(branchId)) .stream().map(tx -> tx.getHash().toString()).collect(Collectors.toList()); }
122426901_387
public void updateChain(Chain chain, int minPrunableLifetime, int maxPrunableLifetime) { Objects.requireNonNull(chain, "Chain cannot be null"); setFields(chain, minPrunableLifetime, maxPrunableLifetime); Map<Integer, BlockchainProperties> blockchainProperties = chain.getBlockchainProperties(); if (bloc...
122429896_1
public static AkkaEngine provider() { AkkaEngine engine = null; // Double checked locking to initialize the weak reference the first time this method // is invoked. if (cachedEngine == null) { synchronized (mutex) { if (cachedEngine == null) { // We could just use the weak reference to get th...
122461562_1
public TargetPlatformSpec prepare(TargetPlatformSpec inputSpec) { try { List<Path> platformArtifacts = install(Arrays.asList(inputSpec.getDependencies()),TargetPlatformSpec.platformPath(targetBase)); Path specArtifact = Files.createDirectories(TargetPlatformSpec.configuration(targetBase)).resolve(BL...
122467588_2
public Single<String> getName() { return Single.create( emitter -> { Gson gson = new Gson(); emitter.onSuccess(gson.fromJson(fileReader.readFile(), User.class).name); }); }
122494549_0
@Override public void start() { try { this.starting = true; Message message = Message.create() .setType("START_SERVER") .set("name", getName()) .set("id", getId()) .set("group", getGroup().getName()) .set("ram", getGroup...
122514469_8
@Override public Float parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to float"); return Float.parseFloat(value); }
122529106_2
public ExecutableElement getSetter(String propertyName) throws UnableToCompleteException { if (ambiguousSetters != null && ambiguousSetters.contains(propertyName)) { logger.die( "Ambiguous setter requested: " + AptUtil.asQualifiedNameable(rawType).getQualifiedName() .toString() + "." + propert...
122573764_0
public static Class<?> forName(String name) { try { return name2class(name); } catch (ClassNotFoundException e) { throw new IllegalStateException("Not found class " + name + ", cause: " + e.getMessage(), e); } }
122577034_11
public InterProcessMutex writeLock() { return writeMutex; }
122583771_0
private Persist addChirp(AddChirp cmd, CommandContext<Done> ctx) { return ctx.thenPersist(new ChirpAdded(cmd.chirp), evt -> { ctx.reply(Done.getInstance()); topic.publish(cmd.chirp); }); }
122638182_96
public PerfPlan parseResource(Resource resource) { requireNonNull(resource); URI uri = resource.getUri(); String source = read(resource); ServiceLoader<cucumber.perf.salad.PlanParser> services =ServiceLoader.load(cucumber.perf.salad.PlanParser.class); Iterator<cucumber.perf.salad.PlanParser> iterato...
122711080_76
public void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum, final long begin, final long end, boolean lock) { if (this.mappedFile.hold()) { int keyHash = indexKeyHashMethod(key); int slotPos = keyHash % this.hashSlotNum; int absSlo...
122751554_12
public Set<Person> getRemainingReceivers() { return IntStream.range(0, satisfiedReceivers.length) .filter(i -> !satisfiedReceivers[i]) .mapToObj(receivers::get) .collect(Collectors.toUnmodifiableSet()); }
122753171_110
@Override public void readFrame( final ChannelHandlerContext ctx, final ByteBuf input, final Http2FrameListener listener) throws Http2Exception { if (readError) { input.skipBytes(input.readableBytes()); return; } try { do { if (readingHeaders) { processHeaderState(input); ...
122852176_0
public boolean createStudent(Student student) throws SQLException, FileNotFoundException, IOException { state = isUserAvailable(student.getChatId()); if (state) { students = connect(); students.store(student); students.commit(); } return state; }
122905230_36
@Deprecated public void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data) { this.fireEvent(instanceId, ref, type, data, null); }
122909761_32
public void restart() { setJSFrameworkInit(false); initWXBridge(WXEnvironment.sRemoteDebugMode); }
122918493_34
@Override public boolean visible(String name, Map<String, Object> connectorConfigs) { return true; }
122954189_6
@Override public void validate(UastNode node) { is(UastNode.Kind.DEFAULT_CASE); hasKeyword("default"); noChild(UastNode.Kind.CONDITION); // FIXME go 'select' nodes are feeding default cases and should be removed // hasAncestor(UastNode.Kind.SWITCH); }
122966349_0
@Override public AccountStatusFilter buildFilter() { AccountStatusFilter result = new AccountStatusFilter(); result.setDate(new ReportDate(DateValueType.Today)); return result; }
122966748_12
public static Date getDateBeforePeriod(String perStr, Date curDate) { Period pr = getPeriod(perStr); DateTime dt = new DateTime(curDate); return dt.minus(pr).toDate(); }
122968674_0
@RolesAllowed("USER") public String sec1a() { return "@RolesAllowed(\"USER\")"; }
123178569_1
public boolean someLibraryMethod() { return true; }
123189523_1
@Override public <T> @Nullable InstanceFactory<T> getFilteredInstanceFactory( Class<T> type, String classifier, FactoryFilter factoryFilter ) { Range range = getOptionalRange(type, classifier); if (range == null) { return null; } if (range.getCount() == 1) { InstanceFactory factory ...
123284439_19
@Override public void checkRecordExists(String id) throws OaiPmhException { ResponseEntity<String> response = getResponseForRecord(id); if (response == null) { throw new IdDoesNotExistException("Record with id '" + id + "' not found"); } }
123335926_5
public static String formatQuantity(BigDecimal pQuantity, String pSymbol, ExchangeInfo pExchangeInfo) { SymbolInfo symbolInfo = pExchangeInfo.getSymbolInfo(pSymbol); String tickSize = symbolInfo.getSymbolFilter(FilterType.LOT_SIZE).getStepSize(); return roundToTickSize(pQuantity, tickSize); }
123340956_1
public String getUsername() { return username; }
123415889_0
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { logger.debug("Post process bean factory has been called"); findJaxrsApplications(beanFactory); // This is done by finding their related Spring beans findJaxrsResourcesAndProviderClasses(beanFactory)...
123463973_5
public void volumeDown(){ audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND); setCurrentVolumeVolume(); }
123532715_1
public static String resolveValue(String value) throws DockerPluginException { int startIndex; if ((startIndex = value.indexOf("$env{")) >= 0) { int endIndex = value.indexOf("}", startIndex); if (endIndex > 0) { String varName = value.substring(startIndex + 5, endIndex).trim(); ...
123532974_6
public static void copyFileOrDirectory(String source, String destination) throws KubernetesPluginException { File src = new File(source); File dst = new File(destination); try { // if source is file if (Files.isRegularFile(Paths.get(source))) { if (Files.isDirectory(dst.toPath())...
123618046_11
public AsyncClient getAsyncClient() { if (!asyncClientIsReady()) { buildAsyncClient(); } return asyncClient.get(); }
123664565_0
public static RxBackoff fixed(long interval, int maxRetryCount) { return new RxBackoff(new Backoff.Builder() .setAlgorithm(new FixedIntervalAlgorithm(interval, TimeUnit.MILLISECONDS)) .setMaxRetryCount(maxRetryCount) .build()); }
123681471_114
public static KnowledgeBase parse(final InputStream stream, final String encoding, final ParserConfiguration parserConfiguration) throws ParsingException { JavaCCParser parser = new JavaCCParser(stream, encoding); parser.setParserConfiguration(parserConfiguration); return doParse(parser); }
123712995_12
@Override public void run(ApplicationArguments args) throws Exception { this.jdbcTemplate.execute("CREATE TABLE tweets (\n" + // " uuid VARCHAR(36) PRIMARY KEY,\n" + // " text VARCHAR(255),\n" + // " username VARCHAR(128),\n" + // " created_at TIMESTAMP\n" + // ");"); this.jdbcTemplat...
123788136_10
public boolean isEmpty() { return this.start >= this.end; }
123808995_14
public MergeBasicProcessorOptions() { }
123822761_2
@Override public <T> T getAttribute(Class<T> type, Supplier<T> defaultValueSupplier) { T result = context.get(type.getName()); if (result == null && defaultValueSupplier != null) { result = defaultValueSupplier.get(); context.put(type.getName(), result); } return result; }
123949037_0
public String getName() { return this.name; }
123960848_6
@Override public boolean isAllowed(Metric metric) { return allowList.stream() .anyMatch(filter -> super.filterMatches(filter, metric)); }
123970806_41
public CryptoCompareResponseDTO getHistorical(CryptoCompareCurrency fromCurrency, List<CryptoCompareCurrency> toCurrency, long timeInSecond) throws Exception { CryptoCompareResponseDTO cryptoCompareResponseDTO = restTemplate.getForObject( getPriceHistoricalURI(fromCurrency, toCurrency, timeInSecond), ...
124004218_29
public static List<FileStatus> listAll(FileSystem fs, Path path, boolean recursive, PathFilter... filters) throws IOException { List<FileStatus> statuses = new ArrayList<>(); listAll(fs, path, recursive, statuses, mergeFilters(filters)); return statuses; }
124063585_3
@PostMapping("/replay") public String replay() { replayer.replay("nl.fourscouts.blog.replays.projections"); return "Replay started..."; }
124093107_0
@Override public void setValue(@Nullable T t) { if (hasActiveObservers() && mBuffer.isEmpty()) { // See onActive super.setValue(t); } else { mBuffer.add(t); } }
124140585_0
public static int calculateDistance(Object[] entities, int start, int end) { boolean[] visited = new boolean[entities.length]; int[] distance = new int[entities.length]; for (int i = 0; i < entities.length; i++) { distance[i] = Integer.MAX_VALUE; } distance[start] = 0; // Create a way ...
124201472_2
}
124230133_6
CompletableFuture<List<Hex>> fetchHashesAsync(Hex hashedPassword) { Call call = httpClient.newCall(buildRequest(hashedPassword)); CompletableFuture<List<Hex>> future = new CompletableFuture<>(); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { ...
124245472_124
public void updateUser(String username, User body) throws RestClientException { Object postBody = body; // verify the required parameter 'username' is set if (username == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling u...
124316286_20
private static int[] merge(int[] arr1, int[] arr2) { int i = 0, j = 0, k = 0; // 创建一个新数组 int[] result = new int[arr1.length + arr2.length]; // 将两个数据中的元素进行一一比较,较小的放入新的数组中 while (i < arr1.length && j < arr2.length) { if (arr1[i] <= arr2[j]) { result[k++] = arr1[i++]; } else...
124364226_0
protected ClusterProperties getClusterProperties() { String keyPrefix = "yfs.gateway."; ClusterProperties clusterProperties = new ClusterProperties(); Map<String, String> map = PropertiesUtil.getProperty("cluster.properties"); Set<Integer> nodeIds = new HashSet<>(); map.entrySet().stream().forEach(e...
124397000_25
public OAuth2AccessTokenResponse getAccessToken(ClientProperties clientProperties) { if (clientProperties == null) { throw new OAuth2ClientException("ClientProperties cannot be null"); } log.debug("getting access_token for grant={}", clientProperties.getGrantType()); if (isGrantType(clientProper...
124447570_0
Maybe<TranslationResult> getOnlineTranslation(String question, String langFrom, String langTo) { if (appState.isOfflineMode) { return Maybe.empty(); } return seznamRetrofit.create(SeznamRestInterface.class) .doTranslate(langFrom + "_" + langTo, question) .flatMap(response -> ...
124503196_5
@Override public void addCollectArticle(int position, FeedArticleData feedArticleData) { addSubscribe(mDataManager.addCollectArticle(feedArticleData.getId()) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleL...
124518729_11
@Override public boolean conforms(final List<String> pMarkdownLines) { return QUOTE_PATTERN.matcher(pMarkdownLines.get(0)).matches(); }
124578706_11
@Override public void handleResult(Object result) { if (result == null) { return; } if (result instanceof Throwable) { THREAD_CONTEXT.set((Throwable) result); } Object obj = result; SshContext ctx = SSH_THREAD_CONTEXT.get(); if (ctx != null && ctx.getPostProcessorsList() != n...
124743561_1
public void set(String name, String value) { List<String> values = headers.get(name); if (values == null) { values = new ArrayList<>(1); headers.put(name, values); } else { values.clear(); } values.add(value); }
124765869_0
public ArtifactDetails fetchArtifact(String slug) throws IOException { URL url = new URL("http", host, API_PREFIX_ARTIFACT + slug + "/"); InputStreamReader reader = null; try { URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", getUserAgent()); ...
124775013_2
public void check(@IdRes int id) { // don't even bother if (id != -1 && (id == checkedId)) { return; } if (checkedId != -1) { setCheckedStateForView(checkedId, false); } if (id != -1) { setCheckedStateForView(id, true); } setCheckedId(id); }
124800527_4
@Override public Authentication authenticate(Authentication authentication) { Assert.notNull(authentication, "Authentication is missing"); Assert.isInstanceOf(JwtAuthenticationToken.class, authentication, "This method only accepts JwtAuthenticationToken"); String jwtToken = authentication.get...
124862112_29
@Override public String handleCommand(String command) { return new BizCommand(command).process(); }
124863824_5
public void doWithRunnable(Runnable runnable) { long currentTimeMillis = System.currentTimeMillis(); if (runImmediately) { runnable.run(); } else if (currentTimeMillis > lastLogTime + waitTime) { synchronized (this) { if (currentTimeMillis > lastLogTime + waitTime) { ...
124864129_2
@Override public void loading() { }
124869132_4
public List<ChangedFile> getChangedFilesForCommit(RevCommit commit) throws IOException, GitAPIException { List<ChangedFile> changedFiles = new ArrayList<>(); int rangeSize = 6; int lowerIntervall = (-1) * (rangeSize / 2); int upperIntervall = (rangeSize / 2) + 1; for (int i = lowerIntervall; i < up...
124882400_142
@Override public Element wrap(String html) { return (Element) super.wrap(html); }
124900009_15
public Customer getFallbackCustomer(Long id, Throwable e) { log.warn("Failed to obtain Customer, " + e.getMessage() + " for customer with id " + id); Customer c = new Customer(); c.setId(id); c.setUsername("Unknown"); c.setName("Unknown"); c.setSurname("Unknown"); c.setAddress("Unknown"); c.setCity("Unknown"); ...
124923731_1
@Override public CompletionStage<List<Prediction<Integer, Float>>> predict( final ScheduledExecutorService scheduler, final Duration timeout, final Integer... input) { return predictorBuilder.predictor().predict(scheduler, timeout, input); }
125110164_1
@Nonnull @SuppressWarnings("unchecked") public static <T extends Enum<T>> WireSafeEnum<T> of(@Nonnull T value) { checkNotNull(value, "value"); Class<T> enumType = (Class<T>) value.getClass(); ensureEnumCacheInitialized(enumType); return (WireSafeEnum<T>) ENUM_LOOKUP_CACHE.get(enumType).get(value); }
125115294_37
public static int headerIndex(String headerRef) { Objects.requireNonNull(headerRef); Matcher m = CELL_REFERENCE_REGEX.matcher(headerRef); if (m.matches()) { // Find if the header reference is in the right format // Get only the letters at the start String alph = m.group(1); if (alph == null) { ...
125157861_34
@SuppressWarnings("unchecked") public final <TARGET> Promise<TARGET> mapResult(Function<Result<? super DATA>, Result<? extends TARGET>> mapper) { requireNonNull(mapper); return (Promise<TARGET>)newSubPromise((Result<DATA> r, Promise<TARGET> targetPromise) -> { val result = mapper.apply(r); targe...
125225914_8
public static String genGeneric(List<? extends TypeParamInfo> params) { StringBuilder sb = new StringBuilder(); if (params.size() > 0) { sb.append("<"); boolean firstParam = true; for (TypeParamInfo p : params) { if (!firstParam) { sb.append(", "); } sb.append(p.getName()); ...
125255822_10
@Override public void execute() throws MojoExecutionException, MojoFailureException { failIfOffline(); tag = getTag(); RepositoryManagerV3Client client = getRepositoryManagerV3Client(); try { List<ComponentInfo> deletedComponents = client.delete(tag); getLog().info(String.format("'%d' components delet...
125371981_24
@Nonnull public Optional<DateRange> getOverlap(@Nonnull DateRange otherRange) { if (this.getGueltigAb().isAfter(otherRange.getGueltigBis()) || this.getGueltigBis().isBefore(otherRange.getGueltigAb())) { return Optional.empty(); } LocalDate ab = otherRange.getGueltigAb().isAfter(this.getGueltigAb()) ? otherRange.g...
125372344_8
@GetMapping("/investors") public List<Investor> fetchAllInvestors() { return investorService.fetchAllInvestors(); }
125381655_0
public void setName(String name) { this.name = name; }
125417291_49
void setDrawable(@NonNull StateDraweeView view) { FrescoImageController.create() .load(getDrawable(view.isEnabled() ? STATE_ON : STATE_OFF)) .into(view); }
125471878_1
public void addNewStock(String symbolName, BigDecimal shareCount) { Date date = new Date(); symbolName = symbolName.trim(); StockPortfolioItem item = new StockPortfolioItem( symbolName, shareCount, date ); portfolioRepository.save(item); getActivity().finis...
125472394_7
public static String extractUserNickName(String json) { /* JsonBody Example) { "resultUserInfo": { "userId": "test123", "userName": "test123_name" }, "resultType": "SUCCESS" } */ JsonParser jp = new JsonParser(); JsonElement je = j...
125498620_7
public static byte[] base64Decode(byte[] base64Decoded) { return ((SodiumDecoder) (in, out, reference) -> Sodium.sodium_base642bin(out, in.length, in, in.length, null, reference, null, VARIANT_URLSAFE_NO_PADDING) ).decode(base64Decoded); }
125508132_80
private SyncCheck(final int syncRateFactor, final int minThresholdSeconds, final int syncRateInSeconds) { this.syncRateInSeconds = syncRateInSeconds; this.lastSyncThresholdSeconds = Math.max(minThresholdSeconds, syncRateFactor * syncRateInSeconds); LOG.info("lastSyncThresholdSeconds={}", lastSyncThresholdS...
125513144_14
public String getRegistryUrl() { return registryUrl; }
125578728_2
@Override public final Collection<String> deleteState(final Collection<String> addresses) throws InternalError, InvalidTransactionException { TpStateDeleteRequest delRequest = TpStateDeleteRequest.newBuilder().addAllAddresses(addresses) .setContextId(this.contextId).build(); Future future = stream.send(Me...
125602657_0
@PostMapping("/sample3") public String save(@RequestBody PointDto requestDto){ messagingTemplate.convertAndSend("sample3", requestDto); return "success"; }
125627767_0
public static JsonObject main(JsonObject args) { JsonObject response = new JsonObject(); response.addProperty("greetings", "Hello! Welcome to OpenWhisk on OpenShift"); return response; }
125639419_16
public void down(final List<? super String> list) { LOG.info(CollectionHelper.toString(list)); String s = list.get(0); // 编译错误 final Object obj = list.get(0); // 可读, 但只能用 Object 接受泛型下界容器的值 LOG.info("list.get(0): " + obj); list.add("ha ha ha"); ...
125640293_0
public void register(String name, ComponentLife componentLife) { componentLifeTreeSet.add(componentLife); if (!name.equals(ComponentLife.class.getCanonicalName())) { componentApplicationHashMap.put(name, componentLife); } componentApplicationHashMap.put(componentLife.getClass().getCanonicalName(...
125691541_55
public int moves() { return solution.size() - 1; }
125705175_1
public void switchCurrentPlayer(Game game) { if (game.isFinished()) { return; } int iterations = 0; Player player = game.getCurrentPlayer(); boolean isMoveFeasible; do { player = getNextPlayer(game, player.getId()); isMoveFeasible = moveFeasibilityChecker .isAnyMoveFeasible(game.getBoar...
125707710_3
public int deleteFile(String fileId) { try { FastDFSClient client = fastDFSPool.getClient(); int result = client.delete_file1(fileId); client.close(); return result; } catch (IOException | MyException e) { e.printStackTrace(); } return 500; }
125752732_452
@Override public <T extends ParseObject> Task<Integer> countAsync( ParseQuery.State<T> state, ParseUser user, Task<Void> cancellationToken) { if (state.isFromLocalDatastore()) { return offlineStore.countFromPinAsync(state.pinName(), state, user); } else { return networkController.countAsync(stat...