id
stringlengths
7
14
text
stringlengths
1
37.2k
51934971_1
@Override public InputStream convert(InputStream fromInputSource, String toMimeType) { try { WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource); FieldUpdater updater = new FieldUpdater(pkg); updater.update(true); File tmpFile = Files.createTempFile(null, null, new FileAttribute<?>[]{...
51949991_110
@Override public String toString() { String str = ""; str += " source=" + m_source; str += " year=" + m_currentYear; str += " lastSeenMessage=" + DateTimeUtils.timestampToHumanDateAndTimeAndStampUTC(m_lastSeenMessageDate.getMillis()); return str; }
51958035_0
public static StatsEstimate calculateMean(StatsEstimate min, StatsEstimate max) { Money meanAverageCpc = calculateMean(min.getAverageCpc(), max.getAverageCpc()); Double meanAveragePosition = calculateMean(min.getAveragePosition(), max.getAveragePosition()); Double meanClicks = calculateMean(min.getClicksPerDay(),...
51960935_1
protected boolean canLoadMoreItems() { final int visibleItemsCount = layoutManager.getChildCount(); final int totalItemsCount = layoutManager.getItemCount(); final int pastVisibleItemsCount = layoutManager.findFirstVisibleItemPosition(); final boolean lastItemShown = visibleItemsCount + pastVisibleItemsCount >=...
51989270_60
@Override public void writeTo(Viewable viewable, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException { // Find engine for this Viewable final ViewEngine engin...
52025119_0
public static <T> IMaybe<T> maybe(IMaybe<T> value) { return value; }
52030103_407
public boolean intersect(int x, int y, int width, int height) { if (this.width > 0 && this.height > 0 && width > 0 && height > 0 && this.x < (x + width) && x < (this.x + this.width) && this.y < (y + height) && y < (this.y + this.height)) { if (this.x < x) { this.width -=...
52040340_135
public void customize() { if (!this.managementCoreService.isUnsatisfied()) { if (certInfo.isValid()) { ManagementCoreService management = this.managementCoreService.get(); if (management == null) { throw SwarmMessages.MESSAGES.httpsRequiresManagementFraction(); ...
52079532_0
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onClick(View v) { switch (v.getId()) { case R.id.fab: JumpUtils.jumpToDataPicker(this, v); break; } }
52081266_35
public void enable() throws PinCommandException { command.enable(this); this.enabled = true; }
52095301_4
public T run(Callable<T> control, Callable<T> candidate) throws Exception { if (isAsync()) { return runAsync(control, candidate); } else { return runSync(control, candidate); } }
52113991_5
@Override public void selectVersion(ConflictResolver.ConflictContext context) throws RepositoryException { ConflictGroup group = new ConflictGroup(); for (ConflictResolver.ConflictItem item : context.getItems()) { DependencyNode node = item.getNode(); VersionConstraint constraint = node.getVersi...
52139656_0
@Nonnull @Override public Observable<T> observe(@Nonnull String key, @Nonnull T defaultValue, @Nonnull IGateway gateway) { return gateway.observeString(key, toString(defaultValue)).map(new Function<String, T>() { @Override public T apply(@NonNull String s) throws Exception { return fromString(s)...
52143457_2
@JsOverlay public static String toCamelCase(String text) { String bactrianCamel = Stream.of(text.split("[^a-zA-Z0-9]")) .map(v -> v.substring(0, 1).toUpperCase() + v.substring(1).toLowerCase()) .collect(Collectors.joining()); return bactrianCamel.toLowerCase().substring(0, 1) + bactrianC...
52145597_9
protected void onTaskUpdate(Task task) { Task tmp; int n = mTasks.size(); for (int i = 0; i < n; i++) { tmp = mTasks.get(i); if (task.getId().equals(tmp.getId())) { tmp.setTitle(task.getTitle()); tmp.setDescription(task.getDescription()); tmp.setCompleted(task.isCompleted()); setSt...
52192427_0
@Override public HelloReply sayHello(HelloRequest req) throws TException { return new HelloReply("Hello " + req.getName()); }
52212248_0
public <T> void post(T event) { if (event == null) { throw new NullPointerException("Event cannot be null"); } synchronized (listenerLock) { for (Map.Entry<Class, List<Subscription>> entry : currentThreadListeners.entrySet()) { checkAndPost(entry.getKey(), event, entry.getValue()...
52227745_2
public static <T> Observable<T> limitSubscriptions(int maxNumber, Observable<T> source) { State state = new State(); return Observable.create(subscriber -> { synchronized (state) { if (state.getNumberOfSubscriptions() == maxNumber) { System.out.println("Subscription not allow...
52228869_0
public static AwsKeyPair generateKeypair() throws NoSuchAlgorithmException { String accessKey = "-"; String secretKey = "-"; while (accessKey.contains("-") || accessKey.contains("_") || secretKey.contains("-") || secretKey.contains("_")) { KeyGenerator generator = KeyGenerator.getInstanc...
52264160_3
public void performSortOperation(int option, List<File> pdf) { switch (option) { case DATE_INDEX: sortFilesByDateNewestToOldest(pdf); break; case NAME_INDEX: sortByNameAlphabetical(pdf); break; case SIZE_INCREASING_ORDER_INDEX: sort...
52371323_51
@Override public MetricId get(final MetricId base, final T key) throws ExecutionException { return cache.get(key, new Callable<MetricId>() { @Override public MetricId call() throws Exception { return loader.load(base, key); } }); }
52404147_87
public static double minimum(double[] xs) { double min = xs[0]; // Stores the minimum value to be returned later; is assumed to be the value at the first Index for (int i = 1; i < xs.length; i++) { // Cycles through the Array to search for the minimum value min = Math.min(min, xs[i]); // If the value at the current...
52451139_19
public ParsedQuery<T> parse(Multimap<String, String> uriParams) { return parse(uriParamParser.multimapToMultivaluedMap(uriParams)); }
52453918_4
public static boolean shouldLoadInApp(String url) { if (url.matches("^(https?://)?((w{3}|preview.)?ello.(co|ninja)|(ello-webapp-epic|ello-webapp-rainbow|ello-fg-stage1|ello-fg-stage2).herokuapp.com)/?\\S*$")) { return true; } else if (url.matches("/\\S*$")) { return true; } else { ...
52460731_1
public static String[] filterPermissions(Context context, String[] permissions, int filter) { final ArrayList<String> filtered = new ArrayList<>(); for (String permission : permissions) { if (checkPermissionInt(context, permission) == filter) { filtered.add(permission); } } return filtered.toArray...
52478731_6
public Collection<Characteristic> getPhenotypes() { return this.phenotypes; }
52507351_18
public static String discoverTablespace(String defaultTableSpace, String query) { if (query == null) { return defaultTableSpace; } final Matcher matcher = TABLE_SPACE_NAME_PATTERN.matcher(query); /* A find will be used, no trim is needed */ if (matcher.find()) { final String tableS...
52509220_290
@UserFunction @Description("apoc.path.combine(path1, path2) - combines the paths into one if the connecting node matches") public Path combine(@Name("first") Path first, @Name("second") Path second) { if (first == null) return second; if (second == null) return first; if (!first.endNode().equals(second.sta...
52518462_1
@Override public boolean onStopJob(JobParameters job) { return false; // Answers the question: "Should this job be retried?" }
52522585_7
public Tuple makeWith(Object...values) { return make(values); }
52531953_1
@Override public void persist(Study entity) { persistUsersIfNecessary(entity.getAdministrators()); persistUsersIfNecessary(entity.getParticipants()); assert entity.getAuthor() != null; super.persist(entity); }
52565845_4
public void setTotalRowCnt(int totalRowCnt) { this.totalRowCnt = totalRowCnt; setPageNums(null); }
52589659_0
public C getC() { return c; }
52597910_0
public static short toShort(final byte[] value) { final byte[] ba = reverseAllBitsAndBytes(value); final ByteBuffer bb = ByteBuffer.wrap(ba); final short s = bb.getShort(); LOGGER.debug("Converting byte array [{}], reversed [{}] into short [{}]", toString(value), toString(ba), s); return s; }
52628247_15
public static double stdev(double[] a) { double m = mean(a); double sumsq = 0; for (double v : a) sumsq += (v-m)*(v-m); return Math.sqrt(sumsq / a.length); }
52632533_7
public BaggageImpl split() { Handlers.preSplit(this); Map<ByteString, SetMultimap<ByteString, ByteString>> copiedData = Maps.newHashMapWithExpectedSize(contents.size()); for (ByteString namespace : contents.keySet()) { copiedData.put(namespace, HashMultimap.create(contents.get(namespace))); } ...
52679228_0
public void notifyMissionMessageReceivers(Message message) { try { for (MessageReceiver receiver : missionMessageReceivers) { switch (message.getPayloadType()) { case AssignMission: receiver.onAssignMissionMessageReceived((AssignMissionMessage) message); ...
52689062_0
public SketchyMovingMAD() { }
52732011_3
public static String asCharDetail(final byte b) { if (b < ' ' || (b & 0xFF) > 127) { // add hex value (always two digits) final String hex = Integer.toHexString(b & 0xFF); if (hex.length() < 2) { return SPECIAL_CHAR + "0" + hex; } else { return SPECIAL_CHAR + hex; } } else { return Characte...
52774196_41
@Override public Set<String> names() { Entries entries = load(); return entries.keySet(); }
52800193_1
static Optional<AutoCaptureSource> newInstance(String value, SourceType type) { boolean isSupportedType = type == SourceType.DEFAULT_PATH || type == SourceType.FILE; Path path = type == SourceType.DEFAULT_PATH ? Paths.get(HoverflyConstants.DEFAULT_HOVERFLY_EXPORT_PATH).resolve(value) : ...
52834791_21
@Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) { try { List<Metric> convertedMetrics = convert(gauges, counters...
52950448_10
String replaceTemplateFields() { if (templateDescriptors.isEmpty()) { return responseBody; } DocumentContext documentContext = JsonPath.parse(responseBody); for (ResponseFieldTemplateDescriptor descriptor: templateDescriptors) { String expression = null; if (uriTemplate != null...
52956887_17
public static int getBitRange(final int b, final int s, final int n) { return (((b & MASK) >> (s & MASK)) & ((1 << (n & MASK)) - 1)) & MASK; }
52997044_6
public static UserPasswordIdentity createFromUserPassword(String user, String password) { return new UserPasswordIdentity(user,password); }
52999284_1
@VisibleForTesting static String toJson(Counters counters) throws SerializationException { ArrayNode countersJsonNode = JsonNodeFactory.instance.arrayNode(); ArrayNode groupsJsonNode = JsonNodeFactory.instance.arrayNode(); for (Group group: counters) { for (Counters.Counter counter: group) { ObjectNode...
53002524_6
public static <T> Func1<T, Boolean> not(final Func1<T, Boolean> func1) { return new Func1<T, Boolean>() { @Override public Boolean call(T t) { return !func1.call(t); } }; }
53019432_1
public static boolean isInt(String s) { return INT.matcher(s).matches(); }
53054065_0
public static Antenna omni(double x0, double y0) { return new Antenna(0, 0, 200e-3, 0.01, 0, x0, y0); }
53066586_1
@Override public ImmutableList<XMLEvent> process(String id, XMLEvent event) { Preconditions.checkNotNull(id); if (event.isStartElement()) { return ImmutableList.of(embeddedSvgStartElement(id)); } else if (event.isEndElement()) { return ImmutableList.of(embeddedSvgEndElement()); } else { throw new IllegalArgu...
53073438_7
public Axiom axiom(int number) { if (number < 1 || number > axioms.size()) { throw new IllegalArgumentException(String.format("Axiom %d is not defined", number)); } return axioms.get(number - 1); }
53084625_1
@RequestMapping public void staticProxy(HttpServletRequest request, HttpServletResponse response) throws IOException, SystemException, PortalException { // /pocjsportlet/p/portletId/path String requestURI = request.getRequestURI(); String portletId = getPortletId(requestURI); javax.portlet.PortletPrefer...
53088165_1
public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... paramTypes) {// NOSONAR try { return clazz.getConstructor(paramTypes); } catch (SecurityException e) { throw new IllegalStateException("Security exception found for Constructor: " + e.getMessage()); } catch (NoSuchMethodException e) { thro...
53127403_391
public List<Instance> findInstancesByIds(Set<Long> instanceIds) { Iterable<Instance> instances = instanceRepository.findAllById(instanceIds); return Lists.newArrayList(instances); }
53169994_0
void getFitnessData() { fitnessSessionDataList.clear(); view.showLoading(); DataReadRequest.Builder dataReadRequestBuilder = getDataReadRequestBuilder(); DataReadRequest dataReadRequest = dataReadRequestBuilder.build(); DataReadRequest dataReadRequestServer = dataReadRequestBuilder.enableServerQuer...
53222598_8
@Override public boolean update(String key, int sequenceId, byte[] value) { boolean isUpdated = false; try { if (hasKey(key)) { byte[] serializedKey = serialize(key); byte[] serializedSequenceId = serialize(sequenceId); if (redis.hexists(serializedKey, serializedSequenceId)) { redis.hset(serializedKey,...
53225573_7
@Override public Subscriber<? super T> call(final Subscriber<? super T> child) { return new Subscriber<T>(child) { @Override public void onCompleted() { Assertions.assertUiThread(); if (shouldForwardNotification()) { child.onCompleted(); } else { ...
53246590_0
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (annotations.isEmpty()) { return true; } long t0 = System.currentTimeMillis(); StaticGsonContext context = new StaticGsonContext(roundEnv, processingEnv); roundEnv.getElementsAnnotated...
53251585_1
static boolean isInside(LocationUSourceData data, Location location) { for (LatLong center : data.locations) { if (inside(center, data.radius, location.getLatitude(), location.getLongitude())) { return true; } } return false; }
53265801_2
@NonNull public static Observable<AppState> monitor(@NonNull Application app) { return Observable.create(new AppStateObservableOnSubscribe(new DefaultAppStateRecognizer(app))); }
53275454_0
public Resource createObjectFromString(String resourceName) throws InstantiationException, IllegalAccessException, NotExtendingResourceException { Class objectClass = registeredClasses.get(resourceName); try { return (Resource) objectClass.newInstance(); } catch (InstantiationException e) { throw e; } c...
53291241_5
public boolean isHelp() { return this.help; }
53291713_0
public static String prettyTime(String timeInMillisec) { if (timeInMillisec == null) { return ""; } return prettyTime(Long.parseLong(timeInMillisec), OmniNotes.getAppContext().getResources().getConfiguration().locale); }
53330030_1
static Properties overrideWithSysProps(Properties props, Logger log) { Properties sysProps = null; try { sysProps = System.getProperties(); } catch (AccessControlException e) { log.warn( "Skipping overriding quartz properties with System properties " + "during initial...
53336998_2
public PaginatedCollection<Person> getAllPeopleInCache() { Collection<Person> allPeople; try { allPeople = peopleRepository.getAll(ReadPolicy.CACHE_ONLY); } catch (Exception e) { allPeople = new ArrayList<>(); } if (allPeople == null) { allPeople = new ArrayList<>(); } ...
53354223_6
public InternalIdToLongIterator(LongToInternalIntBiMap nodesIndexMap, EdgeTypeMask edgeTypeMask) { this.nodesIndexMap = nodesIndexMap; this.edgeTypeMask = edgeTypeMask; this.currentNodeId = 0; }
53367115_69
@Override public <S extends ResourceEntity> S findOne(final Example<S> example) { throw new UnsupportedOperationException(MESSAGE); }
53430304_5
@Override public Observable<ReadResult> read(@NonNull String name) { return Observable.create(new FingerprintAuthOnSubscribe(fingerprintManager, storage, name, // readerScanning, dataLock, this)); }
53431695_1
public static float getHue(float value, float min, float max, int minColor, int maxColor) { float hue; if (min == max || value <= min) { hue = minColor; } else if (value > max) { hue = maxColor; } else { float colorValue = (value - min) / (max - min); // from 0.0 to 1.0 ...
53438686_0
public void startup() throws ConfigurationException, InterruptedException { final Set<Integer> ports = getConfigurationSettings().getPorts(); for (Iterator<Integer> iterator = ports.iterator(); iterator.hasNext();) { final Integer port = iterator.next(); getServerPool().add(new MockTCPServer(po...
53478785_2
public void onDownloadEnd(String torrentFile, int downloadState) { broadcast(DownloadEndBroadcast.createIntent(torrentFile, downloadState)); }
53502006_0
public String injectToTemplate(String template, Object scope) { Mustache mustache = mustacheFactoryUnescapeHtml.compile(new StringReader(template), "template"); StringWriter result = new StringWriter(); try { mustache.execute(result, new Object[] { scope, singletonMap("lowercase", lowercaseFunction...
53510819_2
public void resetDefaultTimeout() { timeoutTime = null; timeoutUnit = null; }
53511222_34
@Override @SuppressWarnings({ "PMD.AvoidDeeplyNestedIfStmts", "checkstyle:nestedifdepth" }) @NonNull public Collection<Emoji> getRecentEmojis() { if (emojiList.size() == 0) { final String savedRecentEmojis = sharedPreferences.getString(RECENT_EMOJIS, ""); if (savedRecentEmojis.length() > 0) { final Str...
53561724_0
@SneakyThrows @Override public <T extends Entity> Optional<T> get(UUID uuid) { Optional<T> result; Connection connection = dataSource.getConnection(); refreshConnectionRegistry(connection); PreparedStatement s = connection .prepareStatement("SELECT layout FROM layouts_v1 WHERE uuid = ?::...
53566183_5
public static <T> Function<T,Integer> unpartitioned() { return zero(); }
53590096_30
public static String dateToStringWithFormat(Date dateToString, String dateFormat) { if (dateToString != null) { DateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); return simpleDateFormat.format(dateToString); } else { return null; } }
53592496_0
protected void selectImageFromGallery( @NonNull final OnImageReturnCallback onImageReturnCallback) { permissionManager.requestPermission(this, new PermissionListener() { @Override public void onPermissionsGranted() { mImageCallback = onImageReturnCallback; mImageProv...
53615697_0
public void acquire(String resource) throws LackException { ResultSet result = statements.acquire(resource, owner); if (!result.wasApplied()) { throw new LackException(String.format(MESSAGE_ACQUIRE, resource)); } }
53645841_12
static long getNextSendingInMillis(Record record, long currentTimeMillis) { int delta = Const.MILLIS_PER_MINUTE; // используется, чтобы избежать повторной отправки в одно время. int repeatType = record.getRepeatType(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, reco...
53684862_11
public static void recycleBitmap(Bitmap bitmap){ if (bitmap != null && !bitmap.isRecycled()) bitmap.recycle(); }
53690584_2
protected boolean isQuoted(String str, int pos) { int start = str.indexOf("\""); if(start < 0 || pos < start) { return false; } int end = str.indexOf("\"", start + 1); if(end < 0) { return false; } if(pos <= end) { return true; } return isQuoted(str.substring...
53691181_2
@Override public boolean onTouch(View v, MotionEvent event) { if (!enabled) return false; final float x = event.getX(); final float y = event.getY(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: // store the time to compute whether future events are 'long presses...
53703548_16
@Override public void init(ServiceProviderBuilder builder) throws Exception { authenticationProviderBean = builder.getSharedObject(SAMLAuthenticationProvider.class); config = builder.getSharedObject(SAMLSSOProperties.class).getAuthenticationProvider(); }
53723623_0
@Override public String getErrorMessage() { return (exception == null) ? DEFAULT_ERROR_MSG : this.exception.getMessage(); }
53726669_15
public void togglePasswordVisibility() { setPasswordVisible(!passwordVisible); }
53789166_0
public boolean check(long time, int location) { if(currentInstant != time) { currentInstant = time; bitSet.clear(); } if(bitSet.get(location)) { return false; } bitSet.set(location); return true; }
53823931_0
@Override public T copy(Kryo kryo, T original) { try { preSerialize(original); try(CopyStream output = new CopyStream(4096)) { HTMObjectOutput writer = serializer.getObjectOutput(output); writer.writeObject(original, original.getClass()); writer.close(); ...
53846545_0
public boolean inc(long key) { // find location for key int index = 0; FingerPrintAux hash = indices.getHash(key); // find current location of key in set index = (int) indices.getOrDefault(hash, -1); // if key is not in set if (index < argmin) { index = Math.max(0, argmin-1); // put key in place this.put(h...
53859223_41
@Override public void validate(Class<?> type, int size, int decimals) { if(!(TypeConverterIntEnum.class.isAssignableFrom(type))) { throw new TypeConverterException("Only supports converting to and from TypeConverterIntEnum"); } if(this.type != null && this.type != type) { throw new TypeConve...
53877122_9
public Activity getActivity() { return activity; }
53932231_31
public List<PatternRule> parse() { if (used) { throw new IllegalStateException("Parser.parse can only be called once per instance"); } used = true; return rules(); }
53940095_2
@Override public InterpreterResult interpret(String cmd, InterpreterContext contextInterpreter) { logger.info("Running Scalding command '" + cmd + "'"); if (cmd == null || cmd.trim().length() == 0) { return new InterpreterResult(Code.SUCCESS); } return interpret(cmd.split("\n"), contextInterpreter); }
53950433_0
@Override public synchronized List<Issue> getIssues() { System.out.println("==== MT lint start ===="); return Arrays.asList( LogDetector.ISSUE, HashMapForJDK7Detector.ISSUE ); }
53966381_4
@EventListener({ HeartbeatEvent.class }) public void discoverLandscape() { logger.debug("Discovering landscape"); List<String> applications = this.discoveryClient.getServices() .stream() .filter(this.applicationFilters) .collect(Collectors.toList()); Catalog catalog = this.catalogService.getCatalog(); di...
53976910_33
public static GramBooleanQuery translate(String regex) throws com.google.re2j.PatternSyntaxException { return translate(regex, TranslatorUtils.DEFAULT_GRAM_LENGTH); }
54034223_9
public static <T> T post(URI url, Object request, Class<T> responseType) { Assert.notNull(url); Assert.notNull(responseType); return restTemplate.postForObject(url, request, responseType); }
54042490_1
public WorkerInfoImmutable workerToWorkerInfoImmutable(Worker worker) { return mapper.map(worker, WorkerInfoImmutable.class); }
54064354_1
static String mimeTypeFromExtension(String path) { if (path == null || path.length() == 0) { return null; } final int indexOfDot = path.lastIndexOf('.'); if (indexOfDot == -1) { return null; } final String ext = path.substring(indexOfDot + 1) .toLowerCase(Locale.g...
54069741_37
public static List<BioAssemblyData> generateBioassemblies(StructureDataInterface structureDataInterface) { int numBioassemblies = structureDataInterface.getNumBioassemblies(); List<BioAssemblyData> outList = new ArrayList<>(); for (int i=0; i<numBioassemblies; i++) { BioAssemblyData bioassembly = new BioAssemblyDa...