id
stringlengths
7
14
text
stringlengths
1
37.2k
31481933_7
public static ResAllocs subtract(ResAllocs first, ResAllocs second) { return new ResAllocsBuilder(first.getTaskGroupName()) .withCores(first.getCores() - second.getCores()) .withMemory(first.getMemory() - second.getMemory()) .withNetworkMbps(first.getNetworkMbps() - second.getNet...
31482799_4
public Object extractResult(Map<String, ?> model) { if (model != null && !model.isEmpty()) { if (model.size() == 1) { return model.values().iterator().next(); } else { if (model.containsKey(CatnapResponseBodyHandlerInterceptor.MODEL_NAME)) { return model.get(C...
31561391_37
@Override public Model convert(ModelContent source, Optional<String> platformKey) { IModel model = source.getModels().get(source.getRoot()); return convert(model, source, platformKey); }
31564630_8
public static double score(INDArray labels,LossFunction lossFunction,INDArray output,double l2,boolean useRegularization) { assert !Nd4j.hasInvalidNumber(output) : "Invalid output on labels. Must not contain nan or infinite numbers."; double ret = 0.0f; double reg = 0.5 * l2; INDArray z = output; a...
31587091_25
public String valueFor(Locale locale) { String result = values.get(locale); if (result == null && !locale.getVariant().isEmpty()) { Locale fallbackLocale = new Locale(locale.getLanguage(), locale.getCountry()); result = values.get(fallbackLocale); } if (result == null && !locale.getCount...
31622667_0
public static int hashCode(double x) { / System.out.println(x + " - " + round(x, (int)-Math.log10(RATE_EPSILON))); return (int)Math.round((round(x, (int)-Math.log10(RATE_EPSILON)) / RATE_EPSILON)); }
31639517_0
public int hashInt(int input) { int k1 = mixK1(input); int h1 = mixH1(seed, k1); return fmix(h1, 4); }
31650129_22
public SensorCommandValue createPressureValue(CommandResult commandResult) { return new PressureValue(commandResult); }
31696454_6
public static String decodeString(ChannelReader reader, Boolean isOptional){ if (reader.readPackedInt() == INCOMING_VARIABLE){ return reader.readUTF(); } else return null; }
31766535_4
public static CuratorFramework curatorFramework() { if (curatorFramework != null) { return curatorFramework; } else synchronized (ZkManager.class) { if (curatorFramework == null) { final String quorum = System.getProperty("zk.quorum", "localhost"); final int sessionTimeou...
31784428_9
@Override public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception { if (request.getMethod().equals("GET")) { verifyTokenAbsence(request, response); } else { verifyToken(request, response); } chain.next(request, response); }
31785239_90
@Override public boolean noneMatch(Predicate<? super T> predicate) { boolean b = stream.noneMatch(predicate); close(); return b; }
31786762_1
static int getCoresFromFileString(String str) { if (str == null || !str.matches("0-[\\d]+$")) { return DEVICEINFO_UNKNOWN; } int cores = Integer.valueOf(str.substring(2)) + 1; return cores; }
31788540_18
@Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof WebClient) { WebClient webClient = (WebClient) bean; return wrapBuilder(webClient.mutate()).build(); } else if (bean instanceof WebClient.Builder) { WebClient.Builder webClientBuilder = (WebClient.Builder...
31789636_0
public CommandCode getCommandCode() { return commandCode; }
31836491_78
@Override public boolean add(FilteredBlock block) throws VerificationException, PrunedException { boolean success = super.add(block); if (success) { trackFilteredTransactions(block.getTransactionCount()); } return success; }
31854274_0
public static long roundUp(long size, int blockSize) { return ((size + blockSize - 1) / blockSize) * blockSize; }
31855721_1
protected static Map<String, URL> getRuntimeFiles(JNAeratorConfig.Runtime runtime, boolean needsObjCRuntime) throws IOException { ClassLoader classLoader = JNAerator.class.getClassLoader(); Map<String, URL> ret = new LinkedHashMap<String, URL>(); String listingFile = runtime.runtimeFilesListFileName; i...
31906331_7
@Override public void close() throws Exception { if (itmManager != null) { itmManager.close(); } if (tzChangeListener != null) { tzChangeListener.close(); } if (tnlIntervalListener != null) { tnlIntervalListener.close(); } if(tnlToggleListener!= null){ tnlTogg...
31909123_2
public Map<Character, Integer> buildCharacterMapper() { Map<Character, Integer> charTOIntMap = new HashMap<Character, Integer>(); charTOIntMap.put('E', 0); charTOIntMap.put('J', 1); charTOIntMap.put('N', 1); charTOIntMap.put('Q', 1); charTOIntMap.put('R', 2); charTOIntMap.put('W', 2); charTOIn...
31911300_104
public void initialize(Properties properties) throws RequiredInputMissingException, ComponentInitializationFailedException { if(properties == null) throw new RequiredInputMissingException("Missing required properties"); ///////////////////////////////////////////////////////////////////////////////// // fetch ...
31923485_6
List<ImmutablePair<String, Integer>> parse(String value) { List<ImmutablePair<String, Integer>> result = newArrayList(); StringTokenizer tokenizer = new StringTokenizer(value, SEPARATORS); while (tokenizer.hasMoreElements()) { String line = (String) tokenizer.nextElement(); String[] parsed =...
31924536_3
public String next() { if (!hasNext()) { throw new IllegalStateException("No next ngram to return"); } CharSequence result = CharBuffer.wrap(_normalized, _normalizedPos, _curNGramLength); nextNGram(); return result.toString(); }
31924590_26
@Override public void filter(final FieldsMap fields) throws FormatException { if (fields instanceof Event) { final Event event = (Event) fields; final List<LogEntry> entries = event.getEntries(); if (entries != null && entries.size() > 0) { final LogEntry entry = entries.get(0); event.putAll(entry); if ...
31935307_2
public static String extractCookie(final HttpServletRequest request, final String name) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie.getValue(); } } } return null; }
31976266_71
@Override public int append(IFrameTupleAccessor tupleAccessor, int tIndex) throws HyracksDataException { byte[] src = tupleAccessor.getBuffer().array(); int tStartOffset = tupleAccessor.getTupleStartOffset(tIndex); int length = tupleAccessor.getTupleLength(tIndex); System.arraycopy(src, tStartOffset, ar...
31989343_18
public void buildQuery(Endpoint endpoint) { if (this.bounceClasses.size() > 0) { endpoint.addParam("bounce_classes", setAsString(this.bounceClasses, ",")); } if (this.campaignIds.size() > 0) { endpoint.addParam("campaign_ids", setAsString(this.campaignIds, ",")); } if (this.events....
32034982_87
protected void upgradeXmlNamespace(Document doc) { //System.out.println( "----------------------------" ); //System.out.println( "DOCUMENT BEFORE CONVERSION:" ); //DocumentUtils.write( doc, System.out ); //System.out.println( "----------------------------" ); XmlUtils.replaceNamespace(doc, StringUt...
32083811_15
public String parse(Query query, QueryOptions queryOptions, String viewName) { Set<String> keySet = query.keySet(); for (String key : keySet) { String value = (String) query.get(key); // sanity check if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { throw new I...
32098238_5
public void copyBusinessFieldsFrom(Student student) { this.setAddress(student.getAddress()); this.setBirthDate(student.getBirthDate()); this.setLastName(student.getLastName()); this.setFirstName(student.getFirstName()); this.setPhoneNumber(student.getPhoneNumber()); this.setGender(student.getGender()); }
32104397_1
public KafkaLogAppender() { }
32104835_210
public int getRegister(final int reg) { return this.getRegister(reg, false); }
32134387_2
public void cat(String[] cmd) throws SimpleShellException { if (cmd.length < 2) { throw new SimpleShellException("USAGE: cat <path>"); } // Locate the file FileObject file; try { file = mgr.resolveFile(cwd, cmd[1]); } catch (FileSystemException ex) { Stri...
32137005_14
public static void logOMStarted() { StringBuilder sb = new StringBuilder("\n"); getLine(sb, "", '#'); getLine(sb, "Openmeetings is up", ' '); getLine(sb, getVersion() + " " + getRevision() + " " + getBuildDate(), ' '); getLine(sb, "and ready to use", ' '); getLine(sb, "", '#'); log.debug(sb.toString()); }
32178402_2
public boolean isLineIntersects(float x0, float y0, float x1, float y1) { final int posOfSecPoint; if ((posOfSecPoint = checkRelativePosition(x1, y1)) == 0) { return true; } while (true) { final int posOfFrstPoint = checkRelativePosition(x0, y0); if (posOfFrstPoint == 0) { break; } if...
32181228_26
final public int getKillerScore(int ply, Move m) { int move = (short)(m.from + (m.to << 6) + (m.promoteTo << 12)); if (ply < ktList.length) { KTEntry ent = ktList[ply]; if (move == ent.move0) { return 4; } else if (move == ent.move1) { return 3; } } ...
32182572_7
public RealMatrix getTranspose() { code.clearOnline(); rcaller.runAndReturnResultOnline(this.name); int[] dims = rcaller.getParser().getDimensions(this.name); double[][] mat = rcaller.getParser().getAsDoubleMatrix(this.name, dims[0], dims[1]); RealMatrix matnew = new RealMatrix(service); matnew....
32199895_7
public static String toHalfwidth(final String katakana) { return translate(katakana, KATAKANA_TO_HALFWIDTH, 1); }
32199982_635
@Override public <K> void scheduleCallback(K key, long timestamp, ScheduledCallback<K> callback) { this.epochTimeScheduler.setTimer(key, timestamp, callback); }
32203040_6
public ColumnType getCategory(int colNumber) { if (colNumber < columns.size()) { return columns.get(colNumber); } return columns.get(columns.size() - 1); }
32216000_20
@Override public void clearLineBuffer() { out.clearLineBuffer(); }
32223373_27
public static void run( Options options) throws Exception { if( options.showVersion()) { System.out.println( getVersion()); return; } logger_.info( "{}", getVersion()); // Identify the system input definition file. File inputDefOption = options.getInputDef(); if( inputDefOption != null && !inputDefOption.isAbs...
32223919_0
public int roll(){ return roll(iTimes, iFaces) + iModifier; }
32232605_7
public static KeyStore loadKeystore(final String keyStoreFile, final String keyStorePassword, final KeyStoreTypeEnum keyStoreType) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { final FileInputStream inputStream = new FileInputStream(keyStoreFile); KeyStore keyStore; tr...
32235391_3
public int nextPort() { Set<Integer> notAvailable = Sets.newHashSet(); int port = from; while (port <= to) { if (!notAvailable.contains(port) && portChecker.apply(port)) { return port; } else { notAvailable.add(port); } port++; } throw new Runt...
32238204_1
public static Role getRole(IdentityManager identityManager, String name) throws IdentityManagementException { if (identityManager == null) { throw MESSAGES.nullArgument("IdentityManager"); } if (isNullOrEmpty(name)) { return null; } IdentityQueryBuilder queryBuilder = identityManag...
32253655_5
public void setVideoUri(Uri uri) { videoId = videoIdParser.parseVideoId(uri); youtubeRepository.getVideoInfo(videoId, this); }
32257863_84
protected boolean updateMediaInfo(Movie movie, String filmwebUrl) { boolean returnValue = Boolean.TRUE; String xml = getPage(filmwebUrl); if (StringUtils.isBlank(xml)) { return Boolean.FALSE; } if (HTMLTools.extractTag(xml, "<title>").contains("Serial") && !movie.isTVShow()) { ...
32289221_0
public String formatKey(@NonNull final String name, @Nullable final String family) { if (TextUtils.isEmpty(family)) { return name; } else { return family.concat("_").concat(name); } }
32310721_110
protected static String getAsAgeString(final Date start, final Date stop) { if (start == null || stop == null) { return ""; } final String s = DurationFormatUtils.formatDurationWords(stop.getTime() - start.getTime(), true, true); final Matcher m = PATTERN.matcher(s); m.matches(); return m.group(1); }
32311287_8
public int[] generateSuggestedPages(int count) { Preconditions.checkState(count > 3,"the count of pages must be more than 3"); int pages = getPages(); if (1 == pages) { return new int[] { 0 }; } int page = getPage(); // current page. if (pages <= count) { return linearSeries...
32312076_16
public PagedResult getDetailedReport(PagedReportsParameter parameters) { String response = fetch(REPORTS_ENDPOINT + "/details?" + parameters.toParamList()); return new PagedResult(response); }
32332642_2
@Override public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Flow>> changes) { if (changes == null) { LOG.info("This line should never be reached because of @Nonnull."); return; } for (DataTreeModification<Flow> change : changes) { if (change == null) { ...
32350084_4
public void run() { while (!halted) { step(); } }
32354897_8
@Override public boolean isDead() { return state == STATE_DEAD; }
32377028_115
@Override public int getLimit() { try { return service.submit(new OperationGetLimit(logDataStore)).get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return 0; }
32398211_16
@Override public void setParams(List<String> params) { if (null != params) { if (params.size() < 5) { LOGGER.warning("Parameters list does not contain required length; you provided " + params.size() + ", expecting: 5 or more"); throw new IllegalArgumentException(); } ...
32398593_45
@SuppressWarnings({ "unchecked" }) public static <T> OperatorSwitchThenUnsubscribe<T> instance() { return (OperatorSwitchThenUnsubscribe<T>)Holder.INSTANCE; }
32399379_5
public void clearAll() { mDynamoMap.clear(); }
32403249_7
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof MavenArtifactDescriptor)) { return false; } return this.mavenGav().equals(((MavenArtifactDescriptor) obj).mavenGav()); }
32407177_7
public void setRootDirectoryAndNotify(File rootDirectory){ this.root = rootDirectory; bus.post(new CurrentRootDirectoryChangedEvent(rootDirectory)); }
32427215_54
public TemplateModel parse(File f) throws IOException, ParserException { if (!f.exists() || !f.canRead()) { throw new IOException("File cannot read or does not exist [" + f + "]"); } TemplateIdentity identity = parseIdentity(this.configuration.getTemplateDirectory(), f); ANTLRFileStrea...
32444134_12
@Override public <T> T unwrap(Class<T> clazz) { return org.vertx.java.core.http.ServerWebSocket.class.isAssignableFrom(clazz) ? clazz.cast(socket) : null; }
32445517_0
@Override public void invoke(Context context, Result result) { try { doInvoke(context, result); } catch (CompileDiagnosticException e) { throwRenderingException(context, result, e); } catch (ParserException e) { throwRenderingException(context, result, e); } catch (RenderingExcep...
32447005_3
@Override public Sentence send(String event, Object data) { return execute(new SendAction(event, data)); }
32447381_27
public String getUid() { return uid; }
32461606_20
@Override public boolean contains(Rule rule) { return this.map.containsValue(rule); }
32461864_18
public void setId(String id) { this.id = id; firePropertyChange(); }
32463056_14
@Override public void sendMetric(final Metric metric) { if (filter.matchesMetric(metric)) { sink.sendMetric(metric); } }
32470641_13
@Override public String format(ExecutableElement method) { return format(method, Optional.<DeclaredType>absent()); }
32472801_81
@Override public boolean removeOnHostAllocationListener(final EventListener<VmHostEventInfo> listener) { return onHostAllocationListeners.remove(requireNonNull(listener)); }
32479235_29
public static Map<Occurrence, AdviceConfig> resolveConfiguration(final Method method, final Class<?> targetClass) { if (GeDAInfrastructure.class.isAssignableFrom(targetClass) || Adapter.class.isAssignableFrom(targetClass)) { retur...
32488797_2
public static void inject(Activity target) { inject(target, target, ResourceFinder.CONTEXT); }
32492849_538
public static void applyFilter(ScriptFilter filter, List<ScriptStep> steps) { boolean allConditionsMustPass = filter.getAllConditionsMustPass(); Set<ScriptStep> stepsToDelete = new HashSet<ScriptStep>(); SortedMap<Integer, ScriptStep> stepsToAdd = new TreeMap<Integer, ScriptStep>(); for (ScriptStep step...
32505934_3
protected static Optional<RDFSyntax> guessRDFSyntax(final Path path) { return fileExtension(path).flatMap(RDFSyntax::byFileExtension); }
32516197_4
public static CmdQuit createCmdQuit() { initialize(); return new CmdQuit(); }
32521417_2
@Override protected void process(final EC2InstanceContext context) { if (context.isTaupageAmi().orElse(false)) { if (!context.getTaupageYaml().isPresent()) { violationSink.put( context.violation() .withType(MISSING_USER_DATA) ...
32525992_14
public String getState(String result) { result = result == null ? "" : result; String state = IN_PROGRESS_STATE; if (result.equalsIgnoreCase("Passed")) { state = SUCCESSFUL_STATE; } else if (result.equalsIgnoreCase("Failed")) { state = FAILED_STATE; } else if (result.equalsIgnoreCase...
32533210_87
public int getIntervalNumber() { return intervalNumber; }
32535364_8
public static ProjectChangeId create(String token) { String mutableToken = token; // Try parsing /c/project/+/numericChangeId where token is project/+/numericChangeId int delimiter = mutableToken.indexOf(PageLinks.PROJECT_CHANGE_DELIMITER); Project.NameKey project = null; if (delimiter > 0) { project = ne...
32540624_0
public long backoff(int attempt) { long duration = base * (long) Math.pow(factor, attempt); if (jitter != 0) { double random = Math.random(); int deviation = (int) Math.floor(random * jitter * duration); if ((((int) Math.floor(random * 10)) & 1) == 0) { duration = duration - deviation; } else ...
32567407_1
public int sum(int num1, int num2){ return num1 + num2; }
32568128_29
public String getContextPath() { return contextPath; }
32571376_48
@Override public void lookup(EndpointPromise future) { final String methodName = "lookup"; logger.entry(this, methodName, future); try { String lookupUri; Endpoint endpoint = null; boolean retry = false; synchronized(state) { if (state.lookupUri == null) { ...
32632538_1
public static AndroidCustomField dir(String type, String... values) { AndroidCustomField property = new AndroidCustomField(); property.dir = true; property.type = type; Collections.addAll(property.values, values); return property; }
32634272_14
public static boolean isWithinBounds (int[] rgParams, int[] rgLowerBound, int[] rgUpperBound) { // sanity checks... OptimizerUtil.checkBoundVars (rgLowerBound, rgUpperBound); if (rgParams == null) throw new NullPointerException ("The argument rgParams must not be null."); if (rgParams.length != rgLowerBound.leng...
32648170_0
public String getString(String key) { try { return res_bund.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } }
32677360_2
@Override protected void onPostExecute(List<Project> result) { listViewController.updateListView(result); }
32693202_87
@Override public Set<String> unset(String data) { Set<String> errors = new HashSet<>(); Map<String, Set<String>> values = TextUtils.parseAssignment(data); values.keySet().forEach( k -> { String enumName = k.toUpperCase(); if (Field.contains(enumName)) { ...
32714807_6
public static String addTrailingIfNeeded(String s, String trailing) { String value = s; if ((null != s) && (null != trailing)) { if (isTruthy(s) && !s.endsWith(trailing)) { value = s + trailing; } } return value; }
32731947_1
public void loadPostsFromAPI() { postsAPI.getPostsObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers .mainThread()) .subscribe(new Subscriber<List<Post>>() { @Override publ...
32739177_0
public static Map<String, MemberInfo> scanBridge(File file) throws IOException { final ScanBridgeAdapter slv = new ScanBridgeAdapter(new EmptyVisitor()); new FileWalker().withStreamHandler(new StreamHandler() { @Override public void handle(boolean isDir, String name, StreamOpener current, Obje...
32753016_28
@Override public String toString() { return osType.label + "-" + versionSingleNumber; }
32771134_7
public final void createEditTodoAction(long todoId, String newDescription) { DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoId); bundle.put(TodoAction.DataKeys.DESCRIPTION, newDescription); actionBus.post(new TodoAction(TodoAction.ActionTypes.EDIT, bu...
32777313_11
@Nullable public BDXR2ProcessIdentifier createProcessIdentifier (@Nullable final String sScheme, @Nullable final String sValue) { final String sRealScheme = nullNotEmpty (sScheme); final String sRealValue = nullNotEmpty (isProcessIdentifierCaseInsensitive (sRealScheme) ? getUnifiedValue (sValue) : sValue); if (i...
32784502_8
public static byte[] derivePublicKey(byte[] privateKey) { return NaCl.derivePublicKey(privateKey); }
32790574_2
static String findWaveBand(Product product, boolean fail, double centralWavelength, double maxDeltaWavelength, String... bandNames) { Band[] bands = product.getBands(); String bestBand = null; double minDelta = Double.MAX_VALUE; for (Band band : bands) { double bandWavelength = band.getSpectralW...
32790911_1
public boolean isDirectoryIntegrationRequired () { return m_aSettings.getAsBoolean (SMPServerConfiguration.KEY_SMP_DIRECTORY_INTEGRATION_REQUIRED, SMPServerConfiguration.DEFAULT_SMP_DIRECTORY_INTEGRATION_REQUIRED); }
32794630_1
static String mangleIndexPage(String data, String mainJS, String mainClass) { Pattern loadClass = Pattern.compile("loadClass *\\( *[\"']" + mainClass); Matcher loadClassMatcher = loadClass.matcher(data); if (loadClassMatcher.find()) { return data; } int endOfBody = data.toLowerCase().lastIn...
32802417_0
public static boolean hasSuperClass(Class<?> classA, Class<?> classB) { // end recursion if (classA.equals(classB)) return true; boolean superclass = false; // check superclass Class<?> superClass = classA.getSuperclass(); if (superClass != null) { if (superClass.equals(classB)) superclass = true; else...