id
stringlengths
7
14
text
stringlengths
1
37.2k
960343_8
public boolean evaluate(Properties properties) { boolean result = true; for (int j = 0; j < getTiers().size(); j++) { for (ITripletValue tiplet : getTier(j)) { ITripletPermutation permutation = getTier(j); boolean aValue = parseBoolean(String.valueOf(properties.get("_" + permutation.getAName()))); boolean bValue = parseBoolean(String.valueOf(properties.get("_" + permutation.getBName()))); boolean cValue = parseBoolean(String.valueOf(properties.get("_" + permutation.getCName()))); if (tiplet.isNotA()) aValue = !aValue; if (tiplet.isNotB()) bValue = !bValue; if (tiplet.isNotC()) cValue = !cValue; result = result && (aValue || bValue || cValue); if (!result) { return result; } } } return result; }
960760_9
@Override public void bringToFront(final DrawingObject dob) { if (threadSafe) { synchronized (lock) { insertionOrder.put(dob, ++insertionOrderLargest); } } else { insertionOrder.put(dob, ++insertionOrderLargest); } }
990281_80
@Override public <T> BeanHolder<T> resolve(Class<T> typeReference) { Contracts.assertNotNull( typeReference, "typeReference" ); try { return beanProvider.forType( typeReference ); } catch (SearchException e) { try { return resolveSingleConfiguredBean( typeReference ); } catch (RuntimeException e2) { throw log.cannotResolveBeanReference( typeReference, e.getMessage(), e2.getMessage(), e, e2 ); } } }
991965_51
public static <T> Iterable<T> mix( final Iterable<T>... iterables ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { final Iterable<Iterator<T>> iterators = toList(map( new Function<Iterable<T>, Iterator<T>>() { @Override public Iterator<T> map( Iterable<T> iterable ) { return iterable.iterator(); } }, Iterables.iterable( iterables) )); return new Iterator<T>() { Iterator<Iterator<T>> iterator; Iterator<T> iter; @Override public boolean hasNext() { for( Iterator<T> iterator : iterators ) { if (iterator.hasNext()) { return true; } } return false; } @Override public T next() { if (iterator == null) { iterator = iterators.iterator(); } while (iterator.hasNext()) { iter = iterator.next(); if (iter.hasNext()) return iter.next(); } iterator = null; return next(); } @Override public void remove() { if (iter != null) iter.remove(); } }; } }; }
992007_8
public static <S, T extends S> Type[] findTypeVariables( Class<T> type, Class<S> searchType ) { return ParameterizedTypes.findParameterizedType( type, searchType ).getActualTypeArguments(); }
992012_3
public Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName ) { String convertedIdentifier = convertIdentifier( qualifiedName ); if( rawData.containsKey( convertedIdentifier ) ) { return rawData.remove( convertedIdentifier ); } return null; }
992971_0
public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); }
993994_1
public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); //ignored } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); //ignored } catch (SAXException e) { log.error("Error while processing url: " + url, e); //ignored } return LoadedXml.EMPTY_XML; }
994088_0
@Override public void setCacheDir(File dir) { // comment below as inmemory configuration does not require dir to be exists // this is relevant when deploy app on readonly file system like heroku and gae if (!dir.isDirectory() && !dir.mkdir()) throw new IllegalArgumentException("not a dir"); checkInitialize_(false); cache_ = new FileCache(dir); }
1001284_61
public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } }
1006123_0
public Wavelet fetchWavelet(WaveId waveId, WaveletId waveletId) throws ClientWaveException { return fetchWavelet(waveId, waveletId, null); }
1007836_19
public List<List<String>> process() { List<List<String>> processed = new ArrayList<List<String>>(); Map<Integer,List<String>> buckets ; List<List<String>> returnArray ; buckets = separateInputBySize(_input); if(buckets == null) return processed; for(int size: buckets.keySet()) { List<String> elements = buckets.get(size); System.out.println("size " + size); while(elements != null && elements.size() > 0) { returnArray = processSameSizeArray(elements); elements = returnArray.get(1) ; processed.add(returnArray.get(0)); } } return processed; }
1014623_5
static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; }
1017889_4
public Path append(Path relative) { if (relative == null) { throw new IllegalArgumentException("Argument 'relative' cannot be null"); } if (relative.isAbsolute()) { throw new IllegalArgumentException("Cannot append an absolute path"); } StringBuilder appended = new StringBuilder(path.length() + 1 + relative.path.length()); appended.append(path); if (!path.endsWith(SEPARATOR)) { appended.append("/"); } appended.append(relative.path); return new Path(appended.toString()); }
1020601_4
public Number convert(MappingContext<Object, Number> context) { Object source = context.getSource(); if (source == null) return null; Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType()); if (source instanceof Number) return numberFor((Number) source, destinationType); if (source instanceof Boolean) return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType); if (source instanceof Date && Long.class.equals(destinationType)) return Long.valueOf(((Date) source).getTime()); if (source instanceof Calendar && Long.class.equals(destinationType)) return Long.valueOf(((Calendar) source).getTime().getTime()); if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType)) return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis(); return numberFor(source.toString(), destinationType); }
1024699_26
public List<Item> getAlbumAndSubAlbums(int albumId) throws G3GalleryException { List<Item> items = new ArrayList<Item>(); Item item = getItems(albumId, items, "album"); // we add to the list the parent album items.add(0, item); return items; }
1025574_2
String toXMlFormatted() throws JAXBException, UnsupportedEncodingException { //Create marshaller Marshaller m = jc.createMarshaller(); m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); m.marshal(this, bos); return bos.toString("UTF-8"); }
1028034_7
public double[] getBasicFunctions(int i, double u) { double[] n = new double[degree + 1]; n[0] = 1.0; double[] left = new double[degree + 1]; double[] right = new double[degree + 1]; for (int j = 1; j <= degree; j++) { left[j] = u - this.knots[(i + 1) - j]; right[j] = this.knots[i + j] - u; double saved = 0.0; for (int r = 0; r < j; r++) { double t = n[r] / (right[r + 1] + left[j - r]); n[r] = saved + (right[r + 1] * t); saved = left[j - r] * t; } n[j] = saved; } return n; }
1031515_0
public Lookup createLookup(List<String> keys) { return new LookupImpl(keys); }
1050944_201
@Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } }
1052717_4
static <X> Set<Field> camelInjectAnnotatedFieldsIn(final Class<X> type) { final Set<Field> camelInjectAnnotatedFields = new HashSet<Field>(); for (final Field fieldToInspect : allFieldsAndSuperclassFieldsIn(type)) { if (isAnnotatedWithOneOf(fieldToInspect, CAMEL)) { camelInjectAnnotatedFields.add(fieldToInspect); } } return Collections.unmodifiableSet(camelInjectAnnotatedFields); }
1057490_435
public static void unregister(String key) { SpaceUtil.wipe(sp, key); }
1068402_84
public boolean versionSupported(final String requiredVersion, final String publishedVersion) { if (requiredVersion == null) { throw new IllegalArgumentException("requiredVersion is null"); } if (publishedVersion == null) { throw new IllegalArgumentException("publishedVersion is null"); } boolean supported; Version versionRequired = new Version(requiredVersion); Version versionBeingTested = new Version(publishedVersion); if (versionRequired.minorVersionSupport() || versionRequired.majorVersionSupport()) { boolean minorVersionSupport = versionRequired.minorVersionSupport(); int[] required; int[] configured; boolean isRange = versionBeingTested.isRange(); try { required = toIntArray(versionRequired.getVersion().split("\\D")); configured = toIntArray(versionBeingTested.getVersion().split("\\D")); } catch(NumberFormatException e) { return false; } if (required.length == 0) return true; if (minorVersionSupport) { supported = checkMinorVersion(required, configured); } else { supported = checkMajorVersion(required, configured); } if (!supported && isRange) { try { configured = toIntArray(versionBeingTested.getEndRange().split("\\D")); } catch(NumberFormatException e) { return false; } if (minorVersionSupport) { supported = checkMinorVersion(required, configured); } else { supported = checkMajorVersion(required, configured); } } } else { if (versionBeingTested.isRange()) { supported = withinRange(versionBeingTested, versionRequired); } else { supported = versionBeingTested.equals(versionRequired); } } return supported; }
1071043_0
@Override public QuestionSet processDocument( Document doc ) throws ParseException { Element root = doc.getRootElement(); if ( !root.getName().equalsIgnoreCase( "QuestionSet" ) ) throw new ParseException( "QuestionSet: Root not <QuestionSet>", 0 ); // Check version number String versionString = root.getAttributeValue( "version" ); if ( versionString == null ) { LOGGER.warning( "No `version' attribute on <QuestionSet> element" ); } else { try { int version = Integer.parseInt( versionString ); if ( version == 1 || version == 2 || version == 3 ) { LOGGER.warning( "QuestionSet version " + version + " is no longer " + "supported: proceeding anyway, but errors may be present." ); } else if ( version == 4 ) { // Supported, do nothing } else { // Unsupported, give warning LOGGER.warning( "QuestionSet format version (" + version + ") is newer than this software and may not be handled correctly." ); } } catch ( NumberFormatException e ) { LOGGER.log( Level.WARNING, "Cannot parse version number: " + versionString, e ); } } List<?> topElements = root.getChildren(); // Loop over the top-level elements String name = null; String description = null; int recommendedTimePerQuestion = -1; String category = ""; List<Question> questions = new ArrayList<Question>(); for ( Object object : topElements ) { Element topElement = (Element) object; String tagName = topElement.getName(); if ( tagName.equalsIgnoreCase( "Name" ) ) { name = topElement.getText(); } else if ( tagName.equalsIgnoreCase( "Description" ) ) { description = topElement.getText(); } else if ( tagName.equalsIgnoreCase( "RecommendedTimePerQuestion" ) ) { recommendedTimePerQuestion = Integer.parseInt( topElement.getText() ); } else if ( tagName.equalsIgnoreCase( "Category" ) ) { category = topElement.getText(); } else if ( tagName.equalsIgnoreCase( "Questions" ) ) { // Loop over each question for ( Object object2 : topElement.getChildren() ) { Element questionElement = (Element) object2; String name2 = questionElement.getName(); try { if ( name2.equalsIgnoreCase( "MultipleChoiceQuestion" ) ) { questions.add( new XmlQuestionSetParser().parseMultipleChoiceQuestion( questionElement, new ParsingProblemRecorder() ) ); } else if ( name2.equalsIgnoreCase( "DragAndDropQuestion" ) ) { questions.add( new DragAndDropQuestion( questionElement ) ); } else { LOGGER.warning( "Unrecognised tag: " + name2 ); } } catch ( ParseException e ) { LOGGER.log( Level.WARNING, "Error parsing Question, skipping", e ); continue; } } } else { LOGGER.warning( "Unrecognised tag: " + tagName ); } } if ( questions.size() == 0 ) throw new ParseException( "No valid questions found in QuestionSet", 0 ); if ( name == null ) { LOGGER.warning( "no <Name> provided" ); name = "No name given"; } if ( recommendedTimePerQuestion == -1 ) { LOGGER.warning( "no <RecommendedTimePerQuestion> provided" ); recommendedTimePerQuestion = 120; // default two minutes per question } if ( category == "" ) { LOGGER.warning( "No category listed for this question set" ); } if ( description == null ) { LOGGER.warning( "no <Description> provided" ); description = "No description given"; } return new QuestionSet( name, description, recommendedTimePerQuestion, category, questions ); }
1071767_0
public IPNMessage parse() { IPNMessage.Builder builder = new IPNMessage.Builder(nvp); if(validated) builder.validated(); for(Map.Entry<String, String> param : nvp.entrySet()) { addVariable(builder, param); } return builder.build(); }
1072630_1
;
1076094_132
@Transactional @SuppressWarnings("unchecked") public Set<GatewayResponse> sendMessage(GatewayRequest gatewayRequest) { if ( gatewayRequest .getMessageRequest() .getMessageType() == MessageType.VOICE ) { return voiceGatewayManager.sendMessage(gatewayRequest); } if ( gatewayRequest .getMessageRequest() .getMessageType() == MessageType.TEXT ) { return textGatewayManager.sendMessage(gatewayRequest); } return new HashSet<GatewayResponse>(); }
1076159_32
static AnalysisResult analyse( Class<?> klass, Constructor<?> constructor) throws IOException { Class<?>[] parameterTypes = constructor.getParameterTypes(); InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class"); if (in == null) { throw new IllegalArgumentException(format("can not find bytecode for %s", klass)); } return analyse(in, klass.getName().replace('.', '/'), klass.getSuperclass().getName().replace('.', '/'), parameterTypes); }
1076632_14
public void sendStaffCareMessages(Date startDate, Date endDate, Date deliveryDate, Date deliveryTime, String[] careGroups, boolean sendUpcoming, boolean blackoutEnabled, boolean sendNoDefaulterAndNoUpcomingCareMessage) { final boolean shouldBlackOut = blackoutEnabled && isMessageTimeWithinBlackoutPeriod(deliveryDate); if (shouldBlackOut) { log.debug("Cancelling nurse messages during blackout"); return; } List<Facility> facilities = motechService().getAllFacilities(); deliveryDate = adjustTime(deliveryDate, deliveryTime); for (Facility facility : facilities) { if (facilityPhoneNumberOrLocationNotAvailable(facility)) { continue; } sendDefaulterMessages(startDate, deliveryDate, careGroups, facility, sendNoDefaulterAndNoUpcomingCareMessage); if (sendUpcoming) { sendUpcomingMessages(startDate, endDate, deliveryDate, careGroups, facility, sendNoDefaulterAndNoUpcomingCareMessage); } } }
1077753_0
public static List<String> statementsFrom(Reader reader) throws IOException { SQLFile file = new SQLFile(); file.parse(reader); return file.getStatements(); }
1079636_7
protected boolean isClassConsidered( final String className ) { // Fix case where class names are reported with '.' final String fixedClassName = className.replace('.', '/'); for ( String exclude : this.excludes ) { final Pattern excludePattern; if( !excludesAreRegExp ) { if ( exclude.contains( "/**/" ) ) { exclude = exclude.replaceAll( "/\\*\\*/", "{0,1}**/" ); } if ( exclude.contains( "/*/" ) ) { exclude = exclude.replaceAll( "/\\*/", "{0,1}*/{0,1}" ); } excludePattern = simplifyRegularExpression( exclude, false ); } else { excludePattern = Pattern.compile( exclude ); } final Matcher excludeMatcher = excludePattern.matcher( fixedClassName ); while ( excludeMatcher.find() ) { return false; } } if ( !this.includes.isEmpty() ) { for ( String include : this.includes ) { final Pattern includePattern; if( !includesAreRegExp ) { if ( include.contains( "/**/" ) ) { include = include.replaceAll( "/\\*\\*/", "{0,1}**/" ); } if ( include.contains( "/*/" ) ) { include = include.replaceAll( "/\\*/", "{0,1}*/{0,1}" ); } includePattern = simplifyRegularExpression( include, false ); } else { includePattern = Pattern.compile( include ); } final Matcher includeMatcher = includePattern.matcher( fixedClassName ); while ( includeMatcher.find() ) { return true; } } return false; } return true; }
1081751_1
@Nonnull public static XProperties from(@Nonnull @NonNull final String absolutePath) throws IOException { final Resource resource = new PathMatchingResourcePatternResolver() .getResource(absolutePath); try (final InputStream in = resource.getInputStream()) { final XProperties xprops = new XProperties(); xprops.included.add(resource.getURI()); xprops.load(in); return xprops; } }
1081991_13
static void writeDependenciesFeature(Writer writer, ProvisionOption<?>... provisionOptions) { XMLOutputFactory xof = XMLOutputFactory.newInstance(); xof.setProperty("javax.xml.stream.isRepairingNamespaces", true); XMLStreamWriter sw = null; try { sw = xof.createXMLStreamWriter(writer); sw.writeStartDocument("UTF-8", "1.0"); sw.setDefaultNamespace(KARAF_FEATURE_NS); sw.writeCharacters("\n"); sw.writeStartElement("features"); sw.writeAttribute("name", "test-dependencies"); sw.writeCharacters("\n"); sw.writeStartElement("feature"); sw.writeAttribute("name", "test-dependencies"); sw.writeCharacters("\n"); for (ProvisionOption<?> provisionOption : provisionOptions) { if (provisionOption.getURL().startsWith("link") || provisionOption.getURL().startsWith("scan-features")) { // well those we've already handled at another location... continue; } sw.writeStartElement("bundle"); if (provisionOption.getStartLevel() != null) { sw.writeAttribute("start-level", provisionOption.getStartLevel().toString()); } sw.writeCharacters(provisionOption.getURL()); endElement(sw); } endElement(sw); endElement(sw); sw.writeEndDocument(); } catch (XMLStreamException e) { throw new RuntimeException("Error writing feature " + e.getMessage(), e); } finally { close(sw); } }
1089023_0
@Override public void subscribe(Completable.Observer subscriber) { completionSignal.subscribe(subscriber); }
1090553_36
@Nullable public <V> V queryValue(@Nullable RegionAssociable subject, Flag<V> flag) { Collection<V> values = queryAllValues(subject, flag, true); return flag.chooseValue(values); }
1091655_1
public String getMBeanName() { return mBeanName; }
1091966_0
public Request read(InputStream in) throws IOException { String header = null; String body = null; byte[] headerBytes = new byte[headerLength]; int n = in.read(headerBytes); if (n > 0) { header = new String(headerBytes, encoding); log.debug("header: #{}# ", header); int length = Integer.parseInt(header.substring(headerBodyLengthBeginIndex, headerBodyLengthEndIndex)); log.debug("length: {}", length); byte[] bodyBytes = new byte[length]; in.read(bodyBytes); body = new String(bodyBytes, encoding); log.debug("body: #{}#", body); } log.info("request: #{}#", header + body); return new Request(header, body); }
1095208_79
@Override public void activate (Instant time, int phaseNumber) { long msec = time.getMillis(); if (msec % (getWeatherReqInterval() * TimeService.HOUR) != 0) { log.info("WeatherService reports not time to grab weather data."); } else { log.info("Timeslot " + timeslotRepo.currentTimeslot().getId() + " WeatherService reports time to make request for weather data"); DateTime dateTime = timeslotRepo.currentTimeslot().getStartTime(); if (blocking) { WeatherRequester wr = new WeatherRequester(dateTime); wr.run(); } else { aheadDays.add(dateTime.plusDays(daysAhead)); while (aheadDays.size() > 0) { WeatherRequester wr = new WeatherRequester(aheadDays.remove(0)); new Thread(wr).start(); } } } broadcastWeatherReports(); broadcastWeatherForecasts(); }
1097987_0
@Override public float lengthNorm(String fieldName, int numTerms) { if (numTerms < 20) { // this shouldn't be possible, but be safe. if (numTerms <= 0) return 0; return ARR[numTerms]; return -0.00606f * numTerms + 0.35f; } //else return (float) (1.0 / Math.sqrt(numTerms)); }
1107344_0
static void printHelp(PrintWriter out) { out.println("Usage:"); out.println(" vark [-f FILE] [options] [targets...]"); out.println(); out.println("Options:"); IArgKeyList keys = Launch.factory().createArgKeyList(); for (IArgKey key : AardvarkOptions.getArgKeys()) { keys.register(key); } keys.printHelp(out); }
1109529_5
public void dbSelect() throws Exception { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/np"; Connection con = DriverManager.getConnection(url, "np", "npnpnp"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(getPlainSQL()); / PreparedStatement stmt = con.prepareStatement(getSql()); / Long[] val = getValue(); / for (int i = 0; i < COUNT; i++) { / stmt.setLong(i + 1, val[i]); / } / ResultSet rs = stmt.executeQuery(); / rs.close(); stmt.close(); con.close(); }
1110934_2
public List<String> extractCprNumbers(String soapResponse) throws CprAbbsException { int start = soapResponse.indexOf("<?xml"); if(start == -1) { throw new CprAbbsException("Invalid message body on call to CPR Abbs"); } String soapResponseWithoutHeader = soapResponse.substring(start); return extractCprNumbersWithoutHeaders(soapResponseWithoutHeader); }
1116314_32
public static <T extends HasTypes> Collector<T, ?, List<T>> closestTypes( T hasTypes ) { return hasTypesToListCollector( hasTypes, new HasAssignableToType<>( hasTypes ) ); }
1146205_24
@Override public int read() throws IOException { return remote.read(); }
1149947_21
@Override public void handleMessage(Exchange exchange) throws HandlerException { // identify ourselves exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) .addLabels(BehaviorLabel.TRANSIENT.label()); if (getState() != State.STARTED) { throw SCAMessages.MESSAGES.referenceBindingNotStarted(_referenceName, _bindingName); } try { // Figure out the QName for the service were invoking QName serviceName = getTargetServiceName(exchange); // Get a handle for the reference and use a copy of the exchange to invoke it ServiceReference ref = exchange.getProvider().getDomain().getServiceReference(serviceName); if (_clustered) { // check to see if local is preferred and available if (_preferLocal && ref != null) { invokeLocal(exchange, ref); } else { invokeRemote(exchange, serviceName); } } else { if (ref == null) { throw SCAMessages.MESSAGES.serviceReferenceNotFoundInDomain(serviceName.toString(), exchange.getProvider().getDomain().getName().toString()); } invokeLocal(exchange, ref); } } catch (SwitchYardException syEx) { throw new HandlerException(syEx.getMessage()); } }
1155836_1
@Override public LogLevel getLogLevel() { Level level = m_delegate.getEffectiveLevel(); return getLogLevel(level); }
1155961_9
public Study getByAccForUser(String acc, String userName) { Query query = entityManager.createQuery("SELECT s " + "FROM Study s join s.users user " + "WHERE " + "s.acc =:acc AND (user.userName =:userName" + " OR s.status =:status)" ) .setParameter("acc", acc) .setParameter("status", VisibilityStatus.PUBLIC) .setParameter("userName", userName); Study study; try { study = (Study) query.getSingleResult(); } catch (NoResultException e) { throw new BIIDAOException("Study with acc " + acc + " doesn't exist for user " + userName, e); } return study; }
1156021_8
public void setStudyOwners(CommandLine cmdl) { String specs[] = cmdl.getOptionValues("o"); if (specs == null) { return; } for (String spec : specs) { setStudyOwners(spec); } }
1156136_4
@Override protected boolean invokeLogic(long keyId) throws Exception { Operation operation = getOperation(operationTypeRandom); OperationTimestampPair prevOperation = timestamps.get(keyId); // first we have to get the value PrivateLogValue prevValue = checkedGetValue(keyId); PrivateLogValue backupValue = null; if (prevOperation != null) { if (prevValue == null || !prevValue.contains(prevOperation.operationId)) { // non-cleaned old value or stale read, try backup backupValue = checkedGetValue(~keyId); boolean txEnabled = manager.getGeneralConfiguration().getTransactionSize() > 0; // Modifying the same key within a single transaction may cause false stale reads, avoid it by checking maxPrunedOperationIds boolean valuePruned = maxPrunedOperationIds.get(keyId) != null && maxPrunedOperationIds.get(keyId) >= prevOperation.operationId; if ((backupValue == null || !backupValue.contains(prevOperation.operationId)) && (!txEnabled || !valuePruned)) { // definitely stale read log.debugf("Detected stale read, keyId=%s, previousValue=%s, complementValue=%s", keyId, prevValue, backupValue); waitForStaleRead(prevOperation.timestamp); return false; } else { if (!txEnabled || !valuePruned) { // pretend that we haven't read it at all prevValue = null; } } } } if (operation == BasicOperations.GET) { // especially GETs are not allowed here, because these would break the deterministic order // - each operationId must be written somewhere throw new UnsupportedOperationException("Only PUT and REMOVE operations are allowed for this logic"); } else if (prevValue == null || operation == BasicOperations.PUT) { PrivateLogValue nextValue; if (prevValue != null) { nextValue = getNextValue(keyId, prevValue); } else { // the value may have been removed, look for backup if (backupValue == null) { backupValue = checkedGetValue(~keyId); } if (backupValue == null) { nextValue = new PrivateLogValue(stressor.id, operationId); } else { nextValue = getNextValue(keyId, backupValue); } } if (nextValue == null) { return false; } checkedPutValue(keyId, nextValue); if (backupValue != null) { delayedRemoveValue(~keyId, backupValue); } } else if (operation == BasicOperations.REMOVE) { PrivateLogValue nextValue = getNextValue(keyId, prevValue); if (nextValue == null) { return false; } checkedPutValue(~keyId, nextValue); delayedRemoveValue(keyId, prevValue); } if (transactionSize > 0) { txModifications.add(new KeyOperationPair(keyId, operationId)); } else { long now = TimeService.currentTimeMillis(); timestamps.put(keyId, new OperationTimestampPair(operationId, now)); log.tracef("Operation %d on %08X finished at %d", operationId, keyId, now); } return true; }
1158118_0
public static String decrypt(String input) { if (isEmpty(input)) { return input; } char[] inputChars = input.toCharArray(); int length = inputChars.length; char[] inputCharsCopy = new char[length]; int j = 0; int i = 0; while (j < length) { inputCharsCopy[j] = ((char) (inputChars[j] - '\1' ^ i)); i = (char) (i + 1); j++; } return new String(inputCharsCopy); }
1158315_44
@Override public void computeEnhancements(ContentItem ci) throws EngineException { IRI contentItemId = ci.getUri(); Graph graph = ci.getMetadata(); LiteralFactory literalFactory = LiteralFactory.getInstance(); //get all the textAnnotations /* * this Map holds the name as key and all the text annotations of * dc:type dbpedia:Place that select this name as value * this map is used to avoid multiple lookups for text annotations * selecting the same name. */ Map<String, Collection<BlankNodeOrIRI>> name2placeEnhancementMap = new HashMap<String, Collection<BlankNodeOrIRI>>(); Iterator<Triple> iterator = graph.filter(null, DC_TYPE, DBPEDIA_PLACE); while (iterator.hasNext()) { BlankNodeOrIRI placeEnhancement = iterator.next().getSubject(); //the enhancement annotating an place //this can still be an TextAnnotation of an EntityAnnotation //so we need to filter TextAnnotation Triple isTextAnnotation = new TripleImpl(placeEnhancement, RDF_TYPE, ENHANCER_TEXTANNOTATION); if (graph.contains(isTextAnnotation)) { //now get the name String name = EnhancementEngineHelper.getString(graph, placeEnhancement, ENHANCER_SELECTED_TEXT); if (name == null) { log.warn("Unable to process TextAnnotation " + placeEnhancement + " because property" + ENHANCER_SELECTED_TEXT + " is not present"); } else { Collection<BlankNodeOrIRI> placeEnhancements = name2placeEnhancementMap.get(name); if (placeEnhancements == null) { placeEnhancements = new ArrayList<BlankNodeOrIRI>(); name2placeEnhancementMap.put(name, placeEnhancements); } placeEnhancements.add(placeEnhancement); } } else { //TODO: if we also ant to process EntityAnnotations with the dc:type dbpedia:Place // than we need to parse the name based on the enhancer:entity-name property } } //Now we do have all the names we need to lookup Map<SearchRequestPropertyEnum, Collection<String>> requestParams = new EnumMap<SearchRequestPropertyEnum, Collection<String>>(SearchRequestPropertyEnum.class); if (getMaxLocationEnhancements() != null) { requestParams.put(SearchRequestPropertyEnum.maxRows, Collections.singleton(getMaxLocationEnhancements().toString())); } for (Map.Entry<String, Collection<BlankNodeOrIRI>> entry : name2placeEnhancementMap.entrySet()) { List<Toponym> results; try { requestParams.put(SearchRequestPropertyEnum.name, Collections.singleton(entry.getKey())); results = geonamesService.searchToponyms(requestParams); } catch (Exception e) { /* * TODO: Review if it makes sense to catch here for each name, or * to catch the whole loop. * This depends if single requests can result in Exceptions * (e.g. because of encoding problems) or if usually Exceptions * are thrown because of general things like connection issues * or service unavailability. */ throw new EngineException(this, ci, e); } if (results != null) { Double maxScore = results.isEmpty() ? null : results.get(0).getScore(); for (Toponym result : results) { log.debug("process result {} {}",result.getGeoNameId(),result.getName()); Double score = getToponymScore(result,maxScore); log.debug(" > score {}",score); if (score != null) { if (score < minScore) { //if score is lower than the under bound, than stop break; } } else { log.warn("NULL returned as Score for " + result.getGeoNameId() + " " + result.getName()); /* * NOTE: If score is not present all suggestions are * added as enhancements to the metadata of the content * item. */ } //write the enhancement! BlankNodeOrIRI locationEnhancement = writeEntityEnhancement( contentItemId, graph, literalFactory, result, entry.getValue(), null, score); log.debug(" > {} >= {}",score,minHierarchyScore); if (score != null && score >= minHierarchyScore) { log.debug(" > getHierarchy for {} {}",result.getGeoNameId(),result.getName()); //get the hierarchy try { Iterator<Toponym> hierarchy = getHierarchy(result).iterator(); for (int level = 0; hierarchy.hasNext(); level++) { Toponym hierarchyEntry = hierarchy.next(); //TODO: filter the interesting entries // maybe add an configuration if (level == 0) { //Mother earth -> ignore continue; } //write it as dependent to the locationEnhancement if (result.getGeoNameId() != hierarchyEntry.getGeoNameId()) { //TODO: add additional checks based on possible // configuration here! log.debug(" - write hierarchy {} {}",hierarchyEntry.getGeoNameId(),hierarchyEntry.getName()); /* * The hierarchy service dose not provide a score, because it would be 1.0 * so we need to set the score to this value. * Currently is is set to the value of the suggested entry */ writeEntityEnhancement(contentItemId, graph, literalFactory, hierarchyEntry, null, Collections.singletonList(locationEnhancement), 1.0); } } } catch (Exception e) { log.warn("Unable to get Hierarchy for " + result.getGeoNameId() + " " + result.getName(), e); } } } } } }
1161604_0
@Override public TriplestoreReader getReader() { if (m_reader == null){ try{ open(); } catch(TrippiException e){ logger.error(e.toString(),e); } } return m_reader; }
1163141_15
private static void validateRELS(PID pid, String dsId, InputStream content) throws ValidationException { logger.debug("Validating " + dsId + " datastream"); new RelsValidator().validate(pid, dsId, content); logger.debug(dsId + " datastream is valid"); }
1163806_197
static String determineCheckoutPath(final FilePath workspacePath, final String localFolder) { final FilePath combinedPath = new FilePath(workspacePath, localFolder); final String result = combinedPath.getRemote(); return result; }
1164965_50
public WebClassesFinder(ServletContext servletContext, ClassLoader classLoader, PackageFilter packageFilter) { super(servletContext, classLoader, packageFilter); }
1165813_0
public static String extract(final String pem, final String passPhrase) throws IOException { final Object priv = PEMDecoder.decode(pem.toCharArray(), passPhrase); if (priv instanceof RSAPrivateKey) { return "ssh-rsa " + DatatypeConverter.printBase64Binary(RSASHA1Verify.encodeSSHRSAPublicKey(((RSAPrivateKey)priv).getPublicKey())); } if (priv instanceof DSAPrivateKey) { return "ssh-dss " + DatatypeConverter.printBase64Binary(DSASHA1Verify.encodeSSHDSAPublicKey(((DSAPrivateKey)priv).getPublicKey())); } throw new IOException("should never happen"); }
1167439_0
public void process(final MessageExchange messageExchange) throws Exception { final ContinuationData data = continuations.remove(messageExchange.getExchangeId()); if (data == null) { logger.error("Unexpected MessageExchange received: {}", messageExchange); } else { binding.runWithCamelContextClassLoader(new Callable<Object>() { public Object call() throws Exception { processReponse(messageExchange, data.exchange); data.callback.done(false); return null; } }); } }
1169309_3
public static boolean isFindBugs2x(final MojoExecution mojoExecution) { try { String[] versions = StringUtils.split(mojoExecution.getVersion(), "."); if (versions.length > 1) { int major = Integer.parseInt(versions[0]); int minor = Integer.parseInt(versions[1]); return major > 2 || (major == 2 && minor >= 4); } } catch (Throwable exception) { // NOCHECKSTYLE NOPMD // ignore and return false } return false; }
1169697_65
static CommonTree parseHost(String s) throws RecognitionException { return (CommonTree) getDeployParser(s).host().getTree(); }
1171506_0
public void subscribe(Class<? extends Subscriber> subscriber) { try { monitor.lock(); if (subscriber.isAnnotationPresent(InterestedEvent.class)) { InterestedEvent ann = subscriber.getAnnotation(InterestedEvent.class); for (Class<? extends Event> interestedEvent : ann.events()) { if (!subscribers.containsKey(interestedEvent)) { subscribers.put(interestedEvent, new LinkedList<Class<? extends Subscriber>>()); } subscribers.get(interestedEvent).add(subscriber); } } } finally { monitor.unlock(); } }
1176274_2
boolean hasPlayerMoved() { final double MAX_MOVE_TOLERANCE = 1.5; return distance3D(player.getLocation(), originalLocation) > MAX_MOVE_TOLERANCE; }
1181284_260
@SuppressWarnings("unchecked") public void execute(TransformContext context) throws PluginTransformationException { XPath xpath = DocumentHelper.createXPath("//@class"); List<Attribute> attributes = xpath.selectNodes(context.getDescriptorDocument()); for (Attribute attr : attributes) { String className = attr.getValue(); scanForHostComponents(context, className); int dotpos = className.lastIndexOf("."); if (dotpos > -1) { String pkg = className.substring(0, dotpos); String pkgPath = pkg.replace('.', '/') + '/'; // Only add an import if the system exports it and the plugin isn't using the package if (context.getSystemExports().isExported(pkg)) { if (context.getPluginArtifact().doesResourceExist(pkgPath)) { log.warn("The plugin '" + context.getPluginArtifact().toString() + "' uses a package '" + pkg + "' that is also exported by the application. It is highly recommended that the " + "plugin use its own packages."); } else { context.getExtraImports().add(pkg); } } } } }
1184582_8
public String parseOutput(String right) { return parseOutput(null, right); }
1193862_8
public void exportProfile(RulesProfile profile, Writer writer) { try { appendXmlHeader(writer); SortedMap<String, Rule> defaultRules = new TreeMap<String, Rule>(DefaultRules.get()); for (ActiveRule activeRule : profile.getActiveRulesByRepository(REPOSITORY_KEY)) { final Rule rule = activeRule.getRule(); final boolean hasParameters= !rule.getParams().isEmpty(); if (defaultRules.remove(rule.getKey()) == null || hasParameters) { appendRule(writer, rule, true, !hasParameters); if (hasParameters) { appendParameters(writer, activeRule); } } } for (Rule rule : defaultRules.values()) { appendRule(writer, rule, false, true); } appendXmlFooter(writer); } catch (IOException e) { throw new SonarException("Fail to export the profile " + profile, e); } }
1194243_15
public static void removeEntities(Reader reader, Writer writer) throws IOException { int curChar = -1; StringBuffer ent = null; if (reader == null) { throw new IllegalArgumentException("null reader arg"); } else if (writer == null) { throw new IllegalArgumentException("null writer arg"); } ent = new StringBuffer(50); while ((curChar = reader.read()) != -1) { if (curChar == '&') { if (ent.length() > 0) { writer.write(ent.toString()); ent.setLength(0); } ent.append((char) curChar); } else if (curChar == ';' && ent.length() > 0) { int entLen = ent.length(); if (entLen > 1) { if (ent.charAt(1) == '#') { if (entLen > 2) { char char2 = ent.charAt(2); try { if (char2 == 'x' || char2 == 'X') { if (entLen > 3) { writer.write(Integer.parseInt(ent .substring(3), 16)); } else { writer.write(ent.toString()); writer.write(curChar); } } else { writer.write(Integer.parseInt(ent .substring(2))); } } catch (NumberFormatException nfe) { // bogus character ref - leave as is. writer.write(ent.toString()); writer.write(curChar); } } else { writer.write("&#;"); } } else { Character character = HTMLEntityLookup .getCharacterCode(ent.substring(1)); if (character != null) { writer.write(character.charValue()); } else { // bogus entity ref - leave as is. writer.write(ent.toString()); writer.write(curChar); } } } else { writer.write("&;"); } ent.setLength(0); } else if (ent.length() > 0) { ent.append((char) curChar); } else { writer.write(curChar); } } if (ent.length() > 0) { writer.write(ent.toString()); } }
1195109_0
public void setFullName(String fullName) { this.fullName = fullName; }
1204957_0
@SuppressWarnings("ConstantConditions") @Override public List<MovieInfo> parseMovieInfo(String content, int maxCount, int posterCount, int backdropCount) throws ParseException { // Minus if (posterCount < 0) { posterCount = Integer.MAX_VALUE; } if (backdropCount < 0) { backdropCount = Integer.MAX_VALUE; } // Result List<MovieInfo> result = new ArrayList<>(); try { // Root node JsonNode rootNode = this.mapper.readTree(content); // Not Found if (rootNode.size() == 1 && "Nothing found.".equalsIgnoreCase(rootNode.path(0).asText())) { return result; } // Loop and create movie info list for (int i = 0; i < rootNode.size() && i < maxCount; i++) { // New MovieInfo MovieInfo movieInfo = this.movieFactory.createMovieInfo(); // Movie Node JsonNode movieNode = rootNode.path(i); movieInfo.setProviderName("TMDb"); movieInfo.setScore(movieNode.path("score").asDouble()); movieInfo.setPopularity(movieNode.path("popularity").asInt()); movieInfo.setAdult(movieNode.path("adult").asBoolean()); movieInfo.setLanguage(movieNode.path("language").asText()); movieInfo.setOriginalName(movieNode.path("original_name").asText()); movieInfo.setName(movieNode.path("name").asText()); movieInfo.setAlternativeName(movieNode.path("alternative_name").asText()); movieInfo.setProviderId(movieNode.path("id").asText()); movieInfo.setIMDbId(movieNode.path("imdb_id").asText()); movieInfo.setUrl(movieNode.path("url").asText()); movieInfo.setVotes(movieNode.path("votes").asInt()); movieInfo.setRating(movieNode.path("rating").asDouble()); movieInfo.setCertification(movieNode.path("certification").asText()); movieInfo.setOverview(movieNode.path("overview").asText()); movieInfo.setVersion(movieNode.path("version").asInt()); try { movieInfo.setReleasedDate(new SimpleDateFormat("yyyy-MM-dd").parse(movieNode.path("released").asText())); } catch (Exception e) { logger.warn("JsonParser catch a Exception during parsing released date: {}.", ExceptionUtils.getMessage(e)); } try { movieInfo.setLastModified(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(movieNode.path("last_modified_at").asText())); } catch (Exception e) { logger.warn("JsonParser catch a Exception during parsing last modified date: {}.", ExceptionUtils.getMessage(e)); } // Movie Poster Node JsonNode posterNode = movieNode.path("posters"); List<String> posterIDs = new ArrayList<>(); for (int j = 0; j < posterNode.size(); j++) { // Image Node JsonNode imageNode = posterNode.path(j).path("image"); // Calculate poster count if (!posterIDs.contains(imageNode.path("id").asText())) { if (posterIDs.size() >= posterCount) { break; } else { posterIDs.add(imageNode.path("id").asText()); } } // New MovieImage MovieImage movieImage = this.movieFactory.createMovieImage(); movieImage.setContentType(imageNode.path("type").asText()); movieImage.setImageType(MovieImage.JPEG_IMAGE_TYPE); movieImage.setSize(imageNode.path("size").asText()); movieImage.setHeight(imageNode.path("height").asInt()); movieImage.setWidth(imageNode.path("width").asInt()); movieImage.setUrl(imageNode.path("url").asText()); movieImage.setProviderId(imageNode.path("id").asText()); // Add to movie info movieInfo.addImage(movieImage); } // Movie Backdrop Node JsonNode backdropNode = movieNode.path("backdrops"); List<String> backdropIDs = new ArrayList<>(); for (int j = 0; j < backdropNode.size(); j++) { // Image Node JsonNode imageNode = backdropNode.path(j).path("image"); // Calculate poster count if (!backdropIDs.contains(imageNode.path("id").asText())) { if (backdropIDs.size() >= backdropCount) { break; } else { backdropIDs.add(imageNode.path("id").asText()); } } // New MovieImage MovieImage movieImage = this.movieFactory.createMovieImage(); movieImage.setContentType(imageNode.path("type").asText()); movieImage.setImageType(MovieImage.JPEG_IMAGE_TYPE); movieImage.setSize(imageNode.path("size").asText()); movieImage.setHeight(imageNode.path("height").asInt()); movieImage.setWidth(imageNode.path("width").asInt()); movieImage.setUrl(imageNode.path("url").asText()); movieImage.setProviderId(imageNode.path("id").asText()); // Add to movie info movieInfo.addImage(movieImage); } // Add to result result.add(movieInfo); } } catch (IOException e) { logger.error("JsonParser catch a IOException during parsing: {}, UNEXPECTED BEHAVIOR! PLEASE REPORT THIS BUG!", ExceptionUtils.getMessage(e)); throw new ParseException(ExceptionUtils.getMessage(e)); } return result; }
1205446_0
public static long calculateNotifTime(Long nowMillis, int hourToNotify) { DateTime now = new DateTime(nowMillis); DateTime timeToNotify = new DateTime(nowMillis); timeToNotify = timeToNotify.withHourOfDay(hourToNotify); if (timeToNotify.isBefore(now)) { timeToNotify = timeToNotify.plusDays(1); } return timeToNotify.getMillis(); }
1205842_1
@Override public List<String> getOperations(String state) { List<String> operationsList = new ArrayList<String>(); for (OperationsDefinition def : this.definition) { if (state.equals(def.getName())) { if ((def.getTransitions() != null)) { for (DestinationDefinition operations : def .getTransitions()) { operationsList.add(operations.getAction()); } } } } return operationsList; }
1206855_188
public JQueryUiTooltip setPosition(JsOption... options) { this.widget.setOption("position", asString(options)); return this; }
1216286_1
public void execute(String script) throws QueryScriptException { try { Context cx = Context.enter(); Scriptable scope = cx.initStandardObjects(); scope.put(ARAS_SCRIPT_ENGINE_CONTEXT, scope, arasCtx); loadRhinoBinding(scope, cx); cx.evaluateString(scope, script, "queryscript", 0, null); } catch (Exception e) { throw new QueryScriptException("Execution of query script failed.", e); } finally { Context.exit(); } }
1228775_2
@Override public Class<?> getBeanClass(Element element) { return ApplicationDecorator.class; }
1229527_2
public static Properties parseInstructions( final String query ) throws MalformedURLException { final Properties instructions = new Properties(); if( query != null ) { try { // just ignore for the moment and try out if we have valid properties separated by "&" final String segments[] = query.split( "&" ); for( String segment : segments ) { // do not parse empty strings if( segment.trim().length() > 0 ) { final Matcher matcher = INSTRUCTIONS_PATTERN.matcher( segment ); if( matcher.matches() ) { String key = matcher.group( 1 ); String val = matcher.group( 2 ); instructions.setProperty( verifyKey(key), val != null ? URLDecoder.decode( val, "UTF-8" ) : "" ); } else { throw new MalformedURLException( "Invalid syntax for instruction [" + segment + "]. Take a look at http://www.aqute.biz/Code/Bnd." ); } } } } catch( UnsupportedEncodingException e ) { // thrown by URLDecoder but it should never happen throwAsMalformedURLException( "Could not retrieve the instructions from [" + query + "]", e ); } } return instructions; }
1231687_1
public boolean isBitSet(int bit) { long bitMask = Long.rotateLeft(1, bit); long result = this.bitMaskValue & bitMask; if (result != 0) { return true; } return false; }
1251091_0
public List<Float> getBinned() { if (last == -1) return null; return new ImmutableList.Builder<Float>().addAll(binned).build(); }
1251538_7
@SuppressWarnings("unchecked") @Override public <T extends EnvironmentService> T getEnvironmentService(Class<T> type) throws UnavailableServiceException { // force NullPointerException if type is null type.toString(); for (EnvironmentService s : this.globalEnvironmentServices) { if (type.isInstance(s)) { return (T) s; } } throw new UnavailableServiceException(type); }
1251856_8
boolean isIgnored(File file){ boolean ignore = false; while(file != null){ String end = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(System.getProperty("file.separator")) + 1); for(String pathToIgnore: ignoredPaths){ ignore = end.matches(pathToIgnore); if(ignore){ return true; } } file = file.getParentFile(); } return ignore; }
1263661_9
public CSVFile downloadFile(CSVFile file) throws ServerCommunicationException, InvalidWriteEnablerException, ImmutableFileExistsException, RemoteFileDoesNotExistException, FailedToVerifySignatureException { return (CSVFile) downloadObject(file); }
1269176_202
public static Snapshot readSnapshot(IdReader reader, Snapshot oldSnapshot) throws IOException { assert reader.idManager == oldSnapshot.idManager; reader.readDiffs(); int snapshotId = reader.readInt(); boolean hasTool = reader.readBoolean(); Tool tool = hasTool ? reader.readTool() : null; Environment environment = Environment.readEnvironment(reader, oldSnapshot.environment); TechPool techPool = environment.techPool; boolean technologiesChanged = techPool != oldSnapshot.techPool; ImmutableArrayList<LibraryBackup> libBackups = oldSnapshot.libBackups; boolean libsChanged = reader.readBoolean(); if (libsChanged) { int libLen = reader.readInt(); LibraryBackup[] libBackupsArray = new LibraryBackup[libLen]; for (int libIndex = 0, numLibs = Math.min(oldSnapshot.libBackups.size(), libLen); libIndex < numLibs; libIndex++) { libBackupsArray[libIndex] = oldSnapshot.libBackups.get(libIndex); } for (;;) { int libIndex = reader.readInt(); if (libIndex == Integer.MAX_VALUE) { break; } if (libIndex >= 0) { LibraryBackup newBackup = LibraryBackup.read(reader); libBackupsArray[libIndex] = newBackup; } else { libIndex = ~libIndex; assert libBackupsArray[libIndex] != null; libBackupsArray[libIndex] = null; } } libBackups = new ImmutableArrayList<LibraryBackup>(libBackupsArray); } int cellLen = reader.readInt(); int cellMax = Math.min(oldSnapshot.cellBackups.size(), cellLen); CellBackup[] cellBackupsArray = new CellBackup[cellLen]; for (int cellIndex = 0; cellIndex < cellMax; cellIndex++) { cellBackupsArray[cellIndex] = oldSnapshot.cellBackups.get(cellIndex); } if (technologiesChanged) { for (int cellIndex = 0; cellIndex < cellLen; cellIndex++) { CellBackup cellBackup = cellBackupsArray[cellIndex]; if (cellBackup == null) { continue; } cellBackupsArray[cellIndex] = cellBackup.withTechPool(techPool); } } for (;;) { int cellIndex = reader.readInt(); if (cellIndex == Integer.MAX_VALUE) { break; } if (cellIndex >= 0) { CellBackup newBackup = CellBackup.read(reader, techPool); cellBackupsArray[cellIndex] = newBackup; } else { cellIndex = ~cellIndex; assert cellBackupsArray[cellIndex] != null; cellBackupsArray[cellIndex] = null; } } ImmutableArrayList<CellBackup> cellBackups = new ImmutableArrayList<CellBackup>(cellBackupsArray); int[] cellGroups = oldSnapshot.cellGroups; CellId[] groupMainSchematics = oldSnapshot.groupMainSchematics; boolean cellGroupsChanged = reader.readBoolean(); if (cellGroupsChanged) { cellGroups = new int[cellBackups.size()]; int maxGroup = -1; for (int cellIndex = 0; cellIndex < cellGroups.length; cellIndex++) { int groupIndex = reader.readInt(); maxGroup = Math.max(maxGroup, groupIndex); cellGroups[cellIndex] = groupIndex; } groupMainSchematics = new CellId[maxGroup + 1]; for (int groupIndex = 0; groupIndex < groupMainSchematics.length; groupIndex++) { CellId mainSchematics = null; int cellIndex = reader.readInt(); if (cellIndex >= 0) { mainSchematics = reader.idManager.getCellId(cellIndex); } groupMainSchematics[groupIndex] = mainSchematics; } } for (int i = 0; i < cellBackups.size(); i++) { assert (cellBackups.get(i) != null) == (cellGroups[i] >= 0); } CellTree[] cellTreesArray = oldSnapshot.computeCellTrees(cellBackups, environment.techPool); ImmutableArrayList<CellTree> cellTrees = new ImmutableArrayList<CellTree>(cellTreesArray); return new Snapshot(oldSnapshot.idManager, snapshotId, tool, cellTrees, cellBackups, cellGroups, groupMainSchematics, libBackups, environment); }
1273791_99
@Override public List<Token> tokenize(String text) { return createTokenList(text); }
1274071_4
public static Result execute(List<AdaptationCommand> cmds) { Result result = new Result(); for (AdaptationCommand cmd : cmds) { try { cmd.execute(); result.executedCmds.add(cmd); } catch (KevoreeAdaptationException e) { result.error = e; return result; } } return result; }
1274332_10
public static BooleanValue ldap_unbind (LdapLinkResource linkIdentifier) { // Avoid NPEs from this being called on non-existent linkIdentifiers. if (linkIdentifier == null) { return BooleanValue.create(false); } boolean success = linkIdentifier.unbind(); return BooleanValue.create(success); }
1287669_60
public static JsonAsserter with(String json) { return new JsonAsserterImpl(JsonPath.parse(json).json()); }
1290826_8
public static String getPublicId(String otp) { if ((otp == null) || (otp.length() < OTP_MIN_LEN)){ //not a valid OTP format, throw an exception throw new IllegalArgumentException("The OTP is too short to be valid"); } Integer len = otp.length(); /* The OTP part is always the last 32 bytes of otp. Whatever is before that * (if anything) is the public ID of the YubiKey. The ID can be set to '' * through personalization. */ return otp.substring(0, len - 32).toLowerCase(); }
1293378_2
public float getMutation() { return mutation; }
1294371_16
public static String getParentOf(String path) { int i = path.lastIndexOf(DELIM); if (i == -1) return ""; if (i == 0) i = 1; return path.substring(0, i); }
1302098_5
public static CompositeData parseComposite(URI uri) throws URISyntaxException { CompositeData rc = new CompositeData(); rc.scheme = uri.getScheme(); String ssp = stripPrefix(uri.getSchemeSpecificPart().trim(), "//").trim(); parseComposite(uri, rc, ssp); rc.fragment = uri.getFragment(); return rc; }
1307005_0
public File newFolder(String folder) throws IOException { return newFolder(new String[]{folder}); }
1307227_2
public static LoggerStore createLoggerStore(final String configuratorType, final String resource) { final InitialLoggerStoreFactory factory = new InitialLoggerStoreFactory(); final Map<String, Object> data = new HashMap<String, Object>(); data.put(INITIAL_FACTORY, getFactoryClassName(configuratorType)); data.put(FILE_LOCATION, resource); return factory.createLoggerStore(data); }
1312627_5
public static String getKernelRevision() { return KERNEL_VERSION.getRevision(); }
1313372_4
protected boolean isAutomaticMessage() throws MessagingException { String[] autoSubmittedHeaders = this.mimeMessage.getHeader(AUTO_SUBMITTED_HEADER); if (autoSubmittedHeaders != null) { for (String autoSubmittedHeader : autoSubmittedHeaders) { if ("auto-generated".equalsIgnoreCase(autoSubmittedHeader) || "auto-replied".equalsIgnoreCase(autoSubmittedHeader) || autoSubmittedHeader.startsWith("auto-notified")) { return true; } } } return false; }
1318639_2
@Override public String[] getJobsInProgress() throws NodeDoesNotExistException, ZooKeeperConnectionException, WatcherException { if (zk == null) { try { initializeZooKeeper(); } catch (Exception e) { throw new ZooKeeperConnectionException(e); } } if (jobsInProgressWatcher == null) { try { initializeJobMonitor("JobsInProgress"); } catch (OrbZKFailure e) { throw new WatcherException(e); } } return jobsInProgress; }
1319605_35
@Override public boolean isValid(CharSequence domain, ConstraintValidatorContext context) { Matcher matcher = DOMAIN_NAME_REGEX.matcher(domain); if (matcher.matches()) { domain = matcher.group(1); return isValidTld(domain.toString()); } return allowLocal && DOMAIN_LABEL.matcher(domain).matches(); }
1320181_158
public Datastore findDatastoreById(final Integer id) { assert id != null; return datastoreDao.findById(id); }
1322545_0
public static boolean validateUrl(String url) { if (TextUtils.isEmpty(url)) { return false; } pattern = Pattern.compile(URL_PATTERN); matcher = pattern.matcher(url); if (matcher.matches()) { return true; } return false; }
1328283_24
@Override public void get(ByteBuffer key, ReaderResult result) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("Original value: "); sb.append(BytesUtils.bytesToHexString(key)); sb.append(" Assigned to partition number: "); sb.append(partNum); byte[] bytes = sb.toString().getBytes(); result.requiresBufferSize(bytes.length); System.arraycopy(bytes, 0, result.getBuffer().array(), 0, bytes.length); result.found(); }
1337781_11
@Override public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) { StringBuffer errorMsgBegin = new StringBuffer(""); List<Object[]> paramCouple = new LinkedList<Object[]>(); paramCouple.addAll(ReflectionHelper.getParametersWithAnnotation(method, Page.class)); for (int i = 0; i < resolvedParams.length; i++) { if (paramCouple.get(i) != null) { Class<?> param = (Class<?>) paramCouple.get(i)[0]; Annotation[] parameterAnnotations = (Annotation[]) paramCouple.get(i)[1]; Object page = createPage(searchContext, parameterAnnotations, null, null, method, param); resolvedParams[i] = page; } } return resolvedParams; }
1338456_1
public void add(final LabelCounters diff) { if (diff.totalBytes != null) { this.totalBytes += diff.totalBytes; } if (diff.totalMessages != null) { this.totalMessages += diff.totalMessages; } if (diff.unreadMessages != null) { this.unreadMessages += diff.unreadMessages; } }
1341207_31
@Nonnull Integer getMaxAbsNumber(@Nonnull Integer[] numbers) { Integer maxAbsNumber = 0; for (Integer number : numbers) { if (number >= 0) { if (number > maxAbsNumber) { maxAbsNumber = number; } } else if (number == Integer.MIN_VALUE) { maxAbsNumber = Integer.MAX_VALUE; } else { if (-number > maxAbsNumber) { maxAbsNumber = -number; } } } return maxAbsNumber; }
1342891_5
public CellTree parse(List<Property> model) { stack.push(root); parseSiblings(model, ""); return cellTree; }