id
stringlengths
7
14
text
stringlengths
1
37.2k
4673630_6
public Map<String, LdapUserMapping> getUserMappings() { if (userMappings == null) { // Use linked hash map to preserve order userMappings = new LinkedHashMap<>(); String[] serverKeys = settings.getStringArray(LDAP_SERVERS_PROPERTY); if (serverKeys.length > 0) { for (String serverKey : serverKeys) { LdapUserMapping userMapping = new LdapUserMapping(settings, LDAP_PROPERTY_PREFIX + "." + serverKey); if (StringUtils.isNotBlank(userMapping.getBaseDn())) { LOG.info("User mapping for server {}: {}", serverKey, userMapping); userMappings.put(serverKey, userMapping); } else { LOG.info("Users will not be synchronized for server {}, because property 'ldap.{}.user.baseDn' is empty.", serverKey, serverKey); } } } else { // Backward compatibility with single server configuration LdapUserMapping userMapping = new LdapUserMapping(settings, LDAP_PROPERTY_PREFIX); if (StringUtils.isNotBlank(userMapping.getBaseDn())) { LOG.info("User mapping: {}", userMapping); userMappings.put(DEFAULT_LDAP_SERVER_KEY, userMapping); } else { LOG.info("Users will not be synchronized, because property 'ldap.user.baseDn' is empty."); } } } return userMappings; }
4676768_3
public static OtaBuildHtmlGenerator getInstance() { return getInstance(null); }
4678495_8
@Override public Boolean exec(Tuple tuple) throws IOException { if (tuple == null || tuple.size() == 0) { return false; } try { Object object = tuple.get(0); if (object == null) { return false; } int i = (Integer) object; return i == 0 || i == 1 || i == 4 || i == 5 || i == 9; } catch (ExecException e) { throw new IOException(e); } }
4685138_0
public void greet() { System.out.println("Hello, I am Java!"); new HelloClojure().hello("Java"); new HelloFrege().hello("Java"); new HelloGosu().hello("Java"); new HelloGroovy().hello("Java"); new HelloJava().hello("Java"); new HelloKotlin().hello("Java"); new HelloPython().hello("Java"); new HelloRuby().hello("Java"); new HelloScala().hello("Java"); new HelloXtend().hello("Java"); }
4694994_16
static String[] getTitleAndSubtitle(String title) { Matcher titleMatcher = Pattern.compile("<\u00ac1>([^<]*)</\u00ac1>").matcher(title); Matcher subtitleMatcher = Pattern.compile("<\u00ac2>([^<]*)</\u00ac2>").matcher(title); if (titleMatcher.find()) { String theTitle = Jsoup.parse(titleMatcher.group(1)).text(); if (subtitleMatcher.find()) { String subtitle = Jsoup.parse(subtitleMatcher.group(1)).text(); return new String[]{theTitle, subtitle}; } else { return new String[]{theTitle}; } } else { return new String[]{title}; } }
4695543_1
public static String camelCaseToLowerUnderscore(String s) { if (s.toUpperCase().equals(s) && isLettersAndDigits(s)) { return s.toLowerCase(); } StringBuilder b = new StringBuilder(); b.append(s.charAt(0)); boolean underscoreAdded = false; boolean lastCharacterUppercase = false; for (int i = 1; i < s.length(); i++) { char ch = s.charAt(i); if (!Character.isLetterOrDigit(ch)) { if (!underscoreAdded) b.append('_'); underscoreAdded = true; lastCharacterUppercase = false; } else if (Character.isUpperCase(ch)) { if (!underscoreAdded && !lastCharacterUppercase) { b.append("_"); } b.append(ch); underscoreAdded = false; lastCharacterUppercase = true; } else { b.append(ch); underscoreAdded = false; lastCharacterUppercase = false; } } return b.toString().toLowerCase(); }
4695732_1
static int writeHeaderBuffer(final MapWriterConfiguration configuration, final TileBasedDataProcessor dataProcessor, final ByteBuffer containerHeaderBuffer) { LOGGER.fine("writing header"); LOGGER.fine("Bounding box for file: " + dataProcessor.getBoundingBox().maxLatitudeE6 + ", " + dataProcessor.getBoundingBox().minLongitudeE6 + ", " + dataProcessor.getBoundingBox().minLatitudeE6 + ", " + dataProcessor.getBoundingBox().maxLongitudeE6); // write file header // MAGIC BYTE byte[] magicBytes = MAGIC_BYTE.getBytes(UTF8_CHARSET); containerHeaderBuffer.put(magicBytes); // HEADER SIZE: Write dummy pattern as header size. It will be replaced // later in time int headerSizePosition = containerHeaderBuffer.position(); containerHeaderBuffer.putInt(DUMMY_INT); // FILE VERSION containerHeaderBuffer.putInt(configuration.getFileSpecificationVersion()); // FILE SIZE: Write dummy pattern as file size. It will be replaced // later in time containerHeaderBuffer.putLong(DUMMY_LONG); // DATE OF CREATION containerHeaderBuffer.putLong(System.currentTimeMillis()); // BOUNDING BOX containerHeaderBuffer.putInt(dataProcessor.getBoundingBox().minLatitudeE6); containerHeaderBuffer.putInt(dataProcessor.getBoundingBox().minLongitudeE6); containerHeaderBuffer.putInt(dataProcessor.getBoundingBox().maxLatitudeE6); containerHeaderBuffer.putInt(dataProcessor.getBoundingBox().maxLongitudeE6); // TILE SIZE containerHeaderBuffer.putShort((short) Constants.DEFAULT_TILE_SIZE); // PROJECTION writeUTF8(PROJECTION, containerHeaderBuffer); // check whether zoom start is a valid zoom level // FLAGS containerHeaderBuffer.put(infoByteOptmizationParams(configuration)); // MAP START POSITION if (configuration.getMapStartPosition() != null) { containerHeaderBuffer.putInt(configuration.getMapStartPosition().latitudeE6); containerHeaderBuffer.putInt(configuration.getMapStartPosition().longitudeE6); } // MAP START ZOOM if (configuration.hasMapStartZoomLevel()) { containerHeaderBuffer.put((byte) configuration.getMapStartZoomLevel()); } // PREFERRED LANGUAGE if (configuration.getPreferredLanguage() != null) { writeUTF8(configuration.getPreferredLanguage(), containerHeaderBuffer); } // COMMENT if (configuration.getComment() != null) { writeUTF8(configuration.getComment(), containerHeaderBuffer); } // CREATED WITH writeUTF8(configuration.getWriterVersion(), containerHeaderBuffer); // AMOUNT POI TAGS containerHeaderBuffer.putShort((short) configuration.getTagMapping().getOptimizedPoiIds().size()); // POI TAGS // retrieves tag ids in order of frequency, most frequent come first for (short tagId : configuration.getTagMapping().getOptimizedPoiIds().keySet()) { OSMTag tag = configuration.getTagMapping().getPoiTag(tagId); writeUTF8(tag.tagKey(), containerHeaderBuffer); } // AMOUNT OF WAY TAGS containerHeaderBuffer.putShort((short) configuration.getTagMapping().getOptimizedWayIds().size()); // WAY TAGS for (short tagId : configuration.getTagMapping().getOptimizedWayIds().keySet()) { OSMTag tag = configuration.getTagMapping().getWayTag(tagId); writeUTF8(tag.tagKey(), containerHeaderBuffer); } // AMOUNT OF ZOOM INTERVALS int numberOfZoomIntervals = dataProcessor.getZoomIntervalConfiguration().getNumberOfZoomIntervals(); containerHeaderBuffer.put((byte) numberOfZoomIntervals); // SET MARK OF THIS BUFFER AT POSITION FOR WRITING ZOOM INTERVAL CONFIG containerHeaderBuffer.mark(); // ZOOM INTERVAL CONFIGURATION: SKIP COMPUTED AMOUNT OF BYTES containerHeaderBuffer.position(containerHeaderBuffer.position() + SIZE_ZOOMINTERVAL_CONFIGURATION * numberOfZoomIntervals); // now write header size // -4 bytes of header size variable itself int headerSize = containerHeaderBuffer.position() - headerSizePosition - BYTES_INT; containerHeaderBuffer.putInt(headerSizePosition, headerSize); return containerHeaderBuffer.position(); }
4709330_67
public void save(User user, FileEntry fileEntry, String encoding) { SVNClientManager svnClientManager = null; ISVNEditor editor = null; String checksum = null; InputStream bais = null; try { svnClientManager = getSVNClientManager(); SVNRepository repo = svnClientManager.createRepository(SVNURL.fromFile(getUserRepoDirectory(user)), true); SVNDirEntry dirEntry = repo.info(fileEntry.getPath(), -1); // Add base paths String fullPath = ""; // Check.. first for (String each : getPathFragment(fileEntry.getPath())) { fullPath = fullPath + "/" + each; SVNDirEntry folderStepEntry = repo.info(fullPath, -1); if (folderStepEntry != null && folderStepEntry.getKind() == SVNNodeKind.FILE) { throw processException("User " + user.getUserId() + " tried to create folder " + fullPath + ". It's file.."); } } editor = repo.getCommitEditor(fileEntry.getDescription(), null, true, null); editor.openRoot(-1); fullPath = ""; for (String each : getPathFragment(fileEntry.getPath())) { fullPath = fullPath + "/" + each; try { editor.addDir(fullPath, null, -1); } catch (Exception e) { // FALL THROUGH noOp(); } } if (fileEntry.getFileType() == FileType.DIR) { editor.addDir(fileEntry.getPath(), null, -1); } else { if (dirEntry == null) { // If it's new file editor.addFile(fileEntry.getPath(), null, -1); } else { // If it's modification editor.openFile(fileEntry.getPath(), -1); } editor.applyTextDelta(fileEntry.getPath(), null); // Calc diff final SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator(); if (fileEntry.getContentBytes() == null && fileEntry.getFileType().isEditable()) { bais = new ByteArrayInputStream(checkNotNull(fileEntry.getContent()).getBytes( encoding == null ? "UTF-8" : encoding)); } else { bais = new ByteArrayInputStream(fileEntry.getContentBytes()); } checksum = deltaGenerator.sendDelta(fileEntry.getPath(), bais, editor, true); } addPropertyValue(editor, fileEntry); editor.closeFile(fileEntry.getPath(), checksum); } catch (Exception e) { abortSVNEditorQuietly(editor); // If it's adding the folder which already exists... ignore.. if (e instanceof SVNException && fileEntry.getFileType() == FileType.DIR) { if (SVNErrorCode.FS_ALREADY_EXISTS.equals(((SVNException) e).getErrorMessage().getErrorCode())) { return; } } LOG.error("Error while saving file to SVN", e); throw processException("Error while saving file to SVN", e); } finally { closeSVNEditorQuietly(editor); closeSVNClientManagerQuietly(svnClientManager); IOUtils.closeQuietly(bais); } }
4713292_14
public List<Mistake> check(Sentence sentence) { List<Mistake> mistakes = new LinkedList<Mistake>(); int offset = sentence.getSpan().getStart(); List<Token> tokens = sentence.getTokens(); String token = tokens.get(0).getLexeme().toLowerCase(); for (int i = 1; i < tokens.size(); i++) { String next = tokens.get(i).getLexeme().toLowerCase(); if (token.equals(next) && !isException(tokens, i)) { int start = tokens.get(i-1).getSpan().getStart() + offset; int end = tokens.get(i).getSpan().getEnd() + offset; mistakes.add(createMistake(ID, createSuggestion(tokens.get(i-1) .getLexeme()), start, end, sentence.getSentence())); } token = next; } return mistakes; }
4726303_127
public List<JsonStream> getOutputs() { final ArrayList<JsonStream> outputs = new ArrayList<JsonStream>(this.maxOutputs); for (int index = 0; index < this.maxOutputs; index++) outputs.add(this.getOutput(index)); return outputs; }
4726428_33
public int getRequiredInt(String property) { String prop = getRequiredString(property); try { return Integer.parseInt(prop); } catch (NumberFormatException e) { throw new IllegalArgumentException("Property " + property + " expected type: int"); } }
4732484_0
public <T, U extends T> T specialize(Class<T> parent, U t) throws SpecializationException { try (Logger l = new Logger("ROOT specialize(" + parent.getSimpleName() + " " + t + ")")) { ClassDescriptor specializedClass = specializeClass(t.getClass(), t); return parent.cast(specializeInstance(specializedClass, t)); } }
4737996_7
@Override public Map<SignatureType, SortedMap<String, SignatureFileInfo>> getAvailableSignatureFiles() { final Path binSigFileDir = config.getSignatureFileDir(); final Path containerSigFileDir = config.getContainerSignatureDir(); //File textSigFileDir = config.getTextSignatureFileDir(); final DirectoryStream.Filter<Path> xmlExtensionFilter = new DirectoryStream.Filter<Path>() { @Override public boolean accept(final Path path) { return (!Files.isDirectory(path)) && FileUtil.fileName(path).endsWith(".xml"); } }; final Map<SignatureType, SortedMap<String, SignatureFileInfo>> availableSigFiles = new HashMap<>(); SignatureInfoParser parser = new SignatureInfoParser(); final String errorMessagePattern = "Unreadable signature file [%s]"; final SortedMap<String, SignatureFileInfo> binSigFiles = new TreeMap<>(); for (final Path file : FileUtil.listFilesQuietly(binSigFileDir, false, xmlExtensionFilter)) { String fileName = FilenameUtils.getBaseName(FileUtil.fileName(file)); try { binSigFiles.put(fileName, forBinarySigFile(file, parser)); } catch (SignatureFileException e) { log.warn(String.format(errorMessagePattern, file)); } } final SortedMap<String, SignatureFileInfo> containerSigFiles = new TreeMap<>(); for (final Path file : FileUtil.listFilesQuietly(containerSigFileDir, false, xmlExtensionFilter)) { String fileName = FilenameUtils.getBaseName(FileUtil.fileName(file)); try { containerSigFiles.put(fileName, forSimpleVersionedFile(file, SignatureType.CONTAINER)); } catch (SignatureFileException e) { log.warn(String.format(errorMessagePattern, file)); } } /* SortedMap<String, SignatureFileInfo> textSigFiles = new TreeMap<String, SignatureFileInfo>(); for (File file : textSigFileDir.listFiles(xmlExtensionFilter)) { String fileName = FilenameUtils.getBaseName(file.getName()); try { textSigFiles.put(fileName, forSimpleVersionedFile(file, SignatureType.TEXT)); } catch (SignatureFileException e) { log.warn(String.format(errorMessagePattern, file)); } } */ availableSigFiles.put(SignatureType.BINARY, binSigFiles); availableSigFiles.put(SignatureType.CONTAINER, containerSigFiles); //availableSigFiles.put(SignatureType.TEXT, textSigFiles); return availableSigFiles; }
4738719_1
@Override public void setAttributes(Properties properties) { // Some lunatics illegally put non String objects into System props // as keys / values - we ignore them. for ( String key : properties.stringPropertyNames() ) { setAttribute( key, properties.getProperty( key ) ); } }
4741942_80
@Override public Status process() throws EventDeliveryException { Status status = null; Iterator<Sink> sinkIterator = selector.createSinkIterator(); while (sinkIterator.hasNext()) { Sink sink = sinkIterator.next(); try { status = sink.process(); break; } catch (Exception ex) { LOGGER.warn("Sink failed to consume event. " + "Attempting next sink if available.", ex); } } if (status == null) { throw new EventDeliveryException("All configured sinks have failed"); } return status; }
4741958_389
@Override public Vector classify(Vector instance) { if (models.get(0) instanceof SoftCluster) { Collection<SoftCluster> clusters = Lists.newArrayList(); List<Double> distances = Lists.newArrayList(); for (Cluster model : models) { SoftCluster sc = (SoftCluster) model; clusters.add(sc); distances.add(sc.getMeasure().distance(instance, sc.getCenter())); } return new FuzzyKMeansClusterer().computePi(clusters, distances); } else { int i = 0; Vector pdfs = new DenseVector(models.size()); for (Cluster model : models) { pdfs.set(i++, model.pdf(new VectorWritable(instance))); } return pdfs.assign(new TimesFunction(), 1.0 / pdfs.zSum()); } }
4744588_1
public String toCommand(LuaWrapper table) { StringBuilder sb = new StringBuilder(table.getString(LuaFields.COMMAND_BASE)); if (!table.isNil(LuaFields.ARGS)) { LuaWrapper a = table.getTable(LuaFields.ARGS); Iterator<LuaPair> namedArgsIter = a.hashIterator(); while (namedArgsIter.hasNext()) { LuaPair lp = namedArgsIter.next(); sb.append(" "); sb.append(lp.key.tojstring()); sb.append("="); sb.append(lp.value.tojstring()); } Iterator<LuaPair> restIter = a.arrayIterator(); while (restIter.hasNext()) { sb.append(" "); sb.append(restIter.next().value.tojstring()); } } return sb.toString(); }
4750298_0
Pair<URL, Map<String, Serializable>> createParams(BufferedReader reader) throws Exception { String line = reader.readLine(); URL resourceId = null; Map<String, Serializable> params = new HashMap<String, Serializable>(); while (line != null) { line = line.trim(); if (line.length() > 0) { if (resourceId == null && line.toLowerCase().startsWith(RESOURCE_ID)) { String spec = line.substring(RESOURCE_ID.length()); spec = spec.replaceAll("\\\\;", ";"); resourceId = new URL(spec); } else { addParam(params, line); } } line = reader.readLine(); } return new Pair<URL, Map<String, Serializable>>(resourceId, params); }
4757131_6
public String save() { // For some reason, WebTest + Tomcat causes version to be 0. Works fine on Jetty. if (user.getId() != null && user.getId() == 0) { user.setId(null); } if (user.getId() == null) { user.setVersion(null); } try { userManager.saveUser(user); } catch (UserExistsException uex) { addError("user.exists"); return "error"; } addMessage("user.saved", user.getFullName()); return "success"; }
4759439_0
public static void processImage(String in, String out) throws IOException { File imageFile = new File(in); BufferedImage bufferedImage= ImageIO.read(imageFile); int width = bufferedImage.getWidth(null); int height = bufferedImage.getHeight(null); BufferedImage alphaImage = new BufferedImage((width+(height/2)), height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d= alphaImage.createGraphics(); g2d.drawImage(bufferedImage, (height/2), 0, null); g2d.dispose(); makeShadow(alphaImage); ImageIO.write(alphaImage, "png", new File(out)); }
4782751_9
public void setMethodName(String methodName) { this.methodName = methodName; }
4805389_0
public String getName() { return name; }
4810329_146
@Override public InferredType type() { Symbol calleeSymbol = calleeSymbol(); if (calleeSymbol != null) { InferredType type = getType(calleeSymbol); if (type.equals(InferredTypes.anyType()) && callee.is(Kind.QUALIFIED_EXPR)) { return getDeclaredType(callee); } return type; } return InferredTypes.anyType(); }
4812336_3
public void register(Object object) { if (object == null) { throw new NullPointerException("Object to register must not be null."); } enforcer.enforce(this); Map<Class<?>, EventProducer> foundProducers = handlerFinder.findAllProducers(object); for (Class<?> type : foundProducers.keySet()) { final EventProducer producer = foundProducers.get(type); EventProducer previousProducer = producersByType.putIfAbsent(type, producer); //checking if the previous producer existed if (previousProducer != null) { throw new IllegalArgumentException("Producer method for type " + type + " found on type " + producer.target.getClass() + ", but already registered by type " + previousProducer.target.getClass() + "."); } Set<EventHandler> handlers = handlersByType.get(type); if (handlers != null && !handlers.isEmpty()) { for (EventHandler handler : handlers) { dispatchProducerResultToHandler(handler, producer); } } } Map<Class<?>, Set<EventHandler>> foundHandlersMap = handlerFinder.findAllSubscribers(object); for (Class<?> type : foundHandlersMap.keySet()) { Set<EventHandler> handlers = handlersByType.get(type); if (handlers == null) { //concurrent put if absent Set<EventHandler> handlersCreation = new CopyOnWriteArraySet<EventHandler>(); handlers = handlersByType.putIfAbsent(type, handlersCreation); if (handlers == null) { handlers = handlersCreation; } } final Set<EventHandler> foundHandlers = foundHandlersMap.get(type); if (!handlers.addAll(foundHandlers)) { throw new IllegalArgumentException("Object already registered."); } } for (Map.Entry<Class<?>, Set<EventHandler>> entry : foundHandlersMap.entrySet()) { Class<?> type = entry.getKey(); EventProducer producer = producersByType.get(type); if (producer != null && producer.isValid()) { Set<EventHandler> foundHandlers = entry.getValue(); for (EventHandler foundHandler : foundHandlers) { if (!producer.isValid()) { break; } if (foundHandler.isValid()) { dispatchProducerResultToHandler(foundHandler, producer); } } } } }
4812472_36
public static double minAbsDiag(Matrix matrix) { double min = Double.MAX_VALUE; for (int i = 0; i < matrix.getColumnDimension(); i++) { double curr = Math.abs(matrix.get(i, i)); if (min > curr) { min = curr; } } return min; }
4820146_5
public boolean CheckPassword(String password, String storedHash) { String hash = cryptPrivate(password, storedHash); MessageDigest md = null; if (hash.startsWith("*")) { // If not phpass, try some algorythms from unix crypt() if (storedHash.startsWith("$6$")) { try { md = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException e) { md = null; } } if (md == null && storedHash.startsWith("$5$")) { try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { md = null; } } if (md == null && storedHash.startsWith("$2")) { return BCrypt.checkpw(password, storedHash); } if (md == null && storedHash.startsWith("$1$")) { try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { md = null; } } // STD_DES and EXT_DES not supported yet. if (md != null) { hash = new String(md.digest(password.getBytes())); } } return hash.equals(storedHash); }
4823750_0
@RequestMapping(method = RequestMethod.POST) public String handleLogin(@RequestParam String username, @RequestParam String password, HttpSession session) throws AuthenticationException { Account account = this.accountService.login(username, password); session.setAttribute(ACCOUNT_ATTRIBUTE, account); String url = (String) session.getAttribute(REQUESTED_URL); session.removeAttribute(REQUESTED_URL); // Remove the attribute if (StringUtils.hasText(url) && !url.contains("login")) { // Prevent loops for the login page. return "redirect:" + url; } else { return "redirect:/index.htm"; } }
4835576_9
@SuppressWarnings("unchecked") public <T> OrderedSet<T> selectMocks(OrderedSet<Object> mocks, Class<T> mockClass) { OrderedSet<T> matchingMocks = new OrderedSet<T>(); for (Object object : mocks) { if (mockClass.isAssignableFrom(object.getClass())) { matchingMocks.add((T) object); } } return matchingMocks; }
4889322_32
public Map<String, ClientActionClassInformation> resolve() { Map<String, ClientActionClassInformation> actionClasses = new HashMap<String, ClientActionClassInformation>(); Map<String, Object> foundActions = springIntegration.getActualContext().getBeansWithAnnotation(ClientActionClass.class); for (Map.Entry<String, Object> actionClassEntry : foundActions.entrySet()) { Object actionClass = actionClassEntry.getValue(); ClientActionClassInformation actionClassInformation = prepareActionClass(actionClass); actionClasses.put(actionClassInformation.getName(), actionClassInformation); } return actionClasses; }
4889980_4
public static ValidatorMandatory getInstance() { return INSTANCE; }
4898786_11
synchronized void tryAcceptTask(TaskHandle taskHandle) throws IllegalStateException { tryCheckLoad(); TaskExclusivity prevExclusivity = currentExclusivity; String prevExclusiveId = currentExclusiveId; boolean canAccept = tryChangeExclusivity(taskHandle); if (canAccept) { try { taskHandle.setAccepted(); acceptedTasks.add(taskHandle.getTaskId()); } catch (IllegalStateException e) { // reset exclusivity setExclusivity(prevExclusivity, prevExclusiveId); throw e; } } else { throw new IllegalStateException("Exclusivity cannot be satisfied"); } updateHostInfo(); }
4908338_0
@Override public void doBeforeRender(final HstRequest request, final HstResponse response) throws HstComponentException { HippoBean doc = getContentBean(request); if (doc == null) { log.warn("Did not find a content bean for relative content path '{}' for pathInfo '{}'", request.getRequestContext().getResolvedSiteMapItem().getRelativeContentPath(), request.getRequestContext().getResolvedSiteMapItem().getPathInfo()); response.setStatus(404); return; } request.setAttribute("document",doc); }
4910671_5
private List<Result> search(Query query, Optional<Sort> sort) { IndexSearcher searcher = null; try { searcher = new IndexSearcher(DirectoryReader.open(directory)); List<Result> result = new ArrayList<>(); TopDocs topDocs = searcher.search(query, 10, sort.or(Sort.RELEVANCE)); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { Document doc = searcher.doc(scoreDoc.doc); result.add(asResult(doc, query)); } return result; } catch (IOException ex) { throw new IllegalStateException(ex); } finally { Utils.close(searcher); } }
4925395_67
@Override public void install(final Version version) { new Thread(new Runnable() { @Override public void run() { wrapped.install(version); } }).start(); }
4937246_21
static List<String> convertFileToOutput(String filepath) throws IOException { FileReader fileReader = new FileReader(filepath); BufferedReader bufferedReader = new BufferedReader(fileReader); String firstLine = bufferedReader.readLine(); Integer numberOfProblems = Integer.valueOf(firstLine); List<String> rv = new ArrayList<String>(numberOfProblems); for (int i = 0; i < numberOfProblems; i++) { int credit = Integer.valueOf(bufferedReader.readLine()); bufferedReader.readLine(); String items = bufferedReader.readLine(); Problem problem = new Problem(credit, items); List<Integer> solution = problem.solveProblem(); StringBuilder output = new StringBuilder(); output.append("Case #"); output.append(i+1); output.append(":"); for (Integer index: solution) { output.append(" "); output.append(index); } rv.add(output.toString()); } bufferedReader.close(); return rv; }
4941867_5
public Set<Class<?>> getAnnotatedClasses() { return annotatedClasses; }
4946769_202
public static String completeUrlWithHttpIfProtocolIsNotHttpOrHttpsOrPropertyExpansion(String endpoint) { if (StringUtils.isNullOrEmpty(endpoint)) { return endpoint; } endpoint = endpoint.trim(); String lowerCaseEndpoint = endpoint.toLowerCase(); if (!lowerCaseEndpoint.startsWith("http://") && !lowerCaseEndpoint.startsWith("https://") && !endpoint.startsWith("$")) { return "http://" + endpoint; } return endpoint; }
4955633_3
public static Builder builder(String previousId) { return new Builder(previousId); }
4955657_3
@Override public Set<PrimitiveImplementor<?>> getAllImplementors() { return Collections.unmodifiableSet(finder.getAllImplementors()); }
4959580_16
@Override public String isComponentScrollBarAtBottom(MarkupContainer component) { return String.format("QuickView.isComponentScrollBarAtBottom('%s');", component.getMarkupId()); }
4992906_267
@Override public List<String> getRuleChainVisits() { initializeXPathExpression(); return super.getRuleChainVisits(); }
5002457_14
public static double splitLineStringIntoPoints(LineString geom, double segmentSizeConstraint, List<Coordinate> pts) { // If the linear sound source length is inferior than half the distance between the nearest point of the sound // source and the receiver then it can be modelled as a single point source double geomLength = geom.getLength(); if(geomLength < segmentSizeConstraint) { // Return mid point Coordinate[] points = geom.getCoordinates(); double segmentLength = 0; final double targetSegmentSize = geomLength / 2.0; for (int i = 0; i < points.length - 1; i++) { Coordinate a = points[i]; final Coordinate b = points[i + 1]; double length = a.distance3D(b); if(length + segmentLength > targetSegmentSize) { double segmentLengthFraction = (targetSegmentSize - segmentLength) / length; Coordinate midPoint = new Coordinate(a.x + segmentLengthFraction * (b.x - a.x), a.y + segmentLengthFraction * (b.y - a.y), a.z + segmentLengthFraction * (b.z - a.z)); pts.add(midPoint); break; } segmentLength += length; } return geom.getLength(); } else { double targetSegmentSize = geomLength / Math.ceil(geomLength / segmentSizeConstraint); Coordinate[] points = geom.getCoordinates(); double segmentLength = 0.; // Mid point of segmented line source Coordinate midPoint = null; for (int i = 0; i < points.length - 1; i++) { Coordinate a = points[i]; final Coordinate b = points[i + 1]; double length = a.distance3D(b); if(Double.isNaN(length)) { length = a.distance(b); } while (length + segmentLength > targetSegmentSize) { //LineSegment segment = new LineSegment(a, b); double segmentLengthFraction = (targetSegmentSize - segmentLength) / length; Coordinate splitPoint = new Coordinate(); splitPoint.x = a.x + segmentLengthFraction * (b.x - a.x); splitPoint.y = a.y + segmentLengthFraction * (b.y - a.y); splitPoint.z = a.z + segmentLengthFraction * (b.z - a.z); if(midPoint == null && length + segmentLength > targetSegmentSize / 2) { segmentLengthFraction = (targetSegmentSize / 2.0 - segmentLength) / length; midPoint = new Coordinate(a.x + segmentLengthFraction * (b.x - a.x), a.y + segmentLengthFraction * (b.y - a.y), a.z + segmentLengthFraction * (b.z - a.z)); } pts.add(midPoint); a = splitPoint; length = a.distance3D(b); if(Double.isNaN(length)) { length = a.distance(b); } segmentLength = 0; midPoint = null; } if(midPoint == null && length + segmentLength > targetSegmentSize / 2) { double segmentLengthFraction = (targetSegmentSize / 2.0 - segmentLength) / length; midPoint = new Coordinate(a.x + segmentLengthFraction * (b.x - a.x), a.y + segmentLengthFraction * (b.y - a.y), a.z + segmentLengthFraction * (b.z - a.z)); } segmentLength += length; } if(midPoint != null) { pts.add(midPoint); } return targetSegmentSize; } }
5003951_0
public void write(Writer writer, Map<String, Object> stringObjectMap, Model model) throws IOException { try { final Var REQUIRE = Var.intern(RT.CLOJURE_NS, Symbol.create("require")); final Symbol REFLECTOR = Symbol.create("org.sonatype.maven.polyglot.clojure.dsl.writer"); REQUIRE.invoke(REFLECTOR); final Var WRITER = Var.intern(Namespace.findOrCreate(REFLECTOR), Symbol.create("write-model")); WRITER.invoke(model, writer); } catch (Exception e) { e.printStackTrace(); // Don't use new IOException(e) because it doesn't exist in Java 5 throw (IOException) new IOException(e.toString()).initCause(e); } }
5017081_2
@Deprecated public Slugify(boolean lowerCase) { this(); withLowerCase(lowerCase); }
5022064_10
public static float example03() { String a = "A quirky thing it is. This is a sentence."; String b = "This sentence is similar; a quirky thing it is."; StringDistance metric = with(new EuclideanDistance<String>()) .tokenize(Tokenizers.whitespace()) .build(); return metric.distance(a, b); // 2.0000 }
5054231_2
static public List<BodyPart> extractMessageAttachments(Log logger, Object content) throws MessagingException, IOException { ArrayList<BodyPart> ret = new ArrayList<BodyPart>(); if (content instanceof Multipart) { Multipart part = (Multipart) content; for (int i = 0; i < part.getCount(); i++) { BodyPart bodyPart = part.getBodyPart(i); String fileName = bodyPart.getFileName(); String[] contentId = bodyPart.getHeader("Content-ID"); if (bodyPart.isMimeType("multipart/*")) { ret.addAll(extractMessageAttachments(logger, bodyPart.getContent())); } else { if (contentId != null || fileName != null) { ret.add(bodyPart); } } } } else { logger.error("Unknown content: " + content.getClass().getName()); } return ret; }
5054234_1
protected CharSequence getValue(String key) { CharSequence val = tagValues.get(key); if (val == null) return getDefault(key); else return val; }
5054237_27
public Integer getNumericValueForTag(String tag, String exceptionMessage) throws SyntaxException { Argument argument = retrieveArgumentIfExists(tag, exceptionMessage); if (argument == null) { return null; } return retrieveNumericValue(argument, exceptionMessage); }
5061371_1
@Override public int getTotalIPLength() { // byte 3 - 4 return this.headers.getUnsignedShort(2); }
5073742_77
@Override public String toString() { return new ToStringBuilder(this) .appendSuper(super.toString()) .append("history", history) .toString(); }
5074598_40
public void run(List<File> files) throws Exception { for (File file : files) { logger.info("processing: " + file.getPath()); try { PomWrapper wrapped = new PomWrapper(file); boolean changed = possiblyUpdateProjectVersion(wrapped) | possiblyUpdateParentVersion(wrapped) | possiblyUpdateDependencies(wrapped); if (changed) { FileOutputStream out = new FileOutputStream(file); try { OutputUtil.compactStream(wrapped.getDom(), out); } finally { IOUtil.closeQuietly(out); } } } catch (Exception ex) { logger.warn("unable to parse file: " + file); } } }
5077412_43
public static Color fromBGR(int blue, int green, int red) throws IllegalArgumentException { return new Color(red, green, blue); }
5084932_20
@Override public List<Job> getJobsAwaitingLibraryCreation(){ List<Job> JobsAwaitingLibraryCreation = new ArrayList<Job>(); for (Job job : getActiveJobs()){ for (Sample sample: job.getSample()){ if (sampleService.isSampleAwaitingLibraryCreation(sample)){ JobsAwaitingLibraryCreation.add(job); break; } } } return JobsAwaitingLibraryCreation; }
5093728_1
public T run() { T result = null; if(context.hasFeature(featureName)) { result = onFeatureEnabled(); } else { result = onFeatureDisabled(); } return result; }
5094929_0
static void sum(InputStream in, PrintStream out) { try ( Scanner scanner = new Scanner(in);) { int a = scanner.nextInt(); int b = scanner.nextInt(); int s = a + b; out.print(s); } }
5104280_226
@Override public boolean satisfiesFilter(String filterCriterion) { return name.toLowerCase(Locale.getDefault()).startsWith(filterCriterion.toLowerCase()) || String.valueOf(ec_number).startsWith(filterCriterion) || String.valueOf(thayi).startsWith(filterCriterion); }
5109749_18
public static String getEnumLocalizationKey(Enum<?> e) { //Enumy zurnalovanych objektu pouzivaji klice, aby se nemusely prekladat dvakrat if (Localizable.class.isAssignableFrom(e.getClass())) return ((Localizable) e).getKey(); return new StringBuilder(e.getDeclaringClass().getName()).append(".").append(e.name()).toString(); }
5122021_99
@Override public JSONObject get() throws JSONException { JSONObject mergedJsonObject = new JSONObject(); for (JSONProvider jsonProvider : jsonProviderList) { JSONObject jsonObject = jsonProvider.get(); mergeInto(mergedJsonObject, jsonObject); } return mergedJsonObject; }
5123943_1
public static double zeta(double x, double q) { // * Check arguments if(x == 1.0) return Double.POSITIVE_INFINITY; if(q < 1.0) return Double.NaN; if(q <= 0.0) if(q == floor(q)) return Double.POSITIVE_INFINITY; else return Double.NaN; double s = pow(q, -x); double a = q; double b = 0.0; int i = 0; boolean done = false; while( (i < 9 || a <= 9.0) && ! done) { i++; a++; b = pow(a, -x); s += b; if(abs(b/s) < EPSILON) done = true; } double k = 0.0; double w = a; s += b * w / (x - 1.0); s -= 0.5 * b; a = 1.0; double t; for(i = 0; i < 12 && ! done; i ++) { a *= x + k; b /= w; t = a * b / m[i]; s += t; t = abs(t/s); if(t < EPSILON) done = true; k += 1.0; a *= x + k; b /= w; k += 1.0; } return s; }
5129094_1
public void addHandler(Pattern uriPattern, RequestHandler requestHandler) { LOGGER.debug("Registering pattern {}", uriPattern.pattern()); synchronized (requestHandles) { requestHandles.add(new RequestHandle(uriPattern, requestHandler)); } }
5151102_34
public BigDecimal getTimeToRepetitionInMinutes() { return new BigDecimal(timeToRepetition.orElse(0).doubleValue() / 1000 / 60); }
5158290_56
public static GEIndividual getIndividual(final GEGrammar grammar, final Phenotype phen, final Genotype genotype, final Fitness fitness) { final GEIndividual gei; grammar instanceof GEGrammar) { gei = new GEIndividual(grammar, phen, genotype, fitness); } else { throw new IllegalArgumentException(grammar+" is not GEGrammar"); return gei; }
5171172_70
public List<Put> insert(long tableId, final Row row) { return insert(tableId, row, store.getSchema(tableId).getIndices()); }
5173512_5
public void ensureVersionCompatible(final String rawVersion) throws Exception { String version = parseVersion(rawVersion); VersionScheme scheme = new GenericVersionScheme(); VersionConstraint constraint = scheme.parseVersionConstraint(VERSION_CONSTRAINT); Version _version = scheme.parseVersion(version); log.debug("Version: " + _version); if (!constraint.containsVersion(_version)) { log.error("Incompatible install4j version detected"); log.error("Raw version: " + rawVersion); log.error("Detected version: " + _version); log.error("Compatible version constraint: " + constraint); throw new MojoExecutionException("Unsupported install4j version: " + rawVersion); } }
5175291_2
@GET @Path("/coordinator") @Produces(MediaType.APPLICATION_JSON) public Response getAllCoordinators(@Context UriInfo uriInfo) { Predicate<CoordinatorStatus> coordinatorPredicate = CoordinatorFilterBuilder.build(uriInfo); List<CoordinatorStatus> coordinators = coordinator.getCoordinators(coordinatorPredicate); return Response.ok(transform(coordinators, fromCoordinatorStatus(coordinator.getCoordinators()))).build(); }
5176218_4
@OnClick({R.id.original_user_icon, R.id.original_user_name}) void showUser() { unitClicks.onNext(post.getOriginalUnit()); }
5176685_4
public AqlQueryBuilder or(AqlItem... items) { if (isNotEmpty(items)) { root.putAll(AqlItem.or((Object[]) items).value()); } return this; }
5185108_32
@JsonProperty public Set<Service> getServices() { return services; }
5194874_8
public String evaluateTemplate(String templateName, Map<String, Object> bindings) { // what is this user thinking? if (templateName == null) { log.info("Template name is null"); return ""; } HL7Template template = getHl7queryService().getHL7TemplateByName(templateName); // didn't find the template, fail early. if (template == null) { log.info("Could not find a template by the name of " + templateName); return ""; } return getHl7queryService().evaluateTemplate(template, bindings); }
5203853_12
public Instance newInstance(String sourceAET, Attributes data, Attributes modified, StoreContext storeContext) throws DicomServiceException { StoreParam storeParam = storeContext.getStoreParam(); Availability rnAvailability = storeParam.getRejectionNoteAvailability(data); if (rnAvailability != null) { processRejectionNote(data, rnAvailability); } Series series = findOrCreateSeries(sourceAET, data, storeContext); Availability availability = rnAvailability != null ? Availability.availabilityOfRejectedObject(rnAvailability) : storeContext.isRejectedByMPPS() ? Availability.INCORRECT_MODALITY_WORKLIST_ENTRY : storeContext.getAvailability(); coerceAttributes(series, data, modified); if (!modified.isEmpty() && storeParam.isStoreOriginalAttributes()) { Attributes item = new Attributes(4); Sequence origAttrsSeq = data.ensureSequence(Tag.OriginalAttributesSequence, 1); origAttrsSeq.add(item); item.setDate(Tag.AttributeModificationDateTime, VR.DT, new Date()); item.setString(Tag.ModifyingSystem, VR.LO, storeParam.getModifyingSystem()); item.setString(Tag.SourceOfPreviousValues, VR.LO, sourceAET); item.newSequence(Tag.ModifiedAttributesSequence, 1).add(modified); } Instance inst = new Instance(); inst.setSeries(series); inst.setConceptNameCode(singleCode(data, Tag.ConceptNameCodeSequence)); inst.setVerifyingObservers(createVerifyingObservers( data.getSequence(Tag.VerifyingObserverSequence), storeParam.getFuzzyStr())); inst.setContentItems( createContentItems(data.getSequence(Tag.ContentSequence))); inst.setRetrieveAETs(storeParam.getRetrieveAETs()); inst.setExternalRetrieveAET(storeParam.getExternalRetrieveAET()); inst.setAvailability(availability); inst.setAttributes(data, storeParam.getAttributeFilter(Entity.Instance), storeParam.getFuzzyStr()); em.persist(inst); em.flush(); em.detach(inst); return inst; }
5208272_30
public GitAddResponse add(File repositoryPath, GitAddOptions options, List<File> paths) throws IOException, JavaGitException { CheckUtilities.checkFileValidity(repositoryPath.getAbsoluteFile()); IClient client = ClientManager.getInstance().getPreferredClient(); IGitAdd gitAdd = client.getGitAddInstance(); return gitAdd.add(repositoryPath, options, paths); }
5208822_0
@Override public void execute() throws MojoExecutionException { getLog().info("Undeploying"); final CloudHubAdapter domainConnection = createDomainConnection(); domainConnection.undeploy(this.maxWaitTime); }
5210246_2
public int compareTo(Expression e) { if (this == e) return 0; if (e instanceof Parameter) { Parameter o = (Parameter) e; return order - o.order; } else { return getClass().getName().compareTo(e.getClass().getName()); } }
5212656_133
public Field replaceWithSimpleField(Field.FieldType fieldType) { int leftLength = textSelection.getText().length(); int index = textSelection.getIndex(); prepareSpanContainer(leftLength, index); Field field = null; switch (fieldType) { case DATE_FIELD: field = Fields.createDateField(spanContainer); break; case FIXED_DATE_FIELD: field = Fields.createFixedDateField(spanContainer); break; case TIME_FIELD: field = Fields.createTimeField(spanContainer); break; case FIXED_TIME_FIELD: field = Fields.createFixedTimeField(spanContainer); break; case PREVIOUS_PAGE_NUMBER_FIELD: field = Fields.createPreviousPageNumberField(spanContainer); break; case CURRENT_PAGE_NUMBER_FIELD: field = Fields.createCurrentPageNumberField(spanContainer); break; case NEXT_PAGE_NUMBER_FIELD: field = Fields.createNextPageNumberField(spanContainer); break; case PAGE_COUNT_FIELD: field = Fields.createPageCountField(spanContainer); break; case TITLE_FIELD: field = Fields.createTitleField(spanContainer); break; case SUBJECT_FIELD: field = Fields.createSubjectField(spanContainer); break; case AUTHOR_NAME_FIELD: field = Fields.createAuthorNameField(spanContainer); break; case AUTHOR_INITIALS_FIELD: field = Fields.createAuthorInitialsField(spanContainer); break; case CHAPTER_FIELD: field = Fields.createChapterField(spanContainer); break; case REFERENCE_FIELD: case SIMPLE_VARIABLE_FIELD: case USER_VARIABLE_FIELD: case CONDITION_FIELD: case HIDDEN_TEXT_FIELD: throw new IllegalArgumentException("this is not a vaild simple field type."); } textSelection.mMatchedText = field.getOdfElement().getTextContent(); int textLength = textSelection.mMatchedText.length(); int offset = textLength - leftLength; SelectionManager.refresh(textSelection.getContainerElement(), offset, index + textLength); return field; }
5223349_1
public static String formatRequest(String url, Position position) { return formatRequest(url, position, null); }
5225735_6
public static EntityNameExtractor<?> forNamedPersistentEntity(String name) { return new NamedPersistentEntityNameExtractor(name); }
5243160_0
Fvdl parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { SMInputFactory inputFactory = FortifyUtils.newStaxParser(); try { SMHierarchicCursor rootC = inputFactory.rootElementCursor(inputStream); rootC.advance(); // <FVDL> SMInputCursor childCursor = rootC.childCursor(); Build build = null; Collection<Description> descriptions = new ArrayList<Description>(); Collection<Vulnerability> vulnerabilities = null; while (childCursor.getNext() != null) { String nodeName = childCursor.getLocalName(); if ("Build".equals(nodeName)) { build = processBuild(childCursor); } else if ("Description".equals(nodeName)) { descriptions.add(processDescription(childCursor)); } else if ("Vulnerabilities".equals(nodeName)) { vulnerabilities = processVulnerabilities(childCursor); } } return new Fvdl(build, descriptions, vulnerabilities); } catch (XMLStreamException e) { throw new IllegalStateException("XML is not valid", e); } }
5243237_3
public VersionRange range(final int... parts) { checkNotNull(parts); checkArgument(parts.length != 0); StringBuilder buff = new StringBuilder() .append("["); for (int i = 0; i < parts.length; i++) { buff.append(parts[i]); if (i + 1 < parts.length) { buff.append("."); } } buff.append(","); for (int i = 0; i < parts.length; i++) { if (i + 1 == parts.length) { buff.append(parts[i] + 1); } else { buff.append(parts[i]) .append("."); } } buff.append(")"); log.trace("Range pattern: {}", buff); return parseRange(buff.toString()); }
5244017_8
@Override public boolean matches(Map<String, Object> nodeCapability, Map<String, Object> requestedCapability) { if (nodeCapability == null || requestedCapability == null) { return false; } for (String key : requestedCapability.keySet()) { if (toConsider.contains(key)) { if (requestedCapability.get(key) != null) { String value = requestedCapability.get(key).toString(); if (!requestedCapability.get(key).equals(nodeCapability.get(key))) { return false; } else { // null value matches anything. } } } } return true; }
5244445_9
@NonNull public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) { Comparator<FeedItem> comparator = null; Permutor<FeedItem> permutor = null; switch (sortOrder) { case EPISODE_TITLE_A_Z: comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTitle(f2)); break; case EPISODE_TITLE_Z_A: comparator = (f1, f2) -> itemTitle(f2).compareTo(itemTitle(f1)); break; case DATE_OLD_NEW: comparator = (f1, f2) -> pubDate(f1).compareTo(pubDate(f2)); break; case DATE_NEW_OLD: comparator = (f1, f2) -> pubDate(f2).compareTo(pubDate(f1)); break; case DURATION_SHORT_LONG: comparator = (f1, f2) -> Integer.compare(duration(f1), duration(f2)); break; case DURATION_LONG_SHORT: comparator = (f1, f2) -> Integer.compare(duration(f2), duration(f1)); break; case FEED_TITLE_A_Z: comparator = (f1, f2) -> feedTitle(f1).compareTo(feedTitle(f2)); break; case FEED_TITLE_Z_A: comparator = (f1, f2) -> feedTitle(f2).compareTo(feedTitle(f1)); break; case RANDOM: permutor = Collections::shuffle; break; case SMART_SHUFFLE_OLD_NEW: permutor = (queue) -> smartShuffle(queue, true); break; case SMART_SHUFFLE_NEW_OLD: permutor = (queue) -> smartShuffle(queue, false); break; } if (comparator != null) { final Comparator<FeedItem> comparator2 = comparator; permutor = (queue) -> Collections.sort(queue, comparator2); } return permutor; }
5258499_1
public HttpUrl createHttpsGatewayUrl(String gatewayUrl) throws MalformedURLException, URIException { HttpMethod method = new GetMethod(gatewayUrl); method.setQueryString("ssl=true"); String url = method.getURI().getEscapedURI(); return new HttpUrl(url); }
5264820_1
public Matrix() { }
5265034_1
public static MTEF parse(InputStream is) throws ParseException, IOException { PushbackInputStream pis = new PushbackInputStream(is); // hack - throw away 28 byte OLE header pis.read(new byte[28]); return new MTEFParser().parse(pis); }
5265087_58
@Override public List<OperationId> execute(MasterContext context, List<MasterOperation> runningOperations) throws Exception { InteractionProtocol protocol = context.getProtocol(); IndexMetaData indexMD = protocol.getIndexMD(_indexName); if (indexMD == null) {// could be undeployed in meantime LOG.info("skip balancing for index '" + _indexName + "' cause it is already undeployed"); return null; } if (!canAndShouldRegulateReplication(protocol, indexMD)) { LOG.info("skip balancing for index '" + _indexName + "' cause there is no possible optimization"); return null; } try { FileSystem fileSystem = context.getFileSystem(indexMD); Path path = new Path(indexMD.getPath()); if (!fileSystem.exists(path)) { LOG.warn("skip balancing for index '" + _indexName + "' cause source '" + path + "' does not exists anymore"); return null; } } catch (Exception e) { LOG.error("skip balancing of index '" + _indexName + "' cause failed to access source '" + indexMD.getPath() + "'", e); return null; } LOG.info("balancing shards for index '" + _indexName + "'"); try { List<OperationId> operationIds = distributeIndexShards(context, indexMD, protocol.getLiveNodes(), runningOperations); return operationIds; } catch (Exception e) { ExceptionUtil.rethrowInterruptedException(e); LOG.error("failed to deploy balance " + _indexName, e); handleMasterDeployException(protocol, indexMD, e); return null; } }
5279091_17
String shortName(String key) { Matcher matcher = KEY_PATTERN.matcher(key); if (!matcher.matches()) throw new IllegalArgumentException("Unexpected key: " + key); StringBuilder result = new StringBuilder(); String annotationSimpleName = matcher.group(1); if (annotationSimpleName != null) { result.append('@').append(annotationSimpleName).append(' '); } String simpleName = matcher.group(2); result.append(simpleName); String typeParameters = matcher.group(3); if (typeParameters != null) { result.append(typeParameters); } String arrays = matcher.group(4); if (arrays != null) { result.append(arrays); } return result.toString(); }
5284141_13
public static String packageNameToDirName(final String packageName) { return "/" + packageName.replace('.', '/'); }
5291703_32
public <ValueType> MutableProperty<ValueType> getProperty( PropertyDef<?, ValueType> propertyDef) { return new DomTrackingProperty<>(propertyDef); }
5294661_0
public static JSONDocTemplate build(Class<?> clazz, Set<Class<?>> jsondocObjects) { final JSONDocTemplate jsonDocTemplate = new JSONDocTemplate(); if(jsondocObjects.contains(clazz)) { try { Set<JSONDocFieldWrapper> fields = getAllDeclaredFields(clazz); for (JSONDocFieldWrapper jsondocFieldWrapper : fields) { Field field = jsondocFieldWrapper.getField(); if (isFinal(field.getModifiers()) && isStatic(field.getModifiers())) { continue; } String fieldName = field.getName(); ApiObjectField apiObjectField = field.getAnnotation(ApiObjectField.class); if (apiObjectField != null && !apiObjectField.name().isEmpty()) { fieldName = apiObjectField.name(); } Object value; // This condition is to avoid StackOverflow in case class "A" // contains a field of type "A" if (field.getType().equals(clazz) || (apiObjectField != null && !apiObjectField.processtemplate())) { value = getValue(Object.class, field.getGenericType(), fieldName, jsondocObjects); } else { value = getValue(field.getType(), field.getGenericType(), fieldName, jsondocObjects); } jsonDocTemplate.put(fieldName, value); } } catch (Exception e) { log.error("Error in JSONDocTemplate creation for class [" + clazz.getCanonicalName() + "]", e); } } return jsonDocTemplate; }
5312808_68
public static nfsace4[] compact(nfsace4[] acl) { int size = acl.length; if (size == 0) { return acl; } for(int i = 0; i < size; i++) { nfsace4 a = acl[i]; utf8str_mixed pricipal = a.who; int processedMask = a.access_mask.value.value; for(int j = i+1; j < size; j++) { nfsace4 b = acl[j]; if (a.flag.value.value != b.flag.value.value || !pricipal.equals(b.who)) { continue; } // remove processed bits b.access_mask.value.value &= ~processedMask; int maskToProcess = b.access_mask.value.value; if(maskToProcess != 0) { if (a.type.value.value == b.type.value.value) { a.access_mask.value.value |= maskToProcess; b.access_mask.value.value &= ~maskToProcess; } else { //b.access_mask.value.value &= ~maskToProcess; } } processedMask |= maskToProcess; } } for (nfsace4 ace : acl) { if (ace.access_mask.value.value == 0) { size--; } } nfsace4[] compact = new nfsace4[size]; int i = 0; for (nfsace4 ace : acl) { if (ace.access_mask.value.value != 0) { compact[i] = ace; i++; } } return compact; }
5320077_16
public static String camelToUpper(String name) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isUpperCase(c)) { buf.append('_'); } else { c = Character.toUpperCase(c); } buf.append(c); } return buf.toString(); }
5346043_623
public static int distance (String str1, String str2){ return distance(Transformations.convertStringToIntArray(str1),Transformations.convertStringToIntArray(str2)); }
5346068_0
public EtagCache resetStats() { hits.set(0); misses.set(0); return this; }
5349536_0
public OHLC[] getHistoricalData(Contract contract, Date endDate, int numPeriods, int periodUnit) throws IOException { if (!(periodUnit == HistoricalDataSource.PERIOD_1_DAY || periodUnit == HistoricalDataSource.PERIOD_1_WEEK || periodUnit == HistoricalDataSource.PERIOD_1_MONTH)) throw new IllegalArgumentException("Must specify a period of day, week, or month."); GregorianCalendar start = new GregorianCalendar(); start.setTime(endDate); if (periodUnit == HistoricalDataSource.PERIOD_1_DAY) start.add(Calendar.DATE, -numPeriods); else if (periodUnit == HistoricalDataSource.PERIOD_1_WEEK) start.add(Calendar.WEEK_OF_YEAR, -numPeriods); else if (periodUnit == HistoricalDataSource.PERIOD_1_MONTH) start.add(Calendar.WEEK_OF_YEAR, -numPeriods); GregorianCalendar end = new GregorianCalendar(); end.setTime(endDate); StringBuilder reqUrl = new StringBuilder(historicalDataUrl); reqUrl.append("?s=").append(contract.getSymbol()); reqUrl.append("&a=").append(start.get(Calendar.MONTH)); reqUrl.append("&b=").append(start.get(Calendar.DAY_OF_MONTH)); reqUrl.append("&c=").append(start.get(Calendar.YEAR)); reqUrl.append("&d=").append(end.get(Calendar.MONTH)); reqUrl.append("&e=").append(end.get(Calendar.DAY_OF_MONTH)); reqUrl.append("&f=").append(end.get(Calendar.YEAR)); reqUrl.append("&g="); if (periodUnit == HistoricalDataSource.PERIOD_1_DAY) reqUrl.append("d"); else if (periodUnit == HistoricalDataSource.PERIOD_1_WEEK) reqUrl.append("w"); else reqUrl.append("m"); reqUrl.append("&ignore=.csv"); ArrayList<OHLC> prices = new ArrayList<OHLC>(); BufferedReader content = new BufferedReader(new InputStreamReader(new URL(reqUrl.toString()).openStream())); String line; for (line = content.readLine(); line != null; line = content.readLine()) { String fields[] = line.split(","); if (fields.length >= 7) { try { SimpleOHLC ohlc = new SimpleOHLC(); ohlc.setDate(df.parse(fields[0])); ohlc.setOpen(Double.parseDouble(fields[1])); ohlc.setHigh(Double.parseDouble(fields[2])); ohlc.setLow(Double.parseDouble(fields[3])); ohlc.setClose(Double.parseDouble(fields[4])); ohlc.setVolume(Long.parseLong(fields[5])); prices.add(ohlc); } catch (ParseException e) { } } } while (line != null); content.close(); return prices.toArray(new OHLC[0]); }
5380818_17
@VisibleForTesting @Nullable String getFilenameFromPath(@Nullable String filePath) { String filename; if (!isEmpty(filePath) && filePath.contains(File.separator) && filePath.contains(".")) { filename = filePath.substring(filePath.lastIndexOf(File.separator) + 1); } else { filename = filePath; } return filename; }
5402142_0
@Override public <T extends Component> T createComponent(Class<T> componentClass) { Unmanaged<T> unmanagedClass = new Unmanaged<T>(componentClass); Unmanaged.UnmanagedInstance<T> instance = unmanagedClass.newInstance(); instance.produce().inject().postConstruct(); return instance.get(); }
5402462_72
@Override public JobReport call() { start(); try { openReader(); openWriter(); setStatus(JobStatus.STARTED); while (moreRecords() && !isInterrupted()) { Batch<O> batch = readAndProcessBatch(); writeBatch(batch); } setStatus(JobStatus.STOPPING); } catch (Exception exception) { fail(exception); return report; } finally { closeReader(); closeWriter(); } teardown(); return report; }
5405905_273
@PostConstruct public void init() { view.init(this); view.initWidgets(queryTarget.view, serverTemplateId.view, dataSource.view, dbSQL.view); queryTarget.setSelectHint(DashboardConstants.INSTANCE.remote_query_target_hint()); List<DropDownEditor.Entry> entries = Stream.of("CUSTOM", "PROCESS", "TASK", "BA_TASK", "PO_TASK", "JOBS", "FILTERED_PROCESS", "FILTERED_BA_TASK", "FILTERED_PO_TASK") .map(s -> queryTarget.newEntry(s, s)).collect(Collectors.toList()); queryTarget.setEntries(entries); queryTarget.addHelpContent(DashboardConstants.INSTANCE.query_target(), DashboardConstants.INSTANCE.query_target_description(), Placement.RIGHT); //bottom placement would interfere with the dropdown serverTemplateId.setSelectHint(DashboardConstants.INSTANCE.remote_server_template_hint()); specManagementService.call((ServerTemplateList serverTemplates) -> { onServerTemplateLoad(serverTemplates); }).listServerTemplates(); serverTemplateId.addHelpContent(DashboardConstants.INSTANCE.server_template(), DashboardConstants.INSTANCE.server_template_description(), Placement.RIGHT); //bottom placement would interfere with the dropdown dataSource.addHelpContent(DashboardConstants.INSTANCE.sql_datasource(), DashboardConstants.INSTANCE.sql_datasource_description(), Placement.BOTTOM); dbSQL.addHelpContent(DashboardConstants.INSTANCE.sql_source(), DashboardConstants.INSTANCE.sql_source_description(), Placement.BOTTOM); }
5405932_0
public static InputStream lookupFile(final String filename) throws IOException { Preconditions.checkNotNull(filename, "filename"); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream stream = classLoader.getResourceAsStream(filename); if (stream == null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format( "Unable to find file {0} in classpath. Searching for this file on the filesystem instead.", filename)); } stream = new FileInputStream(filename); } return stream; }
5418564_0
@Override public E set(int index, E element) { if (wrapped != null) { return wrapped.set(index, element); } throw new UnsupportedOperationException(); }
5426219_354
public int index( Experiment experiment, Map<String, Map<BioentityPropertyName, Set<String>>> bioentityIdToProperties, int batchSize) { List<SolrInputDocument> toLoad = new ArrayList<>(batchSize); int addedIntoThisBatch = 0; int addedInTotal = 0; try (SolrInputDocumentInputStream solrInputDocumentInputStream = new SolrInputDocumentInputStream( experimentDataPointStreamFactory.stream(experiment), bioentityIdToProperties)) { Iterator<SolrInputDocument> it = new IterableObjectInputStream<>(solrInputDocumentInputStream).iterator(); while (it.hasNext()) { while (addedIntoThisBatch < batchSize && it.hasNext()) { SolrInputDocument analyticsInputDocument = it.next(); toLoad.add(analyticsInputDocument); addedIntoThisBatch++; } if (addedIntoThisBatch > 0) { UpdateResponse r = solrClient.add(toLoad); LOGGER.info( "Sent {} documents for {}, qTime:{}", addedIntoThisBatch, experiment.getAccession(), r.getQTime()); addedInTotal += addedIntoThisBatch; addedIntoThisBatch = 0; toLoad.clear(); } } } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } LOGGER.info("Finished: " + experiment.getAccession()); return addedInTotal; }