id
stringlengths
7
14
text
stringlengths
1
37.2k
181322928_0
@Override public List<MonitorBean> getAll(String app, String id) { if (app == null || id == null) { throw new TicketServerException(ResultEnum.ERROR); } Set<String> pres = template.keys(MonitorService.getMonitorPreKeys(app, id)); if (pres == null) { throw new TicketServerException(Result...
181400274_0
@Bean @ConditionalOnMissingBean(DefaultMQProducer.class) @ConditionalOnProperty(prefix = "spring.rocketmq", value = {"name-server", "producer.group"}) public DefaultMQProducer defaultMQProducer(RocketMQProperties rocketMQProperties) { RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer(); ...
181445409_46
@Override public HttpServerOptions apply(HttpServerOptions options) { Ssl ssl = factory.getSsl(); if (ssl == null) { return options; } options.setSsl(ssl.isEnabled()); options.setKeyCertOptions(keyCertOptionsAdapter(ssl)); options.setTrustOptions(trustOptionsAdapter(ssl)); propert...
181519091_56
@NonNull @PostMapping @ResponseStatus(HttpStatus.CREATED) public BlottingPaper createItem(@NonNull @Valid @RequestBody BlottingPaper input) { return this.service.createItem(input); }
181683494_110
public void splitSegment(String context, List<String> clientIds, String processorName) { Map<ClientSegmentPair, SegmentStatus> clientToTracker = buildClientToTrackerMap(clientIds, processorName, REGULAR_ORDER); Integer biggestSegment = clientToTracker.values().stream() ...
181777958_2
public static int[] count(Map<String, Integer> dictionary, String s) { int[] result = new int[dictionary.size()]; VectorText.tokenize(s).forEach(w -> { if (dictionary.containsKey(w)) { result[dictionary.get(w)]++; } }); return result; }
181840596_0
public Element fromSDP(final String sdpData) throws XMLException { final String[] sdp = sdpData.split(LINE); final Element jingle = ElementFactory.create("jingle"); jingle.setXMLNS("urn:xmpp:jingle:1"); / jingle.addChild(ElementFactory.create("sdp", Base64.encode(sdpData.getBytes()), SDP.TIGASE_SDP_XMLNS)); Str...
181845258_121
public PullResult getOpMessage(int queueId, long offset, int nums) { String group = TransactionalMessageUtil.buildConsumerGroup(); String topic = TransactionalMessageUtil.buildOpTopic(); SubscriptionData sub = new SubscriptionData(topic, "*"); return getMessage(group, topic, queueId, offset, nums, sub);...
181888758_2
public void run(String... args) throws Exception { CommandLine cmd = parseCommandLine(args); String inputFile = cmd.getOptionValue("input"); String outputFile = cmd.getOptionValue("output"); String yml = FileUtils.readFileToString(new File(inputFile), (String)null); Service service = fromYaml(yml, Service...
181997557_0
public byte[] update(byte[] input, int offset, int inputLength) { int reserveToApply = Math.min(reserve.length, inputLength); int reserveToRelease = Math.max(reserveToApply - capacity(), 0); byte[] output = new byte[reserveToRelease + (inputLength - reserveToApply)]; read(output, 0, reserveTo...
182006329_182
@Override public boolean open(String topic, String channelName) throws BrokerException { log.info("open topic: {} channelName: {}", topic, channelName); ParamCheckUtils.validateTopicName(topic); validateChannelName(channelName); try { return fabricDelegate.getFabricMap().get(channelName).create...
182082980_6
public Map<String, SshUri> getSshKeysByHostname() { return extractNestedProperties(sshUriProperties); }
182200911_1
public static String create() { return Base64Utils.encodeToUrlSafeString(UUID.randomUUID().toString().getBytes()); }
182454442_4
public GenericScimResource trimRetrievedResource(final T returnedResource) { return trimReturned(returnedResource, null, null); }
182813463_18
public String convert(String format, Object value) { String str = ""; if (value instanceof String) { str = csvConverter("-var-file=%s ", (String) value); } return str; }
182842409_47
public String getFullyQualifiedDatabaseName() { return this.fullyQualifiedDbName; }
183285709_18
static List<SocketAddress> getSeedAddress() { List<SocketAddress> seedAddresses = null; try { String s = conf.getString("netifi.client.seedAddresses"); if (s != null) { seedAddresses = new ArrayList<>(); String[] split = s.split(","); for (String a : split) { String[] split1 = a.sp...
183382045_2
@Override public ServiceCall<NotUsed, String> proxyViaHttp(String id) { return req -> helloService.hello(id).invoke(); }
183462598_0
@Override public String generateCode(String phone) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxLength; i++) { int index = random.nextInt(arr.size()); sb.append(arr.get(index)); if (sb.length() >= minLength) { if (random.nextBoolean()) { br...
183523285_12
public boolean deregisterQuery(String targetApp, String subId, String query) { appToSubscriptionMap.computeIfPresent(targetApp, (k, v) -> { v.deregisterQuery(subId, query); return v; }); return true; }
183536958_1
@Override public Jwt buildJwt(Date issued, Date expiration) { String kid = issuerDid.getDid() + "#" + issuerDid.getKeyId(); return new Jwt.Builder() .alg(issuerDid.getAlgorithm()) .kid(kid) .iss(issuerDid.getDid()) .iat(issued) .exp(expiration) ...
183646665_3
@Override public boolean deepEquals(Object o) { if (this == o) { return true; } if (!(o instanceof Step)) { return false; } Step step = (Step) o; if (this.id != null ? !this.id.equals(step.id) : step.id != null) { return false; } if (this.metadataId != null ? !this.metadataId.equals(step.m...
183863609_0
@GetMapping("/employees") private Flux<Employee> getAllEmpployees() { return employeeService.findAll(); }
183916330_0
@SuppressWarnings("unused") public void insertPair(ArrayList<Object> key, long value) throws IOException, MiniDBException, IllegalStateException { if(root == null) {throw new IllegalStateException("Can't insert to null tree");} conf.padKey(key); // check if our root is full if...
183933015_15
@Override public Status read(String tableName, String key, Set<String> fields, Map<String, ByteIterator> result) { try { StatementType type = new StatementType(StatementType.Type.READ, tableName, 1, "", getShardIndexByKey(key)); PreparedStatement readStatement = cachedStatements.get(type); if (readStateme...
183937162_747
public String readUnicodeString(long index) throws IOException { StringBuffer buffer = new StringBuffer(); while (index < length()) { int ch = readUnsignedShort(index); if (ch == 0) { break; } buffer.append((char) ch); index += 2; } return buffer.toString().trim(); }
184033608_9
@RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public @ResponseBody Long addProject(@RequestBody @Valid Projekt projekt) { LOG.info("POST called on /projects resource"); projektRepository.save(projekt); LOG.info("Projekt successfully saved into DB with id " + projekt.getI...
184035533_3
@NotNull @Override public CompassConfig parse(@NotNull final VirtualFile file, @NotNull final String importPathsRoot, @Nullable final PsiManager psiManager) { return ReadAction.compute(() -> { PsiFile psiFile = psiManager != null ? psiManager.findFile(file) : ...
184219031_10
@Override public String name() { return "hint"; }
184265896_209
protected Rectangle getMonthBoundsAtLocation(int x, int y) { if (!calendarGrid.contains(x, y)) return null; int calendarRow = (y - calendarGrid.y) / fullCalendarHeight; int calendarColumn = (x - calendarGrid.x) / fullCalendarWidth; return new Rectangle(calendarGrid.x + calendarColumn * fullCalen...
184285250_188
public static String l(long v, int width) { return pad(Long.toString(v), width, true); }
184301969_5
public static PathData findShortestPath(Graph graph, String sourceNodeIdentifier, String targetNodeIdentifier) throws ArrayStoreException { return findShortestPath(graph, graph.getNode(sourceNodeIdentifier), graph.getNode(targetNodeIdentifier)); }
184386453_0
public String translate(String text, String lang) { Translation translationResult = translateApi.translate(text, TranslateOption.targetLanguage(lang)); return translationResult.getTranslatedText(); }
184429237_0
@Override public Void handleRequest(S3Event event, Context context) { logger = context.getLogger(); try { initialize(); logger.log(String.format( "Parameters: hostname [%s:%d] index [%s], username [%s], pipeline [%s], ssl/tls [%b]", ELASTIC_HOSTNAME, ELASTIC_POR...
184471389_18
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; // Skip filter if there isn't any selector in the URL String selector = slingRequest.getReques...
184496771_3
@Override public ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final Logger logger) { final SesClient client = ClientBuilder.getClient(); final Res...
184569540_75
public String getFullName() { return getFullName(null); }
184650438_19
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { final String PARAMETER_OFFSET = "_commerce_offset"; final String PARAMETER_LIMIT = "_commerce_limit"; final String PARAMETER_COMMERCE_TYPE = "_commerce_commerce_type"; final Config cfg = new Con...
185170825_0
public long nextId() { long timestamp = System.currentTimeMillis(); if (timestamp < lastTimestamp) { throw new IllegalStateException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp...
185218009_0
public static AdditionalBuildCommands load(Path file) throws IOException { logger.entering(file); AdditionalBuildCommands result = new AdditionalBuildCommands(); result.contents = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(file)) { List<String> buffer = new ArrayList<...
185263418_0
@NotNull public static SchemaTransformer transform(final GraphQLSchema schema) { return new SchemaTransformer(schema); }
185267261_2
@CrossOrigin @RequestMapping(value = L10NAPIV1.UPDATE_TRANSLATION_L10N, method = RequestMethod.POST, produces = { API.API_CHARSET }) @ResponseStatus(HttpStatus.OK) public APIResponseDTO updateTranslation( @RequestBody UpdateTranslationDTO updateTranslationDTO, @PathVariable(APIParamName.PRODUCT_NAME) St...
185394887_8
public static <O> MultiArray<O> wrap(final O elements, final int[] dimensions) { return wrap(elements, 0, dimensions); }
185475705_6
private RawSchema parse() throws SyntaxError { RawSchemaBuilder rawSchemaBuilder = new RawSchemaBuilder(); nextToken(); // first token while (currentToken != TokenType.EOF) { switch (currentToken) { case INTERFACE: rawSchemaBuilder.addInterface(parseEntity()); ...
185565206_0
public static String findConnectorLibPath(String dbType) { DbType type = DbType.valueOf(dbType); URL resource = Thread.currentThread().getContextClassLoader().getResource("logback.xml"); _LOG.info("jar resource: {}", resource); if (resource != null) { try { File file = new File(resource.toURI().getRawPath() + ...
185576294_6
@Override public synchronized void event( long gen, String eventName, String tagName, long tagId, long nanoTime) { writeNnss(gen + EVENT_N2S2_OP, nanoTime, tagId, eventName, tagName); }
185739179_51
@Override public void execute(SensorContext context) { if (shouldExecuteOnProject()) { for (RuleViolation violation : executor.execute()) { pmdViolationRecorder.saveViolation(violation, context); } } }
185796725_67
public final static char toUpperAscii(char c) { if (isLowercaseAlpha(c)) { c -= (char) 0x20; } return c; }
185821779_6
@Override public OAuthUser take() { var user = userSessionRepository.take().getUser(); if (user instanceof OAuthUser) { return (OAuthUser) user; } throw new NoUserFoundException("No OAuth users found in the repository."); }
185828241_1
public boolean exists(long id) { String sqlQuery = "select count(*) from employees where id = ?"; //noinspection ConstantConditions: return value is always an int, so NPE is impossible here int result = jdbcTemplate.queryForObject(sqlQuery, Integer.class, id); return result == 1; }
185871137_25
@SuppressWarnings("unchecked") @Override public <T> T decode(Response response, Class<T> type) { try { if (byte[].class.equals(type)) { return (T) response.toByteArray(); } else if (InputStream.class.isAssignableFrom(type)) { /* return a byte array input stream */ return (T) response.body();...
186128056_7
@DeleteMapping("/{id}") public ResponseEntity<Void> resign(@PathVariable long id) { if (employeeRepository.findById(id).isPresent()) { employeeRepository.deleteById(id); return ResponseEntity.noContent().build(); } else { return ResponseEntity.notFound().build(); } }
186282860_2
public String convert(String input, boolean capitalize) { return transliterate(input, capitalize); }
186347363_1
public void revokeToken(TokenTypeHint tokenTypeHint, String token, String clientId) { if (TokenTypeHint.refresh_token.equals(tokenTypeHint)) { revokeRefreshToken(token, clientId); } else { revokeAccessToken(token, clientId); } }
186361323_1
public static String firstCharToUpperCase(String str) { char firstChar = str.charAt(0); if (firstChar >= 'a' && firstChar <= 'z') { char[] arr = str.toCharArray(); arr[0] -= ('a' - 'A'); return new String(arr); } return str; }
186387230_2
;
186525996_1
public Friend() { }
186556620_53
@Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, ...
186642789_1
public EmployeeFixed findEmployeeById(String id) { return this.employees.stream() .filter(e -> e.getId().equals(id)) .findFirst() .orElse(null); }
186955716_0
public Flux<Reservation> getAllReservations() { return this.client.get() .uri("http://localhost:8080/reservations") .retrieve() .bodyToFlux(Reservation.class); }
186978836_31
public static String getKeyTenant(String dataId, String group, String tenant) { return doGetKey(dataId, group, tenant); }
187556247_613
public void openFile() { openFile( false ); }
187590023_3
@CacheEvict(value = "people", key = "#id") @Override public void remove(Long id) { log.info("删除了id、key为" + id + "的数据缓存"); }
187595602_12
static ProxyProvider createInternalProxy(final DeploymentConfiguration config, final RegistryQueryResult queryResult) throws IOException { final String autoConfigUrl = queryResult.getValue(AUTO_CONFIG_URL_VAL); if (autoConfigUrl != null) { LOG.debug("Registry value '{}' specified. Will use pac based pro...
187648701_0
protected static void generateDiff(OpObject editObject, String field, Map<String, Object> change, Map<String, Object> current, Map<String, Object> oldM, Map<String, Object> newM) { TreeSet<String> removedTags = new TreeSet<>(oldM.keySet()); removedTags.removeAll(newM.keySet()); for(String removedTag : removedTags)...
187765477_5
@Override public LoadedResource loadIfModified(HttpResourceId resourceId, SourceVersion version) { var cacheControl = resourceId.getCacheControl(); if (version == SourceVersion.EMPTY || cacheControl == CacheControlStrategy.NONE) { return loadResource(resourceId); } else if (cacheControl == CacheCont...
187767967_2
@Override public boolean isCollection(Type type) { if (type instanceof Class) { var clazz = (Class)type; if (clazz.isArray()) { return true; } if (Collection.class.isAssignableFrom(clazz)) { return true; } } else if (type instanceof Parame...
187873041_1
@Override public Collection<IPermissionGroup> getGroups() { for (IPermissionGroup permissionGroup : this.permissionGroupsMap.values()) { if (this.testPermissionGroup(permissionGroup)) { this.updateGroup(permissionGroup); } } return this.permissionGroupsMap.values(); }
187946264_2
public static <T extends ServerResponse> RouterFunction<T> route( RequestPredicate predicate, HandlerFunction<T> handlerFunction) { return new DefaultRouterFunction<>(predicate, handlerFunction); }
187972412_38
@Override public List<MessageView> queryMessageByTopic(String topic, final long begin, final long end) { DefaultMQPullConsumer consumer = new DefaultMQPullConsumer(MixAll.TOOLS_CONSUMER_GROUP, null); List<MessageView> messageViewList = Lists.newArrayList(); try { String subExpression = "*"; ...
188055485_6
@Override public CommonResult listItemsByCollectionIdAndProjectId(ProjectParam projectParam){ Integer collectionId = projectParam.getCollectionId(); Integer projectId = projectParam.getProjectId(); List<HashMap> projectDetails; if(collectionId.toString().startsWith("2")){ projectDetails = inspe...
188058370_0
public static boolean isNullOrEmpty(String str) { return str == null || str.isEmpty(); }
188081982_21
public Hand hand(CardSet cardSet) { List<Card> handCards = cardSet.getSortedCards(); // Figure our high card by same color SUIT colorCandidate = handCards.get(0).getSuit(); boolean allSameColor = handCards.stream() .allMatch(card -> card.getSuit().equals(colorCandidate)); if (allSameCol...
188223092_16
public void addModel(final String modeluri, final EObject model) throws IOException { final Resource resource = resourceSet.createResource(createURI(modeluri)); resourceSet.getResources().add(resource); resource.getContents().add(model); resource.save(null); }
188228592_362
public static Builder newBuilder(String name) { return new Builder(name); }
188229074_0
@Override @RolesAllowed(ApplicationAccessControlConfig.PERMISSION_SAVE_KEY_LIST) public KeyListEto saveKeyList(KeyListEto keyList) { Objects.requireNonNull(keyList, "keyList"); KeyListEntity keyListEntity = getBeanMapper().map(keyList, KeyListEntity.class); KeyList entity = keyList; Long id = keyList.getId()...
188279001_0
public PokemonResponse assemble(Pokemon data) { return PokemonResponse.builder() .name(data.getName()) .abilities(data.getAbilities()) .baseExperience(data.getBaseExperience()) .weight(data.getWeight()) .height(data.getHeight()) .build(); }
188292946_0
public static <T> T get(Class<T> supplier) { return getSupplier(requireNonNull(supplier, "supplier is required")); }
188402392_0
@Override public byte[] getValue(List<String> tagNames, String returnTimestamp, boolean excludeNullValue, String nullValueString) throws ProcessException { try { if (opcClient == null) { throw new ProcessException("OPC Client is null. OPC UA service was not enabled properl...
188429680_19
public boolean isMultiSentenceInstruction() { int fromIndex = 0; int dotInd; while ((dotInd = instructionUtterance.indexOf(".", fromIndex)) >= 0){ if (!instructionUtterance.substring(dotInd + 1).trim().isEmpty() && // The dot isn't the end of the utterance. StringUtils.isBlank(instructionUtterance.substring(d...
188534881_1
Optional<String> select(String version) { if (version.isEmpty()) { // of nullable since map could be empty return Optional.ofNullable(m.lastEntry().getValue()); } // strip "v" at head of string version = version.substring(1); int separatorIndex = version.indexOf("."); if (separatorIndex != -1) { // major, m...
188592933_0
public Optional<Long> nextDelay() { if (lastAttemptIndex == 0) { lastAttemptIndex++; return Optional.of(0L); } if (genericRetry.getMaxAttempts() > -1 && lastAttemptIndex >= genericRetry.getMaxAttempts()) { return Optional.empty(); } if (lastAttemptIndex > 1) { current...
188643956_0
public static Inventory create(String productId, String productName) { return Inventory.builder() .id(newUuid()) .productId(productId) .productName(productName) .remains(0) .createdAt(Instant.now()) .build(); }
188644064_0
public static Product create(String name, String description, BigDecimal price, String categoryId) { Product product = Product.builder() .id(newUuid()) .name(name) .description(description) .price(price) .createdAt(Instant.now()) .inventory(0) ...
188857939_0
public void upload(Object openAPI, boolean merge) throws IOException { Map<String, Object> send = new HashMap<>(4); send.put("type", "swagger"); send.put("token", projectToken); send.put("merge", merge); send.put("json", mapper.writeValueAsString(openAPI)); HttpClientUtil.getHttpclient().execut...
189010032_0
@Override @Cacheable(cacheNames = "UserDetails", unless = "#username == null", cacheManager = "JDKCacheManager") public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Assert.notNull(username, "用户名不能为空"); User user = userService.selectByUsername(username); ...
189012247_10
@Override public List<IKafkaMessageHandler<T>> getForTopicOrFail(String topic) { List<IKafkaMessageHandler<T>> topicKafkaMessageHandlers = getForTopic(topic); if (topicKafkaMessageHandlers.isEmpty()) { throw new IllegalStateException("No handler found for topic '" + topic + "'."); } return topicKafkaMessage...
189027594_176
@Override public String decryptCardCode(String encryptCode) throws WxErrorException { JsonObject param = new JsonObject(); param.addProperty("encrypt_code", encryptCode); String responseContent = this.wxMpService.post(CARD_CODE_DECRYPT, param.toString()); JsonElement tmpJsonElement = new JsonParser().parse(resp...
189191730_26
@Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(pattern.pattern(), patternType); return result; }
189204070_1
@Override public List<Room> findRoomsByType(String type) { if (roomTypes.contains(type)) { return roomRepo.findRoomsByRoomType(type); } else { throw new RoomServiceException("Room type: " + type + " not found!"); } }
189356507_1
@Override protected void closeClient() { if (client != null) { // close the producer. while (true) { try { client.close(); break; } catch (InterruptedException e) { // ignore interrupt signal to avoid io thread leaking. } catch (ProducerException e) { LOGGER.warn("Exception caught when clo...
189556566_0
public static String getSizeString(long size){ if(size < 1024){ return String.format(Locale.getDefault(), "%d B", size); }else if(size < 1024 * 1024){ float sizeK = size / 1024f; return String.format(Locale.getDefault(), "%.2f KB", sizeK); }else if(size < 1024 * 1024 * 1024){ ...
189605649_51
@SuppressWarnings("WeakerAccess") public boolean containsAssetType(MediaAssetType assetType) { return mediaAssetTypes.isEmpty() || mediaAssetTypes.contains(assetType) || mediaAssetTypes.contains(MediaAssetType.All); }
189734293_0
@Override public String toString() { return "MethodEvent{" + "className='" + className + '\'' + ", methodAccessFlag=" + methodAccessFlag + ", methodName='" + methodName + '\'' + ", methodDesc='" + methodDesc + '\'' + ", isEnter=" + isEnter + ",...
189841989_2
public static <T> Stream<List<Optional<T>>> combinations(List<T> list) { long n = (long) Math.pow(2, list.size()); return StreamSupport.stream(new Spliterators.AbstractSpliterator<>(n, Spliterator.SIZED) { long i = 0; @Override public boolean tryAdvance(Consumer<? super List<Optional<T...
189845277_4
public static Builder route() { return new RouterFunctionBuilder(); }
190100311_0
@Nonnull @Override public String create() throws IdentityException { Validate.notNull(account.getUsername(), "username must be set"); Validate.notNull(account.getFirstName(), "first name must be set"); Validate.notNull(account.getLastName(), "last name must be set"); Validate.notNull(account.getPassword...
190168097_216
@ChaosExperiment(experimentType = ExperimentType.STATE) public void restartInstance (Experiment experiment) { experiment.setCheckContainerHealth(() -> awsRDSPlatform.getInstanceStatus(dbInstanceIdentifier)); awsRDSPlatform.restartInstance(dbInstanceIdentifier); }
190197552_1
public URI getUri() { return this.uri; }
190209753_0
public static double pow2(int p) { if (p < 0) { return 1.0 / (1L << -p); } if (p > 0) { return 1L << p; } return 1.0; }