id
stringlengths
7
14
text
stringlengths
1
37.2k
111391133_89
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Map<String, String> attachments = setCallChainContextMap(invocation); if (attachments != null) { attachments = new HashMap<String, String>(attachments); attachments.remove(Constants.PATH_KEY); attach...
111433118_3
@Bean @ConditionalOnMissingBean(WebhookController.class) public WebhookController webhookController(SpeechRequestDispatcher dispatcher) { return new WebhookController(dispatcher); }
111445552_5
public static String getUtf8FromByteBuffer(final ByteBuffer bb) { bb.rewind(); byte[] bytes; if (bb.hasArray()) { bytes = bb.array(); } else { bytes = new byte[bb.remaining()]; bb.get(bytes); } return new String(bytes, StandardCharsets.UTF_8); }
111517878_42
public static ShortString parse(ByteBuf buf) { int size = buf.readUnsignedByte(); byte[] data = new byte[size]; buf.readBytes(data); return new ShortString(size, data); }
111640979_1
public void sendtemplateHtmlMail(String subject, String to, String name) { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { // 创建多部件的mail MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject(subject); helper.setTo(to); ...
111669949_29
@Override public boolean equals(Object obj) { return ObjectEquals.of(this) .equals(obj, (orgin, other) -> Objects.equals(orgin.getUsername(), other.getUsername())); }
111680003_0
public void classicalDelete(Long id) { authService.checkAccess(); System.out.println("Delete Product."); }
111690131_4
public static Loan createTermLoan(double commitment, int riskTaking, Date maturity){ return new Loan(null, commitment, 0.00, riskTaking, maturity, null); }
111698811_1
public static ArrayList<VideoStream> getSortedStreamVideosList(Context context, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder) { boolean showHigherResolutions = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.show_higher_resol...
111703773_3
@Override public ImageWriteParam getDefaultWriteParam() { return new OpenJp2ImageWriteParam(); }
111811015_54
public static int getCurrentUid() { return android.os.Process.myUid(); }
111825535_9
@Override public void customize(ConfigurableEmbeddedServletContainer container) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711 mappings.add("html", "text/html;charset=utf-8"); // CloudFoundry issue, see https://g...
111854037_474
@Override @SuppressWarnings("ReferenceEquality") public boolean handleBuffer(ByteBuffer buffer, long presentationTimeUs) throws InitializationException, WriteException { Assertions.checkArgument(inputBuffer == null || buffer == inputBuffer); if (pendingConfiguration != null) { if (!drainAudioProcessorsToEn...
111972694_1
@Override public int execute(final List<String> commandInformation, File workingDir) throws IOException, InterruptedException { int exitValue = -99; try { ProcessBuilder pb = new ProcessBuilder(commandInformation); pb.directory(workingDir); Process process = pb.start(); // y...
112094343_36
public List<Station> listStationsBy(@NonNull final Paging paging, @NonNull final SearchMode searchMode, @NonNull final String searchTerm, final ListParameter...listParam) { MultivaluedMap<String, String> requ...
112101025_42
public RecordManager( String fileName ) { this( fileName, DEFAULT_PAGE_SIZE ); }
112128651_0
public static <T extends ServerResponse> RouterFunction<T> route(RequestPredicate predicate, HandlerFunction<T> handlerFunction) { Assert.notNull(predicate, "'predicate' must not be null"); Assert.notNull(handlerFunction, "'handlerFunction' must not be null"); return new DefaultRouterFunction<>(predicate, handle...
112199510_3
@Override public ProductInfo save(ProductInfo productInfo) { return repository.save(productInfo); }
112254161_6
private int concatBytes(final int msb, final int lsb, final boolean isSigned) { if (isSigned) { return (msb << 8) | (lsb & 0xff); // keep the sign of msb but not of lsb } else { return ((msb & 0xff) << 8) | (lsb & 0xff); } }
112291646_1
public void apply(Project project) { AzureWebAppExtension azureWebAppExtension = new AzureWebAppExtension(project); project.getExtensions().add(WEBAPP_EXTENSION_NAME, azureWebAppExtension); project.getTasks().create(DeployTask.TASK_NAME, DeployTask.class, (task) -> { task.setAzureWebAppExtension(azu...
112332641_0
@PreAuthorize("#oauth2.hasAnyScope('server', 'ui')") @RequestMapping(value = "/{userId}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) @ResponseBody public ResponseEntity delete(@PathVariable UUID userId){ UserCredentials credentials = userService.findCredentialsByUserId(userId); if(cre...
112424920_1
public static String hiddenMiddlePhoneNum(String phoneNumber) throws IOException { if (!isPhoneNumber(phoneNumber)) { throw new IOException("phoneNumber invalid"); } return phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); }
112428883_0
public Mono<Optional<GetCustomerResponse>> findCustomerById(String customerId) { Mono<ClientResponse> response = client .get() .uri(customerServiceUrl + "/customers/{customerId}", customerId) .exchange(); return response.flatMap(resp -> { switch (resp.statusCode()) { case OK:...
112437215_0
public static void toFile(String oldFile, String newFile, ImageParamDTO params) throws IOException { if (StringUtils.isBlank(oldFile) || StringUtils.isBlank(newFile)) { logger.error("原文件名或目标文件名为空"); return; } Thumbnails.Builder builder = Thumbnails.of(oldFile); fillBuilderWithParams(buil...
112444990_135
public CameraParametersDecorator toPlatformParameters(Parameters parameters, CameraParametersDecorator output) { for (Parameters.Type storedType : parameters.storedTypes()) { applyParameter( storedType, parameters, ...
112465036_7
@Override public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { CallAdapter<?, ?> delegate = retrofit.nextCallAdapter(this, returnType, annotations); return new LoggingCallAdapter<>(delegate, logger); }
112628388_4
public static Object convertValueToType(Class<?> fieldType, String formattedValue, String columnName, int rowNum) { Object value = null; if (fieldType == String.class) { value = String.valueOf(formattedValue); } else if (fieldType == LocalDateTime.class) { return Converters.toLocalDateTime.c...
112785414_2
public final boolean match(List<MediaType> acceptedMediaTypes) { boolean match = matchMediaType(acceptedMediaTypes); return (!isNegated() ? match : !match); }
112941183_81
public static int getPid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); // format: "pid@hostname" try { return Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Exception e) { return -1; } }
112945272_3
protected byte[] validateAndStripChecksum(byte[] source) { // retrieve checksum int lastIndexOf = Bytes.lastIndexOf(source, (byte) SEPARATOR); if (lastIndexOf < 0) { throw new RuntimeException("no checksum was found on source: " + new String(source)); } long checkSum = Long.parseLong(new String(Arrays.copyOfRang...
112975556_9
int remainingExtras() { return extras.size(); }
113003835_0
public static boolean hasPermissions(@NonNull Context context, @Size(min = 1) @NonNull String... perms) { // Always return true for SDK < M, let the system deal with the permissions if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Log.w(TAG, "hasPermissions: API ...
113079801_0
public void setContrast(int level) throws IOException, IllegalArgumentException { if (mI2cDevice == null) { throw new IllegalStateException("I2C Device not open"); } if (level < 0 || level > 255) { throw new IllegalArgumentException("Invalid contrast " + String.valueOf(level) + ...
113164027_59
@Transactional @Override public boolean checkAttempt(final MultiplicationResultAttempt attempt) { // Check if the user already exists for that alias Optional<User> user = userRepository.findByAlias(attempt.getUser().getAlias()); // Avoids 'hack' attempts Assert.isTrue(!attempt.isCorrect(), "You can't s...
113194597_6
public final static void main(String[] args) throws Exception { logger.debug(format("CM Client has been called with command line '%s'.", getArgsLogString(args))); CommandLine commandLine = new DefaultParser().parse(Helpers.getStandardParameters(true), args, true); if((commandLine.hasOption(CMOptions.HELP...
113222463_311
public String generate(String schemaName) { return generate(schemaName, schema); }
113356740_1
public static <T extends Message> T buildMessage(T message, Map<String, Object> fields) { @SuppressWarnings("unchecked") T populatedMessage = (T) buildMessage(message.toBuilder(), fields); return populatedMessage; }
113375834_1255
@Override public Object getValue(String key) { Object value = null; if (myExtraColumns.containsKey(key)) { value = myExtraColumns.get(key); } else { value = myOriginal.getValue(key); } return value; }
113380752_0
@Override public API add(API api) { api.setId(UUID.randomUUID().toString()); jpaTemplate.tx( TransactionType.Required, entityManager -> { entityManager.persist(mapTo(api)); entityManager.flush(); }); return api; }
113416930_1
@Override protected void log(int priority, String tag, @NotNull String message, Throwable t) { if (skipLog(priority, tag, message, t)) { return; } if (t != null) { throw new LogPriorityExceededError(priority, getPriorityFilter().getMinPriority(), t); } else { throw new LogPriori...
113425021_115
public Hasher putDouble(double d) { hasher.putDouble(d); return this; }
113428293_6
public static String colorValue(int red, int green, int blue) { return String.format(COLORVALUEFORMAT, red, green, blue); }
113508911_0
public boolean hasNoCertificates() { return (certs == null || certs.length == 0); }
113554956_2
@Override public long[] recommend(String taskName, int userID) { return recommend(taskName, null, null, null, userID); }
113563925_18
public static ScheduledAction getNextScheduledPayment(final @Nonnull LocalDate startOfTerm, final @Nonnull LocalDate fromDate, final @Nonnull LocalDate endOfTerm, ...
113564534_1
public static void process(final Cluster.Builder clusterBuilder, final String contactPoints) { final String[] splitContactPoints = contactPoints.split(","); for (final String contactPoint : splitContactPoints) { if (contactPoint.contains(":")) { final String[] address = contactPoint.split(":"); clus...
113585452_0
public static PahoRxMqttCallback create( Consumer<Throwable> onConnectionLost, BiConsumer<Boolean, String> onConnectComplete) { return create( onConnectionLost, onConnectComplete, token -> { /* NOP */ }); }
113597154_117
@GET public Response performMatchingServiceHealthCheck() { final AggregatedMatchingServicesHealthCheckResult result = matchingServiceHealthCheckHandler.handle(); final Response.ResponseBuilder response = result.isHealthy() ? Response.ok() : Response.serverError(); response.entity(result); return respon...
113597875_26
public static <V> V get(ListenableFuture<V> future) throws ExecutionException, InterruptedException, SuspendExecution { if (Fiber.isCurrentFiber() && !future.isDone()) return new AsyncListenableFuture<>(future).run(); else return future.get(); }
113678320_1
public static String sayHello(String who) throws Exception { return "Hello " + who; }
113689042_2
public boolean addObstacle(Obstacle o) { return verifyObstacle(o) ? obstacles.add(o) : false; }
113726044_0
public Vertex combine(int from, int length) { this.connect(from, length); if (wordnet.isNotContains(from, length)) { return wordnet.put(from, length); } else { return wordnet.getVertex(from, length); } }
113727261_0
public void send(){ String context = "hello" + new Date() ; _logger.info("正在向队列发送消息:{}",context); this.rabbitMqTemplate.convertAndSend(RabbitMqConfig.queueName,context); }
113899964_1
@Override public Optional<Listener> acquire(ContextT context) { return tryAcquire(context).map(delegate -> new Listener() { @Override public void onSuccess() { delegate.onSuccess(); unblock(); } @Override public void onIgnore() { delegate....
114149111_1
@Override public ImmutableList<MetricPoint<V>> getTimestampedValues() { return getTimestampedValues(Instant.now()); }
114157177_36
public boolean eval(DataFile file) { // TODO: detect the case where a column is missing from the file using file's max field id. return visitor().eval(file); }
114263933_47
@Override public UOctet decodeUOctet() throws MALException { return new UOctet((short) (read() & 0xFF)); }
114273718_0
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { try { this.messageSigner.sign(new Request(request)); } catch (GeneralSecurityException e) { throw new HttpException("Can't sign HTTP request '" + request + "'", e); } }
114312965_12
public Set<String> getAllTables(@NotNull String dbName, @Nullable String filter) throws TException { if (filter == null || filter.isEmpty()) { return new HashSet<>(client.get_all_tables(dbName)); } return client.get_all_tables(dbName) .stream() .filter(n -> n.matches(filter)) .collect(Collec...
114408926_0
String cleanseTag(@NonNull String tag) { final String originalTag = tag; tag = tag.toLowerCase().replaceAll(" ", "_").replaceAll("[^A-Za-z0-9_]", ""); if (!originalTag.equals(tag)) { log("Cleansed Tag: [" + originalTag + "] -> [" + tag + "]"); } return tag; }
114418594_45
@Complexity(EASY) public static Flux<String> dropElementsOnBackpressure(Flux<String> upstream) { // TODO: apply backpressure to drop elements on downstream overwhelming // HINT: Flux#onBackpressureDrop throw new RuntimeException("Not implemented"); }
114489910_12
@Override @Transactional(readOnly = true) public IngredientType getIngredientTypeByIngredientId(Long ingredientId) { return ingredientDAO.findById(ingredientId).orElseThrow(RuntimeException::new).getIngredientType(); }
114520717_207
public synchronized void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause) { Listener4Model model = modelHandler.removeOrCreate(task, task.getInfo()); if (assistExtend != null && assistExtend.dispatchTaskEnd(task, cause, realCause, model)) { ...
114619810_1
@Override public void checkJobExecutionEnvironment() throws JobExecutionEnvironmentException { }
114649434_8
public static int MCRF4XX(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x1021, 0xFFFF, data, offset, length, true, true, 0x0000); }
114670580_2
<K, V, U> void onTableAccessReqMsg(final long opId, final TableAccessReqMsg msg) { final String origEvalId = msg.getOrigId(); final OpType opType = msg.getOpType(); final boolean replyRequired = msg.getReplyRequired(); final String tableId = msg.getTableId(); final TableComponents<K, V, U> tableComponents; ...
114688767_69
@Override public Path extract() { if (sptEntry == null || edgeTo == null) return this; if (sptEntry.adjNode != edgeTo.adjNode) throw new IllegalStateException("Locations of the 'to'- and 'from'-Edge has to be the same." + toString() + ", fromEntry:" + sptEntry + ", toEntry:" + edgeTo); ext...
114698912_0
@Override public boolean test(String topicName) { int tc = 0; int fc = 0; while(true) { // begin of path part if( filter.charAt(fc) == '+') { fc++; // eat + // matches one path part, skip all up to / or end in topic while( (tc < topicName.length()) && (topicName.charAt(tc) != '/') ) tc++; ...
114701607_3
private static byte[] bcrypt(char[] password, byte[] salt, int logRounds) { StrictMode.noteSlowCall("bcrypt is a very expensive call and should not be done on the main thread"); return BCrypt.with(CUSTOM_LEGACY_VERSION, new SecureRandom(), rawPassword -> Bytes.wrapNullSafe(rawPassword).copy().array()).hash(logR...
114775425_0
public static FloatProcessor genLaplacianOfGaussianKernel(double sigma) { int size = (int) Math.max(Math.round(sigma * 5)+1, 3); if (size % 2 == 0) size += 1; // make sure we have a 2n+1 matrix float [] kernel = new float[size*size]; float sum = 0; final double a = -1/(Math.PI* pow(sigma, 4)); ...
114886091_6
@Override public void validate(Object target, Errors errors) { SignupForm form = (SignupForm) target; validateUniqueEmail(form, errors); validateUniquePhone(form, errors); validateValidPhone(form, errors); validatePassword(form, errors); }
114928169_21
public boolean hasCustomContent() { return customContent; }
114949862_36
public JobTemplateDeleteResponse deleteJobTemplate(String xProjectId, Long templateId) throws ApiException { ApiResponse<JobTemplateDeleteResponse> resp = deleteJobTemplateWithHttpInfo(xProjectId, templateId); return resp.getData(); }
114983680_64
public static byte[] encode(Object value) { if (value instanceof Integer || value instanceof Long || value instanceof Boolean) { return encodeVarInt(value, 0); } else if (value instanceof Double) { // 固定8byte+1Byte Double val = (Double) value; long longBits = Double.doubleToLongBits(val); byte type = 0; ...
115041372_2
public int getGastoTotal() { int gasto = 0; Iterator<ComponenteElectrico> iterador = estufas.iterator(); while (iterador.hasNext()){ ComponenteElectrico estufa = iterador.next(); gasto = gasto + estufa.getConsumo(); } iterador = cercos.iterator(); while (iterador.hasNext()){...
115077083_1378
public void validateOrchestrationStatus(BuildingBlockExecution execution) { try { execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT, null); String buildingBlockFlowName = execution.getFlowToBeCalled(); BuildingBlockDetail buildingBlockDetail = catalogDbClient.getBuildingBlockDetai...
115260386_8
@Override public void save(Course course) { delete(course.getId()); course.setId(nextId()); courseList.add(course); }
115315431_6
public int updateUserImg(String email, String imgUrl) { return userDao.updateUserImg(imgUrl, email); }
115411826_3
public synchronized Node addNode(Node n) { NodeEntry e = new NodeEntry(node.getId(), n); if (nodes.contains(e)) { nodes.forEach(nodeEntry -> { if (nodeEntry.equals(e)) { nodeEntry.touch(); } }); return null; } NodeEntry lastSeen = buckets[getBucketId(e)].addNode(e); if (lastSee...
115451647_15
@Override public boolean verifyEncoded(String encodedHash, int threads, byte[] secret, byte[] ad, byte[] password, Map<String, Object> options) { if (encodedHash == null) { throw new Jargon2BackendException("Encoded hash cannot be null"); } if ("".equals(encodedHash.trim())) { throw new Jar...
115516500_316
@Override public void close() { if (ch.isOpen()) { ch.close(); } }
115558016_1
@Override public List<BookOutputData> getBooks(BookListByAuthorInputData bookListByAuthorInputData) { Optional<List<Book>> books = bookGateway.findByAuthor(bookListByAuthorInputData.getAuthor()); if (!books.isPresent()) { throw new BooksNotFoundException(); } return books.get().stream().map(Book::mapToBoo...
115569790_68
@Override public void onMessage(String text) { try { JSONObject message = new JSONObject(text); int version = message.optInt("version"); String method = message.optString("method"); Object id = message.opt("id"); Object params = message.opt("params"); if (version != PROTOCOL_VERSION) { ...
115604783_56
public void setVatRate(BigDecimal vatRate) { this.vatRate = vatRate; }
115611046_1
@Override protected RecognitionResult startImpl() throws SpeechException { fireRecognizerEvent(RecognizerEvent.RECOGNIZER_LOADING); assert context != null : "cannot start recognition without a context"; csr = context.getRecognizer(); context.getVadListener().setRecognizer(this); vadInSpeech = false;...
115777140_0
public static String eval(String statement, JsonObject data) { for (String key : data.getMap().keySet()) { DataItem dataItem = new DataItem(data.getJsonObject(key)); statement = eval(statement, dataItem); } return statement; }
115838569_1
@Override public String process(MessageUpdate update, String locale) { StringBuilder response = new StringBuilder(); try { if (canProcess(update.getMessage().getText()) && !update.isEdited()) { List<String> itens = Arrays.asList(update.getMessage().getText().replaceAll("\\r|\\n", " ").split(...
115869675_6
@RequestMapping(method = RequestMethod.GET) public Iterable<Product> getProducts(@RequestParam("category") long categoryId) { return productService.findProductsByCategoryId(categoryId); }
115956753_2
public String toTelegraf(String json) { return json == null ? null : toTelegraf(json.getBytes()); }
116011653_544
@Override public Response getOrderPrice(String orderId, HttpHeaders headers) { Order order = orderOtherRepository.findById(UUID.fromString(orderId)); if (order == null) { return new Response<>(0, orderNotFound, "-1.0"); } else { OrderOtherServiceImpl.LOGGER.info("[Order Other Service][Get Or...
116057862_2
public final @NotNull CompletableFuture<S> subscribeSingleFuture() { final SingleFutureSubscriber<F, S> singleFutureSubscriber = new SingleFutureSubscriber<>(this); final CompletableFuture<S> future = singleFutureSubscriber.getFutureBeforeSubscribe(); singleFutureSubscriber.subscribe(); return future; }
116109319_16
@Override public double probability(int x) { final double logProbability = logProbability(x); return logProbability == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logProbability); }
116109482_0
public String mset(final Map<String, String> keyValueMap) { if (keyValueMap == null || keyValueMap.isEmpty()) { return null; } return new PipelineClusterCommand<String>(this, connectionHandler) { @Override public void pipelineCommand(Pipeline pipeline, List<String> pipelineKeys) { ...
116160086_20
public Long getCustomLongAttribute(String attributeName) { long attribute = 0; JSONObject jwt = getRawIdentityToken(); if (customAttributeExists(attributeName)) { attribute = jwt.optLong(attributeName); } return attribute; }
116163042_0
public static Name of(String name) { return new Name(name); }
116210732_2
public static Map<String,Double> calcRemainRate(Map<String,Long> remain,Map<String,Long> total){ Map<String,Double> doubleMap = new HashMap<>(); if(remain == null || remain.isEmpty() || total == null || total.isEmpty()){ return doubleMap; } String mount = null; long totalSize = 0L; long remainSize = 0L...
116228237_17
private static boolean verify(String body, String signature, PublicKey publicKey) { try { Signature sign = Signature.getInstance("SHA1WithRSA"); sign.initVerify(publicKey); sign.update(body.getBytes("UTF-8")); return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8"))); ...
116243444_0
@Override public TokenStream create(TokenStream tokenStream) { return new SudachiSurfaceFormFilter(tokenStream); }
116309308_53
public boolean fileExists(String path) throws IOException, InvalidTokenException { String url; try { url = getUriBuilder() .setPath(API_PATH_PREFIX + "/mounts/primary/files/info") .setParameter("path", path) .build() .toString(); } catch (URISyntaxExcept...
116324279_0
public static int compare(@Nullable String s1, @Nullable String s2) { if (s1 == s2) { return 0; } else if ((s1 == null) && (s2 != null)) { return -1; } else if ((s1 != null) && (s2 == null)) { return 1; } return s1.compareTo(s2); }