id
stringlengths
7
14
text
stringlengths
1
37.2k
14969366_10
public static byte[] fromBase64String(final String encoded) { if (encoded == null) { return new byte[0]; } try { return decode(encoded, NO_OPTIONS); } catch (IOException e) { e.printStackTrace(System.err); return new byte[0]; } }
14975201_0
@GET @Produces(MediaType.TEXT_PLAIN) public String getIt() { return "Got it!"; }
14996402_11
public List<Cell> getCellsOnPath(Iterable<?> sourcePath) { return getCellsOnPath(sourcePath.iterator()); }
14997161_0
@Nonnull public String getClassForURL(@Nonnull String path) { String servletName = findServletName(path); for (ClassMapping entry : servlets) { if (entry != null && servletName.equals(entry.getServletName())) { return entry.getClassWithPackage(); } } return DEFAULT_SERVLET; }
15032904_120
@SuppressWarnings("unchecked") public static <T> T createInstance(Class<T> interfaceClass, Map<String, Object> backingMap) { return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, new BackingMapInvocationHandler(backingMap, interfaceClass)); }
15040596_16
public CompletableFuture<Result> send(Message message) { try { HttpRequest request = HttpRequest.newBuilder() .uri(uri) .header("Authorization", authorizationHeader) .header("Content-Type", "application/...
15042909_0
public void updateMigration(Migration update) { updateMigration = update; }
15057896_8
@Override public byte[] serialize(Event event) throws RedisSerializerException { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, String> entry : event.getHeaders().entrySet()) { jsonObject.addProperty(entry.getKey(), entry.getValue()); } return jsonObject.toString().getBytes(); ...
15070657_18
public Collection<Field> createFields(Collection<TokenStream> tokenStreams, FieldDescription fieldDescription) throws FieldBuildingException { TokenStream tokenStream = createFieldTokenStream(tokenStreams, fieldDescription); this.fieldDescription = fieldDescription; String fieldName = fieldDescription.getName...
15070661_39
@Override public ScriptApply apply(RutaStream stream, InferenceCrowd crowd) { BlockApply result = new BlockApply(this); getEnvironment().ensureMaterializedInitialValues(new MatchContext(this), stream); crowd.beginVisit(this, result); setRuleElementAnchor(); boolean leftToRight = true; if (direction != nul...
15070662_0
public void executeAE(String aePath, String collectionPath, String outputFilePath, Integer casPoolSize) throws Exception { HamaConfiguration conf = new HamaConfiguration(); // set specific job parameters conf.set("uima.ae.path", aePath); conf.set("output.file", outputFilePath); conf.set("cas.pool.size", Strin...
15070665_72
public static AnalysisEngineDescription createEngineDescription(PearSpecifier pearSpecifier, Object... configurationData) throws InvalidXMLException, IOException { ConfigurationParameterFactory.ensureParametersComeInPairs(configurationData); if (configurationData != null) { for (int i = 0; i < config...
15078952_47
public Object[] keyArray() { return this.orderKeys.toArray(); }
15090649_1
public static void main(String[] args) throws Exception { Logger.getLogger("org.sonews").log(Level.INFO, VERSION); boolean feed = false; // Enable feeding? boolean purger = false; // Enable message purging? int port = -1; for (int n = 0; n < args.length; n++) { switch (args[n]) { ...
15090793_3
@SuppressWarnings("unchecked") public static <T> T shallowCopy(T original) { Class<? extends T> clazz = (Class<? extends T>) original.getClass(); BeanClass<? extends T> beanClass = (BeanClass<? extends T>) classes.get(clazz); if (beanClass == null) { beanClass = BeanClass.buildFrom(clazz); classes.put(clazz,...
15092109_3
private List<String> getSortedDependentCategories(Set<String> originalCategories, LibraryType type, List<String> existingCategories) { final Collection<ClientLibrary> libraries = htmlLibraryManager.getLibraries( originalCategories.toArray(new String[0]), null, // always request all types (to...
15104745_22
public String convert(Object val) { if (val == null) { return null; } String converted; if (val instanceof String) { converted = val.toString(); } else if (val instanceof InetAddress) { converted = val.toString(); } else if (val instanceof UUID) { converted = val.toString(); } else if (val instanceof ...
15106163_0
public static <T> T extractFromXml(@Nonnull File xmlFile, String xPath, Class<T> clazz) throws IOException { return Objects.requireNonNull(FileUtil.executeIoOperation(new ThreadUtil.Operation<T>() { @Nonnull @Override public T run() throws IOException { try { ...
15106392_80
public List<DisplayHierarchyNode> siblings() { return siblings; }
15120144_1
@Override public int countChars (Note note) { String titleAndContent = note.getTitle() + "\n" + note.getContent(); return Observable .from(sanitizeTextForWordsAndCharsCount(note, titleAndContent).split("")) .filter(s -> !s.matches("\\s")) .count().toBlocking().single(); }
15132790_17
public static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); }
15137325_82
@VisibleForTesting protected static void interpretGenus(ParsedName pn, String genus) { // test if name has an abbreviated genus if (pn != null && !Strings.isNullOrEmpty(genus) && pn.getGenusOrAbove() != null && genus.length() > 1) { if (pn.getGenusOrAbove().length() == 2 && pn.getGenusOrAbove().charAt(1...
15137397_5
@Override public <X extends P, P extends IPieEvent, T extends IPieEventTask<P>> void registerTask(Class<X> event, Class<T> task) { Validate.notNull(event); Validate.notNull(task); this.tasks.put(event, task); }
15138385_7
@Override protected Class<? extends Mapper> getMapperClass() { return InBloomFilterMapper.class; }
15162009_6
protected static final boolean isValidNeutronID(String id) { if (id == null) { return false; } boolean isValid = false; logger.trace("id - {}, length - {} ", id, id.length()); /** * check the string length * if length is 36 its a uuid do uuid validation * if length is 32 it ca...
15199543_10
public void add(final ZclCommandFormat messageFormat) { commandFormats.put(messageFormat.getCommand(), messageFormat); }
15209448_1
@Override public ExamplesIterable readFrom(Class<ExamplesIterable> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { if (LOGGER.isDebugEnabled()) if (httpHeaders != null && httpHead...
15221298_30
public void addHtmlDescription(RulesDefinition.NewRule rule) { URL resource = ExternalDescriptionLoader.class.getResource(resourceBasePath + "/" + rule.key() + ".html"); if (resource != null) { addHtmlDescription(rule, resource); } }
15227263_10
public static long pixelXToTileX(double pixelX, byte zoomLevel) { return (long) Math.min(Math.max(pixelX / Tile.TILE_SIZE, 0), Math.pow(2, zoomLevel) - 1); }
15284049_26
@Override public void appendToLog(LogOutput dbLog) { dbLog.newEdge(edge); StreamIterator.stream(edge.properties()) .filter(property -> !propertiesToIgnore.contains(property.key())) .forEach(dbLog::newProperty); }
15289581_19
@Override public RuntimeException propagateException(Object key, ExceptionInformation exceptionInformation) { long expiry = exceptionInformation.getUntil(); String txt = ""; if (expiry > 0) { if (expiry == ExpiryTimeValues.ETERNAL) { txt = "expiry=ETERNAL, caus...
15292023_0
@Override public int next() { return rng.nextInt(upper); }
15293721_6
public String humanize(final Method method) { if (method.isAnnotationPresent(Text.class)) { return method.getAnnotation(Text.class).value(); } else { return humanize(method.getName()); } }
15303802_2
public void convert(URL pdmlUrl, File waveFileDir, SampleRate sampleRate, Channels channels) throws Exception { if (!waveFileDir.isDirectory()) throw new IllegalArgumentException(); Pdml pdml = new PdmlReader().unmarshall(pdmlUrl); RtpStream[] streams = new RtpExtracter().parse(pdml); for (int i...
15322987_4
@GET @Produces({ "application/json", "application/xml" }) @Path("{id}") public Employee get(@PathParam("id") int id) { if (id < bean.getEmployees().size()) return bean.getEmployees().get(id); else return null; }
15326235_0
public static List<String> findTaggedWords(JsonNode rootNode, boolean lookForSequence, String... tags) { ArrayList<String> result = new ArrayList<>(); int size = rootNode.size(); for (int i = 0; i < size; i++) { JsonNode child = rootNode.get(i); List<String> words = findTaggedWords(child, lookForSequence, tags...
15347941_6
public void decode(InputStream in, HeaderListener headerListener) throws IOException { while (in.available() > 0) { switch(state) { case READ_HEADER_REPRESENTATION: byte b = (byte) in.read(); if (maxDynamicTableSizeChangeRequired && (b & 0xE0) != 0x20) { // Encoder MUST signal maximum dyna...
15353990_1
public static int random(int min, int max) { return random.nextInt(max - min + 1) + min; }
15373368_79
@Override public double calculate(TimeSeries series, TradingRecord tradingRecord) { return tradingRecord.getTradeCount(); }
15374337_40
static protected List<String> getPropertyAsList(Properties props, String key) { List<String> retVal = null; String listProp = props.getProperty(key); if (listProp != null) { String[] valueArray = listProp.split(",\\s*"); retVal = Arrays.asList(valueArray); } return retVal; }
15388765_51
@Override public String authenticate(final Auth auth){ for(String template : templates){ String userNameTemplate = convertTemplate(template, auth.getUserName()); LdapConfig config = new LdapConfig(url, userNameTemplate, auth.getPassword()); if(tryAuthenticate(config)){ return auth.getUserName(); } } throw...
15403409_1
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof GCodeWord)) return false; GCodeWord gCodeWord = (GCodeWord) o; if (!word.equals(gCodeWord.word)) return false; return true; }
15416636_13
public String extractFromPdf(String input) { if (input != null && input.endsWith(".pdf")) { Matcher m = p.matcher(input); if (m.find()) return m.group(); } return ""; }
15472368_4
public Logs parallel() { Collection<Dir> dirs = initalizeDirs(); Stream<Log> result = null; for (Dir d : dirs) { Stream<Log> stream = Guavas.toStream(new Dirs.LogIterator(d), true); if (result == null) { result = stream; } else { result = Stream.concat(stream, result); } } if (resu...
15475337_118
@Nonnull public static String acceptStrings(@Nonnull String[] input) { StringBuilder builder = new StringBuilder(); builder.append("("); for (int i = 0; i < input.length; i++) { builder.append(Pattern.quote(input[i])); if (i < input.length - 1) { builder.append("|"); } ...
15491874_16
public void bind() { unbind(); compositeDisposable = new CompositeDisposable(); bindInternal(compositeDisposable); }
15496005_2
public boolean contains(@Nonnull Class<? extends Dhcp6Option> type) { return !options.get(Dhcp6OptionsRegistry.getInstance().getOptionTag(type)).isEmpty(); }
15523927_4
public void addARC(String arcPath) throws Exception { log.info("Persisting new arc-file: " + arcPath); String[] splitPath = splitPath(arcPath); String folder = splitPath[0]; String arcId = splitPath[1]; boolean aRCIDExist = aRCIDExist(arcId); if (aRCIDExist){ throw new IllegalArgumen...
15554335_4
public Validated validateEvent(VersionedEventsModel eventsModel, ObjectNode eventNode) { final EventModel ingressEvent = EventModel.builder(eventNode, false).build(); Validated.ValidatedBuilder builder = Validated.build(); LOG.inc("validated_events"); if (eventsModel == null || eventsModel.getEventsMode...
15555290_0
public String createJsonForElement(Graph graph, Element element, Authorizations authorizations) { try { String indexName = getIndexName(element); IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName, getConfig().isStoreSourceData()); return buildJsonContentFromElement(graph, inde...
15590153_0
public Instances getHeader() { return makeStructure(); }
15590229_0
static String toDebugString(final byte[] bytes, final int len, final Charset charset) { if (charset == null) { return toDebugString(new String(bytes, 0, len, Charset.defaultCharset())); } return toDebugString(new String(bytes, 0, len, charset)); }
15596189_0
public static String getRawCommand(String chatMessage) { Preconditions.checkArgument(chatMessage.charAt(0) == '/', "getRawCommand('%s') requires a command, starting with a slash, to be passed!", chatMessage); String result; int spaceIndex = chatMessage.indexOf(" "); //For finding th...
15611804_5
@Override public <T> T get(String key, Class<T> clazz) { return rootNode.get(key, clazz); }
15655130_44
public ComponentDescription createDescription(Class<? extends Component> componentClass) { checkArgument(componentClass != null, "Component class is mandatory"); Documentation documentation = componentClass.getAnnotation(Documentation.class); checkArgument(documentation != null, "No documentation found for " + comp...
15684181_47
public ObjectHolder() { }
15693035_46
static Matcher validateZkUrl(final String zkUrl) { final Matcher matcher = zkURLPattern.matcher(zkUrl); if (!matcher.matches()) { throw new SystemExitException(String.format("Invalid zk url format: '%s' expected '%s'", zkUrl, validZkUrl), 7); } return matcher; }
15695680_1
public static String toXml(String root, Map<String, String> body) { if (body == null) return ""; return body.keySet().stream().map(key -> { return "<" + key + ">" + body.get(key) + "</" + key + ">"; }).collect(Collectors.joining("", "<" + root + ">", "</" + root + ">")); }
15698466_508
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHost(), config.getProxy().get() .getPort()); ...
15717111_2
public Map<String, MetaData> findInstances() { Map<String, MetaData> instances = new TreeMap<String, MetaData>(); init(); try { for (String path : filters) { logger.debug("checking entries with path filter: " + path); // We need to clean up the input for base path and filt...
15722026_3
@SuppressWarnings("checkstyle:MultipleStringLiterals") public static PaginationParams previousPage(@NonNull PagedResponse.Pagination pagination) throws IllegalArgumentException { if (pagination.getPreviousUri() == null) { return null; } try { String endingBeforeId = getQueryParameter(paginat...
15728671_30
@Override public int size() { return size; }
15729898_5
@GET @Path("/outbound") @Produces("application/json") ** * retrieve the news posted by an individual participant * fetch a participant news * @param id uniquely identifies the participant (required) * @return List<Outbound> */ public List<Outbound> getOutbound(@PathParam("id") LongParam id) { return outboundService....
15751803_10
@Override public Move nextMove(int availableMana, int currentHealth, List<Card> availableCards) { if (currentHealth < 20) { return new Move(lowestCard(availableMana, availableCards), Action.HEALING); } else { return new Move(highestCard(availableMana, availableCards), Action.DAMAGE); } }
15779685_47
public static SkeletonOutput skeleton(List<Point2d> polygon) { return skeleton(polygon, null); }
15784931_0
String emitHumanDescription(List<Binding> bindings) { StringBuilder builder = new StringBuilder(); switch (bindings.size()) { case 1: builder.append(bindings.get(0).getDescription()); break; case 2: builder .append(bindings.get(0).getDescription()) .append(" and ") ...
15800167_1
public static Attributes mergeAndNormalize(Attributes... attrsList) { SpecificCharacterSet globalCs = null; for (Attributes attrs : attrsList) { SpecificCharacterSet cs = attrs.getSpecificCharacterSet(); if (globalCs == null) { globalCs = cs; // first } else { ...
15801589_0
public Object getService( final Bundle bundle, final ServiceRegistration serviceRegistration ) { LOG.info( "Binding bundle: [" + bundle + "] to http service" ); return createService( bundle ); }
15801780_4
void setRollbackCommandConf(RollbackCommandConf rollbackCommandConf) { this.rollbackCommandConf = rollbackCommandConf; }
15802014_105
public static ApnsServiceBuilder newService() { return new ApnsServiceBuilder(); }
15830023_4
public void reset() { hours = 0; minutes = 0; }
15831475_79
public List<Pointer> getPointers() { return pointers; }
15841047_19
public ItemCollection process(final ItemCollection workitem) throws PluginException, ModelException { // check document context if (workitem == null) throw new ProcessingErrorException(WorkflowKernel.class.getSimpleName(), UNDEFINED_WORKITEM, "processing error: workitem is null"); ...
15841325_4
protected final Context getContext() { return mContext; }
15845284_1
@Override protected void onListItemClick(ListView l, View v, int position, long id) { Group g = (Group) getListView().getAdapter().getItem(position); if (!g.isSectionHeader()) { DataSource.getInstance().storeGroup(g); Intent data = new Intent(); data.putExtra("insert_id", g.getId()); ...
15861701_165
@Override boolean isAssignmentValid(AssignableNode node, AssignableReplica replica, ClusterContext clusterContext) { boolean exceedMaxPartitionLimit = node.getMaxPartition() < 0 || node.getAssignedReplicaCount() < node.getMaxPartition(); boolean exceedResourceMaxPartitionLimit = replica.getResourceMaxPart...
15878497_18
public String methodReturns(String method) { return getMethodPart(method, 2); }
15904020_1
static Date getEarliestDate(Optional<Date> o, Date d){ if (o.isPresent()){ d = o.get().before(d) ? o.get() : d; } return d; }
15912903_21
@Override public boolean sequencesMatching(final String phrase1, final String phrase2) { final String phrase1LowerCase = removeNonAlphanumeric(phrase1).toLowerCase(); final String phrase2LowerCase = removeNonAlphanumeric(phrase2).toLowerCase(); final List<String> phrase1Bag = new ArrayList<>(Arrays.asList(...
15928650_0
String sanitizeInputPath( String value ) { if (value != null && value.toUpperCase().contains("WEB-INF")) { return null; } return value; }
15951171_0
public void append(final K id, final UnitOfWork uow) { checkNotNull(id); checkNotNull(uow); final AggregateRootHistory history = getHistoryFor(id); if (!history.getLastVersion().equals(uow.getTargetVersion())){ throw new ConcurrentModificationException(String.format("version %s does not match the expected %s ****...
15958676_25
public static String getArrayDimensionString(Object array) { if (!array.getClass().isArray()) { return ""; } StringBuilder sb = new StringBuilder(); Object current = array; int len = Array.getLength(current); sb.append('[').append(len).append(']'); while (len > 0) { current...
15979754_15
@Command public String osVersion() { return System.getProperty("os.version"); }
15994370_1
@Override @WebMethod(action = "http://www.example.org/periodictableaccess/getElementByAtomicNumber") @WebResult(name = "element", targetNamespace = "") @RequestWrapper(localName = "getElementByAtomicNumber", targetNamespace = "http://www.example.org/periodictableaccess/", className = "com.example.periodictable.ws.acces...
15997656_31
public static Response post(String url) throws URISyntaxException, UnsupportedEncodingException, HttpException { return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), null, null); }
16004885_1
@Override public Iterable<File> asIterable() { ArrayList<File> list = new ArrayList<File>(Arrays.asList(migrationFiles)); Collections.sort(list, comparator); return list; }
16006160_9
public static String urlDecode(final String encoded, final Charset charset) throws MyRuleException { final byte[] buff = new byte[encoded.length()]; // バイト長は文字列長を超えない。 int buffIndex = 0; for (int i = 0; i < encoded.length(); i++) { if (encoded.charAt(i) == '%') { if (i + 2 >= encoded.len...
16037437_0
@Override public IoCComponentProvider getComponentProvider(Class<?> clazz) { return getComponentProvider(null, clazz); }
16047008_14
public int size() { return start_byte.size() - 1; }
16050719_0
public TimeZone getTimeZone() { if (timezone == null) { return getCalendar().getTimeZone(); } return timezone; }
16057180_0
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + height; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + pieceId; result = prime * result + ((unitSquares == null) ? 0 : unitSquares.hashCode()); result = prime * result...
16077092_0
public List<String> getCategoricalInstances() { return ImmutableList.copyOf(categoricalInstances); }
16091126_6
public float[] weightHistogram(int firstindex, int lastindex, int start, int stop, int stepsize, int dedup, Float minweight, ...
16094148_0
@Override protected void runOneIteration() throws Exception { Map<String,Date> inactiveDevices = apnsService.getInactiveDevices(); for (String deviceToken : inactiveDevices.keySet()) { Date inactiveAsOf = inactiveDevices.get(deviceToken); Optional<WebPushUser> userOptional = getUserIfValidTime(d...
16100959_68
public static byte[] getByteContent(Resource resource, String sourceURL) throws RegistryException { try { InputStream is = null; if (sourceURL != null) { is = new URL(sourceURL).openStream(); } else { Object content = resource.getContent(); if( null == con...
16115996_3
public static int countOptimal(int[] coins, int amt) { // solutions[i] contains the no. of solutions for value i. // We build from bottom up using the base case (n = 0) int solutions[] = new int[amt + 1]; solutions[0] = 1; for (Integer i : coins) for (int j = i; j <= amt; j++) solutions[j] += solu...
16121108_8
public String getIdentifierPrefix() { StringBuilder sb = new StringBuilder(); URL baseUrl = this.getRuntime().getServerBaseUrl(); // protocol Boolean httpsEnabled = getBooleanAttribute("https.identifier.enabled"); final String protocol; if (httpsEnabled != null) { protocol = httpsEnabled.booleanValue() ? "http...
16132708_5
@Override public SailConnection getConnection() throws SailException { return new ContextAwareSailConnection(super.getConnection(),context); }
16156598_0
@Override public String toDDP(final Object object) { final String json = GSON.toJson(object, object.getClass()); final StringBuilder buffer = new StringBuilder(json); buffer.insert(1, "\"msg\":\"" + MessageRegistry.get(object.getClass()) + "\","); return buffer.toString(); }
16159416_1
public void download(DbxClientV2 dbxClient, File localFile, String dropboxPath) throws FileNotFoundException, IOException, DbxException { try (OutputStream out = new FileOutputStream(localFile)) { FileMetadata metadata = dbxClient.files().downloadBuilder(dropboxPath) .download(out); System.out.pr...