id
stringlengths
7
14
text
stringlengths
1
37.2k
81201370_26
@Override protected void onError(int error) { finish(CommandResult.createErrorResult(characteristicUUID, error)); }
81201685_18
@Override public int findTokenStart(CharSequence text, int cursor) { // base case: empty string if (text.length() == 0) { return 0; } // iterate back until we find the prefix char separator = getDefaultSeparator(); for (int i = cursor - 1; i >= 0; i--) { if (matchesPrefix(text, ...
81304886_25
public String cleanInlineCode(Object input) { String output = clean(input, false).replace('\n', ' '); if(output.indexOf('`') != -1) { String prepend = ""; if(output.charAt(0) == '`') { prepend = " "; } String append = ""; if(output.charAt(output.length()-1) == '`') { append = " "; } String delim =...
81385470_3
public void addClickHandler(final Context context, final View view) { addClickHandler(context, view, (new AuthUrlBuilder()).build()); }
81391569_1
public void go() { try { doStuff(); } catch (CardException e) { e.printStackTrace(); } } } public ApduStatus doStuff() { StatusResponse status = null; ApduSession session = new ApduSession(new GetVersion()); status = session.transmit(transmitter); byt...
81400811_8
@RequestMapping(value="/{id}") public ActionResultObj get(@PathVariable Long id){ ActionResultObj result = new ActionResultObj(); try{ if(id != 0){ EDict dict = dictDao.fetch(id); if(dict != null){ result.ok(dict); result.okMsg("查询成功!"); }else{ result.errorMsg("查询失败!"); } }else{ result....
81436550_3
public void processOne() throws DriverException, CloseException { Request request; try { request = this.reader.read(); } catch (CloseException ex) { throw ex; } catch (Exception ex) { final Response response = createFatalResponse(ex); try { this.writer.write(r...
81464391_3
@RequestMapping(method = RequestMethod.GET, value = "", params = "fullname", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody User userByFullname(@RequestParam("fullname") String fullname) { return repository.findByFullname(fullname); }
81464583_17
public static int[] fromYearFormat(String yearFormat) { String[] parts = yearFormat.split("/"); if (parts.length != 2) { throw new IllegalArgumentException("Given string is not in expected format: " + yearFormat); } int[] intParts = {Integer.parseInt(parts[0]), Integer.parseInt(parts[1])}; ...
81467673_18
static String readPacket(ByteBuffer input) { if (input.remaining() < LENGTH_FIELD_SIZE) { return null; } // each packet contains 4 bytes representing the String length in hexa, followed by a list of device states, one per line; // each line contains: the device serial, `\t', the state, '\n' ...
81500686_0
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { System.out.println("[FlowR]: generating deep Link Handler..."); MethodSpec.Builder constructorBuilder = generateConstructor(); // Browse all the annotations and create the FlowrDeepLinkHandler constructor...
81569594_24
public Object eval(Object scope) { try { return valueExpression.getValue(new XLContext(scope)); } catch (ELException ele) { return null; // unresolved element yields null value } }
81587412_4
public static SystemBuilder builder() { return new SystemBuilder(); }
81611630_13
public static ContentDisposition parse(String contentDisposition) { List<String> parts = tokenize(contentDisposition); String type = parts.get(0); String name = null; String filename = null; Charset charset = null; Long size = null; ZonedDateTime creationDate = null; ZonedDateTime modifi...
81617098_147
@Override public AbstractBestPracticeResult runTest(PacketAnalyzerResult tracedata) { /* * Reset these total numbers before each test-run due to bean being * singleton. */ totalNumConnectionsCurrentTrace = 0; totalNumHttpConnectionsCurrentTrace = 0; List<Session> sessions = tracedata.getSessionlist(); Map<In...
81649451_0
public synchronized List<Conll> tagging(List<String> tokens, FragmentationType fragmentationType) throws ClassifierModelNotFoundException, IncorrectTokenException { AdvancedTokenHandler<Conll> tokenHandler = new StatefulTokenHandler(fragmentationType); try { this.tt.setHandler(tokenHandler); ...
81653189_6
@TargetApi(25) public static void create(@NonNull Context context) { if (Build.VERSION.SDK_INT < 25) { return; } if (generated == null) { try { generated = Class.forName("shortbread.ShortbreadGenerated"); createShortcuts = generated.getMethod("createShortcuts", Conte...
81654664_6
public Boolean delete(Long jobId){ Job job = jobDao.findById(jobId); if (job == null){ return Boolean.TRUE; } if (jobDao.unbindApp(job.getAppId(), jobId)){ return jobDao.delete(jobId) && jobDao.unIndexJobClass(job.getAppId(), job.getClazz()); } return Boolea...
81678042_0
@Override public List<Issue> getIssues() { return ImmutableList.of(AndroidLogDetector.ISSUE, HardcodedColorsDetector.ISSUE, DirectMaterialPaletteColorUsageDetector.ISSUE, NonMaterialColorsDetector.ISSUE); }
81718052_0
@SuppressWarnings("WeakerAccess") public static void addSupportFragmentToActivity(@NonNull final FragmentManager fragmentManager, @NonNull final Fragment fragment, @NonNull final String tag) { checkNotNull(fragmentManage...
81799714_4
public List<WebappInfo> getAppBarWebInfos(String serverName) { return getAppBarWebInfos(serverName, null); }
81824082_3
@ApiOperation("Get a post by its UUID") @RequestMapping(value = "/uuid/{uuid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Post getPostByUuid(@PathVariable("uuid") String uuid) { return postRepository.findOne(uuid); }
81880059_4
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServiceBrokerApiVersionException { if (version != null && !anyVersionAllowed()) { String apiVersion = request.getHeader(version.getBrokerApiVersionHeader()); boolean contains = false; for (String brokerApi...
81897811_0
@Override public void onMessage(ResponseBody response) throws IOException { if (response.contentType() != WebSocket.TEXT) { FLog.w(TAG, "Websocket received unexpected message with payload of type " + response.contentType()); return; } try { JsonReader reader = new JsonReader(response.charStream()); ...
81928401_1
public static String mapToJSONBean(final Map<String,Object> map) { final JSONObject obj = new JSONObject(); for (String key : map.keySet()) { if (! key.startsWith("#")) { //don't include Camel stats obj.put(key, map.get(key)); } } return obj.toString(); }
81932909_9
@Override protected void dispatchDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(defaultColor); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); canvas.drawCircle(mCenterX, mCenterY, mRadius, paint); if(mTransparentRadius != 0){ Paint paintTransparent = new...
82007769_18
public SortInfo[] getSortInfo () { return m_sortInfos.toArray (new SortInfo[m_sortInfos.size ()]); }
82035099_94
@RequestMapping(value = "/measures/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteMeasureById(@PathVariable("id") Long id) throws SchedulerException { measureService.deleteMeasureById(id); }
82155862_22
@Override public List<Partition> listPartitionsByTopic(String topicName) { return findTopic(topicName, getMeta()).getPartitions(); }
82177245_4
@Override public String format(Long millis) { long diff = System.currentTimeMillis() - millis; if (diff < TimeUnit.HOURS.toMillis(1)) { return resolver.get(R.string.label_minutes, Math.max(1, TimeUnit.MILLISECONDS.toMinutes(diff))); } if (diff < TimeUnit.DAYS.toMillis(1)) { return resolver.get(R.strin...
82179206_55
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that need...
82273737_4
public Spliterator<E> spliterator() { class Splitr implements Spliterator<E> { // The current spine index int splSpineIndex; // Last spine index final int lastSpineIndex; // The current element index into the current spine int splElementIndex; // Last spine...
82282677_3
public static <T> TimingTargetAdapter getTarget(Object object, String propertyName, KeyFrames<T> keyFrames) { return getTargetHelper(object, propertyName, keyFrames, false); }
82304453_8
@Override public final void write(String data) throws IOException { Files.write(this.path(), data.getBytes()); }
82313272_0
public String build() { final StringBuilder nameBuilder = new StringBuilder(); Collections.reverse(enclosingClassSimpleNames); for (String enclosingClassSimpleName : enclosingClassSimpleNames) { nameBuilder.append(enclosingClassSimpleName).append("$"); } return nameBuilder + targetClassSimpl...
82348984_46
@Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Float fieldValue) { state.putFloat(key, fieldValue); }
82384202_23
@Override public int release(String path, int fileHandle) { logger.info("release({}, {})", fileHandle, path); FileChannel fileChannel = openFiles.remove(fileHandle); if (fileChannel == null) { return -ErrorCodes.EBADF(); } safeClose(fileChannel); return SUCCESS; }
82398873_3
public boolean edit(TodoEntity entity) { if(todoDAO.findById(entity.getId()) == null) return false; TodoEntity existingTodoEntity = todoDAO.findByName(entity.getName()); if(existingTodoEntity!=null && existingTodoEntity.getId()!=entity.getId()) return false; if(entity.getStatus()==null) return false; ...
82427374_36
public Role convert(RoleRepresentation representation) { Role role = new Role(representation.getName()); role.setDescription(representation.getDescription()); return role; }
82468869_5
public String getHandlerPackage() { return handlerPackage; }
82477856_2
public static boolean containsIgnoreCase(String str, String searchStr) { if (str != null && searchStr != null) { int len = searchStr.length(); int max = str.length() - len; for (int i = 0; i <= max; ++i) { if (str.regionMatches(true, i, searchStr, 0, len)) { retur...
82480345_2
public static Playlist parse(final InputStream inputStream) { if (inputStream == null) { throw new IllegalArgumentException("Input stream is null!"); } List<Playlist.Track> tracks = new ArrayList<>(); int version = -1, entries = -1; BufferedReader reader = new BufferedReader(new InputStream...
82595458_5
@Override public Map<K, V> getAllKeyValues() { return genericClient.getAllKeyValues(store, keyClass, valueClass, keySerde, valueSerde); }
82604742_339
@Override protected MessageResponseStatus getMessageResponseStatus() { return FaultType.INVALID_GROUP_NAME; }
82675377_26
public static List<Date> getCycleFireDate(Date startTime, Date endTime, CronExpression cronExpression) { List<Date> dateList = new ArrayList<>(); while (true) { startTime = cronExpression.getNextValidTimeAfter(startTime); if (startTime.after(endTime)) { break; } dateList.add(startTime); } ...
82693361_8
public void changeAcceleration(D3Vector input_acceleration) { D3Vector acceleration = input_acceleration; acceleration = limit_acceleration(acceleration); acceleration = this.limit_velocity(acceleration); if (Double.isNaN(acceleration.getX()) || Double.isNaN(acceleration.getY()) || Double.isNaN(accele...
82722869_3
public void debug(Object message) { out.println(message); }
82764073_6
public Single<List<Topic>> getUserTopics(String userLogin, int offset) { return mService.getUserTopics(buildAuthorization(), userLogin, offset, PAGE_LIMIT) .compose(applySingleSchedulers()); }
82809641_2
public Tracer getTracer() { if (tracer == null) { // Initialize on first use initTracer(); } return tracer; }
82821845_17
@VisibleForTesting static FreqBandwidth getFreqAndBandwidth(File file) { if (!"ts".equals(getExtension(file))) return null; String[] parts = file.getName().toLowerCase().split("_"); if (parts.length != 4) return null; if (!"mux".equals(parts[0])) return null; try { long freq = Long.parseLong...
82854849_7
public void addScreens(@NotNull List<S> screens) { for (S screen : screens) { addScreen(screen); } }
82903968_0
public String login(UserForm userForm) { log.debug("LoginController.login {}", userForm); try { if (userForm == null) { return "ERROR"; } else if (loginService.login(userForm)) { return "OK"; } else { return "KO"; } } catch (Exception e) {...
82906551_114
public String getPath() { return path; }
82968973_37
@Override public PointF getDistancePoint(ViewGroup parent, List<View> children) { PointF distancePoint; switch (position) { case TOP_LEFT: distancePoint = new PointF(0, 0); break; case TOP_MIDDLE: distancePoint = new PointF(parent.getWidth() / 2, 0); ...
82982240_0
@SuppressLint("SetJavaScriptEnabled") public static PopupBridge newInstance(AppCompatActivity activity, WebView webView) throws IllegalArgumentException { return newInstance((FragmentActivity)activity, webView); }
83002023_5
Intent createIntentForBrowserSwitchActivityQuery(String returnUrlScheme) { String browserSwitchUrl = String.format("%s://", returnUrlScheme); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserSwitchUrl)); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.addCategory(Intent.CATEGORY_BROWS...
83122389_1
@TaskAction public void exec() throws IOException { Path userHome = Paths.get(System.getProperty("user.home")); final List<Path> intelliJFolders; try (var files = Files.list(userHome)) { intelliJFolders = files .filter( path -> Files.isDirectory(path) ...
83137916_20
@Activate protected void activate(final Map<String, Object> props) throws ServiceException { logger.debug("activate(): props = {}", props); this.filterRoots = PropertiesUtil.toStringArray(props.get(PROP_FILTER_ROOTS), null); if (this.filterRoots == null) { throw new ServiceException(PROP_FILTER_ROOTS + " is manda...
83186903_1
public static <T> String tryGetGeneric(T t) { ParameterizedType pt = null; Type[] types = t.getClass().getGenericInterfaces(); if (types.length != 0 && types[0] instanceof ParameterizedType) { pt = (ParameterizedType) types[0]; } else { Type type = t.getClass().getGenericSuperclass(); ...
83256557_8
public static boolean checkWidget(Observer<?> observer, Widget widget) { if (null == widget) { observer.onError(new NullPointerException("The given widget was null")); return false; } else if (widget.isDisposed()) { observer.onError(new IllegalStateException("The given widget is diposed")); return false; } e...
83275514_27
public static String removeResponseTag(String message) { String responsePrefix = ""; // Regex for reponse tag's namespace prefix String regex = ".*<(\\w+:)*(\\w+R|r)esponse.*?>.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(message); if (matcher.find()) { ...
83414665_11
@Override public final List<Entity> resolveMentionOverlapping( final Map<AnnotatorConfig, List<Entity>> documents) { final List<Entity> finalEntities = new ArrayList<>(); for (final Map.Entry<AnnotatorConfig, List<Entity>> document : documents.entrySet()) { for (final Entity old : document.getValue()) { ...
83457980_12
public float nextFloat(final float origin, final float bound) { return nextFloat(origin, bound, this); }
83562545_0
void saveRDDToEs(JavaRDD javaRDD, String docName) { JavaEsSpark.saveToEs(javaRDD, docName);//); }
83583832_18
public static String getNameOfService(int id) { try { //noinspection ConstantConditions return getService(id).getServiceInfo().getName(); } catch (Exception e) { System.err.println("Service id not known"); e.printStackTrace(); return "<unknown>"; } }
83615384_8
@NonNull public Node createChildNode(@NonNull Node parentNode, @NonNull Object nodeKey) { checkNode(parentNode); checkKey(nodeKey); Node node = new Node(this, parentNode, nodeKey); parentNode.children.add(node); this.addNode(node); return node; }
83664920_147
@VisibleForTesting void setIdentifiersToExclude(String identifiersToExclude) { this.identifiersToExclude = identifiersToExclude; }
83751371_7
public static FailsafeS3Decorator decorate(AmazonS3 s3) { return decorate(s3, defaultCircuitBreaker()); }
83845804_37
public static Distribution poisson(final double average) { checkArgument(average >= 0.0, "average must be >= 0.0 [%s]", average); final String s = String.format("PoissonDistribution [average=%s]", average); return new IntegerDistributionAdapter(new PoissonDistribution(average), s); }
83883701_21
@Override public boolean marathon_select(String value) { boolean selected = Boolean.parseBoolean(value); boolean current = ((ToggleButton) node).isSelected(); if (selected != current) { click(); } return true; }
83904496_5
@Override public ExecutionResult execute(ExecutionContext context, ExecutionParameters parameters) throws NonNullableFieldWasNullException { Map<String, List<Field>> fields = parameters.fields(); Object source = parameters.source(); return complexChangesFlow( context, source, ...
83932318_5
public Observable<String> getPokemonStringObservable(String id) { return pokemonService.getPokemon(id) .map(new Function<Pokemon, String>() { @Override public String apply(@NonNull Pokemon pokemon) throws Exception { return constructPokemon(pokemon); ...
83938778_1
public static void throwIfInvalidMove(Matrix matrix, ScrambleMove move) { switch (move.move) { case SWAP: MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.X1), Plane.X); MatrixValidator.throwIfBadIndex(matrix, move.getArg(ScrambleConstants.Swap.Y1), Plane.Y); MatrixValidator.throwI...
84008299_43
public Date getExpirationDate() { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_WEEK, 1); return c.getTime(); }
84059135_25
@Nullable public double[] getDoubleArray(@Nullable String key) { Object o = map.get(key); if(o == null) { return null; } try { return (double[]) o; } catch(ClassCastException e) { typeWarning(key, o, "double[]", e); return null; } }
84142745_46
public static Map<String, Object> getConstants() { HashMap<String, Object> constants = new HashMap<String, Object>(); constants.put( "UIView", MapBuilder.of( "ContentMode", MapBuilder.of( "ScaleAspectFit", ImageView.ScaleType.FIT_CENTER.ordinal(), ...
84190084_2
public void getMovieDetails(long movieId) { isMovieLoading.set(true); errorViewShowing.set(false); mMoviesRepository.getMovieDetails(movieId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribeWith(new DisposableObserver<Movie>() { ...
84210505_0
URI createUri(String endpoint, String appKey) { if (Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException(); } Pattern verPattern = Pattern.compile("/(v\\d+)$"); Matcher m = verPattern.matcher(endpoint); String fullEndpoint = endpoint; if (!m.find()) { if (!fullEndpoint.endsWith("/...
84302839_8
public static Map<String, Type> getTypeParameters(Class<?> subclass, Class<?> superclass) { // Gather implemented interfaces and superclass. List<Type> genericSupertypes = Stream.concat( Stream.of(subclass.getGenericSuperclass()), Stream.of(subclass.getGenericInterfaces()) ).collect(Collectors.t...
84311940_42
@Override public GoPluginApiResponse execute() throws Exception { Map<String, String> requestParam = Util.GSON.fromJson(request.requestBody(), Map.class); String searchTerm = requestParam.get(SEARCH_TERM); List<AuthConfig> authConfigs = AuthConfig.fromJSONList(request.requestBody()); final Set<User> us...
84320045_0
public static Rectangle createBounds() { return new BufferedImage(800, 600, BufferedImage.TYPE_3BYTE_BGR) .createGraphics() .getDeviceConfiguration() .getBounds(); }
84372863_7
@Override public RelNode run(RelOptPlanner relOptPlanner, RelNode relNode, RelTraitSet relTraitSet, List<RelOptMaterialization> relOptMaterializationList, List<RelOptLattice> relOptLatticeList) { for (Program program : programs) { relNode = program.run(relOptPlanner, relNode, relTraitSet, relOptMaterializati...
84382452_2
public static TransferResult transfer(BankAccount to, BankAccount from, Money money) { BankAccount updatedFrom = from.withdrawTo(to, money); BankAccount updatedTo = to.depositFrom(from, money); return TransferResult.of(updatedTo, updatedFrom); }
84398452_82
public final Optional<Duration> poolValidationInterval() { return poolValidationInterval; }
84427866_1
public CheckoutResult checkOut() throws Exception { CheckoutResult checkOutResult = new CheckoutResult(); // 检查可用库存 ShoppingCart currentCart = null; try { currentCart = getShoppingCart(); }catch (Exception e) { log.error("获取购物车失败", e); } if(currentCart != null) { //...
84439902_1
public static void migrate(final ConnectionContext connectionContext, String fileName, String changeSetsToLoadSeparatedByComma) throws MintleafException { migrate(connectionContext, fileName, changeSetsToLoadSeparatedByComma.split(",")); }
84466727_13
PersistentVolumeClaim getClaim(VolumeRequest volumeRequest) { return claims.computeIfAbsent(volumeRequest, this::createClaim); }
84473688_7
public static void init() { int conNum = getIntProperty(CONNECTIONS_NUMBER_PARAMETER, DEFAULT_CONNECTIONS_NUMBER); if (conNum > 0) { numberOfConnections = conNum; } else { throw new IllegalArgumentException("Negative number of connections value", new IOException()); } ...
84488372_5
@Override public StateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, AttributeNotFoundException { if (!checkValidTime(t)) { throw new TimeRangeException(ssid + " Time:" + t + ", Start:" + startTime + ", End:" + latestTime); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ...
84506236_31
public static boolean invokeSetterQuietly(Object obj, String setterName, Class<?> valueKlass, Object value) { if (obj == null) return false; try { invokeSetter(obj, setterName, valueKlass, value); return true; } catch (Throwable ex) { return false; } }
84521629_2
boolean resourceHierarchyHasACycle(Resource resource) { String resourceType = resource.getResourceType(); Set<String> resourceTypeSet = new HashSet<>(); ResourceResolver resolver = resource.getResourceResolver(); while (resourceType != null) { if (resourceTypeSet.contains(resourceType)) { log.trace("Found a ...
84603051_206
public static ClusterFilter forNextInJoinOrder() { return NEXT_IN_JOIN_ORDER; }
84616200_110
public String getPrimary(final String key) { final List<String> rv = getNodesForKey(hash(key), 1); assert rv != null && rv.get(0) != null: "Found no node for key " + key; return rv.get(0); }
84678166_0
public String getApiHost() { return apiHost; }
84742920_34
public int compareEpsilon(PointD a, PointD b) { return compareEpsilon(a, b, epsilon); }
84750226_67
@Override public RestRequest<Map<String, Auction>> build() { return RestRequestBuilder.<Map<String, Auction>>builder() .withPath("/deep/auction").get() .withResponse(new GenericType<Map<String, Auction>>() {}) .addQueryParam(getSymbols()) .addQueryParam(getFilterParam...
84765740_2
static Config getConfig(String[] args) { Config config = new Config(); CommandLine.run(config, System.err, args); return config; }
84791542_0
public boolean isReady() { return getStatus() == Status.READY; }
84838073_0
public void setPassword(String password) throws UserException { int MIN_PASSWORD_LENGTH = 6; int MAX_PASSWORD_LENGTH = 16; if((password != null && !password.isEmpty()) && (password.length() < MIN_PASSWORD_LENGTH || password.length() > MAX_PASSWORD_LENGTH)){ throw n...
84863865_0
public static void main(String... args) { setDebugLevel(Level.SEVERE); System.err.println("benchtmark"); (new OptimizerBenchmark()).runBenchmarks(); }