query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Builds a batch-fetch capable loader based on the given persister, lock-mode, etc. @param persister The entity persister @param batchSize The maximum number of ids to batch-fetch at once @param lockMode The lock mode @param factory The SessionFactory @param influencers Any influencers that should affect the built query @param innerEntityLoaderBuilder Builder of the entity loader receiving the subset of batches @return The loader.
[ "public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockMode lockMode,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockMode, factory, influencers, innerEntityLoaderBuilder );\n\t}" ]
[ "boolean applyDomainModel(ModelNode result) {\n if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {\n return false;\n }\n final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();\n return callback.applyDomainModel(bootOperations);\n }", "public double stdev() {\n double m = mean();\n\n double total = 0;\n\n final int N = getNumElements();\n if( N <= 1 )\n throw new IllegalArgumentException(\"There must be more than one element to compute stdev\");\n\n\n for( int i = 0; i < N; i++ ) {\n double x = get(i);\n\n total += (x - m)*(x - m);\n }\n\n total /= (N-1);\n\n return Math.sqrt(total);\n }", "public static List<File> listFilesByRegex(String regex, File... directories) {\n return listFiles(directories,\n new RegexFileFilter(regex),\n CanReadFileFilter.CAN_READ);\n }", "public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // now checking constraints\r\n FieldDescriptorConstraints fieldConstraints = new FieldDescriptorConstraints();\r\n ReferenceDescriptorConstraints refConstraints = new ReferenceDescriptorConstraints();\r\n CollectionDescriptorConstraints collConstraints = new CollectionDescriptorConstraints();\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldConstraints.check((FieldDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getReferences(); it.hasNext();)\r\n {\r\n refConstraints.check((ReferenceDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getCollections(); it.hasNext();)\r\n {\r\n collConstraints.check((CollectionDescriptorDef)it.next(), checkLevel);\r\n }\r\n new ClassDescriptorConstraints().check(this, checkLevel);\r\n }", "public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }", "protected I_CmsSearchConfigurationFacetRange parseRangeFacet(String pathPrefix) {\n\n try {\n final String range = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_RANGE);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final String start = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_START);\n final String end = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_END);\n final String gap = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_GAP);\n final String sother = parseOptionalStringValue(pathPrefix + XML_ELEMENT_RANGE_FACET_OTHER);\n List<I_CmsSearchConfigurationFacetRange.Other> other = null;\n if (sother != null) {\n final List<String> sothers = Arrays.asList(sother.split(\",\"));\n other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sothers.size());\n for (String so : sothers) {\n try {\n I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf(\n so);\n other.add(o);\n } catch (final Exception e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e);\n }\n }\n }\n final Boolean hardEnd = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_RANGE_FACET_HARDEND);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetRange(\n range,\n start,\n end,\n gap,\n other,\n hardEnd,\n name,\n minCount,\n label,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_RANGE_FACET_RANGE\n + \", \"\n + XML_ELEMENT_RANGE_FACET_START\n + \", \"\n + XML_ELEMENT_RANGE_FACET_END\n + \", \"\n + XML_ELEMENT_RANGE_FACET_GAP),\n e);\n return null;\n }\n\n }", "private Duration getDuration(TimeUnit units, Double duration)\n {\n Duration result = null;\n if (duration != null)\n {\n double durationValue = duration.doubleValue() * 100.0;\n\n switch (units)\n {\n case MINUTES:\n {\n durationValue *= MINUTES_PER_DAY;\n break;\n }\n\n case HOURS:\n {\n durationValue *= HOURS_PER_DAY;\n break;\n }\n\n case DAYS:\n {\n durationValue *= 3.0;\n break;\n }\n\n case WEEKS:\n {\n durationValue *= 0.6;\n break;\n }\n\n case MONTHS:\n {\n durationValue *= 0.15;\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported time units \" + units);\n }\n }\n\n durationValue = Math.round(durationValue) / 100.0;\n\n result = Duration.getInstance(durationValue, units);\n }\n\n return result;\n }", "private void writeMap(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> map = (Map<String, Object>) value;\n m_writer.writeStartObject(fieldName);\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n Object entryValue = entry.getValue();\n if (entryValue != null)\n {\n DataType type = TYPE_MAP.get(entryValue.getClass().getName());\n if (type == null)\n {\n type = DataType.STRING;\n entryValue = entryValue.toString();\n }\n writeField(entry.getKey(), type, entryValue);\n }\n }\n m_writer.writeEndObject();\n }", "public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }" ]
Go through all node IDs and determine which node @param cluster @param storeRoutingPlan @return
[ "private Map<Integer, Integer> getNodeIdToNaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToNaryCount = Maps.newHashMap();\n\n for(int nodeId: cluster.getNodeIds()) {\n nodeIdToNaryCount.put(nodeId, storeRoutingPlan.getZoneNAryPartitionIds(nodeId).size());\n }\n\n return nodeIdToNaryCount;\n }" ]
[ "I_CmsSerialDateServiceAsync getService() {\r\n\r\n if (SERVICE == null) {\r\n SERVICE = GWT.create(I_CmsSerialDateService.class);\r\n String serviceUrl = CmsCoreProvider.get().link(\"org.opencms.ade.contenteditor.CmsSerialDateService.gwt\");\r\n ((ServiceDefTarget)SERVICE).setServiceEntryPoint(serviceUrl);\r\n }\r\n return SERVICE;\r\n }", "@SuppressWarnings(\"WeakerAccess\")\n public String getProperty(Enum<?> key, boolean lowerCase) {\n final String keyName;\n if (lowerCase) {\n keyName = key.name().toLowerCase(Locale.ENGLISH);\n } else {\n keyName = key.name();\n }\n return getProperty(keyName);\n }", "public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }", "public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnd6ravariables updateresources[] = new nd6ravariables[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nd6ravariables();\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].ceaserouteradv = resources[i].ceaserouteradv;\n\t\t\t\tupdateresources[i].sendrouteradv = resources[i].sendrouteradv;\n\t\t\t\tupdateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption;\n\t\t\t\tupdateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse;\n\t\t\t\tupdateresources[i].managedaddrconfig = resources[i].managedaddrconfig;\n\t\t\t\tupdateresources[i].otheraddrconfig = resources[i].otheraddrconfig;\n\t\t\t\tupdateresources[i].currhoplimit = resources[i].currhoplimit;\n\t\t\t\tupdateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval;\n\t\t\t\tupdateresources[i].minrtadvinterval = resources[i].minrtadvinterval;\n\t\t\t\tupdateresources[i].linkmtu = resources[i].linkmtu;\n\t\t\t\tupdateresources[i].reachabletime = resources[i].reachabletime;\n\t\t\t\tupdateresources[i].retranstime = resources[i].retranstime;\n\t\t\t\tupdateresources[i].defaultlifetime = resources[i].defaultlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JDBC DriverManager\r\n final String driver = jcd.getDriver();\r\n final String url = getDbURL(jcd);\r\n try\r\n {\r\n // loads the driver - NB call to newInstance() added to force initialisation\r\n ClassHelper.getClass(driver, true);\r\n final String user = jcd.getUserName();\r\n final String password = jcd.getPassWord();\r\n final Properties properties = getJdbcProperties(jcd, user, password);\r\n if (properties.isEmpty())\r\n {\r\n if (user == null)\r\n {\r\n retval = DriverManager.getConnection(url);\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, user, password);\r\n }\r\n }\r\n else\r\n {\r\n retval = DriverManager.getConnection(url, properties);\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n throw new LookupException(\"Error getting Connection from DriverManager with url (\" + url + \") and driver (\" + driver + \")\", sqlEx);\r\n }\r\n catch (ClassNotFoundException cnfEx)\r\n {\r\n log.error(cnfEx);\r\n throw new LookupException(\"A class was not found\", cnfEx);\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Instantiation of jdbc driver failed\", e);\r\n throw new LookupException(\"Instantiation of jdbc driver failed\", e);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DriverManager: \"+retval);\r\n return retval;\r\n }", "@Nonnull\n public BiMap<String, String> getOutputMapper() {\n final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();\n if (outputMapper == null) {\n return HashBiMap.create();\n }\n return outputMapper;\n }", "public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {\n DMatrixRMaj A = new DMatrixRMaj(length,length);\n\n symmetric(A,min,max,rand);\n\n return A;\n }", "private void writeCalendars() throws JAXBException\n {\n //\n // Create the new Planner calendar list\n //\n Calendars calendars = m_factory.createCalendars();\n m_plannerProject.setCalendars(calendars);\n writeDayTypes(calendars);\n List<net.sf.mpxj.planner.schema.Calendar> calendar = calendars.getCalendar();\n\n //\n // Process each calendar in turn\n //\n for (ProjectCalendar mpxjCalendar : m_projectFile.getCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerCalendar = m_factory.createCalendar();\n calendar.add(plannerCalendar);\n writeCalendar(mpxjCalendar, plannerCalendar);\n }\n }", "public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {\n final TestSpecification testSpecification = new TestSpecification();\n // Sort buckets by value ascending\n final Map<String,Integer> buckets = Maps.newLinkedHashMap();\n final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {\n @Override\n public int compare(final TestBucket lhs, final TestBucket rhs) {\n return Ints.compare(lhs.getValue(), rhs.getValue());\n }\n }).immutableSortedCopy(testDefinition.getBuckets());\n int fallbackValue = -1;\n if(testDefinitionBuckets.size() > 0) {\n final TestBucket firstBucket = testDefinitionBuckets.get(0);\n fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value\n\n final PayloadSpecification payloadSpecification = new PayloadSpecification();\n if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {\n final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());\n payloadSpecification.setType(payloadType.payloadTypeName);\n if (payloadType == PayloadType.MAP) {\n final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();\n for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {\n payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);\n }\n payloadSpecification.setSchema(payloadSpecificationSchema);\n }\n testSpecification.setPayload(payloadSpecification);\n }\n\n for (int i = 0; i < testDefinitionBuckets.size(); i++) {\n final TestBucket bucket = testDefinitionBuckets.get(i);\n buckets.put(bucket.getName(), bucket.getValue());\n }\n }\n testSpecification.setBuckets(buckets);\n testSpecification.setDescription(testDefinition.getDescription());\n testSpecification.setFallbackValue(fallbackValue);\n return testSpecification;\n }" ]
Delete an object.
[ "public void deleteObject(Object object)\r\n {\r\n PersistenceBroker broker = null;\r\n try\r\n {\r\n broker = getBroker();\r\n broker.delete(object);\r\n }\r\n finally\r\n {\r\n if (broker != null) broker.close();\r\n }\r\n }" ]
[ "public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }", "private void flushOutput() throws IOException {\n outStream.flush();\n outWriter.completeLine();\n errStream.flush();\n errWriter.completeLine();\n }", "@SuppressWarnings(\"unchecked\")\n public LinkedHashMap<String, Field> getValueAsListMap() {\n return (LinkedHashMap<String, Field>) type.convert(getValue(), Type.LIST_MAP);\n }", "public Dataset<String, String> getDataset(Dataset<String, String> oldData, Index<String> goodFeatures) {\r\n //public Dataset getDataset(List data, Collection goodFeatures) {\r\n //makeAnswerArraysAndTagIndex(data);\r\n\r\n int[][] oldDataArray = oldData.getDataArray();\r\n int[] oldLabelArray = oldData.getLabelsArray();\r\n Index<String> oldFeatureIndex = oldData.featureIndex;\r\n\r\n int[] oldToNewFeatureMap = new int[oldFeatureIndex.size()];\r\n\r\n int[][] newDataArray = new int[oldDataArray.length][];\r\n\r\n System.err.print(\"Building reduced dataset...\");\r\n\r\n int size = oldFeatureIndex.size();\r\n int max = 0;\r\n for (int i = 0; i < size; i++) {\r\n oldToNewFeatureMap[i] = goodFeatures.indexOf(oldFeatureIndex.get(i));\r\n if (oldToNewFeatureMap[i] > max) {\r\n max = oldToNewFeatureMap[i];\r\n }\r\n }\r\n\r\n for (int i = 0; i < oldDataArray.length; i++) {\r\n int[] data = oldDataArray[i];\r\n size = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n if (oldToNewFeatureMap[data[j]] > 0) {\r\n size++;\r\n }\r\n }\r\n int[] newData = new int[size];\r\n int index = 0;\r\n for (int j = 0; j < data.length; j++) {\r\n int f = oldToNewFeatureMap[data[j]];\r\n if (f > 0) {\r\n newData[index++] = f;\r\n }\r\n }\r\n newDataArray[i] = newData;\r\n }\r\n\r\n Dataset<String, String> train = new Dataset<String, String>(oldData.labelIndex, oldLabelArray, goodFeatures, newDataArray, newDataArray.length);\r\n\r\n System.err.println(\"done.\");\r\n if (flags.featThreshFile != null) {\r\n System.err.println(\"applying thresholds...\");\r\n List<Pair<Pattern,Integer>> thresh = getThresholds(flags.featThreshFile);\r\n train.applyFeatureCountThreshold(thresh);\r\n } else if (flags.featureThreshold > 1) {\r\n System.err.println(\"Removing Features with counts < \" + flags.featureThreshold);\r\n train.applyFeatureCountThreshold(flags.featureThreshold);\r\n }\r\n train.summaryStatistics();\r\n return train;\r\n }", "public static base_response enable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance enableresource = new clusterinstance();\n\t\tenableresource.clid = clid;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public static List<DbModule> getAllSubmodules(final DbModule module) {\n final List<DbModule> submodules = new ArrayList<DbModule>();\n submodules.addAll(module.getSubmodules());\n\n for(final DbModule submodule: module.getSubmodules()){\n submodules.addAll(getAllSubmodules(submodule));\n }\n\n return submodules;\n }", "protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }", "public static final char getChar(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getString(key).charAt(0));\n }", "public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }" ]
Log a trace message.
[ "public void trace(String msg) {\n\t\tlogIfEnabled(Level.TRACE, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}" ]
[ "@SuppressWarnings(\"deprecation\")\n private final void operationTimeout() {\n\n /**\n * first kill async http worker; before suicide LESSON: MUST KILL AND\n * WAIT FOR CHILDREN to reply back before kill itself.\n */\n cancelCancellable();\n if (asyncWorker != null && !asyncWorker.isTerminated()) {\n asyncWorker\n .tell(RequestWorkerMsgType.PROCESS_ON_TIMEOUT, getSelf());\n\n } else {\n logger.info(\"asyncWorker has been killed or uninitialized (null). \"\n + \"Not send PROCESS ON TIMEOUT.\\nREQ: \"\n + request.toString());\n replyErrors(PcConstants.OPERATION_TIMEOUT,\n PcConstants.OPERATION_TIMEOUT, PcConstants.NA,\n PcConstants.NA_INT);\n }\n\n }", "public final static int readUntil(final StringBuilder out, final String in, final int start, final char end)\n {\n int pos = start;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n if (ch == end)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }", "public static Multimap<String, String> getParameters(final String rawQuery) {\n Multimap<String, String> result = HashMultimap.create();\n if (rawQuery == null) {\n return result;\n }\n\n StringTokenizer tokens = new StringTokenizer(rawQuery, \"&\");\n while (tokens.hasMoreTokens()) {\n String pair = tokens.nextToken();\n int pos = pair.indexOf('=');\n String key;\n String value;\n if (pos == -1) {\n key = pair;\n value = \"\";\n } else {\n\n try {\n key = URLDecoder.decode(pair.substring(0, pos), \"UTF-8\");\n value = URLDecoder.decode(pair.substring(pos + 1), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n\n result.put(key, value);\n }\n return result;\n }", "public static String replaceParameters(final InputStream stream) {\n String content = IOUtil.asStringPreservingNewLines(stream);\n return resolvePlaceholders(content);\n }", "public void removeAccessory(HomekitAccessory accessory) {\n this.registry.remove(accessory);\n logger.info(\"Removed accessory \" + accessory.getLabel());\n if (started) {\n registry.reset();\n webHandler.resetConnections();\n }\n }", "public static final ProjectFile setProjectNameAndRead(File directory) throws MPXJException\n {\n List<String> projects = listProjectNames(directory);\n\n if (!projects.isEmpty())\n {\n P3DatabaseReader reader = new P3DatabaseReader();\n reader.setProjectName(projects.get(0));\n return reader.read(directory);\n }\n\n return null;\n }", "private String alterPrefix(String word, String oldPrefix, String newPrefix) {\n\n if (word.startsWith(oldPrefix)) {\n return word.replaceFirst(oldPrefix, newPrefix);\n }\n return (newPrefix + word);\n }", "private void writeResourceAssignment(ResourceAssignment record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(formatResource(record.getResource()));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatUnits(record.getUnits())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getBaselineWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getActualWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getOvertimeWork())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getBaselineCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatCurrency(record.getActualCost())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTime(record.getFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDuration(record.getDelay())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getResourceUniqueID()));\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n\n ResourceAssignmentWorkgroupFields workgroup = record.getWorkgroupAssignment();\n if (workgroup == null)\n {\n workgroup = ResourceAssignmentWorkgroupFields.EMPTY;\n }\n writeResourceAssignmentWorkgroupFields(workgroup);\n\n m_eventManager.fireAssignmentWrittenEvent(record);\n }", "public static boolean hasValidContentAdditionParameterDefined(ModelNode operation) {\n for (String s : DeploymentAttributes.MANAGED_CONTENT_ATTRIBUTES.keySet()) {\n if (operation.hasDefined(s)) {\n return true;\n }\n }\n return false;\n }" ]
converts Map of data to json string @param data map data to converted to json @return {@link String}
[ "private String jsonifyData(Map<String, ? extends Object> data) {\n JSONObject jsonData = new JSONObject(data);\n\n return jsonData.toString();\n }" ]
[ "public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster,\n final int randomSwapAttempts,\n final int randomSwapSuccesses,\n final List<Integer> randomSwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(randomSwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(randomSwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n int successes = 0;\n for(int i = 0; i < randomSwapAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n if(nextUtility < currentUtility) {\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (improvement \" + successes\n + \" on swap attempt \" + i + \")\");\n successes++;\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n if(successes >= randomSwapSuccesses) {\n // Enough successes, move on.\n break;\n }\n }\n return returnCluster;\n }", "public static Transformers.ResourceIgnoredTransformationRegistry createServerIgnoredRegistry(final RequiredConfigurationHolder rc, final Transformers.ResourceIgnoredTransformationRegistry delegate) {\n return new Transformers.ResourceIgnoredTransformationRegistry() {\n @Override\n public boolean isResourceTransformationIgnored(PathAddress address) {\n final int length = address.size();\n if (length == 0) {\n return false;\n } else if (length >= 1) {\n if (delegate.isResourceTransformationIgnored(address)) {\n return true;\n }\n\n final PathElement element = address.getElement(0);\n final String type = element.getKey();\n switch (type) {\n case ModelDescriptionConstants.EXTENSION:\n // Don't ignore extensions for now\n return false;\n// if (local) {\n// return false; // Always include all local extensions\n// } else if (rc.getExtensions().contains(element.getValue())) {\n// return false;\n// }\n// break;\n case ModelDescriptionConstants.PROFILE:\n if (rc.getProfiles().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SERVER_GROUP:\n if (rc.getServerGroups().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SOCKET_BINDING_GROUP:\n if (rc.getSocketBindings().contains(element.getValue())) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n };\n }", "protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public T insert(T entity) {\n\n if (!hasPrimaryKey(entity)) {\n throw new RuntimeException(String.format(\"Tried to insert entity of type %s with null or zero primary key\",\n entity.getClass().getSimpleName()));\n }\n\n InsertCreator insert = new InsertCreator(table);\n\n insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity));\n\n if (versionColumn != null) {\n insert.setValue(versionColumn.getColumnName(), 0);\n }\n\n for (Column column : columns) {\n if (!column.isReadOnly()) {\n insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));\n }\n }\n\n new JdbcTemplate(ormConfig.getDataSource()).update(insert);\n\n if (versionColumn != null) {\n ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0);\n }\n\n return entity;\n }", "private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }", "public int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedRefresh == null) {\n\t\t\tmappedRefresh = MappedRefresh.build(dao, tableInfo);\n\t\t}\n\t\treturn mappedRefresh.executeRefresh(databaseConnection, data, objectCache);\n\t}", "public Info changeMessage(String newMessage) {\n Info newInfo = new Info();\n newInfo.setMessage(newMessage);\n\n URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(newInfo.getPendingChanges());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonResponse = JsonObject.readFrom(response.getJSON());\n\n return new Info(jsonResponse);\n }", "public static void acceptsNodeMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id list\")\n .withRequiredArg()\n .describedAs(\"node-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }", "protected void runQuery() {\n\n String pool = m_pool.getValue();\n String stmt = m_script.getValue();\n if (stmt.trim().isEmpty()) {\n return;\n }\n CmsStringBufferReport report = new CmsStringBufferReport(Locale.ENGLISH);\n List<Throwable> errors = new ArrayList<>();\n CmsSqlConsoleResults result = m_console.execute(stmt, pool, report, errors);\n if (errors.size() > 0) {\n CmsErrorDialog.showErrorDialog(report.toString() + errors.get(0).getMessage(), errors.get(0));\n } else {\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_SQLCONSOLE_QUERY_RESULTS_0));\n window.setContent(new CmsSqlConsoleResultsForm(result, report.toString()));\n A_CmsUI.get().addWindow(window);\n window.center();\n }\n\n }" ]
Starts the HTTP service. @throws Exception if the service failed to started
[ "public synchronized void start() throws Exception {\n if (state == State.RUNNING) {\n LOG.debug(\"Ignore start() call on HTTP service {} since it has already been started.\", serviceName);\n return;\n }\n if (state != State.NOT_STARTED) {\n if (state == State.STOPPED) {\n throw new IllegalStateException(\"Cannot start the HTTP service \"\n + serviceName + \" again since it has been stopped\");\n }\n throw new IllegalStateException(\"Cannot start the HTTP service \"\n + serviceName + \" because it was failed earlier\");\n }\n\n try {\n LOG.info(\"Starting HTTP Service {} at address {}\", serviceName, bindAddress);\n channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);\n resourceHandler.init(handlerContext);\n eventExecutorGroup = createEventExecutorGroup(execThreadPoolSize);\n bootstrap = createBootstrap(channelGroup);\n Channel serverChannel = bootstrap.bind(bindAddress).sync().channel();\n channelGroup.add(serverChannel);\n\n bindAddress = (InetSocketAddress) serverChannel.localAddress();\n\n LOG.debug(\"Started HTTP Service {} at address {}\", serviceName, bindAddress);\n state = State.RUNNING;\n } catch (Throwable t) {\n // Release resources if there is any failure\n channelGroup.close().awaitUninterruptibly();\n try {\n if (bootstrap != null) {\n shutdownExecutorGroups(0, 5, TimeUnit.SECONDS,\n bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup);\n } else {\n shutdownExecutorGroups(0, 5, TimeUnit.SECONDS, eventExecutorGroup);\n }\n } catch (Throwable t2) {\n t.addSuppressed(t2);\n }\n state = State.FAILED;\n throw t;\n }\n }" ]
[ "private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef)\r\n {\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName());\r\n\r\n if ((curCollDef != null) &&\r\n !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "void reset()\n {\n if (!hasStopped)\n {\n throw new IllegalStateException(\"cannot reset a non stopped queue poller\");\n }\n hasStopped = false;\n run = true;\n lastLoop = null;\n loop = new Semaphore(0);\n }", "public static String pad(String str, int totalChars) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int slen = str.length();\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < totalChars - slen; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n }", "public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) {\n return Filter.newBuilder()\n .setCompositeFilter(CompositeFilter.newBuilder()\n .addAllFilters(subfilters)\n .setOp(CompositeFilter.Operator.AND));\n }", "public Info getInfo() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }", "public static DMatrixSparseCSC convert(DMatrixSparseTriplet src , DMatrixSparseCSC dst , int hist[] ) {\n if( dst == null )\n dst = new DMatrixSparseCSC(src.numRows, src.numCols , src.nz_length);\n else\n dst.reshape(src.numRows, src.numCols, src.nz_length);\n\n if( hist == null )\n hist = new int[ src.numCols ];\n else if( hist.length >= src.numCols )\n Arrays.fill(hist,0,src.numCols, 0);\n else\n throw new IllegalArgumentException(\"Length of hist must be at least numCols\");\n\n // compute the number of elements in each columns\n for (int i = 0; i < src.nz_length; i++) {\n hist[src.nz_rowcol.data[i*2+1]]++;\n }\n\n // define col_idx\n dst.histogramToStructure(hist);\n System.arraycopy(dst.col_idx,0,hist,0,dst.numCols);\n\n // now write the row indexes and the values\n for (int i = 0; i < src.nz_length; i++) {\n int row = src.nz_rowcol.data[i*2];\n int col = src.nz_rowcol.data[i*2+1];\n double value = src.nz_value.data[i];\n\n int index = hist[col]++;\n dst.nz_rows[index] = row;\n dst.nz_values[index] = value;\n }\n dst.indicesSorted = false;\n\n return dst;\n }", "public void addDefaultCalendarHours(Day day)\n {\n ProjectCalendarHours hours = addCalendarHours(day);\n\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n hours.addRange(DEFAULT_WORKING_MORNING);\n hours.addRange(DEFAULT_WORKING_AFTERNOON);\n }\n }", "public void growInternal(int amount ) {\n int tmp[] = new int[ data.length + amount ];\n\n System.arraycopy(data,0,tmp,0,data.length);\n this.data = tmp;\n }", "public String tag(ImapRequestLineReader request) throws ProtocolException {\n CharacterValidator validator = new TagCharValidator();\n return consumeWord(request, validator);\n }" ]
Find a Constructor on the given type that matches the given arguments. @param <T> the object type @param clazz the type to create @param args the arguments to the constructor @return a Constructor from the given type that matches the given arguments @throws NoSuchConstructorException if there is not a constructor that matches the given arguments @throws AmbiguousConstructorException if there is more than one constructor that matches the given arguments
[ "@SuppressWarnings(\"rawtypes\")\n private static <T> Constructor<T> findConstructor(final Class<T> clazz, final Object... args)\n throws NoSuchConstructorException, AmbiguousConstructorException {\n final Object[] cArgs = (args == null) ? new Object[0] : args;\n Constructor<T> constructorToUse = null;\n final Constructor<?>[] candidates = clazz.getConstructors();\n Arrays.sort(candidates, ConstructorComparator.INSTANCE);\n int minTypeDiffWeight = Integer.MAX_VALUE;\n Set<Constructor<?>> ambiguousConstructors = null;\n for (final Constructor candidate : candidates) {\n final Class[] paramTypes = candidate.getParameterTypes();\n if (constructorToUse != null && cArgs.length > paramTypes.length) {\n // Already found greedy constructor that can be satisfied.\n // Do not look any further, there are only less greedy\n // constructors left.\n break;\n }\n if (paramTypes.length != cArgs.length) {\n continue;\n }\n final int typeDiffWeight = getTypeDifferenceWeight(paramTypes, cArgs);\n if (typeDiffWeight < minTypeDiffWeight) { \n // Choose this constructor if it represents the closest match.\n constructorToUse = candidate;\n minTypeDiffWeight = typeDiffWeight;\n ambiguousConstructors = null;\n } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {\n if (ambiguousConstructors == null) {\n ambiguousConstructors = new LinkedHashSet<Constructor<?>>();\n ambiguousConstructors.add(constructorToUse);\n }\n ambiguousConstructors.add(candidate);\n }\n }\n if (ambiguousConstructors != null && !ambiguousConstructors.isEmpty()) {\n throw new AmbiguousConstructorException(clazz, cArgs, ambiguousConstructors);\n }\n if (constructorToUse == null) {\n throw new NoSuchConstructorException(clazz, cArgs);\n }\n return constructorToUse;\n }" ]
[ "private void persistDisabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n try {\n disabledMarker.createNewFile();\n } catch (IOException e) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain disabled only until the next restart.\", e);\n }\n }", "public static base_responses update(nitro_service client, responderpolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tresponderpolicy updateresources[] = new responderpolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new responderpolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].undefaction = resources[i].undefaction;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].logaction = resources[i].logaction;\n\t\t\t\tupdateresources[i].appflowaction = resources[i].appflowaction;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "public Map<String, CmsCategory> getReadCategory() {\n\n if (null == m_categories) {\n m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object categoryPath) {\n\n try {\n CmsCategoryService catService = CmsCategoryService.getInstance();\n return catService.localizeCategory(\n m_cms,\n catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()),\n m_cms.getRequestContext().getLocale());\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_categories;\n }", "public IndexDescriptorDef getIndexDescriptor(String name)\r\n {\r\n IndexDescriptorDef indexDef = null;\r\n\r\n for (Iterator it = _indexDescriptors.iterator(); it.hasNext(); )\r\n {\r\n indexDef = (IndexDescriptorDef)it.next();\r\n if (indexDef.getName().equals(name))\r\n {\r\n return indexDef;\r\n }\r\n }\r\n return null;\r\n }", "private String formatRelationList(List<Relation> value)\n {\n String result = null;\n\n if (value != null && value.size() != 0)\n {\n StringBuilder sb = new StringBuilder();\n for (Relation relation : value)\n {\n if (sb.length() != 0)\n {\n sb.append(m_delimiter);\n }\n\n sb.append(formatRelation(relation));\n }\n\n result = sb.toString();\n }\n\n return (result);\n }", "public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }", "public static void requireNamespace(final XMLExtendedStreamReader reader, final Namespace requiredNs) throws XMLStreamException {\n Namespace actualNs = Namespace.forUri(reader.getNamespaceURI());\n if (actualNs != requiredNs) {\n throw unexpectedElement(reader);\n }\n }", "static JndiContext createJndiContext() throws NamingException\n {\n try\n {\n if (!NamingManager.hasInitialContextFactoryBuilder())\n {\n JndiContext ctx = new JndiContext();\n NamingManager.setInitialContextFactoryBuilder(ctx);\n return ctx;\n }\n else\n {\n return (JndiContext) NamingManager.getInitialContext(null);\n }\n }\n catch (Exception e)\n {\n jqmlogger.error(\"Could not create JNDI context: \" + e.getMessage());\n NamingException ex = new NamingException(\"Could not initialize JNDI Context\");\n ex.setRootCause(e);\n throw ex;\n }\n }" ]
Instantiates an instance of input Java shader class, which must be derived from GVRShader or GVRShaderTemplate. @param id Java class which implements shaders of this type. @param ctx GVRContext shader belongs to @return GVRShader subclass which implements this shader type
[ "GVRShader makeTemplate(Class<? extends GVRShader> id, GVRContext ctx)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor(GVRContext.class);\n return maker.newInstance(ctx);\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex)\n {\n try\n {\n Constructor<? extends GVRShader> maker = id.getDeclaredConstructor();\n return maker.newInstance();\n }\n catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex2)\n {\n ctx.getEventManager().sendEvent(ctx, IErrorEvents.class, \"onError\", new Object[] {ex2.getMessage(), this});\n return null;\n }\n }\n }" ]
[ "public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}", "private void calcCurrentItem() {\n int pointerAngle;\n\n // calculate the correct pointer angle, depending on clockwise drawing or not\n if(mOpenClockwise) {\n pointerAngle = (mIndicatorAngle + 360 - mPieRotation) % 360;\n }\n else {\n pointerAngle = (mIndicatorAngle + 180 + mPieRotation) % 360;\n }\n\n for (int i = 0; i < mPieData.size(); ++i) {\n PieModel model = mPieData.get(i);\n if (model.getStartAngle() <= pointerAngle && pointerAngle <= model.getEndAngle()) {\n if (i != mCurrentItem) {\n setCurrentItem(i, false);\n }\n break;\n }\n }\n }", "public ReferenceDescriptorDef getReference(String name)\r\n {\r\n ReferenceDescriptorDef refDef;\r\n\r\n for (Iterator it = _references.iterator(); it.hasNext(); )\r\n {\r\n refDef = (ReferenceDescriptorDef)it.next();\r\n if (refDef.getName().equals(name))\r\n {\r\n return refDef;\r\n }\r\n }\r\n return null;\r\n }", "public static RelationType getInstance(Locale locale, String type)\n {\n int index = -1;\n\n String[] relationTypes = LocaleData.getStringArray(locale, LocaleData.RELATION_TYPES);\n for (int loop = 0; loop < relationTypes.length; loop++)\n {\n if (relationTypes[loop].equalsIgnoreCase(type) == true)\n {\n index = loop;\n break;\n }\n }\n\n RelationType result = null;\n if (index != -1)\n {\n result = RelationType.getInstance(index);\n }\n\n return (result);\n }", "public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) {\n return rootDir.listFiles(new FileFilter() {\n\n public boolean accept(File pathName) {\n if(checkVersionDirName(pathName)) {\n long versionId = getVersionId(pathName);\n if(versionId != -1 && versionId <= maxId && versionId >= minId) {\n return true;\n }\n }\n return false;\n }\n });\n }", "public String getSearchJsonModel() throws IOException {\n DbSearch search = new DbSearch();\n search.setArtifacts(new ArrayList<>());\n search.setModules(new ArrayList<>());\n return JsonUtils.serialize(search);\n }", "protected Container findContainer(ContainerContext ctx, StringBuilder dump) {\n Container container = null;\n // 1. Custom container class\n String containerClassName = ctx.getServletContext().getInitParameter(Container.CONTEXT_PARAM_CONTAINER_CLASS);\n if (containerClassName != null) {\n try {\n Class<Container> containerClass = Reflections.classForName(resourceLoader, containerClassName);\n container = SecurityActions.newInstance(containerClass);\n WeldServletLogger.LOG.containerDetectionSkipped(containerClassName);\n } catch (Exception e) {\n WeldServletLogger.LOG.unableToInstantiateCustomContainerClass(containerClassName);\n WeldServletLogger.LOG.catchingDebug(e);\n }\n }\n if (container == null) {\n // 2. Service providers\n Iterable<Container> extContainers = ServiceLoader.load(Container.class, getClass().getClassLoader());\n container = checkContainers(ctx, dump, extContainers);\n if (container == null) {\n // 3. Built-in containers in predefined order\n container = checkContainers(ctx, dump,\n Arrays.asList(TomcatContainer.INSTANCE, JettyContainer.INSTANCE, UndertowContainer.INSTANCE, GwtDevHostedModeContainer.INSTANCE));\n }\n }\n return container;\n }", "public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }", "@SuppressWarnings(\"unused\")\n private void setTextureNumber(int type, int number) {\n m_numTextures.put(AiTextureType.fromRawValue(type), number);\n }" ]
Abort and close the transaction. Calling abort abandons all persistent object modifications and releases the associated locks. Aborting a transaction does not restore the state of modified transient objects
[ "public void abort()\r\n {\r\n /*\r\n do nothing if already rolledback\r\n */\r\n if (txStatus == Status.STATUS_NO_TRANSACTION\r\n || txStatus == Status.STATUS_UNKNOWN\r\n || txStatus == Status.STATUS_ROLLEDBACK)\r\n {\r\n log.info(\"Nothing to abort, tx is not active - status is \" + TxUtil.getStatusString(txStatus));\r\n return;\r\n }\r\n // check status of tx\r\n if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED &&\r\n txStatus != Status.STATUS_MARKED_ROLLBACK)\r\n {\r\n throw new IllegalStateException(\"Illegal state for abort call, state was '\" + TxUtil.getStatusString(txStatus) + \"'\");\r\n }\r\n if(log.isEnabledFor(Logger.INFO))\r\n {\r\n log.info(\"Abort transaction was called on tx \" + this);\r\n }\r\n try\r\n {\r\n try\r\n {\r\n doAbort();\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while abort transaction, will be skipped\", e);\r\n }\r\n\r\n // used in managed environments, ignored in non-managed\r\n this.implementation.getTxManager().abortExternalTx(this);\r\n\r\n try\r\n {\r\n if(hasBroker() && getBroker().isInTransaction())\r\n {\r\n getBroker().abortTransaction();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while do abort used broker instance, will be skipped\", e);\r\n }\r\n }\r\n finally\r\n {\r\n txStatus = Status.STATUS_ROLLEDBACK;\r\n // cleanup things, e.g. release all locks\r\n doClose();\r\n }\r\n }" ]
[ "@SuppressWarnings(\"unchecked\") private Object formatType(DataType type, Object value)\n {\n switch (type)\n {\n case DATE:\n {\n value = formatDateTime(value);\n break;\n }\n\n case CURRENCY:\n {\n value = formatCurrency((Number) value);\n break;\n }\n\n case UNITS:\n {\n value = formatUnits((Number) value);\n break;\n }\n\n case PERCENTAGE:\n {\n value = formatPercentage((Number) value);\n break;\n }\n\n case ACCRUE:\n {\n value = formatAccrueType((AccrueType) value);\n break;\n }\n\n case CONSTRAINT:\n {\n value = formatConstraintType((ConstraintType) value);\n break;\n }\n\n case WORK:\n case DURATION:\n {\n value = formatDuration(value);\n break;\n }\n\n case RATE:\n {\n value = formatRate((Rate) value);\n break;\n }\n\n case PRIORITY:\n {\n value = formatPriority((Priority) value);\n break;\n }\n\n case RELATION_LIST:\n {\n value = formatRelationList((List<Relation>) value);\n break;\n }\n\n case TASK_TYPE:\n {\n value = formatTaskType((TaskType) value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return (value);\n }", "@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }", "public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }", "protected void layoutChild(final int dataIndex) {\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n float offset = mOffset.get(Axis.X);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.X, offset);\n }\n\n offset = mOffset.get(Axis.Y);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Y, offset);\n }\n\n offset = mOffset.get(Axis.Z);\n if (!equal(offset, 0)) {\n updateTransform(child, Axis.Z, offset);\n }\n }\n }", "private static LogType findLogType() {\n\n\t\t// see if the log-type was specified as a system property\n\t\tString logTypeString = System.getProperty(LOG_TYPE_SYSTEM_PROPERTY);\n\t\tif (logTypeString != null) {\n\t\t\ttry {\n\t\t\t\treturn LogType.valueOf(logTypeString);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tLog log = new LocalLog(LoggerFactory.class.getName());\n\t\t\t\tlog.log(Level.WARNING, \"Could not find valid log-type from system property '\" + LOG_TYPE_SYSTEM_PROPERTY\n\t\t\t\t\t\t+ \"', value '\" + logTypeString + \"'\");\n\t\t\t}\n\t\t}\n\n\t\tfor (LogType logType : LogType.values()) {\n\t\t\tif (logType.isAvailable()) {\n\t\t\t\treturn logType;\n\t\t\t}\n\t\t}\n\t\t// fall back is always LOCAL, never reached\n\t\treturn LogType.LOCAL;\n\t}", "protected Map<String, String> getGalleryOpenParams(\n CmsObject cms,\n CmsMessages messages,\n I_CmsWidgetParameter param,\n String resource,\n long hashId) {\n\n Map<String, String> result = new HashMap<String, String>();\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, A_CmsAjaxGallery.MODE_WIDGET);\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_STORAGE_PREFIX, getGalleryStoragePrefix());\n result.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, getGalleryTypes());\n if (param.getId() != null) {\n result.put(I_CmsGalleryProviderConstants.KEY_FIELD_ID, param.getId());\n // use javascript to read the current field value\n result.put(\n I_CmsGalleryProviderConstants.CONFIG_CURRENT_ELEMENT,\n \"'+document.getElementById('\" + param.getId() + \"').getAttribute('value')+'\");\n }\n result.put(I_CmsGalleryProviderConstants.KEY_HASH_ID, \"\" + hashId);\n // the edited resource\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resource)) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, resource);\n }\n // the start up gallery path\n CmsGalleryWidgetConfiguration configuration = getWidgetConfiguration(cms, messages, param);\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getStartup())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_PATH, configuration.getStartup());\n }\n // set gallery types if available\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration.getGalleryTypes())) {\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_TYPES, configuration.getGalleryTypes());\n }\n result.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_NAME, getGalleryName());\n return result;\n }", "private static void throwFault(String code, String message, Throwable t) throws PutEventsFault {\n if (LOG.isLoggable(Level.SEVERE)) {\n LOG.log(Level.SEVERE, \"Throw Fault \" + code + \" \" + message, t);\n }\n\n FaultType faultType = new FaultType();\n faultType.setFaultCode(code);\n faultType.setFaultMessage(message);\n\n StringWriter stringWriter = new StringWriter();\n PrintWriter printWriter = new PrintWriter(stringWriter);\n\n t.printStackTrace(printWriter);\n\n faultType.setStackTrace(stringWriter.toString());\n\n throw new PutEventsFault(message, faultType, t);\n }", "public DateTimeZone getZone(String id) {\n if (id == null) {\n return null;\n }\n\n Object obj = iZoneInfoMap.get(id);\n if (obj == null) {\n return null;\n }\n\n if (id.equals(obj)) {\n // Load zone data for the first time.\n return loadZoneData(id);\n }\n\n if (obj instanceof SoftReference<?>) {\n @SuppressWarnings(\"unchecked\")\n SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;\n DateTimeZone tz = ref.get();\n if (tz != null) {\n return tz;\n }\n // Reference cleared; load data again.\n return loadZoneData(id);\n }\n\n // If this point is reached, mapping must link to another.\n return getZone((String) obj);\n }", "public double getBearing(LatLong end) {\n if (this.equals(end)) {\n return 0;\n }\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n double lat2 = end.latToRadians();\n double lon2 = end.longToRadians();\n\n double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),\n Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)\n * Math.cos(lat2) * Math.cos(lon1 - lon2));\n\n if (angle < 0.0) {\n angle += Math.PI * 2.0;\n }\n if (angle > Math.PI) {\n angle -= Math.PI * 2.0;\n }\n\n return Math.toDegrees(angle);\n }" ]
Given a list of store definitions return a list of store names @param storeDefList The list of store definitions @return Returns a list of store names
[ "public static List<String> getStoreNames(List<StoreDefinition> storeDefList) {\n List<String> storeList = new ArrayList<String>();\n for(StoreDefinition def: storeDefList) {\n storeList.add(def.getName());\n }\n return storeList;\n }" ]
[ "public Feature toDto(InternalFeature feature, int featureIncludes) throws GeomajasException {\n\t\tif (feature == null) {\n\t\t\treturn null;\n\t\t}\n\t\tFeature dto = new Feature(feature.getId());\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES) != 0 && null != feature.getAttributes()) {\n\t\t\t// need to assure lazy attributes are converted to non-lazy attributes\n\t\t\tMap<String, Attribute> attributes = new HashMap<String, Attribute>();\n\t\t\tfor (Map.Entry<String, Attribute> entry : feature.getAttributes().entrySet()) {\n\t\t\t\tAttribute value = entry.getValue();\n\t\t\t\tif (value instanceof LazyAttribute) {\n\t\t\t\t\tvalue = ((LazyAttribute) value).instantiate();\n\t\t\t\t}\n\t\t\t\tattributes.put(entry.getKey(), value);\n\t\t\t}\n\t\t\tdto.setAttributes(attributes);\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_LABEL) != 0) {\n\t\t\tdto.setLabel(feature.getLabel());\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_GEOMETRY) != 0) {\n\t\t\tdto.setGeometry(toDto(feature.getGeometry()));\n\t\t}\n\t\tif ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_STYLE) != 0 && null != feature.getStyleInfo()) {\n\t\t\tdto.setStyleId(feature.getStyleInfo().getStyleId());\n\t\t}\n\t\tInternalFeatureImpl vFeature = (InternalFeatureImpl) feature;\n\t\tdto.setClipped(vFeature.isClipped());\n\t\tdto.setUpdatable(feature.isEditable());\n\t\tdto.setDeletable(feature.isDeletable());\n\t\treturn dto;\n\t}", "protected void updateFontTable()\n {\n PDResources resources = pdpage.getResources();\n if (resources != null)\n {\n try\n {\n processFontResources(resources, fontTable);\n } catch (IOException e) {\n log.error(\"Error processing font resources: \"\n + \"Exception: {} {}\", e.getMessage(), e.getClass());\n }\n }\n }", "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }", "public int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedRefresh == null) {\n\t\t\tmappedRefresh = MappedRefresh.build(dao, tableInfo);\n\t\t}\n\t\treturn mappedRefresh.executeRefresh(databaseConnection, data, objectCache);\n\t}", "public Rectangle toRelative(Rectangle rect) {\n\t\treturn new Rectangle(rect.getLeft() - origX, rect.getBottom() - origY, rect.getRight() - origX, rect.getTop()\n\t\t\t\t- origY);\n\t}", "public static vpnglobal_binding get(nitro_service service) throws Exception{\n\t\tvpnglobal_binding obj = new vpnglobal_binding();\n\t\tvpnglobal_binding response = (vpnglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private String getIntegerString(Number value)\n {\n return (value == null ? null : Integer.toString(value.intValue()));\n }", "public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}", "public byte[] getByteArrayValue(int index)\n {\n byte[] result = null;\n\n if (m_array[index] != null)\n {\n result = (byte[]) m_array[index];\n }\n\n return (result);\n }" ]
Return primary key values of given Identity object. @param cld @param oid @return Object[] @throws PersistenceBrokerException
[ "public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, oid, true);\r\n }" ]
[ "void pumpEvents(InputStream eventStream) {\n try {\n Deserializer deserializer = new Deserializer(eventStream, refLoader);\n\n IEvent event = null;\n while ((event = deserializer.deserialize()) != null) {\n switch (event.getType()) {\n case APPEND_STDERR:\n case APPEND_STDOUT:\n // Ignore these two on activity heartbeats. GH-117\n break;\n default:\n lastActivity = System.currentTimeMillis();\n break;\n }\n\n try {\n switch (event.getType()) {\n case QUIT:\n eventBus.post(event);\n return;\n\n case IDLE:\n eventBus.post(new SlaveIdle(stdinWriter));\n break;\n\n case BOOTSTRAP:\n clientCharset = Charset.forName(((BootstrapEvent) event).getDefaultCharsetName());\n stdinWriter = new OutputStreamWriter(stdin, clientCharset);\n eventBus.post(event);\n break;\n\n case APPEND_STDERR:\n case APPEND_STDOUT:\n assert streamsBuffer.getFilePointer() == streamsBuffer.length();\n final long bufferStart = streamsBuffer.getFilePointer();\n IStreamEvent streamEvent = (IStreamEvent) event;\n streamEvent.copyTo(streamsBufferWrapper);\n final long bufferEnd = streamsBuffer.getFilePointer();\n\n event = new OnDiskStreamEvent(event.getType(), streamsBuffer, bufferStart, bufferEnd);\n eventBus.post(event);\n break;\n \n default:\n eventBus.post(event);\n }\n } catch (Throwable t) {\n warnStream.println(\"Event bus dispatch error: \" + t.toString());\n t.printStackTrace(warnStream);\n }\n }\n lastActivity = null;\n } catch (Throwable e) {\n if (!stopping) {\n warnStream.println(\"Event stream error: \" + e.toString());\n e.printStackTrace(warnStream);\n }\n }\n }", "<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) {\n return handlers.get(artifact);\n }", "private <T> void requestAsync(ClientRequest<T> delegate,\n NonblockingStoreCallback callback,\n long timeoutMs,\n String operationName) {\n pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName);\n }", "private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }", "public final void setVolumeByIncrement(float level) throws IOException {\n Volume volume = this.getStatus().volume;\n float total = volume.level;\n\n if (volume.increment <= 0f) {\n throw new ChromeCastException(\"Volume.increment is <= 0\");\n }\n\n // With floating points we always have minor decimal variations, using the Math.min/max\n // works around this issue\n // Increase volume\n if (level > total) {\n while (total < level) {\n total = Math.min(total + volume.increment, level);\n setVolume(total);\n }\n // Decrease Volume\n } else if (level < total) {\n while (total > level) {\n total = Math.max(total - volume.increment, level);\n setVolume(total);\n }\n }\n }", "public static List<DesignDocument> fromDirectory(File directory) throws FileNotFoundException {\r\n List<DesignDocument> designDocuments = new ArrayList<DesignDocument>();\r\n if (directory.isDirectory()) {\r\n Collection<File> files = FileUtils.listFiles(directory, null, true);\r\n for (File designDocFile : files) {\r\n designDocuments.add(fromFile(designDocFile));\r\n }\r\n } else {\r\n designDocuments.add(fromFile(directory));\r\n }\r\n return designDocuments;\r\n }", "public Operation.Info create( char op , Variable input ) {\n switch( op ) {\n case '\\'':\n return Operation.transpose(input, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }", "@Override\n public void close() {\n status = TrStatus.CLOSED;\n try {\n node.close();\n } catch (IOException e) {\n log.error(\"Failed to close ephemeral node\");\n throw new IllegalStateException(e);\n }\n }", "public final void visitChildren(final Visitor visitor)\n\t{\n\t\tfor (final DiffNode child : children.values())\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tchild.visit(visitor);\n\t\t\t}\n\t\t\tcatch (final StopVisitationException e)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}" ]
Creates the server bootstrap.
[ "private ServerBootstrap createBootstrap(final ChannelGroup channelGroup) throws Exception {\n EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-boss-thread-%d\"));\n EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-worker-thread-%d\"));\n ServerBootstrap bootstrap = new ServerBootstrap();\n bootstrap\n .group(bossGroup, workerGroup)\n .channel(NioServerSocketChannel.class)\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) throws Exception {\n channelGroup.add(ch);\n\n ChannelPipeline pipeline = ch.pipeline();\n if (sslHandlerFactory != null) {\n // Add SSLHandler if SSL is enabled\n pipeline.addLast(\"ssl\", sslHandlerFactory.create(ch.alloc()));\n }\n pipeline.addLast(\"codec\", new HttpServerCodec());\n pipeline.addLast(\"compressor\", new HttpContentCompressor());\n pipeline.addLast(\"chunkedWriter\", new ChunkedWriteHandler());\n pipeline.addLast(\"keepAlive\", new HttpServerKeepAliveHandler());\n pipeline.addLast(\"router\", new RequestRouter(resourceHandler, httpChunkLimit, sslHandlerFactory != null));\n if (eventExecutorGroup == null) {\n pipeline.addLast(\"dispatcher\", new HttpDispatcher());\n } else {\n pipeline.addLast(eventExecutorGroup, \"dispatcher\", new HttpDispatcher());\n }\n\n if (pipelineModifier != null) {\n pipelineModifier.modify(pipeline);\n }\n }\n });\n\n for (Map.Entry<ChannelOption, Object> entry : channelConfigs.entrySet()) {\n bootstrap.option(entry.getKey(), entry.getValue());\n }\n for (Map.Entry<ChannelOption, Object> entry : childChannelConfigs.entrySet()) {\n bootstrap.childOption(entry.getKey(), entry.getValue());\n }\n\n return bootstrap;\n }" ]
[ "public void finishFlow(final String code, final String state) throws ApiException {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (codeVerifier == null)\n throw new IllegalArgumentException(\"code_verifier is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(\"grant_type=\");\n builder.append(encode(\"authorization_code\"));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&code=\");\n builder.append(encode(code));\n builder.append(\"&code_verifier=\");\n builder.append(encode(codeVerifier));\n update(account, builder.toString());\n }", "public OJBLock atomicGetOrCreateLock(Object resourceId, Object isolationId)\r\n {\r\n synchronized(globalLocks)\r\n {\r\n MultiLevelLock lock = getLock(resourceId);\r\n if(lock == null)\r\n {\r\n lock = createLock(resourceId, isolationId);\r\n }\r\n return (OJBLock) lock;\r\n }\r\n }", "@SuppressWarnings(\"unchecked\")\n public void setHeaders(final Map<String, Object> headers) {\n this.headers.clear();\n for (Map.Entry<String, Object> entry: headers.entrySet()) {\n if (entry.getValue() instanceof List) {\n List value = (List) entry.getValue();\n // verify they are all strings\n for (Object o: value) {\n Assert.isTrue(o instanceof String, o + \" is not a string it is a: '\" +\n o.getClass() + \"'\");\n }\n this.headers.put(entry.getKey(), (List<String>) entry.getValue());\n } else if (entry.getValue() instanceof String) {\n final List<String> value = Collections.singletonList((String) entry.getValue());\n this.headers.put(entry.getKey(), value);\n } else {\n throw new IllegalArgumentException(\"Only strings and list of strings may be headers\");\n }\n }\n }", "private List<CmsResource> getDetailContainerResources(CmsObject cms, CmsResource res) throws CmsException {\n\n CmsRelationFilter filter = CmsRelationFilter.relationsFromStructureId(res.getStructureId()).filterType(\n CmsRelationType.DETAIL_ONLY);\n List<CmsResource> result = Lists.newArrayList();\n List<CmsRelation> relations = cms.readRelations(filter);\n for (CmsRelation relation : relations) {\n try {\n result.add(relation.getTarget(cms, CmsResourceFilter.ALL));\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return result;\n }", "@Override\n protected void initBuilderSpecific() throws Exception {\n reset();\n FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);\n FilePath gradlePropertiesPath = new FilePath(workspace, \"gradle.properties\");\n if (releaseProps == null) {\n releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());\n }\n if (nextIntegProps == null) {\n nextIntegProps =\n PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());\n }\n }", "public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }", "public ParallelTaskBuilder setSshPassword(String password) {\n this.sshMeta.setPassword(password);\n this.sshMeta.setSshLoginType(SshLoginType.PASSWORD);\n return this;\n }", "private <T> void requestAsync(ClientRequest<T> delegate,\n NonblockingStoreCallback callback,\n long timeoutMs,\n String operationName) {\n pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName);\n }", "public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Used to create a new retention policy with optional parameters. @param api the API connection to be used by the created user. @param name the name of the retention policy. @param type the type of the retention policy. Can be "finite" or "indefinite". @param length the duration in days that the retention policy will be active for after being assigned to content. @param action the disposition action can be "permanently_delete" or "remove_retention". @param optionalParams the optional parameters. @return the created retention policy's info.
[ "private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action,\r\n RetentionPolicyParams optionalParams) {\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_name\", name)\r\n .add(\"policy_type\", type)\r\n .add(\"disposition_action\", action);\r\n if (!type.equals(TYPE_INDEFINITE)) {\r\n requestJSON.add(\"retention_length\", length);\r\n }\r\n if (optionalParams != null) {\r\n requestJSON.add(\"can_owner_extend_retention\", optionalParams.getCanOwnerExtendRetention());\r\n requestJSON.add(\"are_owners_notified\", optionalParams.getAreOwnersNotified());\r\n\r\n List<BoxUser.Info> customNotificationRecipients = optionalParams.getCustomNotificationRecipients();\r\n if (customNotificationRecipients.size() > 0) {\r\n JsonArray users = new JsonArray();\r\n for (BoxUser.Info user : customNotificationRecipients) {\r\n JsonObject userJSON = new JsonObject()\r\n .add(\"type\", \"user\")\r\n .add(\"id\", user.getID());\r\n users.add(userJSON);\r\n }\r\n requestJSON.add(\"custom_notification_recipients\", users);\r\n }\r\n }\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicy createdPolicy = new BoxRetentionPolicy(api, responseJSON.get(\"id\").asString());\r\n return createdPolicy.new Info(responseJSON);\r\n }" ]
[ "public double multi8p(int x, int y, double masc) {\n int aR = getIntComponent0(x - 1, y - 1);\n int bR = getIntComponent0(x - 1, y);\n int cR = getIntComponent0(x - 1, y + 1);\n int aG = getIntComponent1(x - 1, y - 1);\n int bG = getIntComponent1(x - 1, y);\n int cG = getIntComponent1(x - 1, y + 1);\n int aB = getIntComponent1(x - 1, y - 1);\n int bB = getIntComponent1(x - 1, y);\n int cB = getIntComponent1(x - 1, y + 1);\n\n\n int dR = getIntComponent0(x, y - 1);\n int eR = getIntComponent0(x, y);\n int fR = getIntComponent0(x, y + 1);\n int dG = getIntComponent1(x, y - 1);\n int eG = getIntComponent1(x, y);\n int fG = getIntComponent1(x, y + 1);\n int dB = getIntComponent1(x, y - 1);\n int eB = getIntComponent1(x, y);\n int fB = getIntComponent1(x, y + 1);\n\n\n int gR = getIntComponent0(x + 1, y - 1);\n int hR = getIntComponent0(x + 1, y);\n int iR = getIntComponent0(x + 1, y + 1);\n int gG = getIntComponent1(x + 1, y - 1);\n int hG = getIntComponent1(x + 1, y);\n int iG = getIntComponent1(x + 1, y + 1);\n int gB = getIntComponent1(x + 1, y - 1);\n int hB = getIntComponent1(x + 1, y);\n int iB = getIntComponent1(x + 1, y + 1);\n\n double rgb = 0;\n\n rgb = ((aR * masc) + (bR * masc) + (cR * masc) +\n (dR * masc) + (eR * masc) + (fR * masc) +\n (gR * masc) + (hR * masc) + (iR * masc));\n\n return (rgb);\n\n }", "public boolean classifyDocumentStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n int blankLines = 0;\r\n while ((line = is.readLine()) != null) {\r\n if (line.trim().equals(\"\")) {\r\n \t ++blankLines;\r\n \t if (blankLines > 3) {\r\n \t\t return false;\r\n \t } else if (blankLines > 2) {\r\n\t\t\t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n\t \t classifyAndWriteAnswers(documents, readerWriter);\r\n \t\t text = \"\";\r\n \t } else {\r\n \t\t text += sentence + eol;\r\n \t }\r\n } else {\r\n \t text += line + eol;\r\n \t blankLines = 0;\r\n }\r\n }\r\n // Classify last document before input stream end\r\n if (text.trim() != \"\") {\r\n ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n \t classifyAndWriteAnswers(documents, readerWriter);\r\n }\r\n return (line == null); // reached eol\r\n }", "public boolean isExit() {\n if (currentRow > finalRow) { //request new block of work\n String newBlock = this.sendRequestSync(\"this/request/block\");\n LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0);\n\n if (newBlock.contains(\"exit\")) {\n getExitFlag().set(true);\n makeReport(true);\n return true;\n } else {\n block.buildFromResponse(newBlock);\n }\n\n currentRow = block.getStart();\n finalRow = block.getStop();\n } else { //report the number of lines written\n makeReport(false);\n\n if (exit.get()) {\n getExitFlag().set(true);\n return true;\n }\n }\n\n return false;\n }", "public static <T> NewSessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager) {\n EnhancedAnnotatedType<T> type = beanManager.getServices().get(ClassTransformer.class).getEnhancedAnnotatedType(ejbDescriptor.getBeanClass(), beanManager.getId());\n return new NewSessionBean<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifierForNew(ejbDescriptor)), beanManager);\n }", "public void readFrom(DataInput instream) throws Exception {\n host = S3Util.readString(instream);\n port = instream.readInt();\n protocol = S3Util.readString(instream);\n }", "public void addFkToItemClass(String column)\r\n {\r\n if (fksToItemClass == null)\r\n {\r\n fksToItemClass = new Vector();\r\n }\r\n fksToItemClass.add(column);\r\n fksToItemClassAry = null;\r\n }", "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }", "private static double pointsDistance(Point a, Point b) {\n int dx = b.x - a.x;\n int dy = b.y - a.y;\n return Math.sqrt(dx * dx + dy * dy);\n }", "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }" ]
Adds OPT_J | OPT_JSON option to OptionParser, with multiple arguments. @param parser OptionParser to be modified @param required Tells if this option is required or optional
[ "public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }" ]
[ "private void deleteUnusedCaseSteps( ReportModel model ) {\n\n for( ScenarioModel scenarioModel : model.getScenarios() ) {\n if( scenarioModel.isCasesAsTable() && !hasAttachment( scenarioModel ) ) {\n List<ScenarioCaseModel> cases = scenarioModel.getScenarioCases();\n for( int i = 1; i < cases.size(); i++ ) {\n ScenarioCaseModel caseModel = cases.get( i );\n caseModel.setSteps( Collections.<StepModel>emptyList() );\n }\n }\n }\n }", "public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {\r\n for (String name : names) {\r\n if (hasAnnotation(node, name)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public DbProduct getProduct(final String name) {\n final DbProduct dbProduct = repositoryHandler.getProduct(name);\n\n if(dbProduct == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Product \" + name + \" does not exist.\").build());\n }\n\n return dbProduct;\n }", "synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }", "protected boolean isSavedConnection(DatabaseConnection connection) {\n\t\tNestedConnection currentSaved = specialConnection.get();\n\t\tif (currentSaved == null) {\n\t\t\treturn false;\n\t\t} else if (currentSaved.connection == connection) {\n\t\t\t// ignore the release when we have a saved connection\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "public static void hideOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.showAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }", "@Override\r\n public V put(K key, V value) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.put(key, value);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.put(key, value));\r\n }\r\n }\r\n }", "public void bindDelete(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws SQLException\r\n {\r\n if (cld.getDeleteProcedure() != null)\r\n {\r\n this.bindProcedure(stmt, cld, obj, cld.getDeleteProcedure());\r\n }\r\n else\r\n {\r\n int index = 1;\r\n ValueContainer[] values, currentLockingValues;\r\n\r\n currentLockingValues = cld.getCurrentLockingValues(obj);\r\n // parameters for WHERE-clause pk\r\n values = getKeyValues(m_broker, cld, obj);\r\n for (int i = 0; i < values.length; i++)\r\n {\r\n setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());\r\n index++;\r\n }\r\n\r\n // parameters for WHERE-clause locking\r\n values = currentLockingValues;\r\n for (int i = 0; i < values.length; i++)\r\n {\r\n setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());\r\n index++;\r\n }\r\n }\r\n }", "private Class[] getInterfaces(Class clazz) {\r\n Class superClazz = clazz;\r\n Class[] interfaces = clazz.getInterfaces();\r\n\r\n // clazz can be an interface itself and when getInterfaces()\r\n // is called on an interface it returns only the extending\r\n // interfaces, not the interface itself.\r\n if (clazz.isInterface()) {\r\n Class[] tempInterfaces = new Class[interfaces.length + 1];\r\n tempInterfaces[0] = clazz;\r\n\r\n System.arraycopy(interfaces, 0, tempInterfaces, 1, interfaces.length);\r\n interfaces = tempInterfaces;\r\n }\r\n\r\n // add all interfaces implemented by superclasses to the interfaces array\r\n while ((superClazz = superClazz.getSuperclass()) != null) {\r\n Class[] superInterfaces = superClazz.getInterfaces();\r\n Class[] combInterfaces = new Class[interfaces.length + superInterfaces.length];\r\n System.arraycopy(interfaces, 0, combInterfaces, 0, interfaces.length);\r\n System.arraycopy(superInterfaces, 0, combInterfaces, interfaces.length, superInterfaces.length);\r\n interfaces = combInterfaces;\r\n }\r\n\r\n /**\r\n * Must remove duplicate interfaces before calling Proxy.getProxyClass().\r\n * Duplicates can occur if a subclass re-declares that it implements\r\n * the same interface as one of its ancestor classes.\r\n **/\r\n HashMap unique = new HashMap();\r\n for (int i = 0; i < interfaces.length; i++) {\r\n unique.put(interfaces[i].getName(), interfaces[i]);\r\n }\r\n /* Add the OJBProxy interface as well */\r\n unique.put(OJBProxy.class.getName(), OJBProxy.class);\r\n\r\n interfaces = (Class[])unique.values().toArray(new Class[unique.size()]);\r\n\r\n return interfaces;\r\n }" ]
Convert Day instance to MPX day index. @param day Day instance @return day index
[ "public static Integer getDay(Day day)\n {\n Integer result = null;\n if (day != null)\n {\n result = DAY_MAP.get(day);\n }\n return (result);\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_CHECK);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n\n // execute command\n if(metaKeys.size() == 0\n || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(MetadataStore.CLUSTER_KEY);\n metaKeys.add(MetadataStore.STORES_KEY);\n metaKeys.add(MetadataStore.SERVER_STATE_KEY);\n }\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheck(adminClient, metaKeys);\n }", "public void register() {\n synchronized (loaders) {\n loaders.add(this);\n\n maximumHeaderLength = 0;\n for (GVRCompressedTextureLoader loader : loaders) {\n int headerLength = loader.headerLength();\n if (headerLength > maximumHeaderLength) {\n maximumHeaderLength = headerLength;\n }\n }\n }\n }", "private String formatDuration(Object value)\n {\n String result = null;\n if (value instanceof Duration)\n {\n Duration duration = (Duration) value;\n result = m_formats.getDurationDecimalFormat().format(duration.getDuration()) + formatTimeUnit(duration.getUnits());\n }\n return result;\n }", "public static BoxTermsOfService.Info create(BoxAPIConnection api,\n BoxTermsOfService.TermsOfServiceStatus termsOfServiceStatus,\n BoxTermsOfService.TermsOfServiceType termsOfServiceType, String text) {\n URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"status\", termsOfServiceStatus.toString())\n .add(\"tos_type\", termsOfServiceType.toString())\n .add(\"text\", text);\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxTermsOfService createdTermsOfServices = new BoxTermsOfService(api, responseJSON.get(\"id\").asString());\n\n return createdTermsOfServices.new Info(responseJSON);\n }", "public void update(Record record, boolean isText) throws MPXJException\n {\n int length = record.getLength();\n\n for (int i = 0; i < length; i++)\n {\n if (isText == true)\n {\n add(getTaskCode(record.getString(i)));\n }\n else\n {\n add(record.getInteger(i).intValue());\n }\n }\n }", "protected long preConnection() throws SQLException{\r\n\t\tlong statsObtainTime = 0;\r\n\t\t\r\n\t\tif (this.pool.poolShuttingDown){\r\n\t\t\tthrow new SQLException(this.pool.shutdownStackTrace);\r\n\t\t}\r\n\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tstatsObtainTime = System.nanoTime();\r\n\t\t\tthis.pool.statistics.incrementConnectionsRequested();\r\n\t\t}\r\n\t\t\r\n\t\treturn statsObtainTime;\r\n\t}", "public int getBoneIndex(String bonename)\n {\n for (int i = 0; i < getNumBones(); ++i)\n\n if (mBoneNames[i].equals(bonename))\n return i;\n return -1;\n }", "public static void extractHouseholderRow( ZMatrixRMaj A ,\n int row ,\n int col0, int col1 , double u[], int offsetU )\n {\n int indexU = (offsetU+col0)*2;\n u[indexU] = 1;\n u[indexU+1] = 0;\n\n int indexA = (row*A.numCols + (col0+1))*2;\n System.arraycopy(A.data,indexA,u,indexU+2,(col1-col0-1)*2);\n }", "public static base_responses add(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy addresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dospolicy();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].qdepth = resources[i].qdepth;\n\t\t\t\taddresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Returns a portion of the Bytes object @param start index of subsequence start (inclusive) @param end index of subsequence end (exclusive)
[ "public Bytes subSequence(int start, int end) {\n if (start > end || start < 0 || end > length) {\n throw new IndexOutOfBoundsException(\"Bad start and/end start = \" + start + \" end=\" + end\n + \" offset=\" + offset + \" length=\" + length);\n }\n return new Bytes(data, offset + start, end - start);\n }" ]
[ "private boolean hasReceivedHeartbeat() {\n long currentTimeMillis = System.currentTimeMillis();\n boolean result = lastTimeMessageReceived + heartbeatTimeoutMs >= currentTimeMillis;\n\n if (!result)\n Jvm.warn().on(getClass(), Integer.toHexString(hashCode()) + \" missed heartbeat, lastTimeMessageReceived=\" + lastTimeMessageReceived\n + \", currentTimeMillis=\" + currentTimeMillis);\n return result;\n }", "public static long count(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "protected boolean inViewPort(final int dataIndex) {\n boolean inViewPort = true;\n\n for (Layout layout: mLayouts) {\n inViewPort = inViewPort && (layout.inViewPort(dataIndex) || !layout.isClippingEnabled());\n }\n return inViewPort;\n }", "public static Chart getTrajectoryChart(String title, Trajectory t){\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[t.size()];\n\t\t double[] yData = new double[t.size()];\n\t\t for(int i = 0; i < t.size(); i++){\n\t\t \txData[i] = t.get(i).x;\n\t\t \tyData[i] = t.get(i).y;\n\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(title, \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\n\t\t return chart;\n\t\t //Show it\n\t\t // SwingWrapper swr = new SwingWrapper(chart);\n\t\t // swr.displayChart();\n\t\t} \n\t\treturn null;\n\t}", "public static Set<Annotation> flattenInterceptorBindings(EnhancedAnnotatedType<?> clazz, BeanManagerImpl beanManager, Collection<Annotation> annotations, boolean addTopLevelInterceptorBindings,\n boolean addInheritedInterceptorBindings) {\n Set<Annotation> flattenInterceptorBindings = new InterceptorBindingSet(beanManager);\n MetaAnnotationStore metaAnnotationStore = beanManager.getServices().get(MetaAnnotationStore.class);\n\n if (addTopLevelInterceptorBindings) {\n addInterceptorBindings(clazz, annotations, flattenInterceptorBindings, metaAnnotationStore);\n }\n if (addInheritedInterceptorBindings) {\n for (Annotation annotation : annotations) {\n addInheritedInterceptorBindings(clazz, annotation.annotationType(), metaAnnotationStore, flattenInterceptorBindings);\n }\n }\n return flattenInterceptorBindings;\n }", "public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) {\n final CompositeGeneratorNode node = this.trace(rootTrace, code);\n this.generateTracedFile(fsa, path, node);\n }", "private void deliverDeviceUpdate(final DeviceUpdate update) {\n for (DeviceUpdateListener listener : getUpdateListeners()) {\n try {\n listener.received(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device update to listener\", t);\n }\n }\n }", "protected void concatenateReports() {\n\n if (!concatenatedReports.isEmpty()) { // dummy group for page break if needed\n DJGroup globalGroup = createDummyGroup();\n report.getColumnsGroups().add(0, globalGroup);\n }\n\n for (Subreport subreport : concatenatedReports) {\n DJGroup globalGroup = createDummyGroup();\n globalGroup.getFooterSubreports().add(subreport);\n report.getColumnsGroups().add(0, globalGroup);\n }\n }", "public static <X> ServiceTypeLoader<X> load(Class<X> serviceType) {\n return load(serviceType, Thread.currentThread().getContextClassLoader());\n }" ]
Unmarshal test suite from given file.
[ "public static TestSuiteResult unmarshal(File testSuite) throws IOException {\n try (InputStream stream = new FileInputStream(testSuite)) {\n return unmarshal(stream);\n }\n }" ]
[ "public InputStream call(String methodName, MessageLite request) throws DatastoreException {\n logger.fine(\"remote datastore call \" + methodName);\n\n long startTime = System.currentTimeMillis();\n try {\n HttpResponse httpResponse;\n try {\n rpcCount.incrementAndGet();\n ProtoHttpContent payload = new ProtoHttpContent(request);\n HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload);\n httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION);\n // Don't throw an HTTPResponseException on error. It converts the response to a String and\n // throws away the original, whereas we need the raw bytes to parse it as a proto.\n httpRequest.setThrowExceptionOnExecuteError(false);\n // Datastore requests typically time out after 60s; set the read timeout to slightly longer\n // than that by default (can be overridden via the HttpRequestInitializer).\n httpRequest.setReadTimeout(65 * 1000);\n if (initializer != null) {\n initializer.initialize(httpRequest);\n }\n httpResponse = httpRequest.execute();\n if (!httpResponse.isSuccessStatusCode()) {\n try (InputStream content = GzipFixingInputStream.maybeWrap(httpResponse.getContent())) {\n throw makeException(url, methodName, content,\n httpResponse.getContentType(), httpResponse.getContentCharset(), null,\n httpResponse.getStatusCode());\n }\n }\n return GzipFixingInputStream.maybeWrap(httpResponse.getContent());\n } catch (SocketTimeoutException e) {\n throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, \"Deadline exceeded\", e);\n } catch (IOException e) {\n throw makeException(url, methodName, Code.UNAVAILABLE, \"I/O error\", e);\n }\n } finally {\n long elapsedTime = System.currentTimeMillis() - startTime;\n logger.fine(\"remote datastore call \" + methodName + \" took \" + elapsedTime + \" ms\");\n }\n }", "@Override\n\tpublic void handlePopups() {\n\t\t/*\n\t\t * try { executeJavaScript(\"window.alert = function(msg){return true;};\" +\n\t\t * \"window.confirm = function(msg){return true;};\" +\n\t\t * \"window.prompt = function(msg){return true;};\"); } catch (CrawljaxException e) {\n\t\t * LOGGER.error(\"Handling of PopUp windows failed\", e); }\n\t\t */\n\n\t\t/* Workaround: Popups handling currently not supported in PhantomJS. */\n\t\tif (browser instanceof PhantomJSDriver) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (ExpectedConditions.alertIsPresent().apply(browser) != null) {\n\t\t\ttry {\n\t\t\t\tbrowser.switchTo().alert().accept();\n\t\t\t\tLOGGER.info(\"Alert accepted\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"Handling of PopUp windows failed\");\n\t\t\t}\n\t\t}\n\t}", "public String tag(ImapRequestLineReader request) throws ProtocolException {\n CharacterValidator validator = new TagCharValidator();\n return consumeWord(request, validator);\n }", "public static Map<String,String> unserializeBuildInfo(final String buildInfo) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(buildInfo, new TypeReference<Map<String, Object>>(){});\n }", "public static <E> Collection<E> sampleWithReplacement(Collection<E> c, int n) {\r\n return sampleWithReplacement(c, n, new Random());\r\n }", "public static CoordinateReferenceSystem parseProjection(\n final String projection, final Boolean longitudeFirst) {\n try {\n if (longitudeFirst == null) {\n return CRS.decode(projection);\n } else {\n return CRS.decode(projection, longitudeFirst);\n }\n } catch (NoSuchAuthorityCodeException e) {\n throw new RuntimeException(projection + \" was not recognized as a crs code\", e);\n } catch (FactoryException e) {\n throw new RuntimeException(\"Error occurred while parsing: \" + projection, e);\n }\n }", "public String getStatement()\r\n {\r\n if(sql == null)\r\n {\r\n StringBuffer stmt = new StringBuffer(128);\r\n ClassDescriptor cld = getClassDescriptor();\r\n\r\n FieldDescriptor[] fieldDescriptors = cld.getPkFields();\r\n if(fieldDescriptors == null || fieldDescriptors.length == 0)\r\n {\r\n throw new OJBRuntimeException(\"No PK fields defined in metadata for \" + cld.getClassNameOfObject());\r\n }\r\n FieldDescriptor field = fieldDescriptors[0];\r\n\r\n stmt.append(SELECT);\r\n stmt.append(field.getColumnName());\r\n stmt.append(FROM);\r\n stmt.append(cld.getFullTableName());\r\n appendWhereClause(cld, false, stmt);\r\n\r\n sql = stmt.toString();\r\n }\r\n return sql;\r\n }", "public static Collection<Field> getAttributes(\n final Class<?> classToInspect, final Predicate<Field> filter) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), filter);\n return allFields;\n }", "@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }" ]
Use this API to fetch auditsyslogpolicy_systemglobal_binding resources of given name .
[ "public static auditsyslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_systemglobal_binding obj = new auditsyslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_systemglobal_binding response[] = (auditsyslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public void setInRGB(IntRange inRGB) {\r\n this.inRed = inRGB;\r\n this.inGreen = inRGB;\r\n this.inBlue = inRGB;\r\n\r\n CalculateMap(inRGB, outRed, mapRed);\r\n CalculateMap(inRGB, outGreen, mapGreen);\r\n CalculateMap(inRGB, outBlue, mapBlue);\r\n }", "public InsertBuilder set(String column, String value) {\n columns.add(column);\n values.add(value);\n return this;\n }", "public static audit_stats get(nitro_service service, options option) throws Exception{\n\t\taudit_stats obj = new audit_stats();\n\t\taudit_stats[] response = (audit_stats[])obj.stat_resources(service,option);\n\t\treturn response[0];\n\t}", "public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }", "public static BoxRetentionPolicyAssignment.Info createAssignmentToEnterprise(BoxAPIConnection api,\r\n String policyID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_ENTERPRISE), null);\r\n }", "public static base_response disable(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 disableresource = new nsacl6();\n\t\tdisableresource.acl6name = resource.acl6name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "public void setPublishQueueShutdowntime(String publishQueueShutdowntime) {\n\n if (m_frozen) {\n throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0));\n }\n m_publishQueueShutdowntime = Integer.parseInt(publishQueueShutdowntime);\n }", "private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) {\n\t\tSet<Class<?>> entities = new HashSet<Class<?>>();\n\t\t//first build the \"entities\" set containing all indexed subtypes of \"selection\".\n\t\tfor ( Class<?> entityType : selection ) {\n\t\t\tIndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( IndexedTypeSets.fromClass( entityType ) );\n\t\t\tif ( targetedClasses.isEmpty() ) {\n\t\t\t\tString msg = entityType.getName() + \" is not an indexed entity or a subclass of an indexed entity\";\n\t\t\t\tthrow new IllegalArgumentException( msg );\n\t\t\t}\n\t\t\tentities.addAll( targetedClasses.toPojosSet() );\n\t\t}\n\t\tSet<Class<?>> cleaned = new HashSet<Class<?>>();\n\t\tSet<Class<?>> toRemove = new HashSet<Class<?>>();\n\t\t//now remove all repeated types to avoid duplicate loading by polymorphic query loading\n\t\tfor ( Class<?> type : entities ) {\n\t\t\tboolean typeIsOk = true;\n\t\t\tfor ( Class<?> existing : cleaned ) {\n\t\t\t\tif ( existing.isAssignableFrom( type ) ) {\n\t\t\t\t\ttypeIsOk = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( type.isAssignableFrom( existing ) ) {\n\t\t\t\t\ttoRemove.add( existing );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( typeIsOk ) {\n\t\t\t\tcleaned.add( type );\n\t\t\t}\n\t\t}\n\t\tcleaned.removeAll( toRemove );\n\t\tlog.debugf( \"Targets for indexing job: %s\", cleaned );\n\t\treturn IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) );\n\t}", "public boolean hasDeploymentSubsystemModel(final String subsystemName) {\n final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);\n final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);\n return root.hasChild(subsystem);\n }" ]
Search for the second entry in the second database. Use this method for databases configured with no duplicates. @param second second key (value for first). @return null if no entry found, otherwise the value.
[ "@Nullable\n public ByteIterable get2(@NotNull final Transaction txn, @NotNull final ByteIterable second) {\n return this.second.get(txn, second);\n }" ]
[ "static void tryAutoAttaching(final SlotReference slot) {\n if (!MetadataFinder.getInstance().getMountedMediaSlots().contains(slot)) {\n logger.error(\"Unable to auto-attach cache to empty slot {}\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getMetadataCache(slot) != null) {\n logger.info(\"Not auto-attaching to slot {}; already has a cache attached.\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getAutoAttachCacheFiles().isEmpty()) {\n logger.debug(\"No auto-attach files configured.\");\n return;\n }\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5); // Give us a chance to find out what type of media is in the new mount.\n final MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null && details.mediaType == CdjStatus.TrackType.REKORDBOX) {\n // First stage attempt: See if we can match based on stored media details, which is both more reliable and\n // less disruptive than trying to sample the player database to compare entries.\n boolean attached = false;\n for (File file : MetadataFinder.getInstance().getAutoAttachCacheFiles()) {\n final MetadataCache cache = new MetadataCache(file);\n try {\n if (cache.sourceMedia != null && cache.sourceMedia.hashKey().equals(details.hashKey())) {\n // We found a solid match, no need to probe tracks.\n final boolean changed = cache.sourceMedia.hasChanged(details);\n logger.info(\"Auto-attaching metadata cache \" + cache.getName() + \" to slot \" + slot +\n \" based on media details \" + (changed? \"(changed since created)!\" : \"(unchanged).\"));\n MetadataFinder.getInstance().attachMetadataCacheInternal(slot, cache);\n attached = true;\n return;\n }\n } finally {\n if (!attached) {\n cache.close();\n }\n }\n }\n\n // Could not match based on media details; fall back to older method based on probing track metadata.\n ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {\n @Override\n public Object useClient(Client client) throws Exception {\n tryAutoAttachingWithConnection(slot, client);\n return null;\n }\n };\n ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, \"trying to auto-attach metadata cache\");\n }\n } catch (Exception e) {\n logger.error(\"Problem trying to auto-attach metadata cache for slot \" + slot, e);\n }\n\n }\n }, \"Metadata cache file auto-attachment attempt\").start();\n }", "private String getPathSelectString() {\n String queryString = \"SELECT \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \",\" + Constants.PATH_PROFILE_PATHNAME +\n \",\" + Constants.PATH_PROFILE_ACTUAL_PATH +\n \",\" + Constants.PATH_PROFILE_BODY_FILTER +\n \",\" + Constants.PATH_PROFILE_GROUP_IDS +\n \",\" + Constants.DB_TABLE_PATH + \".\" + Constants.PATH_PROFILE_PROFILE_ID +\n \",\" + Constants.PATH_PROFILE_PATH_ORDER +\n \",\" + Constants.REQUEST_RESPONSE_REPEAT_NUMBER +\n \",\" + Constants.REQUEST_RESPONSE_REQUEST_ENABLED +\n \",\" + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED +\n \",\" + Constants.PATH_PROFILE_CONTENT_TYPE +\n \",\" + Constants.PATH_PROFILE_REQUEST_TYPE +\n \",\" + Constants.PATH_PROFILE_GLOBAL +\n \" FROM \" + Constants.DB_TABLE_PATH +\n \" JOIN \" + Constants.DB_TABLE_REQUEST_RESPONSE +\n \" ON \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID +\n \"=\" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.REQUEST_RESPONSE_PATH_ID +\n \" AND \" + Constants.DB_TABLE_REQUEST_RESPONSE + \".\" + Constants.GENERIC_CLIENT_UUID + \" = ?\";\n\n return queryString;\n }", "public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }", "public void deleteInactiveContent() throws PatchingException {\n List<File> dirs = getInactiveHistory();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n dirs = getInactiveOverlays();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n }", "private void injectAdditionalStyles() {\n\n try {\n Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();\n for (String stylesheet : stylesheets) {\n A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }", "public static int cudnnGetConvolutionNdDescriptor(\n cudnnConvolutionDescriptor convDesc, \n int arrayLengthRequested, \n int[] arrayLength, \n int[] padA, \n int[] strideA, \n int[] dilationA, \n int[] mode, \n int[] computeType)/** convolution data type */\n {\n return checkResult(cudnnGetConvolutionNdDescriptorNative(convDesc, arrayLengthRequested, arrayLength, padA, strideA, dilationA, mode, computeType));\n }", "private static String wordShapeDan1(String s) {\r\n boolean digit = true;\r\n boolean upper = true;\r\n boolean lower = true;\r\n boolean mixed = true;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!Character.isDigit(c)) {\r\n digit = false;\r\n }\r\n if (!Character.isLowerCase(c)) {\r\n lower = false;\r\n }\r\n if (!Character.isUpperCase(c)) {\r\n upper = false;\r\n }\r\n if ((i == 0 && !Character.isUpperCase(c)) || (i >= 1 && !Character.isLowerCase(c))) {\r\n mixed = false;\r\n }\r\n }\r\n if (digit) {\r\n return \"ALL-DIGITS\";\r\n }\r\n if (upper) {\r\n return \"ALL-UPPER\";\r\n }\r\n if (lower) {\r\n return \"ALL-LOWER\";\r\n }\r\n if (mixed) {\r\n return \"MIXED-CASE\";\r\n }\r\n return \"OTHER\";\r\n }", "public static java.sql.Time newTime() {\n return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);\n }", "public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {\n return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);\n }" ]
Adds a collection of listeners to the current project. @param listeners collection of listeners
[ "public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }" ]
[ "public static final Integer getInteger(String value)\n {\n Integer result;\n\n try\n {\n result = Integer.valueOf(Integer.parseInt(value));\n }\n\n catch (Exception ex)\n {\n result = null;\n }\n\n return (result);\n }", "@SuppressWarnings(\"unchecked\")\n public void updateStoreDefinitions(Versioned<byte[]> valueBytes) {\n // acquire write lock\n writeLock.lock();\n\n try {\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n Versioned<Object> valueObject = convertStringToObject(STORES_KEY, value);\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) valueObject.getValue();\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n StoreDefinitionUtils.validateNewStoreDefsAreNonBreaking(getStoreDefList(), storeDefinitions);\n\n // Go through each store definition and do a corresponding put\n for(StoreDefinition storeDef: storeDefinitions) {\n if(!this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Cannot update a store which does not exist !\");\n }\n\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n // TODO: Make this more fine grained.. i.e only update listeners for\n // a specific store.\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }", "static void initSingleParam(String key, String initValue, DbConn cnx)\n {\n try\n {\n cnx.runSelectSingle(\"globalprm_select_by_key\", 2, String.class, key);\n return;\n }\n catch (NoResultException e)\n {\n GlobalParameter.create(cnx, key, initValue);\n }\n catch (NonUniqueResultException e)\n {\n // It exists! Nothing to do...\n }\n }", "private void checkProcedures(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ProcedureDef procDef;\r\n String type;\r\n String name;\r\n String fieldName;\r\n String argName;\r\n \r\n for (Iterator it = classDef.getProcedures(); it.hasNext();)\r\n {\r\n procDef = (ProcedureDef)it.next();\r\n type = procDef.getName();\r\n name = procDef.getProperty(PropertyHelper.OJB_PROPERTY_NAME);\r\n if ((name == null) || (name.length() == 0))\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure in class \"+classDef.getName()+\" doesn't have a name\");\r\n }\r\n fieldName = procDef.getProperty(PropertyHelper.OJB_PROPERTY_RETURN_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n for (CommaListIterator argIt = new CommaListIterator(procDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS)); argIt.hasNext();)\r\n {\r\n argName = argIt.getNext();\r\n if (classDef.getProcedureArgument(argName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-procedure \"+name+\" in class \"+classDef.getName()+\" references an unknown argument \"+argName);\r\n }\r\n }\r\n }\r\n\r\n ProcedureArgumentDef argDef;\r\n\r\n for (Iterator it = classDef.getProcedureArguments(); it.hasNext();)\r\n {\r\n argDef = (ProcedureArgumentDef)it.next();\r\n type = argDef.getProperty(PropertyHelper.OJB_PROPERTY_TYPE);\r\n if (\"runtime\".equals(type))\r\n {\r\n fieldName = argDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELD_REF);\r\n if ((fieldName != null) && (fieldName.length() > 0))\r\n {\r\n if (classDef.getField(fieldName) == null)\r\n {\r\n throw new ConstraintException(\"The \"+type+\"-argument \"+argDef.getName()+\" in class \"+classDef.getName()+\" references an unknown or non-persistent return field \"+fieldName);\r\n }\r\n }\r\n }\r\n }\r\n }", "public Bundler put(String key, Parcelable value) {\n delegate.putParcelable(key, value);\n return this;\n }", "public void close()\n {\n inputManager.unregisterInputDeviceListener(inputDeviceListener);\n mouseDeviceManager.forceStopThread();\n gamepadDeviceManager.forceStopThread();\n controllerIds.clear();\n cache.clear();\n controllers.clear();\n }", "public static Iterable<BoxCollection.Info> getAllCollections(final BoxAPIConnection api) {\n return new Iterable<BoxCollection.Info>() {\n public Iterator<BoxCollection.Info> iterator() {\n URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL());\n return new BoxCollectionIterator(api, url);\n }\n };\n }", "public DynamicReportBuilder setProperty(String name, String value) {\n this.report.setProperty(name, value);\n return this;\n }", "public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (newFooterItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);\n }" ]
Use this API to fetch statistics of service_stats resource of given name .
[ "public static service_stats get(nitro_service service, String name) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tobj.set_name(name);\n\t\tservice_stats response = (service_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException {\n AssemblyResponse response;\n do {\n response = getClient().getAssemblyByUrl(url);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new LocalOperationException(e);\n }\n } while (!response.isFinished());\n\n setState(State.FINISHED);\n return response;\n }", "public static void getHistory() throws Exception{\n Client client = new Client(\"ProfileName\", false);\n\n // Obtain the 100 history entries starting from offset 0\n History[] history = client.refreshHistory(100, 0);\n\n client.clearHistory();\n }", "public boolean isAlive(Connection conn)\r\n {\r\n try\r\n {\r\n return con != null ? !con.isClosed() : false;\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"IsAlive check failed, running connection was invalid!!\", e);\r\n return false;\r\n }\r\n }", "public static base_responses delete(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 deleteresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tdeleteresources[i] = new nsacl6();\n\t\t\t\tdeleteresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public void updateIntegerBelief(String name, int value) {\n introspector.storeBeliefValue(this, name, getIntegerBelief(name) + value);\n }", "public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,\n ArtifactoryServer pipelineServer) {\n\n if (artifactoryServerID == null && pipelineServer == null) {\n return null;\n }\n if (artifactoryServerID != null && pipelineServer != null) {\n return null;\n }\n if (pipelineServer != null) {\n CredentialsConfig credentials = pipelineServer.createCredentialsConfig();\n\n return new org.jfrog.hudson.ArtifactoryServer(null, pipelineServer.getUrl(), credentials,\n credentials, pipelineServer.getConnection().getTimeout(), pipelineServer.isBypassProxy(), pipelineServer.getConnection().getRetry(), pipelineServer.getDeploymentThreads());\n }\n org.jfrog.hudson.ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(artifactoryServerID, RepositoriesUtils.getArtifactoryServers());\n if (server == null) {\n return null;\n }\n return server;\n }", "private void captureEye(GVRScreenshotCallback callback, GVRRenderTarget renderTarget, GVRViewManager.EYE eye, boolean useMultiview) {\n if (null == callback) {\n return;\n }\n readRenderResult(renderTarget,eye,useMultiview);\n returnScreenshotToCaller(callback, mReadbackBufferWidth, mReadbackBufferHeight);\n }", "public synchronized HttpServer<Buffer, Buffer> start() throws Exception {\n\t\tif (server == null) {\n\t\t\tserver = createProtocolListener();\n\t\t}\n\t\treturn server;\n\t}", "private boolean hidden(ProgramElementDoc c) {\n\tif (c.tags(\"hidden\").length > 0 || c.tags(\"view\").length > 0)\n\t return true;\n\tOptions opt = optionProvider.getOptionsFor(c instanceof ClassDoc ? (ClassDoc) c : c.containingClass());\n\treturn opt.matchesHideExpression(c.toString()) //\n\t\t|| (opt.hidePrivateInner && c instanceof ClassDoc && c.isPrivate() && ((ClassDoc) c).containingClass() != null);\n }" ]
Throws one RendererException if the content parent or layoutInflater are null.
[ "private void validateAttributes() {\n if (content == null) {\n throw new NullContentException(\"RendererBuilder needs content to create Renderer instances\");\n }\n\n if (parent == null) {\n throw new NullParentException(\"RendererBuilder needs a parent to inflate Renderer instances\");\n }\n\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to inflate Renderer instances\");\n }\n }" ]
[ "public static base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void writeTagsToJavaScript(Writer writer) throws IOException\n {\n writer.append(\"function fillTagService(tagService) {\\n\");\n writer.append(\"\\t// (name, isPrime, isPseudo, color), [parent tags]\\n\");\n for (Tag tag : definedTags.values())\n {\n writer.append(\"\\ttagService.registerTag(new Tag(\");\n escapeOrNull(tag.getName(), writer);\n writer.append(\", \");\n escapeOrNull(tag.getTitle(), writer);\n writer.append(\", \").append(\"\" + tag.isPrime())\n .append(\", \").append(\"\" + tag.isPseudo())\n .append(\", \");\n escapeOrNull(tag.getColor(), writer);\n writer.append(\")\").append(\", [\");\n\n // We only have strings, not references, so we're letting registerTag() getOrCreate() the tag.\n for (Tag parentTag : tag.getParentTags())\n {\n writer.append(\"'\").append(StringEscapeUtils.escapeEcmaScript(parentTag.getName())).append(\"',\");\n }\n writer.append(\"]);\\n\");\n }\n writer.append(\"}\\n\");\n }", "public ViewPort then(Functions.Func1<ViewPortChange> then, ViewPortFallback fallback) {\n assert then != null : \"'then' callback cannot be null\";\n this.then = then;\n this.fallback = fallback;\n return load();\n }", "public void addBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final boolean statementBatchingSupported = m_batchStatementsInProgress.containsKey(stmt);\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n stmt.executeUpdate();\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.addBatch(stmt);\r\n }\r\n }", "public static base_response add(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy addresource = new spilloverpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.comment = resource.comment;\n\t\treturn addresource.add_resource(client);\n\t}", "public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) {\n\n if (resList == null) {\n return new CmsResourceTypeStatResultList();\n }\n\n resList.deleteOld();\n return resList;\n }", "@Override\n\tpublic String toNormalizedString() {\n\t\tString result = normalizedString;\n\t\tif(result == null) {\n\t\t\tnormalizedString = result = toNormalizedString(false);\n\t\t}\n\t\treturn result;\n\t}", "String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }", "private String getHierarchyTable(ClassDescriptorDef classDef)\r\n {\r\n ArrayList queue = new ArrayList();\r\n String tableName = null;\r\n\r\n queue.add(classDef);\r\n\r\n while (!queue.isEmpty())\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)queue.get(0);\r\n\r\n queue.remove(0);\r\n\r\n if (curClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true))\r\n {\r\n if (tableName != null)\r\n {\r\n if (!tableName.equals(curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n return null;\r\n }\r\n }\r\n else\r\n {\r\n tableName = curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE);\r\n }\r\n }\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curClassDef = (ClassDescriptorDef)it.next();\r\n\r\n if (curClassDef.getReference(\"super\") == null)\r\n {\r\n queue.add(curClassDef);\r\n }\r\n }\r\n }\r\n return tableName;\r\n }" ]
Uploads files from the given file input fields.<p< @param fields the set of names of fields containing the files to upload @param filenameCallback the callback to call with the resulting map from field names to file paths @param errorCallback the callback to call with an error message
[ "public void uploadFields(\n final Set<String> fields,\n final Function<Map<String, String>, Void> filenameCallback,\n final I_CmsErrorCallback errorCallback) {\n\n disableAllFileFieldsExcept(fields);\n final String id = CmsJsUtils.generateRandomId();\n updateFormAction(id);\n // Using an array here because we can only store the handler registration after it has been created , but\n final HandlerRegistration[] registration = {null};\n registration[0] = addSubmitCompleteHandler(new SubmitCompleteHandler() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void onSubmitComplete(SubmitCompleteEvent event) {\n\n enableAllFileFields();\n registration[0].removeHandler();\n CmsUUID sessionId = m_formSession.internalGetSessionId();\n RequestBuilder requestBuilder = CmsXmlContentUgcApi.SERVICE.uploadFiles(\n sessionId,\n fields,\n id,\n new AsyncCallback<Map<String, String>>() {\n\n public void onFailure(Throwable caught) {\n\n m_formSession.getContentFormApi().handleError(caught, errorCallback);\n\n }\n\n public void onSuccess(Map<String, String> fileNames) {\n\n filenameCallback.apply(fileNames);\n\n }\n });\n m_formSession.getContentFormApi().getRpcHelper().executeRpc(requestBuilder);\n m_formSession.getContentFormApi().getRequestCounter().decrement();\n }\n });\n m_formSession.getContentFormApi().getRequestCounter().increment();\n submit();\n }" ]
[ "private TableModel createTableModel(Object object, Set<String> excludedMethods)\n {\n List<Method> methods = new ArrayList<Method>();\n for (Method method : object.getClass().getMethods())\n {\n if ((method.getParameterTypes().length == 0) || (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == int.class))\n {\n String name = method.getName();\n if (!excludedMethods.contains(name) && (name.startsWith(\"get\") || name.startsWith(\"is\")))\n {\n methods.add(method);\n }\n }\n }\n\n Map<String, String> map = new TreeMap<String, String>();\n for (Method method : methods)\n {\n if (method.getParameterTypes().length == 0)\n {\n getSingleValue(method, object, map);\n }\n else\n {\n getMultipleValues(method, object, map);\n }\n }\n\n String[] headings = new String[]\n {\n \"Property\",\n \"Value\"\n };\n\n String[][] data = new String[map.size()][2];\n int rowIndex = 0;\n for (Entry<String, String> entry : map.entrySet())\n {\n data[rowIndex][0] = entry.getKey();\n data[rowIndex][1] = entry.getValue();\n ++rowIndex;\n }\n\n TableModel tableModel = new DefaultTableModel(data, headings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n return tableModel;\n }", "public boolean assertValidPkForDelete(ClassDescriptor cld, Object obj)\r\n {\r\n if(!ProxyHelper.isProxy(obj))\r\n {\r\n FieldDescriptor fieldDescriptors[] = cld.getPkFields();\r\n int fieldDescriptorSize = fieldDescriptors.length;\r\n for(int i = 0; i < fieldDescriptorSize; i++)\r\n {\r\n FieldDescriptor fd = fieldDescriptors[i];\r\n Object pkValue = fd.getPersistentField().get(obj);\r\n if (representsNull(fd, pkValue))\r\n {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }", "private void getMonthlyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n if (m_relative)\n {\n getMonthlyRelativeDates(calendar, frequency, dates);\n }\n else\n {\n getMonthlyAbsoluteDates(calendar, frequency, dates);\n }\n }", "private static LogPriorType intToType(int intPrior) {\r\n LogPriorType[] values = LogPriorType.values();\r\n for (LogPriorType val : values) {\r\n if (val.ordinal() == intPrior) {\r\n return val;\r\n }\r\n }\r\n throw new IllegalArgumentException(intPrior + \" is not a legal LogPrior.\");\r\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> T getJlsDefaultValue(Class<T> type) {\n if(!type.isPrimitive()) {\n return null;\n }\n return (T) JLS_PRIMITIVE_DEFAULT_VALUES.get(type);\n }", "private void initModeSwitch(final EditMode current) {\n\n FormLayout modes = new FormLayout();\n modes.setHeight(\"100%\");\n modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);\n\n m_modeSelect = new ComboBox();\n m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));\n\n // add Modes\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));\n\n // set current mode as selected\n m_modeSelect.setValue(current);\n\n m_modeSelect.setNewItemsAllowed(false);\n m_modeSelect.setTextInputAllowed(false);\n m_modeSelect.setNullSelectionAllowed(false);\n\n m_modeSelect.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void valueChange(ValueChangeEvent event) {\n\n m_listener.handleModeChange((EditMode)event.getProperty().getValue());\n\n }\n });\n\n modes.addComponent(m_modeSelect);\n m_modeSwitch = modes;\n }", "private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }", "public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\n }", "private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\n }" ]
Create User Application Properties Create application properties for a user @param userId User Id (required) @param properties Properties to be updated (required) @param aid Application ID (optional) @return PropertiesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid);\n return resp.getData();\n }" ]
[ "public Conditionals ifModifiedSince(LocalDateTime time) {\n Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));\n Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE));\n time = time.withNano(0);\n return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty());\n }", "protected static boolean fileDoesNotExist(String file, String path,\n String dest_dir) {\n\n File f = new File(dest_dir);\n if (!f.isDirectory())\n return false;\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n\n File javaFile = new File(f, file);\n boolean result = !javaFile.exists();\n\n return result;\n }", "public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}", "protected void postDestroyConnection(ConnectionHandle handle){\r\n\t\tConnectionPartition partition = handle.getOriginatingPartition();\r\n\r\n\t\tif (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety\r\n\t\t\tthis.finalizableRefs.remove(handle.getInternalConnection());\r\n\t\t\t//\t\t\tassert o != null : \"Did not manage to remove connection from finalizable ref queue\";\r\n\t\t}\r\n\r\n\t\tpartition.updateCreatedConnections(-1);\r\n\t\tpartition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization\r\n\r\n\r\n\t\t// \"Destroying\" for us means: don't put it back in the pool.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onDestroy(handle);\r\n\t\t}\r\n\r\n\t}", "public FieldType getFieldByAlias(FieldTypeClass typeClass, String alias)\n {\n return m_aliasMap.get(new Pair<FieldTypeClass, String>(typeClass, alias));\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal);\n }", "public static void recursiveAddZip(File parent, ZipOutputStream zout, File fileSource)\n throws IOException {\n\n File[] files = fileSource.listFiles();\n\n for (int i = 0; i < files.length; i++) {\n if (files[i].isDirectory()) {\n recursiveAddZip(parent, zout, files[i]);\n continue;\n }\n\n byte[] buffer = new byte[1024];\n\n FileInputStream fin = new FileInputStream(files[i]);\n\n ZipEntry zipEntry =\n new ZipEntry(files[i].getAbsolutePath()\n .replace(parent.getAbsolutePath(), \"\").substring(1)); //$NON-NLS-1$\n zout.putNextEntry(zipEntry);\n\n int length;\n while ((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n\n fin.close();\n\n }\n\n }", "public static Statement open(String driverklass, String jdbcuri,\n Properties props) {\n try {\n Driver driver = (Driver) ObjectUtils.instantiate(driverklass);\n Connection conn = driver.connect(jdbcuri, props);\n if (conn == null)\n throw new DukeException(\"Couldn't connect to database at \" +\n jdbcuri);\n return conn.createStatement();\n\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }", "public Association getAssociation(String collectionRole) {\n\t\tif ( associations == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn associations.get( collectionRole );\n\t}" ]
Creates a namespace if needed.
[ "public void createNamespace() {\n Map<String, String> namespaceAnnotations = annotationProvider.create(session.getId(), Constants.RUNNING_STATUS);\n if (namespaceService.exists(session.getNamespace())) {\n //namespace exists\n } else if (configuration.isNamespaceLazyCreateEnabled()) {\n namespaceService.create(session.getNamespace(), namespaceAnnotations);\n } else {\n throw new IllegalStateException(\"Namespace [\" + session.getNamespace() + \"] doesn't exist and lazily creation of namespaces is disabled. \"\n + \"Either use an existing one, or set `namespace.lazy.enabled` to true.\");\n }\n }" ]
[ "public History[] refreshHistory(int limit, int offset) throws Exception {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"limit\", String.valueOf(limit)),\n new BasicNameValuePair(\"offset\", String.valueOf(offset))\n };\n return constructHistory(params);\n }", "public static String getSerializedVectorClocks(List<VectorClock> vectorClocks) {\n List<VectorClockWrapper> vectorClockWrappers = new ArrayList<VectorClockWrapper>();\n for(VectorClock vc: vectorClocks) {\n vectorClockWrappers.add(new VectorClockWrapper(vc));\n }\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vectorClockWrappers);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }", "public Filter geoSearch(String value) {\n GeopositionComparator comp = (GeopositionComparator) prop.getComparator();\n double dist = comp.getMaxDistance();\n double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0);\n Shape circle = spatialctx.makeCircle(parsePoint(value), degrees);\n SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);\n return strategy.makeFilter(args);\n }", "public static systemcollectionparam get(nitro_service service) throws Exception{\n\t\tsystemcollectionparam obj = new systemcollectionparam();\n\t\tsystemcollectionparam[] response = (systemcollectionparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) {\n\n if ((null == request) || !request.isInitialized()) {\n return null;\n }\n\n final String[] wordsToCheck = request.m_wordsToCheck;\n\n final ModifiableSolrParams params = new ModifiableSolrParams();\n params.set(\"spellcheck\", \"true\");\n params.set(\"spellcheck.dictionary\", request.m_dictionaryToUse);\n params.set(\"spellcheck.extendedResults\", \"true\");\n\n // Build one string from array of words and use it as query.\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < wordsToCheck.length; i++) {\n builder.append(wordsToCheck[i] + \" \");\n }\n\n params.set(\"spellcheck.q\", builder.toString());\n\n final SolrQuery query = new SolrQuery();\n query.setRequestHandler(\"/spell\");\n query.add(params);\n\n try {\n QueryResponse qres = m_solrClient.query(query);\n return qres.getSpellCheckResponse();\n } catch (Exception e) {\n LOG.debug(\"Exception while performing spellcheck query...\", e);\n }\n\n return null;\n }", "public static <T> boolean addAll(Collection<T> self, Iterator<T> items) {\n boolean changed = false;\n while (items.hasNext()) {\n T next = items.next();\n if (self.add(next)) changed = true;\n }\n return changed;\n }", "public static long count(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}", "public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }" ]
For each node, checks if the store exists and then verifies that the remote schema matches the new one. If the remote store doesn't exist, it creates it.
[ "private void verifyOrAddStore(String clusterURL,\n String keySchema,\n String valueSchema) {\n String newStoreDefXml = VoldemortUtils.getStoreDefXml(\n storeName,\n props.getInt(BUILD_REPLICATION_FACTOR, 2),\n props.getInt(BUILD_REQUIRED_READS, 1),\n props.getInt(BUILD_REQUIRED_WRITES, 1),\n props.getNullableInt(BUILD_PREFERRED_READS),\n props.getNullableInt(BUILD_PREFERRED_WRITES),\n props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema),\n props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema),\n description,\n owners);\n\n log.info(\"Verifying store against cluster URL: \" + clusterURL + \"\\n\" + newStoreDefXml.toString());\n StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml);\n\n try {\n adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, \"BnP config/data\",\n enableStoreCreation, this.storeVerificationExecutorService);\n } catch (UnreachableStoreException e) {\n log.info(\"verifyOrAddStore() failed on some nodes for clusterURL: \" + clusterURL + \" (this is harmless).\", e);\n // When we can't reach some node, we just skip it and won't create the store on it.\n // Next time BnP is run while the node is up, it will get the store created.\n } // Other exceptions need to bubble up!\n\n storeDef = newStoreDef;\n }" ]
[ "public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}", "public static base_responses add(nitro_service client, authenticationradiusaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tauthenticationradiusaction addresources[] = new authenticationradiusaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new authenticationradiusaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].serverport = resources[i].serverport;\n\t\t\t\taddresources[i].authtimeout = resources[i].authtimeout;\n\t\t\t\taddresources[i].radkey = resources[i].radkey;\n\t\t\t\taddresources[i].radnasip = resources[i].radnasip;\n\t\t\t\taddresources[i].radnasid = resources[i].radnasid;\n\t\t\t\taddresources[i].radvendorid = resources[i].radvendorid;\n\t\t\t\taddresources[i].radattributetype = resources[i].radattributetype;\n\t\t\t\taddresources[i].radgroupsprefix = resources[i].radgroupsprefix;\n\t\t\t\taddresources[i].radgroupseparator = resources[i].radgroupseparator;\n\t\t\t\taddresources[i].passencoding = resources[i].passencoding;\n\t\t\t\taddresources[i].ipvendorid = resources[i].ipvendorid;\n\t\t\t\taddresources[i].ipattributetype = resources[i].ipattributetype;\n\t\t\t\taddresources[i].accounting = resources[i].accounting;\n\t\t\t\taddresources[i].pwdvendorid = resources[i].pwdvendorid;\n\t\t\t\taddresources[i].pwdattributetype = resources[i].pwdattributetype;\n\t\t\t\taddresources[i].defaultauthenticationgroup = resources[i].defaultauthenticationgroup;\n\t\t\t\taddresources[i].callingstationid = resources[i].callingstationid;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static nsconfig get(nitro_service service) throws Exception{\n\t\tnsconfig obj = new nsconfig();\n\t\tnsconfig[] response = (nsconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static DMatrixRMaj[] splitIntoVectors(DMatrix1Row A , boolean column )\n {\n int w = column ? A.numCols : A.numRows;\n\n int M = column ? A.numRows : 1;\n int N = column ? 1 : A.numCols;\n\n int o = Math.max(M,N);\n\n DMatrixRMaj[] ret = new DMatrixRMaj[w];\n\n for( int i = 0; i < w; i++ ) {\n DMatrixRMaj a = new DMatrixRMaj(M,N);\n\n if( column )\n subvector(A,0,i,o,false,0,a);\n else\n subvector(A,i,0,o,true,0,a);\n\n ret[i] = a;\n }\n\n return ret;\n }", "private boolean costRateTableWriteRequired(CostRateTableEntry entry, Date from)\n {\n boolean fromDate = (DateHelper.compare(from, DateHelper.FIRST_DATE) > 0);\n boolean toDate = (DateHelper.compare(entry.getEndDate(), DateHelper.LAST_DATE) > 0);\n boolean costPerUse = (NumberHelper.getDouble(entry.getCostPerUse()) != 0);\n boolean overtimeRate = (entry.getOvertimeRate() != null && entry.getOvertimeRate().getAmount() != 0);\n boolean standardRate = (entry.getStandardRate() != null && entry.getStandardRate().getAmount() != 0);\n return (fromDate || toDate || costPerUse || overtimeRate || standardRate);\n }", "public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static protocoludp_stats get(nitro_service service) throws Exception{\n\t\tprotocoludp_stats obj = new protocoludp_stats();\n\t\tprotocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }" ]
Writes all data that was collected about properties to a json file.
[ "private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"properties.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\tint count = 0;\n\t\t\tfor (Entry<Integer, PropertyRecord> propertyEntry : this.propertyRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + propertyEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, propertyEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" properties.\");\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}" ]
[ "public synchronized void start() throws SocketException {\n if (!isRunning()) {\n DeviceFinder.getInstance().addLifecycleListener(lifecycleListener);\n DeviceFinder.getInstance().addDeviceAnnouncementListener(announcementListener);\n DeviceFinder.getInstance().start();\n for (DeviceAnnouncement device: DeviceFinder.getInstance().getCurrentDevices()) {\n requestPlayerDBServerPort(device);\n }\n\n new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (isRunning()) {\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n logger.warn(\"Interrupted sleeping to close idle dbserver clients\");\n }\n closeIdleClients();\n }\n logger.info(\"Idle dbserver client closer shutting down.\");\n }\n }, \"Idle dbserver client closer\").start();\n\n running.set(true);\n deliverLifecycleAnnouncement(logger, true);\n }\n }", "private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }", "public static long get1D(DMatrixRMaj A , int n ) {\n\n long before = System.currentTimeMillis();\n\n double total = 0;\n\n for( int iter = 0; iter < n; iter++ ) {\n\n int index = 0;\n for( int i = 0; i < A.numRows; i++ ) {\n int end = index+A.numCols;\n while( index != end ) {\n total += A.get(index++);\n }\n }\n }\n\n long after = System.currentTimeMillis();\n\n // print to ensure that ensure that an overly smart compiler does not optimize out\n // the whole function and to show that both produce the same results.\n System.out.println(total);\n\n return after-before;\n }", "private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }", "private ValidationResult _mergeListInternalForKey(String key, JSONArray left,\n JSONArray right, boolean remove, ValidationResult vr) {\n\n if (left == null) {\n vr.setObject(null);\n return vr;\n }\n\n if (right == null) {\n vr.setObject(left);\n return vr;\n }\n\n int maxValNum = Constants.MAX_MULTI_VALUE_ARRAY_LENGTH;\n\n JSONArray mergedList = new JSONArray();\n\n HashSet<String> set = new HashSet<>();\n\n int lsize = left.length(), rsize = right.length();\n\n BitSet dupSetForAdd = null;\n\n if (!remove)\n dupSetForAdd = new BitSet(lsize + rsize);\n\n int lidx = 0;\n\n int ridx = scan(right, set, dupSetForAdd, lsize);\n\n if (!remove && set.size() < maxValNum) {\n lidx = scan(left, set, dupSetForAdd, 0);\n }\n\n for (int i = lidx; i < lsize; i++) {\n try {\n if (remove) {\n String _j = (String) left.get(i);\n\n if (!set.contains(_j)) {\n mergedList.put(_j);\n }\n } else if (!dupSetForAdd.get(i)) {\n mergedList.put(left.get(i));\n }\n\n } catch (Throwable t) {\n //no-op\n }\n }\n\n if (!remove && mergedList.length() < maxValNum) {\n\n for (int i = ridx; i < rsize; i++) {\n\n try {\n if (!dupSetForAdd.get(i + lsize)) {\n mergedList.put(right.get(i));\n }\n } catch (Throwable t) {\n //no-op\n }\n }\n }\n\n // check to see if the list got trimmed in the merge\n if (ridx > 0 || lidx > 0) {\n vr.setErrorDesc(\"Multi value property for key \" + key + \" exceeds the limit of \" + maxValNum + \" items. Trimmed\");\n vr.setErrorCode(521);\n }\n\n vr.setObject(mergedList);\n\n return vr;\n }", "boolean isUserPasswordReset(CmsUser user) {\n\n if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before\n if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map\n return false;\n }\n if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load.\n return true; //Set gets flushed on reloading table\n }\n }\n CmsUser currentUser = user;\n if (user.getAdditionalInfo().size() < 3) {\n\n try {\n currentUser = m_cms.readUser(user.getId());\n } catch (CmsException e) {\n LOG.error(\"Can not read user\", e);\n }\n }\n if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) {\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true));\n m_checkedUserPasswordReset.add(currentUser.getId());\n return true;\n }\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false));\n return false;\n }", "@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}", "public byte[] encrypt(byte[] plainData) {\n checkArgument(plainData.length >= OVERHEAD_SIZE,\n \"Invalid plainData, %s bytes\", plainData.length);\n\n // workBytes := initVector || payload || zeros:4\n byte[] workBytes = plainData.clone();\n ByteBuffer workBuffer = ByteBuffer.wrap(workBytes);\n boolean success = false;\n\n try {\n // workBytes := initVector || payload || I(signature)\n int signature = hmacSignature(workBytes);\n workBuffer.putInt(workBytes.length - SIGNATURE_SIZE, signature);\n // workBytes := initVector || E(payload) || I(signature)\n xorPayloadToHmacPad(workBytes);\n\n if (logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted\", plainData, workBytes));\n }\n\n success = true;\n return workBytes;\n } finally {\n if (!success && logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted (failed)\", plainData, workBytes));\n }\n }\n }", "public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }" ]
Edit the text of a comment as the currently authenticated user. This method requires authentication with 'write' permission. @param commentId The id of the comment to edit. @param commentText Update the comment to this text. @throws FlickrException
[ "public void editComment(String commentId, String commentText) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COMMENT);\r\n\r\n parameters.put(\"comment_id\", commentId);\r\n parameters.put(\"comment_text\", commentText);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty\r\n // sucess response if it completes without error.\r\n }" ]
[ "private void processFile(InputStream is) throws MPXJException\n {\n int line = 1;\n\n try\n {\n //\n // Test the header and extract the separator. If this is successful,\n // we reset the stream back as far as we can. The design of the\n // BufferedInputStream class means that we can't get back to character\n // zero, so the first record we will read will get \"RMHDR\" rather than\n // \"ERMHDR\" in the first field position.\n //\n BufferedInputStream bis = new BufferedInputStream(is);\n byte[] data = new byte[6];\n data[0] = (byte) bis.read();\n bis.mark(1024);\n bis.read(data, 1, 5);\n\n if (!new String(data).equals(\"ERMHDR\"))\n {\n throw new MPXJException(MPXJException.INVALID_FILE);\n }\n\n bis.reset();\n\n InputStreamReader reader = new InputStreamReader(bis, getCharset());\n Tokenizer tk = new ReaderTokenizer(reader);\n tk.setDelimiter('\\t');\n List<String> record = new ArrayList<String>();\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n readRecord(tk, record);\n if (!record.isEmpty())\n {\n if (processRecord(record))\n {\n break;\n }\n }\n ++line;\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR + \" (failed at line \" + line + \")\", ex);\n }\n }", "public static String getHotPartitionsDueToContiguity(final Cluster cluster,\n int hotContiguityCutoff) {\n StringBuilder sb = new StringBuilder();\n\n for(int zoneId: cluster.getZoneIds()) {\n Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId);\n for(Integer initialPartitionId: idToRunLength.keySet()) {\n int runLength = idToRunLength.get(initialPartitionId);\n if(runLength < hotContiguityCutoff)\n continue;\n\n int hotPartitionId = (initialPartitionId + runLength)\n % cluster.getNumberOfPartitions();\n Node hotNode = cluster.getNodeForPartitionId(hotPartitionId);\n sb.append(\"\\tNode \" + hotNode.getId() + \" (\" + hotNode.getHost()\n + \") has hot primary partition \" + hotPartitionId\n + \" that follows contiguous run of length \" + runLength + Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }", "public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }", "private File decompileType(final DecompilerSettings settings, final WindupMetadataSystem metadataSystem, final String typeName) throws IOException\n {\n log.fine(\"Decompiling \" + typeName);\n\n final TypeReference type;\n\n // Hack to get around classes whose descriptors clash with primitive types.\n if (typeName.length() == 1)\n {\n final MetadataParser parser = new MetadataParser(IMetadataResolver.EMPTY);\n final TypeReference reference = parser.parseTypeDescriptor(typeName);\n type = metadataSystem.resolve(reference);\n }\n else\n type = metadataSystem.lookupType(typeName);\n\n if (type == null)\n {\n log.severe(\"Failed to load class: \" + typeName);\n return null;\n }\n\n final TypeDefinition resolvedType = type.resolve();\n if (resolvedType == null)\n {\n log.severe(\"Failed to resolve type: \" + typeName);\n return null;\n }\n\n boolean nested = resolvedType.isNested() || resolvedType.isAnonymous() || resolvedType.isSynthetic();\n if (!this.procyonConf.isIncludeNested() && nested)\n return null;\n\n settings.setJavaFormattingOptions(new JavaFormattingOptions());\n\n final FileOutputWriter writer = createFileWriter(resolvedType, settings);\n final PlainTextOutput output;\n\n output = new PlainTextOutput(writer);\n output.setUnicodeOutputEnabled(settings.isUnicodeOutputEnabled());\n if (settings.getLanguage() instanceof BytecodeLanguage)\n output.setIndentToken(\" \");\n\n DecompilationOptions options = new DecompilationOptions();\n options.setSettings(settings); // I'm missing why these two classes are split.\n\n // --------- DECOMPILE ---------\n final TypeDecompilationResults results = settings.getLanguage().decompileType(resolvedType, output, options);\n\n writer.flush();\n writer.close();\n\n // If we're writing to a file and we were asked to include line numbers in any way,\n // then reformat the file to include that line number information.\n final List<LineNumberPosition> lineNumberPositions = results.getLineNumberPositions();\n\n if (!this.procyonConf.getLineNumberOptions().isEmpty())\n {\n\n final LineNumberFormatter lineFormatter = new LineNumberFormatter(writer.getFile(), lineNumberPositions,\n this.procyonConf.getLineNumberOptions());\n\n lineFormatter.reformatFile();\n }\n return writer.getFile();\n }", "public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }", "public static RouteInfo of(ActionContext context) {\n H.Method m = context.req().method();\n String path = context.req().url();\n RequestHandler handler = context.handler();\n if (null == handler) {\n handler = UNKNOWN_HANDLER;\n }\n return new RouteInfo(m, path, handler);\n }", "public void updateRepeatNumber(int newNum, int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"repeat_number\", newNum, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }", "public static Value.Builder makeValue(Value value1, Value value2, Value... rest) {\n ArrayValue.Builder arrayValue = ArrayValue.newBuilder();\n arrayValue.addValues(value1);\n arrayValue.addValues(value2);\n arrayValue.addAllValues(Arrays.asList(rest));\n return Value.newBuilder().setArrayValue(arrayValue);\n }", "public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }" ]
Set the default host running the Odo instance to configure. Allows default profile methods and PathValueClient to operate on remote hosts @param hostName name of host
[ "public static void setDefaultHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n DEFAULT_BASE_URL = \"http://\" + hostName + \":\" + DEFAULT_API_PORT + \"/\" + API_BASE + \"/\";\n }" ]
[ "private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }", "public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalStateException(message);\n return value;\n }", "public void setMesh(GVRMesh mesh) {\n mMesh = mesh;\n NativeMeshCollider.setMesh(getNative(), mesh.getNative());\n }", "protected void onLegendDataChanged() {\n\n int legendCount = mLegendList.size();\n float margin = (mGraphWidth / legendCount);\n float currentOffset = 0;\n\n for (LegendModel model : mLegendList) {\n model.setLegendBounds(new RectF(currentOffset, 0, currentOffset + margin, mLegendHeight));\n currentOffset += margin;\n }\n\n Utils.calculateLegendInformation(mLegendList, 0, mGraphWidth, mLegendPaint);\n\n invalidateGlobal();\n }", "public static int cudnnSetTensor4dDescriptorEx(\n cudnnTensorDescriptor tensorDesc, \n int dataType, /** image data type */\n int n, /** number of inputs (batch size) */\n int c, /** number of input feature maps */\n int h, /** height of input section */\n int w, /** width of input section */\n int nStride, \n int cStride, \n int hStride, \n int wStride)\n {\n return checkResult(cudnnSetTensor4dDescriptorExNative(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride));\n }", "static int createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, DbConn cnx)\n {\n QueryResult qr = cnx.runUpdate(\"deliverable_insert\", fileFamily, path, jobId, originalFileName, UUID.randomUUID().toString());\n return qr.getGeneratedId();\n }", "public void useNewSOAPService(boolean direct) throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n org.customer.service.CustomerServiceService service = \n new org.customer.service.CustomerServiceService(wsdlURL);\n \n org.customer.service.CustomerService customerService = \n direct ? service.getCustomerServicePort() : service.getCustomerServiceNewPort();\n\n System.out.println(\"Using new SOAP CustomerService with new client\");\n \n customer.v2.Customer customer = createNewCustomer(\"Barry New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry New SOAP\");\n printNewCustomerDetails(customer);\n }", "protected boolean lacksSomeLanguage(ItemDocument itemDocument) {\n\t\tfor (int i = 0; i < arabicNumeralLanguages.length; i++) {\n\t\t\tif (!itemDocument.getLabels()\n\t\t\t\t\t.containsKey(arabicNumeralLanguages[i])) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "@Nonnull\n public static Proctor construct(@Nonnull final TestMatrixArtifact matrix, ProctorLoadResult loadResult, FunctionMapper functionMapper) {\n final ExpressionFactory expressionFactory = RuleEvaluator.EXPRESSION_FACTORY;\n\n final Map<String, TestChooser<?>> testChoosers = Maps.newLinkedHashMap();\n final Map<String, String> versions = Maps.newLinkedHashMap();\n\n for (final Entry<String, ConsumableTestDefinition> entry : matrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n final TestType testType = testDefinition.getTestType();\n final TestChooser<?> testChooser;\n if (TestType.RANDOM.equals(testType)) {\n testChooser = new RandomTestChooser(expressionFactory, functionMapper, testName, testDefinition);\n } else {\n testChooser = new StandardTestChooser(expressionFactory, functionMapper, testName, testDefinition);\n }\n testChoosers.put(testName, testChooser);\n versions.put(testName, testDefinition.getVersion());\n }\n\n return new Proctor(matrix, loadResult, testChoosers);\n }" ]
Write resource assignment workgroup. @param record resource assignment workgroup instance @throws IOException
[ "private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getMessageUniqueID()));\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getConfirmed() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(record.getResponsePending() ? \"1\" : \"0\");\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getScheduleID()));\n\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }" ]
[ "public void ifMemberTagValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n if (isTagValueEqual(attributes, FOR_FIELD)) {\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (isTagValueEqual(attributes, FOR_METHOD)) {\r\n generate(template);\r\n }\r\n }\r\n }", "protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "protected String getDBManipulationUrl()\r\n {\r\n JdbcConnectionDescriptor jcd = getConnection();\r\n\r\n return jcd.getProtocol()+\":\"+jcd.getSubProtocol()+\":\"+jcd.getDbAlias();\r\n }", "public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public String generateDigest(InputStream stream) {\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Calcuate the digest using the stream.\n DigestInputStream dis = new DigestInputStream(stream, digest);\n try {\n int value = dis.read();\n while (value != -1) {\n value = dis.read();\n }\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading the stream failed.\", ioe);\n }\n\n //Get the calculated digest for the stream\n byte[] digestBytes = digest.digest();\n return Base64.encode(digestBytes);\n }", "public static int[] convertBytesToInts(byte[] bytes)\n {\n if (bytes.length % 4 != 0)\n {\n throw new IllegalArgumentException(\"Number of input bytes must be a multiple of 4.\");\n }\n int[] ints = new int[bytes.length / 4];\n for (int i = 0; i < ints.length; i++)\n {\n ints[i] = convertBytesToInt(bytes, i * 4);\n }\n return ints;\n }", "public static void write(BufferedWriter writer, DatabaseFieldConfig config, String tableName) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config, tableName);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}", "public Identity refreshIdentity()\r\n {\r\n Identity oldOid = getIdentity();\r\n this.oid = getBroker().serviceIdentity().buildIdentity(myObj);\r\n return oldOid;\r\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n List<String> metaKeys = null;\n String url = null;\n\n // parse command-line input\n args = AdminToolUtils.copyArrayAddFirst(args, \"--\" + OPT_HEAD_META_CHECK);\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK);\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK);\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n\n // execute command\n if(metaKeys.size() == 0\n || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) {\n metaKeys = Lists.newArrayList();\n metaKeys.add(MetadataStore.CLUSTER_KEY);\n metaKeys.add(MetadataStore.STORES_KEY);\n metaKeys.add(MetadataStore.SERVER_STATE_KEY);\n }\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheck(adminClient, metaKeys);\n }" ]
Use this API to fetch vpntrafficpolicy_vpnglobal_binding resources of given name .
[ "public static vpntrafficpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_vpnglobal_binding obj = new vpntrafficpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_vpnglobal_binding response[] = (vpntrafficpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public boolean getHidden() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_HIDDEN);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return personElement.getAttribute(\"hidden\").equals(\"1\") ? true : false;\r\n }", "public void alias( Object ...args ) {\n if( args.length % 2 == 1 )\n throw new RuntimeException(\"Even number of arguments expected\");\n\n for (int i = 0; i < args.length; i += 2) {\n aliasGeneric( args[i], (String)args[i+1]);\n }\n }", "public String calculateCacheKey(String sql, int[] columnIndexes) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\tfor (int i=0; i < columnIndexes.length; i++){\r\n\t\t\ttmp.append(columnIndexes[i]);\r\n\t\t\ttmp.append(\"CI,\");\r\n\t\t}\r\n\t\treturn tmp.toString();\r\n\t}", "public String genId() {\n S.Buffer sb = S.newBuffer();\n sb.a(longEncoder.longToStr(nodeIdProvider.nodeId()))\n .a(longEncoder.longToStr(startIdProvider.startId()))\n .a(longEncoder.longToStr(sequenceProvider.seqId()));\n return sb.toString();\n }", "public static Region create(String name, String label) {\n Region region = VALUES_BY_NAME.get(name.toLowerCase());\n if (region != null) {\n return region;\n } else {\n return new Region(name, label);\n }\n }", "public static base_response add(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl addresource = new nssimpleacl();\n\t\taddresource.aclname = resource.aclname;\n\t\taddresource.aclaction = resource.aclaction;\n\t\taddresource.td = resource.td;\n\t\taddresource.srcip = resource.srcip;\n\t\taddresource.destport = resource.destport;\n\t\taddresource.protocol = resource.protocol;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}", "private List<DumpProcessingAction> handleArguments(String[] args) {\n\t\tCommandLine cmd;\n\t\tCommandLineParser parser = new GnuParser();\n\n\t\ttry {\n\t\t\tcmd = parser.parse(options, args);\n\t\t} catch (ParseException e) {\n\t\t\tlogger.error(\"Failed to parse arguments: \" + e.getMessage());\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\t// Stop processing if a help text is to be printed:\n\t\tif ((cmd.hasOption(CMD_OPTION_HELP)) || (args.length == 0)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<DumpProcessingAction> configuration = new ArrayList<>();\n\n\t\thandleGlobalArguments(cmd);\n\n\t\tif (cmd.hasOption(CMD_OPTION_ACTION)) {\n\t\t\tDumpProcessingAction action = handleActionArguments(cmd);\n\t\t\tif (action != null) {\n\t\t\t\tconfiguration.add(action);\n\t\t\t}\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CONFIG_FILE)) {\n\t\t\ttry {\n\t\t\t\tList<DumpProcessingAction> configFile = readConfigFile(cmd\n\t\t\t\t\t\t.getOptionValue(CMD_OPTION_CONFIG_FILE));\n\t\t\t\tconfiguration.addAll(configFile);\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"Failed to read configuration file \\\"\"\n\t\t\t\t\t\t+ cmd.getOptionValue(CMD_OPTION_CONFIG_FILE) + \"\\\": \"\n\t\t\t\t\t\t+ e.toString());\n\t\t\t}\n\n\t\t}\n\n\t\treturn configuration;\n\n\t}", "@SuppressWarnings(\"unchecked\")\n\t/* @Nullable */\n\tpublic <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\t\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\treturn (T) f.get(receiver);\n\t}", "private int getItemViewType(Class prototypeClass) {\n int itemViewType = -1;\n for (Renderer renderer : prototypes) {\n if (renderer.getClass().equals(prototypeClass)) {\n itemViewType = getPrototypeIndex(renderer);\n break;\n }\n }\n if (itemViewType == -1) {\n throw new PrototypeNotFoundException(\n \"Review your RendererBuilder implementation, you are returning one\"\n + \" prototype class not found in prototypes collection\");\n }\n return itemViewType;\n }" ]
Use this API to flush nssimpleacl.
[ "public static base_response flush(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl flushresource = new nssimpleacl();\n\t\tflushresource.estsessions = resource.estsessions;\n\t\treturn flushresource.perform_operation(client,\"flush\");\n\t}" ]
[ "static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n if (ENABLE_INVALIDATION) {\n updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG);\n backup(context, file);\n }\n } else if (mode == PatchingTaskContext.Mode.ROLLBACK) {\n updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG);\n restore(context, file);\n } else {\n throw new IllegalStateException();\n }\n }", "public float getBoundsWidth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.x - v.minCorner.x;\n }\n return 0f;\n }", "private Key insert(Entity entity) throws DatastoreException {\n CommitRequest req = CommitRequest.newBuilder()\n\t.addMutations(Mutation.newBuilder()\n\t .setInsert(entity))\n .setMode(CommitRequest.Mode.NON_TRANSACTIONAL)\n\t.build();\n return datastore.commit(req).getMutationResults(0).getKey();\n }", "public static <E extends Enum<? extends Style.HasCssName>> E fromStyleName(final String styleName,\n final Class<E> enumClass,\n final E defaultValue) {\n return EnumHelper.fromStyleName(styleName, enumClass, defaultValue, true);\n }", "private static String buildErrorMsg(List<String> dependencies, String message) {\n final StringBuilder buffer = new StringBuilder();\n boolean isFirstElement = true;\n for (String dependency : dependencies) {\n if (!isFirstElement) {\n buffer.append(\", \");\n }\n // check if it is an instance of Artifact - add the gavc else append the object\n buffer.append(dependency);\n\n isFirstElement = false;\n }\n return String.format(message, buffer.toString());\n }", "public Class<E> getEventClass() {\n if (cachedClazz != null) {\n return cachedClazz;\n }\n Class<?> clazz = this.getClass();\n while (clazz != Object.class) {\n try {\n Type mySuperclass = clazz.getGenericSuperclass();\n Type tType = ((ParameterizedType) mySuperclass).getActualTypeArguments()[0];\n cachedClazz = (Class<E>) Class.forName(tType.getTypeName());\n return cachedClazz;\n } catch (Exception e) {\n }\n clazz = clazz.getSuperclass();\n }\n throw new IllegalStateException(\"Failed to load event class - \" + this.getClass().getCanonicalName());\n }", "public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}", "private void addTables(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Table table : file.getTables())\n {\n final Table t = table;\n MpxjTreeNode childNode = new MpxjTreeNode(table, TABLE_EXCLUDED_METHODS)\n {\n @Override public String toString()\n {\n return t.getName();\n }\n };\n parentNode.add(childNode);\n\n addColumns(childNode, table);\n }\n }", "public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }" ]
Cache key calculation. @param sql @param resultSetType @param resultSetConcurrency @return cache key
[ "private StringBuilder calculateCacheKeyInternal(String sql,\r\n\t\t\tint resultSetType, int resultSetConcurrency) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+20);\r\n\t\ttmp.append(sql);\r\n\r\n\t\ttmp.append(\", T\");\r\n\t\ttmp.append(resultSetType);\r\n\t\ttmp.append(\", C\");\r\n\t\ttmp.append(resultSetConcurrency);\r\n\t\treturn tmp;\r\n\t}" ]
[ "protected InternalHttpResponse sendInternalRequest(HttpRequest request) {\n InternalHttpResponder responder = new InternalHttpResponder();\n httpResourceHandler.handle(request, responder);\n return responder.getResponse();\n }", "public String getRecordSchema() throws IOException {\n Schema schema = getInputPathAvroSchema();\n String recSchema = schema.toString();\n return recSchema;\n }", "public static Trajectory combineTrajectory(Trajectory a, Trajectory b){\n\t\tif(a.getDimension()!=b.getDimension()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not have the same dimension\");\n\t\t}\n\t\tif(a.size()!=b.size()){\n\t\t\tthrow new IllegalArgumentException(\"Combination not possible: The trajectorys does not \"\n\t\t\t\t\t+ \"have the same number of steps a=\"+a.size() + \" b=\"+b.size());\n\t\t}\n\t\tTrajectory c = new Trajectory(a.getDimension());\n\t\t\n\t\tfor(int i = 0 ; i < a.size(); i++){\n\t\t\tPoint3d pos = new Point3d(a.get(i).x+b.get(i).x, \n\t\t\t\t\ta.get(i).y+b.get(i).y, \n\t\t\t\t\ta.get(i).z+b.get(i).z);\n\t\t\tc.add(pos);\n\t\t}\n\t\t\n\t\treturn c;\n\t}", "protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }", "public MtasCQLParserSentenceCondition createFullSentence()\n throws ParseException {\n if (fullCondition == null) {\n if (secondSentencePart == null) {\n if (firstBasicSentence != null) {\n fullCondition = new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength);\n\n } else {\n fullCondition = firstSentence;\n }\n fullCondition.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n if (firstOptional) {\n fullCondition.setOptional(firstOptional);\n }\n return fullCondition;\n } else {\n if (!orOperator) {\n if (firstBasicSentence != null) {\n firstBasicSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstBasicSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(\n firstBasicSentence, ignoreClause, maximumIgnoreLength);\n } else {\n firstSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(firstSentence,\n ignoreClause, maximumIgnoreLength);\n }\n fullCondition.addSentenceToEndLatestSequence(\n secondSentencePart.createFullSentence());\n } else {\n MtasCQLParserSentenceCondition sentence = secondSentencePart\n .createFullSentence();\n if (firstBasicSentence != null) {\n sentence.addSentenceAsFirstOption(\n new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength));\n } else {\n sentence.addSentenceAsFirstOption(firstSentence);\n }\n fullCondition = sentence;\n }\n return fullCondition;\n }\n } else {\n return fullCondition;\n }\n }", "public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) {\n d.negate();\n Quaternionf q = new Quaternionf();\n // check for exception condition\n if ((d.x == 0) && (d.z == 0)) {\n // exception condition if direction is (0,y,0):\n // straight up, straight down or all zero's.\n if (d.y > 0) { // direction straight up\n AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0,\n 0);\n q.set(angleAxis);\n } else if (d.y < 0) { // direction straight down\n AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0);\n q.set(angleAxis);\n } else { // All zero's. Just set to identity quaternion\n q.identity();\n }\n } else {\n d.normalize();\n Vector3f up = new Vector3f(0, 1, 0);\n Vector3f s = new Vector3f();\n d.cross(up, s);\n s.normalize();\n Vector3f u = new Vector3f();\n d.cross(s, u);\n u.normalize();\n Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x,\n d.y, d.z, 0, 0, 0, 0, 1);\n q.setFromNormalized(matrix);\n }\n return q;\n }", "private Map<UUID, List<DateRange>> processDayTypes(List<MapRow> types)\n {\n Map<UUID, List<DateRange>> map = new HashMap<UUID, List<DateRange>>();\n for (MapRow row : types)\n {\n List<DateRange> ranges = new ArrayList<DateRange>();\n for (MapRow range : row.getRows(\"TIME_RANGES\"))\n {\n ranges.add(new DateRange(range.getDate(\"START\"), range.getDate(\"END\")));\n }\n map.put(row.getUUID(\"UUID\"), ranges);\n }\n\n return map;\n }", "private MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)\n {\n Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);\n if (!mavenProjectModels.iterator().hasNext())\n {\n return null;\n }\n for (MavenProjectModel mavenProjectModel : mavenProjectModels)\n {\n if (mavenProjectModel.getRootFileModel() == null)\n {\n // this is a stub... we can fill it in with details\n return mavenProjectModel;\n }\n }\n return null;\n }", "private static boolean isAssignableFrom(WildcardType type1, Type type2) {\n if (!isAssignableFrom(type1.getUpperBounds()[0], type2)) {\n return false;\n }\n if (type1.getLowerBounds().length > 0 && !isAssignableFrom(type2, type1.getLowerBounds()[0])) {\n return false;\n }\n return true;\n }" ]
Notifies that multiple header items are inserted. @param positionStart the position. @param itemCount the item count.
[ "public final void notifyHeaderItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (newHeaderItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart, itemCount);\n }" ]
[ "public Document createDOM(PDDocument doc) throws IOException\n {\n /* We call the original PDFTextStripper.writeText but nothing should\n be printed actually because our processing methods produce no output.\n They create the DOM structures instead */\n super.writeText(doc, new OutputStreamWriter(System.out));\n return this.doc;\n }", "public static appfwprofile_crosssitescripting_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_crosssitescripting_binding obj = new appfwprofile_crosssitescripting_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_crosssitescripting_binding response[] = (appfwprofile_crosssitescripting_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public PropertiesEnvelope getUserProperties(String userId, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = getUserPropertiesWithHttpInfo(userId, aid);\n return resp.getData();\n }", "public Map<String, Table> process(File directory, String prefix) throws IOException\n {\n String filePrefix = prefix.toUpperCase();\n Map<String, Table> tables = new HashMap<String, Table>();\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n String name = file.getName().toUpperCase();\n if (!name.startsWith(filePrefix))\n {\n continue;\n }\n\n int typeIndex = name.lastIndexOf('.') - 3;\n String type = name.substring(typeIndex, typeIndex + 3);\n TableDefinition definition = TABLE_DEFINITIONS.get(type);\n if (definition != null)\n {\n Table table = new Table();\n TableReader reader = new TableReader(definition);\n reader.read(file, table);\n tables.put(type, table);\n //dumpCSV(type, definition, table);\n }\n }\n }\n return tables;\n }", "public void invalidate(final int dataIndex) {\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"invalidate [%d]\", dataIndex);\n mMeasuredChildren.remove(dataIndex);\n }\n }", "public static vpnvserver_vpnsessionpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnsessionpolicy_binding obj = new vpnvserver_vpnsessionpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnsessionpolicy_binding response[] = (vpnvserver_vpnsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static final GVRPickedObject[] pickObjects(GVRScene scene, float ox, float oy, float oz, float dx,\n float dy, float dz) {\n sFindObjectsLock.lock();\n try {\n final GVRPickedObject[] result = NativePicker.pickObjects(scene.getNative(), 0L, ox, oy, oz, dx, dy, dz);\n return result;\n } finally {\n sFindObjectsLock.unlock();\n }\n }", "public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs);\n recordAsyncOpTimeNs(null, opTimeNs);\n } else {\n this.asynOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }", "private ClassMatcher buildMatcher(String tagText) {\n\t// check there are at least @match <type> and a parameter\n\tString[] strings = StringUtil.tokenize(tagText);\n\tif (strings.length < 2) {\n\t System.err.println(\"Skipping uncomplete @match tag, type missing: \" + tagText + \" in view \" + viewDoc);\n\t return null;\n\t}\n\t\n\ttry {\n\t if (strings[0].equals(\"class\")) {\n\t\treturn new PatternMatcher(Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"context\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"outgoingContext\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"interface\")) {\n\t\treturn new InterfaceMatcher(root, Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"subclass\")) {\n\t\treturn new SubclassMatcher(root, Pattern.compile(strings[1]));\n\t } else {\n\t\tSystem.err.println(\"Skipping @match tag, unknown match type, in view \" + viewDoc);\n\t }\n\t} catch (PatternSyntaxException pse) {\n\t System.err.println(\"Skipping @match tag due to invalid regular expression '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t} catch (Exception e) {\n\t System.err.println(\"Skipping @match tag due to an internal error '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t e.printStackTrace();\n\t}\n\treturn null;\n }" ]
Find the current layout and extract the activity code order and visibility. @param phoenixProject phoenix project data
[ "private void processLayouts(Project phoenixProject)\n {\n //\n // Find the active layout\n //\n Layout activeLayout = getActiveLayout(phoenixProject);\n\n //\n // Create a list of the visible codes in the correct order\n //\n for (CodeOption option : activeLayout.getCodeOptions().getCodeOption())\n {\n if (option.isShown().booleanValue())\n {\n m_codeSequence.add(getUUID(option.getCodeUuid(), option.getCode()));\n }\n }\n }" ]
[ "public RandomVariable[] getGradient(){\r\n\r\n\t\t// for now let us take the case for output-dimension equal to one!\r\n\t\tint numberOfVariables = getNumberOfVariablesInList();\r\n\t\tint numberOfCalculationSteps = factory.getNumberOfEntriesInList();\r\n\r\n\t\tRandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\t// first entry gets initialized\r\n\t\tomega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\t/*\r\n\t\t * TODO: Find way that calculations form here on are not 'recorded' by the factory\r\n\t\t * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!\r\n\t\t * */\r\n\r\n\t\tfor(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){\r\n\t\t\t// apply chain rule\r\n\t\t\tomega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\t/*TODO: save all D_{i,j}*\\omega_j in vector and sum up later */\r\n\t\t\tfor(RandomVariableUniqueVariable parent:parentsVariables){\r\n\r\n\t\t\t\tint variableIndex = parent.getVariableID();\r\n\r\n\t\t\t\tomega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex]));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!\r\n\t\t * Thus save the indices of the true variables and recover them after finalizing all the calculations\r\n\t\t * IDEA: quit calculation after minimal true variable index is reached */\r\n\t\tRandomVariable[] gradient = new RandomVariable[numberOfVariables];\r\n\r\n\t\t/* TODO: sort array in correct manner! */\r\n\t\tint[] indicesOfVariables = getIDsOfVariablesInList();\r\n\r\n\t\tfor(int i = 0; i < numberOfVariables; i++){\r\n\t\t\tgradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]];\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}", "public void setNodeMetaData(Object key, Object value) {\n if (key==null) throw new GroovyBugError(\"Tried to set meta data with null key on \"+this+\".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n Object old = metaDataMap.put(key,value);\n if (old!=null) throw new GroovyBugError(\"Tried to overwrite existing meta data \"+this+\".\");\n }", "private void configureConfigurationSelector() {\n\n if (m_checkinBean.getConfigurations().size() < 2) {\n // Do not show the configuration selection at all.\n removeComponent(m_configurationSelectionPanel);\n } else {\n for (CmsGitConfiguration configuration : m_checkinBean.getConfigurations()) {\n m_configurationSelector.addItem(configuration);\n m_configurationSelector.setItemCaption(configuration, configuration.getName());\n }\n m_configurationSelector.setNullSelectionAllowed(false);\n m_configurationSelector.setNewItemsAllowed(false);\n m_configurationSelector.setWidth(\"350px\");\n m_configurationSelector.select(m_checkinBean.getCurrentConfiguration());\n\n // There is really a choice between configurations\n m_configurationSelector.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"synthetic-access\")\n public void valueChange(ValueChangeEvent event) {\n\n updateForNewConfiguration((CmsGitConfiguration)event.getProperty().getValue());\n restoreFieldsFromUserInfo();\n\n }\n });\n }\n }", "private boolean shouldIgnore(String typeReference)\n {\n typeReference = typeReference.replace('/', '.').replace('\\\\', '.');\n return JavaClassIgnoreResolver.singletonInstance().matches(typeReference);\n }", "protected ExpectState prepareClosure(int pairIndex, MatchResult result) {\n /* TODO: potentially remove this?\n {\n System.out.println( \"Begin: \" + result.beginOffset(0) );\n System.out.println( \"Length: \" + result.length() );\n System.out.println( \"Current: \" + input.getCurrentOffset() );\n System.out.println( \"Begin: \" + input.getMatchBeginOffset() );\n System.out.println( \"End: \" + input.getMatchEndOffset() );\n //System.out.println( \"Match: \" + input.match() );\n //System.out.println( \"Pre: >\" + input.preMatch() + \"<\");\n //System.out.println( \"Post: \" + input.postMatch() );\n }\n */\n\n // Prepare Closure environment\n ExpectState state;\n Map<String, Object> prevMap = null;\n if (g_state != null) {\n prevMap = g_state.getVars();\n }\n\n int matchedWhere = result.beginOffset(0);\n String matchedText = result.toString(); // expect_out(0,string)\n\n // Unmatched upto end of match\n // expect_out(buffer)\n char[] chBuffer = input.getBuffer();\n String copyBuffer = new String(chBuffer, 0, result.endOffset(0) );\n\n List<String> groups = new ArrayList<>();\n for (int j = 1; j <= result.groups(); j++) {\n String group = result.group(j);\n groups.add( group );\n }\n state = new ExpectState(copyBuffer.toString(), matchedWhere, matchedText, pairIndex, groups, prevMap);\n\n return state;\n }", "public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }", "private void validateJUnit4() throws BuildException {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n throw new BuildException(\"At least JUnit version 4.10 is required on junit4's taskdef classpath.\");\n }\n } catch (ClassNotFoundException e) {\n throw new BuildException(\"JUnit JAR must be added to junit4 taskdef's classpath.\");\n }\n }", "public Map<String, T> parseMap(JsonParser jsonParser) throws IOException {\n HashMap<String, T> map = new HashMap<String, T>();\n while (jsonParser.nextToken() != JsonToken.END_OBJECT) {\n String key = jsonParser.getText();\n jsonParser.nextToken();\n if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) {\n map.put(key, null);\n } else{\n map.put(key, parse(jsonParser));\n }\n }\n return map;\n }", "static void initSingleParam(String key, String initValue, DbConn cnx)\n {\n try\n {\n cnx.runSelectSingle(\"globalprm_select_by_key\", 2, String.class, key);\n return;\n }\n catch (NoResultException e)\n {\n GlobalParameter.create(cnx, key, initValue);\n }\n catch (NonUniqueResultException e)\n {\n // It exists! Nothing to do...\n }\n }" ]
Should be called after new data is inserted. Will be automatically called, when the view dimensions has changed. Calculates the start- and end-angles for every PieSlice.
[ "@Override\n protected void onDataChanged() {\n super.onDataChanged();\n\n int currentAngle = 0;\n int index = 0;\n int size = mPieData.size();\n\n for (PieModel model : mPieData) {\n int endAngle = (int) (currentAngle + model.getValue() * 360.f / mTotalValue);\n if(index == size-1) {\n endAngle = 360;\n }\n\n model.setStartAngle(currentAngle);\n model.setEndAngle(endAngle);\n currentAngle = model.getEndAngle();\n index++;\n }\n calcCurrentItem();\n onScrollFinished();\n }" ]
[ "public Map<String, ClientWidgetInfo> securityClone(Map<String, ClientWidgetInfo> widgetInfo) {\n\t\tMap<String, ClientWidgetInfo> res = new HashMap<String, ClientWidgetInfo>();\n\t\tfor (Map.Entry<String, ClientWidgetInfo> entry : widgetInfo.entrySet()) {\n\t\t\tClientWidgetInfo value = entry.getValue();\n\t\t\tif (!(value instanceof ServerSideOnlyInfo)) {\n\t\t\t\tres.put(entry.getKey(), value);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}", "public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }", "private void batchStatusLog(int batchCount,\n int numBatches,\n int partitionStoreCount,\n int numPartitionStores,\n long totalTimeMs) {\n // Calculate the estimated end time and pretty print stats\n double rate = 1;\n long estimatedTimeMs = 0;\n if(numPartitionStores > 0) {\n rate = partitionStoreCount / numPartitionStores;\n estimatedTimeMs = (long) (totalTimeMs / rate) - totalTimeMs;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Batch Complete!\")\n .append(Utils.NEWLINE)\n .append(\"\\tbatches moved: \")\n .append(batchCount)\n .append(\" out of \")\n .append(numBatches)\n .append(Utils.NEWLINE)\n .append(\"\\tPartition stores moved: \")\n .append(partitionStoreCount)\n .append(\" out of \")\n .append(numPartitionStores)\n .append(Utils.NEWLINE)\n .append(\"\\tPercent done: \")\n .append(decimalFormatter.format(rate * 100.0))\n .append(Utils.NEWLINE)\n .append(\"\\tEstimated time left: \")\n .append(estimatedTimeMs)\n .append(\" ms (\")\n .append(TimeUnit.MILLISECONDS.toHours(estimatedTimeMs))\n .append(\" hours)\");\n RebalanceUtils.printBatchLog(batchCount, logger, sb.toString());\n }", "private void remove(String directoryName) {\n if ((directoryName == null) || (conn == null))\n return;\n\n String key = S3Util.sanitize(directoryName) + \"/\" + S3Util.sanitize(DC_FILE_NAME);\n try {\n Map headers = new TreeMap();\n headers.put(\"Content-Type\", Arrays.asList(\"text/plain\"));\n if (usingPreSignedUrls()) {\n conn.delete(pre_signed_delete_url).connection.getResponseMessage();\n } else {\n conn.delete(location, key, headers).connection.getResponseMessage();\n }\n }\n catch(Exception e) {\n ROOT_LOGGER.cannotRemoveS3File(e);\n }\n }", "public SimplifySpanBuild append(String text) {\n if (TextUtils.isEmpty(text)) return this;\n\n mNormalSizeText.append(text);\n mStringBuilder.append(text);\n return this;\n }", "@Override\n public Integer getMasterPartition(byte[] key) {\n return abs(hash.hash(key)) % (Math.max(1, this.partitionToNode.length));\n }", "public ChangesResult getChanges() {\n final URI uri = this.databaseHelper.changesUri(\"feed\", \"normal\");\n return client.get(uri, ChangesResult.class);\n }", "public static autoscaleaction get(nitro_service service, String name) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tobj.set_name(name);\n\t\tautoscaleaction response = (autoscaleaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected final <T> StyleSupplier<T> createStyleSupplier(\n final Template template,\n final String styleRef) {\n return new StyleSupplier<T>() {\n @Override\n public Style load(\n final MfClientHttpRequestFactory requestFactory,\n final T featureSource) {\n final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser;\n return OptionalUtils.or(\n () -> template.getStyle(styleRef),\n () -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef))\n .orElse(template.getConfiguration().getDefaultStyle(NAME));\n }\n };\n }" ]
This method is used to extract the task hyperlink attributes from a block of data and call the appropriate modifier methods to configure the specified task object. @param task task instance @param data hyperlink data block
[ "private void processHyperlinkData(Task task, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n String hyperlink;\n String address;\n String subaddress;\n\n offset += 12;\n hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n subaddress = MPPUtility.getUnicodeString(data, offset);\n\n task.setHyperlink(hyperlink);\n task.setHyperlinkAddress(address);\n task.setHyperlinkSubAddress(subaddress);\n }\n }" ]
[ "ValidationResult cleanObjectKey(String name) {\n ValidationResult vr = new ValidationResult();\n name = name.trim();\n for (String x : objectKeyCharsNotAllowed)\n name = name.replace(x, \"\");\n\n if (name.length() > Constants.MAX_KEY_LENGTH) {\n name = name.substring(0, Constants.MAX_KEY_LENGTH-1);\n vr.setErrorDesc(name.trim() + \"... exceeds the limit of \"+ Constants.MAX_KEY_LENGTH + \" characters. Trimmed\");\n vr.setErrorCode(520);\n }\n\n vr.setObject(name.trim());\n\n return vr;\n }", "public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }", "public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\n }", "PathAddress toPathAddress(final ObjectName name) {\n return ObjectNameAddressUtil.toPathAddress(rootObjectInstance.getObjectName(), getRootResourceAndRegistration().getRegistration(), name);\n }", "public static String readContent(InputStream is) {\n String ret = \"\";\n try {\n String line;\n BufferedReader in = new BufferedReader(new InputStreamReader(is));\n StringBuffer out = new StringBuffer();\n\n while ((line = in.readLine()) != null) {\n out.append(line).append(CARRIAGE_RETURN);\n }\n ret = out.toString();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return ret;\n }", "private void pushDeviceToken(final String token, final boolean register, final PushType type) {\n pushDeviceToken(this.context, token, register, type);\n }", "private void onRead0() {\n assert inWire.startUse();\n\n ensureCapacity();\n\n try {\n\n while (!inWire.bytes().isEmpty()) {\n\n try (DocumentContext dc = inWire.readingDocument()) {\n if (!dc.isPresent())\n return;\n\n try {\n if (YamlLogging.showServerReads())\n logYaml(dc);\n onRead(dc, outWire);\n onWrite(outWire);\n } catch (Exception e) {\n Jvm.warn().on(getClass(), \"inWire=\" + inWire.getClass() + \",yaml=\" + Wires.fromSizePrefixedBlobs(dc), e);\n }\n }\n }\n\n } finally {\n assert inWire.endUse();\n }\n }", "public final Set<String> getOutputFormatsNames() {\n SortedSet<String> formats = new TreeSet<>();\n for (String formatBeanName: this.outputFormat.keySet()) {\n int endingIndex = formatBeanName.indexOf(MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING);\n if (endingIndex < 0) {\n endingIndex = formatBeanName.indexOf(OUTPUT_FORMAT_BEAN_NAME_ENDING);\n }\n formats.add(formatBeanName.substring(0, endingIndex));\n }\n return formats;\n }", "public static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) {\n List<String> storeNames = Lists.newArrayList();\n List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId)\n .getValue();\n\n for(StoreDefinition storeDefinition: storeDefinitionList) {\n storeNames.add(storeDefinition.getName());\n }\n return storeNames;\n }" ]
Additional objects to include with the requested group. Note that all the optional includes depend on "assignments" also being included. @param includes List of included objects to return @return this object to continue building options
[ "public GetAssignmentGroupOptions includes(List<Include> includes) {\n List<Include> assignmentDependents = Arrays.asList(Include.DISCUSSION_TOPIC, Include.ASSIGNMENT_VISIBILITY, Include.SUBMISSION);\n if(includes.stream().anyMatch(assignmentDependents::contains) && !includes.contains(Include.ASSIGNMENTS)) {\n throw new IllegalArgumentException(\"Including discussion topics, all dates, assignment visibility or submissions is only valid if you also include submissions\");\n }\n addEnumList(\"include[]\", includes);\n return this;\n }" ]
[ "public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\n }", "public UseCase selectUseCase()\r\n {\r\n displayUseCases();\r\n System.out.println(\"type in number to select a use case\");\r\n String in = readLine();\r\n int index = Integer.parseInt(in);\r\n return (UseCase) useCases.get(index);\r\n }", "public void append(float[] newValue) {\n if ( (newValue.length % 2) == 0) {\n for (int i = 0; i < (newValue.length/2); i++) {\n value.add( new SFVec2f(newValue[i*2], newValue[i*2+1]) );\n }\n }\n else {\n Log.e(TAG, \"X3D MFVec3f append set with array length not divisible by 2\");\n }\n }", "public void pauseUpload() throws LocalOperationException {\n if (state == State.UPLOADING) {\n setState(State.PAUSED);\n executor.hardStop();\n } else {\n throw new LocalOperationException(\"Attempt to pause upload while assembly is not uploading\");\n }\n }", "public int evaluate(FieldContainer container)\n {\n //\n // First step - determine the list of criteria we are should use\n //\n List<GraphicalIndicatorCriteria> criteria;\n if (container instanceof Task)\n {\n Task task = (Task) container;\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n if (m_projectSummaryInheritsFromSummaryRows == false)\n {\n criteria = m_projectSummaryCriteria;\n }\n else\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n if (task.getSummary() == true)\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n // It is possible to have a resource summary row, but at the moment\n // I can't see how you can determine this.\n criteria = m_nonSummaryRowCriteria;\n }\n\n //\n // Now we have the criteria, evaluate each one until we get a result\n //\n int result = -1;\n for (GraphicalIndicatorCriteria gic : criteria)\n {\n result = gic.evaluate(container);\n if (result != -1)\n {\n break;\n }\n }\n\n //\n // If we still don't have a result at the end, return the\n // default value, which is 0\n //\n if (result == -1)\n {\n result = 0;\n }\n\n return (result);\n }", "private int convertMoneyness(double moneyness) {\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\treturn (int) Math.round(moneyness * 100);\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\treturn - (int) Math.round(moneyness * 10000);\r\n\t\t} else {\r\n\t\t\treturn (int) Math.round(moneyness * 10000);\r\n\t\t}\r\n\t}", "private DBHandling createDBHandling() throws BuildException\r\n {\r\n if ((_handling == null) || (_handling.length() == 0))\r\n {\r\n throw new BuildException(\"No handling specified\");\r\n }\r\n try\r\n {\r\n String className = \"org.apache.ojb.broker.platforms.\"+\r\n \t\t\t\t\t Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+\r\n \t\t\t\t\t \"DBHandling\";\r\n Class handlingClass = ClassHelper.getClass(className);\r\n\r\n return (DBHandling)handlingClass.newInstance();\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new BuildException(\"Invalid handling '\"+_handling+\"' specified\");\r\n }\r\n }", "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }", "public static Comment createComment(final String entityId,\n\t\t\t\t\t\t\t\t\t\tfinal String entityType,\n\t\t\t\t\t\t\t\t\t\tfinal String action,\n\t\t\t\t\t\t\t\t\t\tfinal String commentedText,\n\t\t\t\t\t\t\t\t\t\tfinal String user,\n\t\t\t\t\t\t\t\t\t\tfinal Date date) {\n\n\t\tfinal Comment comment = new Comment();\n\t\tcomment.setEntityId(entityId);\n\t\tcomment.setEntityType(entityType);\n\t\tcomment.setAction(action);\n\t\tcomment.setCommentText(commentedText);\n\t\tcomment.setCommentedBy(user);\n\t\tcomment.setCreatedDateTime(date);\n\t\treturn comment;\n\t}" ]
Extracts the column from a matrix. @param a Input matrix @param column Which column is to be extracted @param out output. Storage for the extracted column. If null then a new vector will be returned. @return The extracted column.
[ "public static DMatrixRMaj extractColumn(DMatrixRMaj a , int column , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(a.numRows,1);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numRows )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numRows);\n\n int index = column;\n for (int i = 0; i < a.numRows; i++, index += a.numCols ) {\n out.data[i] = a.data[index];\n }\n return out;\n }" ]
[ "private void addSequence(String sequenceName, HighLowSequence seq)\r\n {\r\n // lookup the sequence map for calling DB\r\n String jcdAlias = getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias();\r\n Map mapForDB = (Map) sequencesDBMap.get(jcdAlias);\r\n if(mapForDB == null)\r\n {\r\n mapForDB = new HashMap();\r\n }\r\n mapForDB.put(sequenceName, seq);\r\n sequencesDBMap.put(jcdAlias, mapForDB);\r\n }", "public UriComponentsBuilder replaceQueryParam(String name, Object... values) {\n\t\tAssert.notNull(name, \"'name' must not be null\");\n\t\tthis.queryParams.remove(name);\n\t\tif (!ObjectUtils.isEmpty(values)) {\n\t\t\tqueryParam(name, values);\n\t\t}\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}", "public static AccumuloClient getClient(FluoConfiguration config) {\n return Accumulo.newClient().to(config.getAccumuloInstance(), config.getAccumuloZookeepers())\n .as(config.getAccumuloUser(), config.getAccumuloPassword()).build();\n }", "public static UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }", "public static void d(ISubsystem subsystem, String tag, String pattern, Object... parameters) {\n if (!isEnabled(subsystem)) return;\n d(subsystem, tag, format(pattern, parameters));\n }", "public long countByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zlexcount(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }", "public PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }", "protected boolean waitForJobs() throws InterruptedException {\n final Pair<Long, Job> peekPair;\n try (Guard ignored = timeQueue.lock()) {\n peekPair = timeQueue.peekPair();\n }\n if (peekPair == null) {\n awake.acquire();\n return true;\n }\n final long timeout = Long.MAX_VALUE - peekPair.getFirst() - System.currentTimeMillis();\n if (timeout < 0) {\n return false;\n }\n return awake.tryAcquire(timeout, TimeUnit.MILLISECONDS);\n }", "public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }" ]
Obtains the Constructor specified from the given Class and argument types @throws NoSuchMethodException
[ "public static Constructor<?> getConstructor(final Class<?> clazz,\n final Class<?>... argumentTypes) throws NoSuchMethodException {\n try {\n return AccessController\n .doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {\n public Constructor<?> run()\n throws NoSuchMethodException {\n return clazz.getConstructor(argumentTypes);\n }\n });\n }\n // Unwrap\n catch (final PrivilegedActionException pae) {\n final Throwable t = pae.getCause();\n // Rethrow\n if (t instanceof NoSuchMethodException) {\n throw (NoSuchMethodException) t;\n } else {\n // No other checked Exception thrown by Class.getConstructor\n try {\n throw (RuntimeException) t;\n }\n // Just in case we've really messed up\n catch (final ClassCastException cce) {\n throw new RuntimeException(\n \"Obtained unchecked Exception; this code should never be reached\",\n t);\n }\n }\n }\n }" ]
[ "@JsonInclude(Include.NON_EMPTY)\n\t@JsonProperty(\"id\")\n\tpublic String getJsonId() {\n\t\tif (!EntityIdValue.SITE_LOCAL.equals(this.siteIri)) {\n\t\t\treturn this.entityId;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}", "public static base_response restore(nitro_service client, appfwprofile resource) throws Exception {\n\t\tappfwprofile restoreresource = new appfwprofile();\n\t\trestoreresource.archivename = resource.archivename;\n\t\treturn restoreresource.perform_operation(client,\"restore\");\n\t}", "public void promote() {\n URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, \"current\");\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"type\", \"file_version\");\n jsonObject.add(\"id\", this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(jsonObject.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n this.parseJSON(JsonObject.readFrom(response.getJSON()));\n }", "@Override public void render() {\n Video video = getContent();\n renderThumbnail(video);\n renderTitle(video);\n renderMarker(video);\n renderLabel();\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getClientList(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier) throws Exception {\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n return Utils.getJQGridJSON(clientService.findAllClients(profileId), \"clients\");\n }", "public void spawnThread(DukeController controller, int check_interval) {\n this.controller = controller;\n timer = mgr.schedule(this, 0, check_interval * 1000); // convert to ms\n }", "private int calcItemWidth(RecyclerView rvCategories) {\n if (itemWidth == null || itemWidth == 0) {\n for (int i = 0; i < rvCategories.getChildCount(); i++) {\n itemWidth = rvCategories.getChildAt(i).getWidth();\n if (itemWidth != 0) {\n break;\n }\n }\n }\n // in case of call before view was created\n if (itemWidth == null) {\n itemWidth = 0;\n }\n return itemWidth;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public String formatCueCountdown() {\n int count = getCueCountdown();\n\n if (count == 511) {\n return \"--.-\";\n }\n\n if ((count >= 1) && (count <= 256)) {\n int bars = (count - 1) / 4;\n int beats = ((count - 1) % 4) + 1;\n return String.format(\"%02d.%d\", bars, beats);\n }\n\n if (count == 0) {\n return \"00.0\";\n }\n\n return \"??.?\";\n }", "public Collection values()\r\n {\r\n if (values != null) return values;\r\n values = new AbstractCollection()\r\n {\r\n public int size()\r\n {\r\n return size;\r\n }\r\n\r\n public void clear()\r\n {\r\n ReferenceMap.this.clear();\r\n }\r\n\r\n public Iterator iterator()\r\n {\r\n return new ValueIterator();\r\n }\r\n };\r\n return values;\r\n }" ]
With the QR algorithm it is possible for the found singular values to be negative. This makes them all positive by multiplying it by a diagonal matrix that has
[ "private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = qralg.getSingularValue(i);\n\n if( val < 0 ) {\n singularValues[i] = 0.0 - val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.set(j, 0.0 - Ut.get(j));\n }\n }\n } else {\n singularValues[i] = val;\n }\n }\n }" ]
[ "@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }", "private void stop() {\n\t\tfor (int i = 0; i < mDownloadDispatchers.length; i++) {\n\t\t\tif (mDownloadDispatchers[i] != null) {\n\t\t\t\tmDownloadDispatchers[i].quit();\n\t\t\t}\n\t\t}\n\t}", "public int getGeoPerms() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GEO_PERMS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n int perm = -1;\r\n Element personElement = response.getPayload();\r\n String geoPerms = personElement.getAttribute(\"geoperms\");\r\n try {\r\n perm = Integer.parseInt(geoPerms);\r\n } catch (NumberFormatException e) {\r\n throw new FlickrException(\"0\", \"Unable to parse geoPermission\");\r\n }\r\n return perm;\r\n }", "public final void setAttributes(final Map<String, Attribute> attributes) {\n for (Map.Entry<String, Attribute> entry: attributes.entrySet()) {\n Object attribute = entry.getValue();\n if (!(attribute instanceof Attribute)) {\n final String msg =\n \"Attribute: '\" + entry.getKey() + \"' is not an attribute. It is a: \" + attribute;\n LOGGER.error(\"Error setting the Attributes: {}\", msg);\n throw new IllegalArgumentException(msg);\n } else {\n ((Attribute) attribute).setConfigName(entry.getKey());\n }\n }\n this.attributes = attributes;\n }", "public CmsJspInstanceDateBean getToInstanceDate() {\n\n if (m_instanceDate == null) {\n m_instanceDate = new CmsJspInstanceDateBean(getToDate(), m_cms.getRequestContext().getLocale());\n }\n return m_instanceDate;\n }", "public int getIndexFromOffset(int offset)\n {\n int result = -1;\n\n for (int loop = 0; loop < m_offset.length; loop++)\n {\n if (m_offset[loop] == offset)\n {\n result = loop;\n break;\n }\n }\n\n return (result);\n }", "public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }", "public static long readBytes(byte[] bytes, int offset, int numBytes) {\n int shift = 0;\n long value = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n value |= (bytes[i] & 0xFFL) << shift;\n shift += 8;\n }\n return value;\n }", "@TargetApi(VERSION_CODES.KITKAT)\n public static void showSystemUI(Activity activity) {\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n );\n }" ]
Sobel method to generate bump map from a height map @param input - A height map @return bump map
[ "@Override\n public ImageSource apply(ImageSource input) {\n int w = input.getWidth();\n int h = input.getHeight();\n\n MatrixSource output = new MatrixSource(input);\n\n Vector3 n = new Vector3(0, 0, 1);\n\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n\n if (x < border || x == w - border || y < border || y == h - border) {\n output.setRGB(x, y, VectorHelper.Z_NORMAL);\n continue;\n }\n\n float s0 = input.getR(x - 1, y + 1);\n float s1 = input.getR(x, y + 1);\n float s2 = input.getR(x + 1, y + 1);\n float s3 = input.getR(x - 1, y);\n float s5 = input.getR(x + 1, y);\n float s6 = input.getR(x - 1, y - 1);\n float s7 = input.getR(x, y - 1);\n float s8 = input.getR(x + 1, y - 1);\n\n float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);\n float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);\n\n n.set(nx, ny, scale);\n n.nor();\n\n int rgb = VectorHelper.vectorToColor(n);\n output.setRGB(x, y, rgb);\n }\n }\n\n return new MatrixSource(output);\n }" ]
[ "public static Node addPartitionToNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition));\n }", "public ServerRedirect updateServerRedirectHost(int serverMappingId, String hostHeader) {\n ServerRedirect redirect = new ServerRedirect();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"hostHeader\", hostHeader),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVER + \"/\" + serverMappingId + \"/host\", params));\n redirect = getServerRedirectFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return redirect;\n }", "public void fireRelationWrittenEvent(Relation relation)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.relationWritten(relation);\n }\n }\n }", "public String toNormalizedString(boolean keepMixed, IPv6StringOptions params) {\n\t\tif(keepMixed && fromString != null && getAddressfromString().isMixedIPv6() && !params.makeMixed()) {\n\t\t\tparams = new IPv6StringOptions(\n\t\t\t\t\tparams.base,\n\t\t\t\t\tparams.expandSegments,\n\t\t\t\t\tparams.wildcardOption,\n\t\t\t\t\tparams.wildcards,\n\t\t\t\t\tparams.segmentStrPrefix,\n\t\t\t\t\ttrue,\n\t\t\t\t\tparams.ipv4Opts,\n\t\t\t\t\tparams.compressOptions,\n\t\t\t\t\tparams.separator,\n\t\t\t\t\tparams.zoneSeparator,\n\t\t\t\t\tparams.addrLabel,\n\t\t\t\t\tparams.addrSuffix,\n\t\t\t\t\tparams.reverse,\n\t\t\t\t\tparams.splitDigits,\n\t\t\t\t\tparams.uppercase);\n\t\t}\n\t\treturn toNormalizedString(params);\n\t}", "public boolean hasPossibleMethod(String name, Expression arguments) {\n int count = 0;\n\n if (arguments instanceof TupleExpression) {\n TupleExpression tuple = (TupleExpression) arguments;\n // TODO this won't strictly be true when using list expansion in argument calls\n count = tuple.getExpressions().size();\n }\n ClassNode node = this;\n do {\n for (MethodNode method : getMethods(name)) {\n if (method.getParameters().length == count && !method.isStatic()) {\n return true;\n }\n }\n node = node.getSuperClass();\n }\n while (node != null);\n return false;\n }", "@Override\n public boolean applyLayout(Layout itemLayout) {\n boolean applied = false;\n if (itemLayout != null && mItemLayouts.add(itemLayout)) {\n\n // apply the layout to all visible pages\n List<Widget> views = getAllViews();\n for (Widget view: views) {\n view.applyLayout(itemLayout.clone());\n }\n applied = true;\n }\n return applied;\n }", "public static Method getGetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"get\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\tif (sourceMethod == null) {\r\n\t\t\tsourceMethodName = \"is\"\r\n\t\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\t\t\tsourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\t\t\tif (sourceMethod != null\r\n\t\t\t\t\t&& sourceMethod.getReturnType() != Boolean.TYPE) {\r\n\t\t\t\tsourceMethod = null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sourceMethod;\r\n\t}", "private boolean hasToBuilderMethod(\n DeclaredType builder,\n boolean isExtensible,\n Iterable<ExecutableElement> methods) {\n for (ExecutableElement method : methods) {\n if (isToBuilderMethod(builder, method)) {\n if (!isExtensible) {\n messager.printMessage(ERROR,\n \"No accessible no-args Builder constructor available to implement toBuilder\",\n method);\n }\n return true;\n }\n }\n return false;\n }", "private void checkExistingTracks() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n checkIfSignatureReady(entry.getKey().player);\n }\n }\n }\n });\n }" ]
Gets information about all of the group memberships for this group. Does not support paging. @return a collection of information about the group memberships for this group.
[ "public Collection<BoxGroupMembership.Info> getMemberships() {\n final BoxAPIConnection api = this.getAPI();\n final String groupID = this.getID();\n\n Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID);\n return new BoxGroupMembershipIterator(api, url);\n }\n };\n\n // We need to iterate all results because this method must return a Collection. This logic should be removed in\n // the next major version, and instead return the Iterable directly.\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>();\n for (BoxGroupMembership.Info membership : iter) {\n memberships.add(membership);\n }\n return memberships;\n }" ]
[ "public T removeBundle(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createBundleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }", "public static base_response enable(nitro_service client, Long clid) throws Exception {\n\t\tclusterinstance enableresource = new clusterinstance();\n\t\tenableresource.clid = clid;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }", "protected static void validateSignature(final DataInput input) throws IOException {\n final byte[] signatureBytes = new byte[4];\n input.readFully(signatureBytes);\n if (!Arrays.equals(ManagementProtocol.SIGNATURE, signatureBytes)) {\n throw ProtocolLogger.ROOT_LOGGER.invalidSignature(Arrays.toString(signatureBytes));\n }\n }", "public static vpnclientlessaccesspolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy_binding obj = new vpnclientlessaccesspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy_binding response = (vpnclientlessaccesspolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public GeoPermissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // response:\r\n // <perms id=\"240935723\" ispublic=\"1\" iscontact=\"0\" isfriend=\"0\" isfamily=\"0\"/>\r\n GeoPermissions perms = new GeoPermissions();\r\n Element permsElement = response.getPayload();\r\n perms.setPublic(\"1\".equals(permsElement.getAttribute(\"ispublic\")));\r\n perms.setContact(\"1\".equals(permsElement.getAttribute(\"iscontact\")));\r\n perms.setFriend(\"1\".equals(permsElement.getAttribute(\"isfriend\")));\r\n perms.setFamily(\"1\".equals(permsElement.getAttribute(\"isfamily\")));\r\n perms.setId(permsElement.getAttribute(\"id\"));\r\n // I ignore the id attribute. should be the same as the given\r\n // photo id.\r\n return perms;\r\n }", "@Override\r\n public String upload(InputStream in, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(in);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public AT_Row setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private static Properties loadGradleProperties(FilePath gradlePropertiesFilePath)\n throws IOException, InterruptedException {\n return gradlePropertiesFilePath.act(new MasterToSlaveFileCallable<Properties>() {\n public Properties invoke(File gradlePropertiesFile, VirtualChannel channel) throws IOException, InterruptedException {\n Properties gradleProps = new Properties();\n if (gradlePropertiesFile.exists()) {\n debuggingLogger.fine(\"Gradle properties file exists at: \" + gradlePropertiesFile.getAbsolutePath());\n FileInputStream stream = null;\n try {\n stream = new FileInputStream(gradlePropertiesFile);\n gradleProps.load(stream);\n } catch (IOException e) {\n debuggingLogger.fine(\"IO exception occurred while trying to read properties file from: \" +\n gradlePropertiesFile.getAbsolutePath());\n throw new RuntimeException(e);\n } finally {\n IOUtils.closeQuietly(stream);\n }\n }\n return gradleProps;\n }\n });\n\n }" ]
Convert an object to another object with given type @param <T> @param source object to convert @param typeReference reference to {@link java.lang.reflect.Type} @return the converted object if conversion failed @throws ConverterException
[ "public <T> T convert(Object source, TypeReference<T> typeReference)\r\n\t\t\tthrows ConverterException {\r\n\t\treturn (T) convert(new ConversionContext(), source, typeReference);\r\n\t}" ]
[ "static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}", "public boolean isMaskCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\tif(!isMultiple()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn super.isMaskCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}", "public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }", "public static String md5(byte[] source) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest();\n char str[] = new char[32];\n int k = 0;\n for (byte b : tmp) {\n str[k++] = hexDigits[b >>> 4 & 0xf];\n str[k++] = hexDigits[b & 0xf];\n }\n return new String(str);\n\n } catch (Exception e) {\n throw new IllegalArgumentException(e);\n }\n }", "InputStream openContentStream(final ContentItem item) throws IOException {\n final File file = getFile(item);\n if (file == null) {\n throw new IllegalStateException();\n }\n return new FileInputStream(file);\n }", "public static SimpleMatrix diag( Class type, double ...vals ) {\n SimpleMatrix M = new SimpleMatrix(vals.length,vals.length,type);\n for (int i = 0; i < vals.length; i++) {\n M.set(i,i,vals[i]);\n }\n return M;\n }", "public void addExportedPackages(Set<String> exportedPackages) {\n\t\taddExportedPackages(exportedPackages.toArray(new String[exportedPackages.size()]));\n\t}", "public static final void setSize(UIObject o, Rect size) {\n o.setPixelSize(size.w, size.h);\n\n }", "private static <T> void writeConfig(BufferedWriter writer, DatabaseTableConfig<T> config) throws IOException,\n\t\t\tSQLException {\n\t\twriter.append(CONFIG_FILE_START_MARKER);\n\t\twriter.newLine();\n\t\tif (config.getDataClass() != null) {\n\t\t\twriter.append(FIELD_NAME_DATA_CLASS).append('=').append(config.getDataClass().getName());\n\t\t\twriter.newLine();\n\t\t}\n\t\tif (config.getTableName() != null) {\n\t\t\twriter.append(FIELD_NAME_TABLE_NAME).append('=').append(config.getTableName());\n\t\t\twriter.newLine();\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_START);\n\t\twriter.newLine();\n\t\tif (config.getFieldConfigs() != null) {\n\t\t\tfor (DatabaseFieldConfig field : config.getFieldConfigs()) {\n\t\t\t\tDatabaseFieldConfigLoader.write(writer, field, config.getTableName());\n\t\t\t}\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_END);\n\t\twriter.newLine();\n\t\twriter.append(CONFIG_FILE_END_MARKER);\n\t\twriter.newLine();\n\t}" ]
Returns an empty model of a Dependency in Json @return String @throws IOException
[ "public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }" ]
[ "@Override\n public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {\n return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);\n }", "static BsonDocument getFreshVersionDocument() {\n final BsonDocument versionDoc = new BsonDocument();\n\n versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1));\n versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString()));\n versionDoc.append(Fields.VERSION_COUNTER_FIELD, new BsonInt64(0L));\n\n return versionDoc;\n }", "public int size(final K1 firstKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap = map.get(firstKey);\n\t\tif( innerMap == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap.size();\n\t}", "protected void failedToCleanupDir(final File file) {\n checkForGarbageOnRestart = true;\n PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath());\n }", "private void processScheduleOptions()\n {\n List<Row> rows = getRows(\"schedoptions\", \"proj_id\", m_projectID);\n if (rows.isEmpty() == false)\n {\n Row row = rows.get(0);\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", row.getString(\"sched_calendar_on_relationship_lag\"));\n customProperties.put(\"RetainedLogic\", Boolean.valueOf(row.getBoolean(\"sched_retained_logic\")));\n customProperties.put(\"ProgressOverride\", Boolean.valueOf(row.getBoolean(\"sched_progress_override\")));\n customProperties.put(\"IgnoreOtherProjectRelationships\", row.getString(\"sched_outer_depend_type\"));\n customProperties.put(\"StartToStartLagCalculationType\", Boolean.valueOf(row.getBoolean(\"sched_lag_early_start_flag\")));\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n }\n }", "public void setIntegerAttribute(String name, Integer value) {\n\t\tensureValue();\n\t\tAttribute attribute = new IntegerAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}", "private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n CollectionDescriptorDef collDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)\r\n {\r\n collDef = (CollectionDescriptorDef)collIt.next();\r\n if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))\r\n {\r\n checkIndirectionTable(modelDef, collDef);\r\n }\r\n else\r\n { \r\n checkCollectionForeignkeys(modelDef, collDef);\r\n }\r\n }\r\n }\r\n }\r\n }", "public static void checkMinimumArrayLength(String parameterName,\n int actualLength, int minimumLength) {\n if (actualLength < minimumLength) {\n throw Exceptions\n .IllegalArgument(\n \"Array %s should have at least %d elements, but it only has %d\",\n parameterName, minimumLength, actualLength);\n }\n }", "public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\n }" ]
Process each regex group matched substring of the given CharSequence. If the closure parameter takes one argument, an array with all match groups is passed to it. If the closure takes as many arguments as there are match groups, then each parameter will be one match group. @param self the source CharSequence @param regex a Regex CharSequence @param closure a closure with one parameter or as much parameters as groups @return the source CharSequence @see #eachMatch(String, String, groovy.lang.Closure) @since 1.8.2
[ "public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n eachMatch(self.toString(), regex.toString(), closure);\n return self;\n }" ]
[ "private void populateConstraints(Row row, Task task)\n {\n Date endDateMax = row.getTimestamp(\"ZGIVENENDDATEMAX_\");\n Date endDateMin = row.getTimestamp(\"ZGIVENENDDATEMIN_\");\n Date startDateMax = row.getTimestamp(\"ZGIVENSTARTDATEMAX_\");\n Date startDateMin = row.getTimestamp(\"ZGIVENSTARTDATEMIN_\");\n\n ConstraintType constraintType = null;\n Date constraintDate = null;\n\n if (endDateMax != null)\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = endDateMax;\n }\n\n if (endDateMin != null)\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = endDateMin;\n }\n\n if (endDateMin != null && endDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = endDateMin;\n }\n\n if (startDateMax != null)\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = startDateMax;\n }\n\n if (startDateMin != null)\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = startDateMin;\n }\n\n if (startDateMin != null && startDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = endDateMin;\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }", "private void processWorkWeekDay(byte[] data, int offset, ProjectCalendarWeek week, Day day)\n {\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 60, false));\n\n int dayType = MPPUtility.getShort(data, offset + 0);\n if (dayType == 1)\n {\n week.setWorkingDay(day, DayType.DEFAULT);\n }\n else\n {\n ProjectCalendarHours hours = week.addCalendarHours(day);\n int rangeCount = MPPUtility.getShort(data, offset + 2);\n if (rangeCount == 0)\n {\n week.setWorkingDay(day, DayType.NON_WORKING);\n }\n else\n {\n week.setWorkingDay(day, DayType.WORKING);\n Calendar cal = DateHelper.popCalendar();\n for (int index = 0; index < rangeCount; index++)\n {\n Date startTime = DateHelper.getCanonicalTime(MPPUtility.getTime(data, offset + 8 + (index * 2)));\n int durationInSeconds = MPPUtility.getInt(data, offset + 20 + (index * 4)) * 6;\n cal.setTime(startTime);\n cal.add(Calendar.SECOND, durationInSeconds);\n Date finishTime = DateHelper.getCanonicalTime(cal.getTime());\n hours.addRange(new DateRange(startTime, finishTime));\n }\n DateHelper.pushCalendar(cal);\n }\n }\n }", "public LuaScriptBlock endBlockReturn(LuaValue value) {\n add(new LuaAstReturnStatement(argument(value)));\n return new LuaScriptBlock(script);\n }", "static String encodeUriComponent(String source, String encoding, Type type) throws UnsupportedEncodingException {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tAssert.hasLength(encoding, \"Encoding must not be empty\");\n\t\tbyte[] bytes = encodeBytes(source.getBytes(encoding), type);\n\t\treturn new String(bytes, \"US-ASCII\");\n\t}", "public static String getDumpFilePostfix(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.POSTFIXES.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.POSTFIXES.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}", "public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationForLocations(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {alert('rec:'+status);\\ndocument.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n LOG.trace(\"ElevationService direct call: \" + r.toString());\n \n getJSObject().eval(r.toString());\n \n }", "public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) {\n double tau = 0;\n for (int i = xStart; i < xEnd ; i++) {\n double val = x[i] /= max;\n tau += val*val;\n }\n tau = Math.sqrt(tau);\n if( x[xStart] < 0 ) {\n tau = -tau;\n }\n double u_0 = x[xStart] + tau;\n gamma.value = u_0/tau;\n x[xStart] = 1;\n for (int i = xStart+1; i < xEnd ; i++) {\n x[i] /= u_0;\n }\n\n return -tau*max;\n }", "public static <E> Set<E> union(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n s.addAll(s1);\r\n s.addAll(s2);\r\n return s;\r\n }", "private void initStyleGenerators() {\n\n if (m_model.hasMasterMode()) {\n m_styleGenerators.put(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER)));\n }\n m_styleGenerators.put(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n new CmsMessageBundleEditorTypes.TranslateTableCellStyleGenerator(\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT)));\n\n }" ]
Calculate the pointer's coordinates on the color wheel using the supplied angle. @param angle The position of the pointer expressed as angle (in rad). @return The coordinates of the pointer's center in our internal coordinate system.
[ "private float[] calculatePointerPosition(float angle) {\n\t\tfloat x = (float) (mColorWheelRadius * Math.cos(angle));\n\t\tfloat y = (float) (mColorWheelRadius * Math.sin(angle));\n\n\t\treturn new float[] { x, y };\n\t}" ]
[ "public static clusterinstance_binding get(nitro_service service, Long clid) throws Exception{\n\t\tclusterinstance_binding obj = new clusterinstance_binding();\n\t\tobj.set_clid(clid);\n\t\tclusterinstance_binding response = (clusterinstance_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static void append(File file, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new FileWriter(file, true);\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "private void checkAndAddNodeStore() {\n for(Node node: metadata.getCluster().getNodes()) {\n if(!routedStore.getInnerStores().containsKey(node.getId())) {\n if(!storeRepository.hasNodeStore(getName(), node.getId())) {\n storeRepository.addNodeStore(node.getId(), createNodeStore(node));\n }\n routedStore.getInnerStores().put(node.getId(),\n storeRepository.getNodeStore(getName(),\n node.getId()));\n }\n }\n }", "private void setObjectForStatement(PreparedStatement stmt, int index, Object value, int sqlType)\r\n throws SQLException\r\n {\r\n if (value == null)\r\n {\r\n m_platform.setNullForStatement(stmt, index, sqlType);\r\n }\r\n else\r\n {\r\n m_platform.setObjectForStatement(stmt, index, value, sqlType);\r\n }\r\n }", "protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }", "public static String toJson(Date date) {\n if (date == null) {\n return NULL_VALUE;\n }\n\n CharBuf buffer = CharBuf.create(26);\n writeDate(date, buffer);\n\n return buffer.toString();\n }", "private static JSONArray parseChildShapesRecursive(ArrayList<Shape> childShapes) throws JSONException {\n if (childShapes != null) {\n JSONArray childShapesArray = new JSONArray();\n\n for (Shape childShape : childShapes) {\n JSONObject childShapeObject = new JSONObject();\n\n childShapeObject.put(\"resourceId\",\n childShape.getResourceId().toString());\n childShapeObject.put(\"properties\",\n parseProperties(childShape.getProperties()));\n childShapeObject.put(\"stencil\",\n parseStencil(childShape.getStencilId()));\n childShapeObject.put(\"childShapes\",\n parseChildShapesRecursive(childShape.getChildShapes()));\n childShapeObject.put(\"outgoing\",\n parseOutgoings(childShape.getOutgoings()));\n childShapeObject.put(\"bounds\",\n parseBounds(childShape.getBounds()));\n childShapeObject.put(\"dockers\",\n parseDockers(childShape.getDockers()));\n\n if (childShape.getTarget() != null) {\n childShapeObject.put(\"target\",\n parseTarget(childShape.getTarget()));\n }\n\n childShapesArray.put(childShapeObject);\n }\n\n return childShapesArray;\n }\n\n return new JSONArray();\n }", "public static base_response delete(nitro_service client, String ipv6address) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static base_responses export(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey exportresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new sslfipskey();\n\t\t\t\texportresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\texportresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}" ]
Returns a copy of this year-quarter with the new year and quarter, checking to see if a new object is in fact required. @param newYear the year to represent, validated from MIN_YEAR to MAX_YEAR @param newQuarter the quarter-of-year to represent, validated not null @return the year-quarter, not null
[ "private YearQuarter with(int newYear, Quarter newQuarter) {\n if (year == newYear && quarter == newQuarter) {\n return this;\n }\n return new YearQuarter(newYear, newQuarter);\n }" ]
[ "private String findLoggingProfile(final ResourceRoot resourceRoot) {\n final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);\n if (manifest != null) {\n final String loggingProfile = manifest.getMainAttributes().getValue(LOGGING_PROFILE);\n if (loggingProfile != null) {\n LoggingLogger.ROOT_LOGGER.debugf(\"Logging profile '%s' found in '%s'.\", loggingProfile, resourceRoot);\n return loggingProfile;\n }\n }\n return null;\n }", "private void writeResource(Resource mpxjResource, net.sf.mpxj.planner.schema.Resource plannerResource)\n {\n ProjectCalendar resourceCalendar = mpxjResource.getResourceCalendar();\n if (resourceCalendar != null)\n {\n plannerResource.setCalendar(getIntegerString(resourceCalendar.getUniqueID()));\n }\n\n plannerResource.setEmail(mpxjResource.getEmailAddress());\n plannerResource.setId(getIntegerString(mpxjResource.getUniqueID()));\n plannerResource.setName(getString(mpxjResource.getName()));\n plannerResource.setNote(mpxjResource.getNotes());\n plannerResource.setShortName(mpxjResource.getInitials());\n plannerResource.setType(mpxjResource.getType() == ResourceType.MATERIAL ? \"2\" : \"1\");\n //plannerResource.setStdRate();\n //plannerResource.setOvtRate();\n plannerResource.setUnits(\"0\");\n //plannerResource.setProperties();\n m_eventManager.fireResourceWrittenEvent(mpxjResource);\n }", "protected Iterator<MACAddress> iterator(MACAddress original) {\r\n\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\tboolean isSingle = !isMultiple();\r\n\t\treturn iterator(\r\n\t\t\t\tisSingle ? original : null, \r\n\t\t\t\tcreator,//using a lambda for this one results in a big performance hit\r\n\t\t\t\tisSingle ? null : segmentsIterator(),\r\n\t\t\t\tgetNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets() ? null : getPrefixLength());\r\n\t}", "public boolean isHomeKeyPresent() {\n final GVRApplication application = mApplication.get();\n if (null != application) {\n final String model = getHmtModel();\n if (null != model && model.contains(\"R323\")) {\n return true;\n }\n }\n return false;\n }", "public static base_response delete(nitro_service client, appfwlearningdata resource) throws Exception {\n\t\tappfwlearningdata deleteresource = new appfwlearningdata();\n\t\tdeleteresource.profilename = resource.profilename;\n\t\tdeleteresource.starturl = resource.starturl;\n\t\tdeleteresource.cookieconsistency = resource.cookieconsistency;\n\t\tdeleteresource.fieldconsistency = resource.fieldconsistency;\n\t\tdeleteresource.formactionurl_ffc = resource.formactionurl_ffc;\n\t\tdeleteresource.crosssitescripting = resource.crosssitescripting;\n\t\tdeleteresource.formactionurl_xss = resource.formactionurl_xss;\n\t\tdeleteresource.sqlinjection = resource.sqlinjection;\n\t\tdeleteresource.formactionurl_sql = resource.formactionurl_sql;\n\t\tdeleteresource.fieldformat = resource.fieldformat;\n\t\tdeleteresource.formactionurl_ff = resource.formactionurl_ff;\n\t\tdeleteresource.csrftag = resource.csrftag;\n\t\tdeleteresource.csrfformoriginurl = resource.csrfformoriginurl;\n\t\tdeleteresource.xmldoscheck = resource.xmldoscheck;\n\t\tdeleteresource.xmlwsicheck = resource.xmlwsicheck;\n\t\tdeleteresource.xmlattachmentcheck = resource.xmlattachmentcheck;\n\t\tdeleteresource.totalxmlrequests = resource.totalxmlrequests;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public boolean isResourceExcluded(final PathAddress address) {\n if (!localHostControllerInfo.isMasterDomainController() && address.size() > 0) {\n IgnoredDomainResourceRoot root = this.rootResource;\n PathElement firstElement = address.getElement(0);\n IgnoreDomainResourceTypeResource typeResource = root == null ? null : root.getChildInternal(firstElement.getKey());\n if (typeResource != null) {\n if (typeResource.hasName(firstElement.getValue())) {\n return true;\n }\n }\n }\n return false;\n }", "public SqlStatement getPreparedInsertStatement(ClassDescriptor cld)\r\n {\r\n SqlStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getInsertSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getInsertProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlInsertStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setInsertSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }", "private void addNewGenderName(EntityIdValue entityIdValue, String name) {\n\t\tthis.genderNames.put(entityIdValue, name);\n\t\tthis.genderNamesList.add(entityIdValue);\n\t}", "public static void dumpMaterialProperty(AiMaterial.Property property) {\n System.out.print(property.getKey() + \" \" + property.getSemantic() + \n \" \" + property.getIndex() + \": \");\n Object data = property.getData();\n \n if (data instanceof ByteBuffer) {\n ByteBuffer buf = (ByteBuffer) data;\n for (int i = 0; i < buf.capacity(); i++) {\n System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + \" \");\n }\n \n System.out.println();\n }\n else {\n System.out.println(data.toString());\n }\n }" ]
Attempts to add classification to a file. If classification already exists then do update. @param classificationType the metadata classification type. @return the metadata classification type on the file.
[ "public String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }" ]
[ "private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public void addAttribute(String attributeName, String attributeValue)\r\n {\r\n if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))\r\n {\r\n final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);\r\n jdbcProperties.setProperty(jdbcPropertyName, attributeValue);\r\n }\r\n else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))\r\n {\r\n final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);\r\n dbcpProperties.setProperty(dbcpPropertyName, attributeValue);\r\n }\r\n else\r\n {\r\n super.addAttribute(attributeName, attributeValue);\r\n }\r\n }", "private void readTextsCompressed(File dir, HashMap results) throws IOException\r\n {\r\n if (dir.exists() && dir.isDirectory())\r\n {\r\n File[] files = dir.listFiles();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (files[idx].isDirectory())\r\n {\r\n continue;\r\n }\r\n results.put(files[idx].getName(), readTextCompressed(files[idx]));\r\n }\r\n }\r\n }", "public static base_response add(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile addresource = new dbdbprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.interpretquery = resource.interpretquery;\n\t\taddresource.stickiness = resource.stickiness;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.conmultiplex = resource.conmultiplex;\n\t\treturn addresource.add_resource(client);\n\t}", "private static int[] getMode3PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n int[] postcodeNums = new int[postcode.length()];\r\n\r\n postcode = postcode.toUpperCase();\r\n for (int i = 0; i < postcodeNums.length; i++) {\r\n postcodeNums[i] = postcode.charAt(i);\r\n if (postcode.charAt(i) >= 'A' && postcode.charAt(i) <= 'Z') {\r\n // (Capital) letters shifted to Code Set A values\r\n postcodeNums[i] -= 64;\r\n }\r\n if (postcodeNums[i] == 27 || postcodeNums[i] == 31 || postcodeNums[i] == 33 || postcodeNums[i] >= 59) {\r\n // Not a valid postal code character, use space instead\r\n postcodeNums[i] = 32;\r\n }\r\n // Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital\r\n // letters in Code Set A (e.g. LF becomes 'J')\r\n }\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNums[5] & 0x03) << 4) | 3;\r\n primary[1] = ((postcodeNums[4] & 0x03) << 4) | ((postcodeNums[5] & 0x3c) >> 2);\r\n primary[2] = ((postcodeNums[3] & 0x03) << 4) | ((postcodeNums[4] & 0x3c) >> 2);\r\n primary[3] = ((postcodeNums[2] & 0x03) << 4) | ((postcodeNums[3] & 0x3c) >> 2);\r\n primary[4] = ((postcodeNums[1] & 0x03) << 4) | ((postcodeNums[2] & 0x3c) >> 2);\r\n primary[5] = ((postcodeNums[0] & 0x03) << 4) | ((postcodeNums[1] & 0x3c) >> 2);\r\n primary[6] = ((postcodeNums[0] & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }", "public static int rank(DMatrixRMaj A , double threshold ) {\n SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(A.numRows,A.numCols,false,false,true);\n\n if( svd.inputModified() )\n A = A.copy();\n\n if( !svd.decompose(A) )\n throw new RuntimeException(\"Decomposition failed\");\n\n return SingularOps_DDRM.rank(svd, threshold);\n }", "public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }", "public static IndexedContainer getGroupsOfUser(\n CmsObject cms,\n CmsUser user,\n String caption,\n String iconProp,\n String ou,\n String propStatus,\n Function<CmsGroup, CmsCssIcon> iconProvider) {\n\n IndexedContainer container = new IndexedContainer();\n container.addContainerProperty(caption, String.class, \"\");\n container.addContainerProperty(ou, String.class, \"\");\n container.addContainerProperty(propStatus, Boolean.class, new Boolean(true));\n if (iconProvider != null) {\n container.addContainerProperty(iconProp, CmsCssIcon.class, null);\n }\n try {\n for (CmsGroup group : cms.getGroupsOfUser(user.getName(), true)) {\n Item item = container.addItem(group);\n item.getItemProperty(caption).setValue(group.getSimpleName());\n item.getItemProperty(ou).setValue(group.getOuFqn());\n if (iconProvider != null) {\n item.getItemProperty(iconProp).setValue(iconProvider.apply(group));\n }\n }\n } catch (CmsException e) {\n LOG.error(\"Unable to read groups from user\", e);\n }\n return container;\n }", "private void addDownloadButton(final CmsLogFileView view) {\n\n Button button = CmsToolBar.createButton(\n FontOpenCms.DOWNLOAD,\n CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n button.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n Window window = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.wide);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n window.setContent(new CmsLogDownloadDialog(window, view.getCurrentFile()));\n A_CmsUI.get().addWindow(window);\n }\n });\n m_uiContext.addToolbarButton(button);\n }" ]
Checks whether the property of the given name is allowed for the model element. @param defClass The class of the model element @param propertyName The name of the property @return <code>true</code> if the property is allowed for this type of model elements
[ "public static boolean isPropertyAllowed(Class defClass, String propertyName)\r\n {\r\n HashMap props = (HashMap)_properties.get(defClass);\r\n\r\n return (props == null ? true : props.containsKey(propertyName));\r\n }" ]
[ "private void handleChange(Object propertyId) {\n\n if (!m_saveBtn.isEnabled()) {\n m_saveBtn.setEnabled(true);\n m_saveExitBtn.setEnabled(true);\n }\n m_model.handleChange(propertyId);\n\n }", "static String expandUriComponent(String source, UriTemplateVariables uriVariables) {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (source.indexOf('{') == -1) {\n\t\t\treturn source;\n\t\t}\n\t\tMatcher matcher = NAMES_PATTERN.matcher(source);\n\t\tStringBuffer sb = new StringBuffer();\n\t\twhile (matcher.find()) {\n\t\t\tString match = matcher.group(1);\n\t\t\tString variableName = getVariableName(match);\n\t\t\tObject variableValue = uriVariables.getValue(variableName);\n\t\t\tif (UriTemplateVariables.SKIP_VALUE.equals(variableValue)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString variableValueString = getVariableValueAsString(variableValue);\n\t\t\tString replacement = Matcher.quoteReplacement(variableValueString);\n\t\t\tmatcher.appendReplacement(sb, replacement);\n\t\t}\n\t\tmatcher.appendTail(sb);\n\t\treturn sb.toString();\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) {\n return requestMetadataInternal(track, trackType, false);\n }", "private static boolean mayBeIPv6Address(String input) {\n if (input == null) {\n return false;\n }\n\n boolean result = false;\n int colonsCounter = 0;\n int length = input.length();\n for (int i = 0; i < length; i++) {\n char c = input.charAt(i);\n if (c == '.' || c == '%') {\n // IPv4 in IPv6 or Zone ID detected, end of checking.\n break;\n }\n if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')\n || (c >= 'A' && c <= 'F') || c == ':')) {\n return false;\n } else if (c == ':') {\n colonsCounter++;\n }\n }\n if (colonsCounter >= 2) {\n result = true;\n }\n return result;\n }", "private static int getTrimmedXStart(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int xStart = width;\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j < xStart) {\n xStart = j;\n break;\n }\n }\n }\n\n return xStart;\n }", "public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> iterators) {\n Preconditions.checkArgumentNotNull(iterators, \"iterators\");\n return new CombinedIterator<T>(iterators);\n }", "public void deleteOrganization(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n repositoryHandler.deleteOrganization(dbOrganization.getName());\n repositoryHandler.removeModulesOrganization(dbOrganization);\n }", "public void checkin(AdminClient client) {\n if (isClosed.get()) {\n throw new IllegalStateException(\"Pool is closing\");\n }\n\n if (client == null) {\n throw new IllegalArgumentException(\"client is null\");\n }\n\n boolean isCheckedIn = clientCache.offer(client);\n\n if (!isCheckedIn) {\n // Cache is already full, close this AdminClient\n client.close();\n }\n }", "public void fillTile(InternalTile tile, Envelope maxTileExtent)\n\t\t\tthrows GeomajasException {\n\t\tList<InternalFeature> origFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tfor (InternalFeature feature : origFeatures) {\n\t\t\tif (!addTileCode(tile, maxTileExtent, feature.getGeometry())) {\n\t\t\t\tlog.debug(\"add feature\");\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t}" ]
Creates a descriptor for the currently edited message bundle. @return <code>true</code> if the descriptor could be created, <code>false</code> otherwise.
[ "public boolean addDescriptor() {\n\n saveLocalization();\n IndexedContainer oldContainer = m_container;\n try {\n createAndLockDescriptorFile();\n unmarshalDescriptor();\n updateBundleDescriptorContent();\n m_hasMasterMode = true;\n m_container = createContainer();\n m_editorState.put(EditMode.DEFAULT, getDefaultState());\n m_editorState.put(EditMode.MASTER, getMasterState());\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n if (m_descContent != null) {\n m_descContent = null;\n }\n if (m_descFile != null) {\n m_descFile = null;\n }\n if (m_desc != null) {\n try {\n m_cms.deleteResource(m_desc, CmsResourceDeleteMode.valueOf(1));\n } catch (CmsException ex) {\n LOG.error(ex.getLocalizedMessage(), ex);\n }\n m_desc = null;\n }\n m_hasMasterMode = false;\n m_container = oldContainer;\n return false;\n }\n m_removeDescriptorOnCancel = true;\n return true;\n }" ]
[ "@Deprecated\n public synchronized FailureDetectorConfig setNodes(Collection<Node> nodes) {\n Utils.notNull(nodes);\n this.nodes = new HashSet<Node>(nodes);\n return this;\n }", "public List<FailedEventInvocation> getFailedInvocations() {\n synchronized (this.mutex) {\n if (this.failedEvents == null) {\n return Collections.emptyList();\n }\n return Collections.unmodifiableList(this.failedEvents);\n }\n }", "protected void handleRequestOut(T message) throws Fault {\n String flowId = FlowIdHelper.getFlowId(message);\n if (flowId == null\n && message.containsKey(PhaseInterceptorChain.PREVIOUS_MESSAGE)) {\n // Web Service consumer is acting as an intermediary\n @SuppressWarnings(\"unchecked\")\n WeakReference<Message> wrPreviousMessage = (WeakReference<Message>) message\n .get(PhaseInterceptorChain.PREVIOUS_MESSAGE);\n Message previousMessage = (Message) wrPreviousMessage.get();\n flowId = FlowIdHelper.getFlowId(previousMessage);\n if (flowId != null && LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"flowId '\" + flowId + \"' found in previous message\");\n }\n }\n\n if (flowId == null) {\n // No flowId found. Generate one.\n flowId = ContextUtils.generateUUID();\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Generate new flowId '\" + flowId + \"'\");\n }\n }\n\n FlowIdHelper.setFlowId(message, flowId);\n }", "protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) {\n validateGeneralBean(bean, beanManager);\n if (bean instanceof NewBean) {\n return;\n }\n if (bean instanceof DecorableBean) {\n validateDecorators(beanManager, (DecorableBean<?>) bean);\n }\n if ((bean instanceof AbstractClassBean<?>)) {\n AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean;\n // validate CDI-defined interceptors\n if (classBean.hasInterceptors()) {\n validateInterceptors(beanManager, classBean);\n }\n }\n // for each producer bean validate its disposer method\n if (bean instanceof AbstractProducerBean<?, ?, ?>) {\n AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean);\n if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) {\n AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean\n .getProducer());\n if (producer.getDisposalMethod() != null) {\n for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) {\n // pass the producer bean instead of the disposal method bean\n validateInjectionPointForDefinitionErrors(ip, null, beanManager);\n validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD);\n validateEventMetadataInjectionPoint(ip);\n validateInjectionPointForDeploymentProblems(ip, null, beanManager);\n }\n }\n }\n }\n }", "public void setJdbcLevel(String jdbcLevel)\r\n {\r\n if (jdbcLevel != null)\r\n {\r\n try\r\n {\r\n double intLevel = Double.parseDouble(jdbcLevel);\r\n setJdbcLevel(intLevel);\r\n }\r\n catch(NumberFormatException nfe)\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was not numeric (Value=\" + jdbcLevel + \"), used default jdbc level of 2.0 \");\r\n }\r\n }\r\n else\r\n {\r\n setJdbcLevel(2.0);\r\n logger.info(\"Specified JDBC level was null, used default jdbc level of 2.0 \");\r\n }\r\n }", "public static boolean streamHasText(InputStream in, String text) {\n final byte[] readBuffer = new byte[8192];\n\n StringBuffer sb = new StringBuffer();\n try {\n if (in.available() > 0) {\n int bytesRead = 0;\n while ((bytesRead = in.read(readBuffer)) != -1) {\n sb.append(new String(readBuffer, 0, bytesRead));\n\n if (sb.toString().contains(text)) {\n sb = null;\n return true;\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return false;\n }", "protected Connection newConnectionFromDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JNDI lookup\r\n DataSource ds = jcd.getDataSource();\r\n\r\n if (ds == null)\r\n {\r\n // [tomdz] Would it suffice to store the datasources only at the JCDs ?\r\n // Only possible problem would be serialization of the JCD because\r\n // the data source object in the JCD does not 'survive' this\r\n ds = (DataSource) dataSourceCache.get(jcd.getDatasourceName());\r\n }\r\n try\r\n {\r\n if (ds == null)\r\n {\r\n /**\r\n * this synchronization block won't be a big deal as we only look up\r\n * new datasources not found in the map.\r\n */\r\n synchronized (dataSourceCache)\r\n {\r\n InitialContext ic = new InitialContext();\r\n ds = (DataSource) ic.lookup(jcd.getDatasourceName());\r\n /**\r\n * cache the datasource lookup.\r\n */\r\n dataSourceCache.put(jcd.getDatasourceName(), ds);\r\n }\r\n }\r\n if (jcd.getUserName() == null)\r\n {\r\n retval = ds.getConnection();\r\n }\r\n else\r\n {\r\n retval = ds.getConnection(jcd.getUserName(), jcd.getPassWord());\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n throw new LookupException(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n }\r\n catch (NamingException namingEx)\r\n {\r\n log.error(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() + \")\", namingEx);\r\n throw new LookupException(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() +\r\n \")\", namingEx);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DataSource: \"+retval);\r\n return retval;\r\n }", "protected static void main(String args[]) {\r\n\tint from = Integer.parseInt(args[0]);\t\r\n\tint to = Integer.parseInt(args[1]);\r\n\t\r\n\tstatistics(from,to);\r\n}", "protected void checkObserverMethods() {\n Collection<EnhancedAnnotatedMethod<?, ? super T>> observerMethods = BeanMethods.getObserverMethods(this.getEnhancedAnnotated());\n Collection<EnhancedAnnotatedMethod<?, ? super T>> asyncObserverMethods = BeanMethods.getAsyncObserverMethods(this.getEnhancedAnnotated());\n checkObserverMethods(observerMethods);\n checkObserverMethods(asyncObserverMethods);\n }" ]
Validates this string is a valid address, and if not, throws an exception with a descriptive message indicating why it is not. @throws AddressStringException
[ "@Override\n\tpublic void validate() throws AddressStringException {\n\t\tif(isValidated()) {\n\t\t\treturn;\n\t\t}\n\t\tsynchronized(this) {\n\t\t\tif(isValidated()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t//we know nothing about this address. See what it is.\n\t\t\ttry {\n\t\t\t\tparsedAddress = getValidator().validateAddress(this);\n\t\t\t\tisValid = true;\n\t\t\t} catch(AddressStringException e) {\n\t\t\t\tcachedException = e;\n\t\t\t\tisValid = false;\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}" ]
[ "public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }", "private void removeFromInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.removeNavigationalInformationFromInverseSide();\n\t}", "public void addControl(String name, JSONObject properties, Widget.OnTouchListener listener) {\n final JSONObject allowedProperties = new JSONObject();\n put(allowedProperties, Widget.Properties.name, optString(properties, Widget.Properties.name));\n put(allowedProperties, Widget.Properties.size, new PointF(mControlDimensions.x, mControlDimensions.y));\n put(allowedProperties, Widget.Properties.states, optJSONObject(properties, Widget.Properties.states));\n\n Widget control = new Widget(getGVRContext(), allowedProperties);\n setupControl(name, control, listener, -1);\n }", "public synchronized void submitOperation(int requestId, AsyncOperation operation) {\n if(this.operations.containsKey(requestId))\n throw new VoldemortException(\"Request \" + requestId\n + \" already submitted to the system\");\n\n this.operations.put(requestId, operation);\n scheduler.scheduleNow(operation);\n logger.debug(\"Handling async operation \" + requestId);\n }", "public static<T> SessionVar<T> vendSessionVar(T defValue) {\n\treturn (new VarsJBridge()).vendSessionVar(defValue, new Exception());\n }", "private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }", "private static Document getProjection(List<String> fieldNames) {\n\t\tDocument projection = new Document();\n\t\tfor ( String column : fieldNames ) {\n\t\t\tprojection.put( column, 1 );\n\t\t}\n\n\t\treturn projection;\n\t}", "private static Map<String, Integer> findClasses(Path path)\n {\n List<String> paths = findPaths(path, true);\n Map<String, Integer> results = new HashMap<>();\n for (String subPath : paths)\n {\n if (subPath.endsWith(\".java\") || subPath.endsWith(\".class\"))\n {\n String qualifiedName = PathUtil.classFilePathToClassname(subPath);\n addClassToMap(results, qualifiedName);\n }\n }\n return results;\n }", "public void rename(String newName) {\n URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject updateInfo = new JsonObject();\n updateInfo.add(\"name\", newName);\n\n request.setBody(updateInfo.toString());\n BoxAPIResponse response = request.send();\n response.disconnect();\n }" ]
Return the releaseId @return releaseId
[ "private Integer getReleaseId() {\n\t\tfinal String[] versionParts = stringVersion.split(\"-\");\n\t\t\n\t\tif(isBranch() && versionParts.length >= 3){\n\t\t\treturn Integer.valueOf(versionParts[2]);\n\t\t}\n\t\telse if(versionParts.length >= 2){\n\t\t\treturn Integer.valueOf(versionParts[1]);\n\t\t}\n\n\t\treturn 0;\n\t}" ]
[ "private List<Pair<Integer, Double>> integerPixelCoordinatesAndWeights(double d, int numPixels) {\n if (d <= 0.5) return Collections.singletonList(new Pair<>(0, 1.0));\n else if (d >= numPixels - 0.5) return Collections.singletonList(new Pair<>(numPixels - 1, 1.0));\n else {\n double shifted = d - 0.5;\n double floor = Math.floor(shifted);\n double floorWeight = 1 - (shifted - floor);\n double ceil = Math.ceil(shifted);\n double ceilWeight = 1 - floorWeight;\n assert (floorWeight + ceilWeight == 1);\n return Arrays.asList(new Pair<>((int) floor, floorWeight), new Pair<>((int) ceil, ceilWeight));\n }\n }", "private static IndexOptions prepareOptions(MongoDBIndexType indexType, Document options, String indexName, boolean unique) {\n\t\tIndexOptions indexOptions = new IndexOptions();\n\t\tindexOptions.name( indexName ).unique( unique ).background( options.getBoolean( \"background\" , false ) );\n\n\t\tif ( unique ) {\n\t\t\t// MongoDB only allows one null value per unique index which is not in line with what we usually consider\n\t\t\t// as the definition of a unique constraint. Thus, we mark the index as sparse to only index values\n\t\t\t// defined and avoid this issue. We do this only if a partialFilterExpression has not been defined\n\t\t\t// as partialFilterExpression and sparse are exclusive.\n\t\t\tindexOptions.sparse( !options.containsKey( \"partialFilterExpression\" ) );\n\t\t}\n\t\telse if ( options.containsKey( \"partialFilterExpression\" ) ) {\n\t\t\tindexOptions.partialFilterExpression( (Bson) options.get( \"partialFilterExpression\" ) );\n\t\t}\n\t\tif ( options.containsKey( \"expireAfterSeconds\" ) ) {\n\t\t\t//@todo is it correct?\n\t\t\tindexOptions.expireAfter( options.getInteger( \"expireAfterSeconds\" ).longValue() , TimeUnit.SECONDS );\n\n\t\t}\n\n\t\tif ( MongoDBIndexType.TEXT.equals( indexType ) ) {\n\t\t\t// text is an option we take into account to mark an index as a full text index as we cannot put \"text\" as\n\t\t\t// the order like MongoDB as ORM explicitly checks that the order is either asc or desc.\n\t\t\t// we remove the option from the Document so that we don't pass it to MongoDB\n\t\t\tif ( options.containsKey( \"default_language\" ) ) {\n\t\t\t\tindexOptions.defaultLanguage( options.getString( \"default_language\" ) );\n\t\t\t}\n\t\t\tif ( options.containsKey( \"weights\" ) ) {\n\t\t\t\tindexOptions.weights( (Bson) options.get( \"weights\" ) );\n\t\t\t}\n\n\t\t\toptions.remove( \"text\" );\n\t\t}\n\t\treturn indexOptions;\n\t}", "static Object getLCState(StateManagerInternal sm)\r\n\t{\r\n\t\t// unfortunately the LifeCycleState classes are package private.\r\n\t\t// so we have to do some dirty reflection hack to access them\r\n\t\ttry\r\n\t\t{\r\n\t\t\tField myLC = sm.getClass().getDeclaredField(\"myLC\");\r\n\t\t\tmyLC.setAccessible(true);\r\n\t\t\treturn myLC.get(sm);\r\n\t\t}\r\n\t\tcatch (NoSuchFieldException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\r\n\t\tcatch (IllegalAccessException e)\r\n\t\t{\r\n\t\t\treturn e;\r\n\t\t}\t\r\n\t}", "public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\n\t}", "@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }", "public static vpnvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_cachepolicy_binding obj = new vpnvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_cachepolicy_binding response[] = (vpnvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength);\n recordResourceRequestQueueLength(null, queueLength);\n } else {\n this.resourceRequestQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "public String getModulePaths() {\n final StringBuilder result = new StringBuilder();\n if (addDefaultModuleDir) {\n result.append(wildflyHome.resolve(\"modules\").toString());\n }\n if (!modulesDirs.isEmpty()) {\n if (addDefaultModuleDir) result.append(File.pathSeparator);\n for (Iterator<String> iterator = modulesDirs.iterator(); iterator.hasNext(); ) {\n result.append(iterator.next());\n if (iterator.hasNext()) {\n result.append(File.pathSeparator);\n }\n }\n }\n return result.toString();\n }", "public static OptionalString ofNullable(ResourceKey key, String value) {\n return new GenericOptionalString(RUNTIME_SOURCE, key, value);\n }" ]
Retrieves the calendar used for this resource assignment. @return ProjectCalendar instance
[ "public ProjectCalendar getCalendar()\n {\n ProjectCalendar calendar = null;\n Resource resource = getResource();\n if (resource != null)\n {\n calendar = resource.getResourceCalendar();\n }\n\n Task task = getTask();\n if (calendar == null || task.getIgnoreResourceCalendar())\n {\n calendar = task.getEffectiveCalendar();\n }\n\n return calendar;\n }" ]
[ "public final void error(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.ERROR, pObject, null);\r\n\t}", "protected void doConfigure() {\n if (config != null) {\n for (UserBean user : config.getUsersToCreate()) {\n setUser(user.getEmail(), user.getLogin(), user.getPassword());\n }\n getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled());\n }\n }", "private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }", "public final void setAttributes(final Map<String, Attribute> attributes) {\n for (Map.Entry<String, Attribute> entry: attributes.entrySet()) {\n Object attribute = entry.getValue();\n if (!(attribute instanceof Attribute)) {\n final String msg =\n \"Attribute: '\" + entry.getKey() + \"' is not an attribute. It is a: \" + attribute;\n LOGGER.error(\"Error setting the Attributes: {}\", msg);\n throw new IllegalArgumentException(msg);\n } else {\n ((Attribute) attribute).setConfigName(entry.getKey());\n }\n }\n this.attributes = attributes;\n }", "public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }", "private boolean computeEigenValues() {\n // make a copy of the internal tridiagonal matrix data for later use\n diagSaved = helper.copyDiag(diagSaved);\n offSaved = helper.copyOff(offSaved);\n\n vector.setQ(null);\n vector.setFastEigenvalues(true);\n\n // extract the eigenvalues\n if( !vector.process(-1,null,null) )\n return false;\n\n // save a copy of them since this data structure will be recycled next\n values = helper.copyEigenvalues(values);\n return true;\n }", "public ItemRequest<Task> findById(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public CollectionValuedMap<K, V> deltaClone() {\r\n CollectionValuedMap<K, V> result = new CollectionValuedMap<K, V>(null, cf, true);\r\n result.map = new DeltaMap<K, Collection<V>>(this.map);\r\n return result;\r\n }", "private org.apache.tools.ant.types.Path resolveFiles(org.apache.tools.ant.types.Path path) {\n org.apache.tools.ant.types.Path cloned = new org.apache.tools.ant.types.Path(getProject());\n for (String location : path.list()) {\n cloned.createPathElement().setLocation(new File(location));\n }\n return cloned;\n }" ]
Get the spin scripting environment @param language the language name @return the environment script as string or null if the language is not in the set of languages supported by spin.
[ "public static String get(String language) {\n language = language.toLowerCase();\n if(\"ecmascript\".equals(language)) {\n language = \"javascript\";\n }\n\n String extension = extensions.get(language);\n if(extension == null) {\n return null;\n\n } else {\n return loadScriptEnv(language, extension);\n\n }\n }" ]
[ "@SuppressWarnings(\"WeakerAccess\")\n public Color segmentColor(final int segment, final boolean front) {\n final ByteBuffer bytes = getData();\n if (isColor) {\n final int base = segment * 6;\n final int backHeight = segmentHeight(segment, false);\n if (backHeight == 0) {\n return Color.BLACK;\n }\n final int maxLevel = front? 255 : 191;\n final int red = Util.unsign(bytes.get(base + 3)) * maxLevel / backHeight;\n final int green = Util.unsign(bytes.get(base + 4)) * maxLevel / backHeight;\n final int blue = Util.unsign(bytes.get(base + 5)) * maxLevel / backHeight;\n return new Color(red, green, blue);\n } else {\n final int intensity = getData().get(segment * 2 + 1) & 0x07;\n return (intensity >= 5) ? INTENSE_COLOR : NORMAL_COLOR;\n }\n }", "public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) {\n\t\tdouble x = lognormalVolatiltiy * Math.sqrt(maturity / 8);\n\t\tdouble y = org.apache.commons.math3.special.Erf.erf(x);\n\t\tdouble normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y;\n\n\t\treturn normalVol;\n\t}", "private String getWorkingDayString(ProjectCalendar mpxjCalendar, Day day)\n {\n String result = null;\n net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);\n if (type == null)\n {\n type = net.sf.mpxj.DayType.DEFAULT;\n }\n\n switch (type)\n {\n case WORKING:\n {\n result = \"0\";\n break;\n }\n\n case NON_WORKING:\n {\n result = \"1\";\n break;\n }\n\n case DEFAULT:\n {\n result = \"2\";\n break;\n }\n }\n\n return (result);\n }", "public String getGroup(String groupId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUP);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n return payload.getAttribute(\"url\");\r\n }", "public static String getPostString(InputStream is, String encoding) {\n try {\n StringWriter sw = new StringWriter();\n IOUtils.copy(is, sw, encoding);\n\n return sw.toString();\n } catch (IOException e) {\n // no op\n return null;\n } finally {\n IOUtils.closeQuietly(is);\n }\n }", "private void createCodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int realOffsetStart, int realOffsetEnd, List<Integer> codePositions)\n throws IOException {\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, filterString(stringValues[0].trim()));\n token.setOffset(offsetStart, offsetEnd);\n token.setRealOffset(realOffsetStart, realOffsetEnd);\n token.addPositions(codePositions.stream().mapToInt(i -> i).toArray());\n tokenCollection.add(token);\n level.tokens.add(token);\n }", "private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature,\n String webHookPayload, String deliveryTimestamp) {\n if (actualSignature == null) {\n return false;\n }\n\n byte[] actual = Base64.decode(actualSignature);\n byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp);\n\n return Arrays.equals(expected, actual);\n }", "public void setProxy(String proxyHost, int proxyPort, String username, String password) {\n setProxy(proxyHost, proxyPort);\n proxyAuth = true;\n proxyUser = username;\n proxyPassword = password;\n }", "private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day)\n {\n ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate());\n if (day.isIsDayWorking())\n {\n for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n mpxjException.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }" ]
Remove a module. @param moduleName the module name @param slot the module slot @param existingHash the existing hash @return the builder
[ "public T removeModule(final String moduleName, final String slot, final byte[] existingHash) {\n final ContentItem item = createModuleItem(moduleName, slot, NO_CONTENT);\n addContentModification(createContentModification(item, ModificationType.REMOVE, existingHash));\n return returnThis();\n }" ]
[ "public static void saveContentMap(Map<String, String> map, File file) throws IOException {\n\n FileWriter out = new FileWriter(file);\n for (String key : map.keySet()) {\n if (map.get(key) != null) {\n out.write(key.replace(\":\", \"#escapedtwodots#\") + \":\"\n + map.get(key).replace(\":\", \"#escapedtwodots#\") + \"\\r\\n\");\n }\n }\n out.close();\n }", "public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}", "public void writeTo(IIMWriter writer) throws IOException {\r\n\t\tfinal boolean doLog = log != null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\twriter.write(ds);\r\n\t\t\tif (doLog) {\r\n\t\t\t\tlog.debug(\"Wrote data set \" + ds);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor_binding obj = new hanode_routemonitor_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private Send handle(SelectionKey key, Receive request) {\n final short requestTypeId = request.buffer().getShort();\n final RequestKeys requestType = RequestKeys.valueOf(requestTypeId);\n if (requestLogger.isTraceEnabled()) {\n if (requestType == null) {\n throw new InvalidRequestException(\"No mapping found for handler id \" + requestTypeId);\n }\n String logFormat = \"Handling %s request from %s\";\n requestLogger.trace(format(logFormat, requestType, channelFor(key).socket().getRemoteSocketAddress()));\n }\n RequestHandler handlerMapping = requesthandlerFactory.mapping(requestType, request);\n if (handlerMapping == null) {\n throw new InvalidRequestException(\"No handler found for request\");\n }\n long start = System.nanoTime();\n Send maybeSend = handlerMapping.handler(requestType, request);\n stats.recordRequest(requestType, System.nanoTime() - start);\n return maybeSend;\n }", "public static int wavelengthToRGB(float wavelength) {\n\t\tfloat gamma = 0.80f;\n\t\tfloat r, g, b, factor;\n\n\t\tint w = (int)wavelength;\n\t\tif (w < 380) {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 440) {\n\t\t\tr = -(wavelength - 440) / (440 - 380);\n\t\t\tg = 0.0f;\n\t\t\tb = 1.0f;\n\t\t} else if (w < 490) {\n\t\t\tr = 0.0f;\n\t\t\tg = (wavelength - 440) / (490 - 440);\n\t\t\tb = 1.0f;\n\t\t} else if (w < 510) {\n\t\t\tr = 0.0f;\n\t\t\tg = 1.0f;\n\t\t\tb = -(wavelength - 510) / (510 - 490);\n\t\t} else if (w < 580) {\n\t\t\tr = (wavelength - 510) / (580 - 510);\n\t\t\tg = 1.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 645) {\n\t\t\tr = 1.0f;\n\t\t\tg = -(wavelength - 645) / (645 - 580);\n\t\t\tb = 0.0f;\n\t\t} else if (w <= 780) {\n\t\t\tr = 1.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t}\n\n\t\t// Let the intensity fall off near the vision limits\n\t\tif (380 <= w && w <= 419)\n\t\t\tfactor = 0.3f + 0.7f*(wavelength - 380) / (420 - 380);\n\t\telse if (420 <= w && w <= 700)\n\t\t\tfactor = 1.0f;\n\t\telse if (701 <= w && w <= 780)\n\t\t\tfactor = 0.3f + 0.7f*(780 - wavelength) / (780 - 700);\n\t\telse\n\t\t\tfactor = 0.0f;\n\n\t\tint ir = adjust(r, factor, gamma);\n\t\tint ig = adjust(g, factor, gamma);\n\t\tint ib = adjust(b, factor, gamma);\n\n\t\treturn 0xff000000 | (ir << 16) | (ig << 8) | ib;\n\t}", "public static SimpleMatrix diag( Class type, double ...vals ) {\n SimpleMatrix M = new SimpleMatrix(vals.length,vals.length,type);\n for (int i = 0; i < vals.length; i++) {\n M.set(i,i,vals[i]);\n }\n return M;\n }", "private void deEndify(List<CoreLabel> tokens) {\r\n if (flags.retainEntitySubclassification) {\r\n return;\r\n }\r\n tokens = new PaddedList<CoreLabel>(tokens, new CoreLabel());\r\n int k = tokens.size();\r\n String[] newAnswers = new String[k];\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n CoreLabel p = tokens.get(i - 1);\r\n if (c.get(AnswerAnnotation.class).length() > 1 && c.get(AnswerAnnotation.class).charAt(1) == '-') {\r\n String base = c.get(AnswerAnnotation.class).substring(2);\r\n String pBase = (p.get(AnswerAnnotation.class).length() <= 2 ? p.get(AnswerAnnotation.class) : p.get(AnswerAnnotation.class).substring(2));\r\n boolean isSecond = (base.equals(pBase));\r\n boolean isStart = (c.get(AnswerAnnotation.class).charAt(0) == 'B' || c.get(AnswerAnnotation.class).charAt(0) == 'S');\r\n if (isSecond && isStart) {\r\n newAnswers[i] = intern(\"B-\" + base);\r\n } else {\r\n newAnswers[i] = intern(\"I-\" + base);\r\n }\r\n } else {\r\n newAnswers[i] = c.get(AnswerAnnotation.class);\r\n }\r\n }\r\n for (int i = 0; i < k; i++) {\r\n CoreLabel c = tokens.get(i);\r\n c.set(AnswerAnnotation.class, newAnswers[i]);\r\n }\r\n }", "public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }" ]
Send a packet to the target device telling it to load the specified track from the specified source player. @param target an update from the player that you want to have load a track @param rekordboxId the identifier of a track within the source player's rekordbox database @param sourcePlayer the device number of the player from which the track should be loaded @param sourceSlot the media slot from which the track should be loaded @param sourceType the type of track to be loaded @throws IOException if there is a problem sending the command @throws IllegalStateException if the {@code VirtualCdj} is not active
[ "public void sendLoadTrackCommand(DeviceUpdate target, int rekordboxId,\n int sourcePlayer, CdjStatus.TrackSourceSlot sourceSlot, CdjStatus.TrackType sourceType)\n throws IOException {\n ensureRunning();\n byte[] payload = new byte[LOAD_TRACK_PAYLOAD.length];\n System.arraycopy(LOAD_TRACK_PAYLOAD, 0, payload, 0, LOAD_TRACK_PAYLOAD.length);\n payload[0x02] = getDeviceNumber();\n payload[0x05] = getDeviceNumber();\n payload[0x09] = (byte)sourcePlayer;\n payload[0x0a] = sourceSlot.protocolValue;\n payload[0x0b] = sourceType.protocolValue;\n Util.numberToBytes(rekordboxId, payload, 0x0d, 4);\n assembleAndSendPacket(Util.PacketType.LOAD_TRACK_COMMAND, payload, target.getAddress(), UPDATE_PORT);\n }" ]
[ "@JsonProperty(\"paging\")\n void paging(String paging) {\n builder.paging(IndexPagingState.fromByteBuffer(ByteBufferUtils.byteBuffer(paging)));\n }", "public final void notifyContentItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= contentItemCount || toPosition >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \"\n + toPosition + \" is not within the position bounds for content items [0 - \" + (contentItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount, toPosition + headerItemCount);\n }", "public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }", "public static base_responses delete(nitro_service client, String sitename[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite deleteresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tdeleteresources[i] = new gslbsite();\n\t\t\t\tdeleteresources[i].sitename = sitename[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public boolean isExit() {\n if (currentRow > finalRow) { //request new block of work\n String newBlock = this.sendRequestSync(\"this/request/block\");\n LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0);\n\n if (newBlock.contains(\"exit\")) {\n getExitFlag().set(true);\n makeReport(true);\n return true;\n } else {\n block.buildFromResponse(newBlock);\n }\n\n currentRow = block.getStart();\n finalRow = block.getStop();\n } else { //report the number of lines written\n makeReport(false);\n\n if (exit.get()) {\n getExitFlag().set(true);\n return true;\n }\n }\n\n return false;\n }", "private static Date getSentDate(MimeMessage msg, Date defaultVal) {\r\n if (msg == null) {\r\n return defaultVal;\r\n }\r\n try {\r\n Date sentDate = msg.getSentDate();\r\n if (sentDate == null) {\r\n return defaultVal;\r\n } else {\r\n return sentDate;\r\n }\r\n } catch (MessagingException me) {\r\n return new Date();\r\n }\r\n }", "void setLanguage(final Locale locale) {\n\n if (!m_languageSelect.getValue().equals(locale)) {\n m_languageSelect.setValue(locale);\n }\n }", "public synchronized Message simpleRequest(Message.KnownType requestType, Message.KnownType responseType,\n Field... arguments)\n throws IOException {\n final NumberField transaction = assignTransactionNumber();\n final Message request = new Message(transaction, new NumberField(requestType.protocolValue, 2), arguments);\n sendMessage(request);\n final Message response = Message.read(is);\n if (response.transaction.getValue() != transaction.getValue()) {\n throw new IOException(\"Received response with wrong transaction ID. Expected: \" + transaction.getValue() +\n \", got: \" + response);\n }\n if (responseType != null && response.knownType != responseType) {\n throw new IOException(\"Received response with wrong type. Expected: \" + responseType +\n \", got: \" + response);\n }\n return response;\n }", "public static String readTextFile(Context context, String asset) {\n try {\n InputStream inputStream = context.getAssets().open(asset);\n return org.gearvrf.utility.TextFile.readTextFile(inputStream);\n } catch (FileNotFoundException f) {\n Log.w(TAG, \"readTextFile(): asset file '%s' doesn't exist\", asset);\n } catch (IOException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"readTextFile()\");\n }\n return null;\n }" ]
Return a long value from a prepared query.
[ "public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);\n\t\tDatabaseResults results = null;\n\t\ttry {\n\t\t\tresults = compiledStatement.runQuery(null);\n\t\t\tif (results.first()) {\n\t\t\t\treturn results.getLong(0);\n\t\t\t} else {\n\t\t\t\tthrow new SQLException(\"No result found in queryForLong: \" + preparedStmt.getStatement());\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(results, \"results\");\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}" ]
[ "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }", "void lockInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireInterruptibly(permit);\n }", "private void calculateSCL(double[] x) {\r\n //System.out.println(\"Checking at: \"+x[0]+\" \"+x[1]+\" \"+x[2]);\r\n value = 0.0;\r\n Arrays.fill(derivative, 0.0);\r\n double[] sums = new double[numClasses];\r\n double[] probs = new double[numClasses];\r\n double[] counts = new double[numClasses];\r\n Arrays.fill(counts, 0.0);\r\n for (int d = 0; d < data.length; d++) {\r\n // if (d == testMin) {\r\n // d = testMax - 1;\r\n // continue;\r\n // }\r\n int[] features = data[d];\r\n // activation\r\n Arrays.fill(sums, 0.0);\r\n for (int c = 0; c < numClasses; c++) {\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n sums[c] += x[i];\r\n }\r\n }\r\n // expectation (slower routine replaced by fast way)\r\n // double total = Double.NEGATIVE_INFINITY;\r\n // for (int c=0; c<numClasses; c++) {\r\n // total = SloppyMath.logAdd(total, sums[c]);\r\n // }\r\n double total = ArrayMath.logSum(sums);\r\n int ld = labels[d];\r\n for (int c = 0; c < numClasses; c++) {\r\n probs[c] = Math.exp(sums[c] - total);\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], c);\r\n derivative[i] += probs[ld] * probs[c];\r\n }\r\n }\r\n // observed\r\n for (int f = 0; f < features.length; f++) {\r\n int i = indexOf(features[f], labels[d]);\r\n derivative[i] -= probs[ld];\r\n }\r\n value -= probs[ld];\r\n }\r\n // priors\r\n if (true) {\r\n for (int i = 0; i < x.length; i++) {\r\n double k = 1.0;\r\n double w = x[i];\r\n value += k * w * w / 2.0;\r\n derivative[i] += k * w;\r\n }\r\n }\r\n }", "protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public boolean fling(float velocityX, float velocityY, float velocityZ) {\n boolean scrolled = true;\n float viewportX = mScrollable.getViewPortWidth();\n if (Float.isNaN(viewportX)) {\n viewportX = 0;\n }\n float maxX = Math.min(MAX_SCROLLING_DISTANCE,\n viewportX * MAX_VIEWPORT_LENGTHS);\n\n float viewportY = mScrollable.getViewPortHeight();\n if (Float.isNaN(viewportY)) {\n viewportY = 0;\n }\n float maxY = Math.min(MAX_SCROLLING_DISTANCE,\n viewportY * MAX_VIEWPORT_LENGTHS);\n\n float xOffset = (maxX * velocityX)/VELOCITY_MAX;\n float yOffset = (maxY * velocityY)/VELOCITY_MAX;\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"fling() velocity = [%f, %f, %f] offset = [%f, %f]\",\n velocityX, velocityY, velocityZ,\n xOffset, yOffset);\n\n if (equal(xOffset, 0)) {\n xOffset = Float.NaN;\n }\n\n if (equal(yOffset, 0)) {\n yOffset = Float.NaN;\n }\n\n// TODO: Think about Z-scrolling\n mScrollable.scrollByOffset(xOffset, yOffset, Float.NaN, mInternalScrollListener);\n\n return scrolled;\n }", "private boolean operations(Options opt, ConstructorDoc m[]) {\n\tboolean printed = false;\n\tfor (ConstructorDoc cd : m) {\n\t if (hidden(cd))\n\t\tcontinue;\n\t stereotype(opt, cd, Align.LEFT);\n\t String cs = visibility(opt, cd) + cd.name() //\n\t\t + (opt.showType ? \"(\" + parameter(opt, cd.parameters()) + \")\" : \"()\");\n\t tableLine(Align.LEFT, cs);\n\t tagvalue(opt, cd);\n\t printed = true;\n\t}\n\treturn printed;\n }", "public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }", "String getRangeUri(PropertyIdValue propertyIdValue) {\n\t\tString datatype = this.propertyRegister\n\t\t\t\t.getPropertyType(propertyIdValue);\n\n\t\tif (datatype == null)\n\t\t\treturn null;\n\n\t\tswitch (datatype) {\n\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.RDF_LANG_STRING;\n\t\tcase DatatypeIdValue.DT_STRING:\n\t\tcase DatatypeIdValue.DT_EXTERNAL_ID:\n\t\tcase DatatypeIdValue.DT_MATH:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.XSD_STRING;\n\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\tcase DatatypeIdValue.DT_ITEM:\n\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\tcase DatatypeIdValue.DT_LEXEME:\n\t\tcase DatatypeIdValue.DT_FORM:\n\t\tcase DatatypeIdValue.DT_SENSE:\n\t\tcase DatatypeIdValue.DT_TIME:\n\t\tcase DatatypeIdValue.DT_URL:\n\t\tcase DatatypeIdValue.DT_GEO_SHAPE:\n\t\tcase DatatypeIdValue.DT_TABULAR_DATA:\n\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\tthis.rdfConversionBuffer.addObjectProperty(propertyIdValue);\n\t\t\treturn Vocabulary.OWL_THING;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}", "public @Nullable String build() {\n StringBuilder queryString = new StringBuilder();\n\n for (NameValuePair param : params) {\n if (queryString.length() > 0) {\n queryString.append(PARAM_SEPARATOR);\n }\n queryString.append(Escape.urlEncode(param.getName()));\n queryString.append(VALUE_SEPARATOR);\n queryString.append(Escape.urlEncode(param.getValue()));\n }\n\n if (queryString.length() > 0) {\n return queryString.toString();\n }\n else {\n return null;\n }\n }" ]
Execute a HTTP request and handle common error cases. @param connection the HttpConnection request to execute @return the executed HttpConnection @throws CouchDbException for HTTP error codes or if an IOException was thrown
[ "public HttpConnection execute(HttpConnection connection) {\n\n //set our HttpUrlFactory on the connection\n connection.connectionFactory = factory;\n\n // all CouchClient requests want to receive application/json responses\n connection.requestProperties.put(\"Accept\", \"application/json\");\n connection.responseInterceptors.addAll(this.responseInterceptors);\n connection.requestInterceptors.addAll(this.requestInterceptors);\n InputStream es = null; // error stream - response from server for a 500 etc\n\n // first try to execute our request and get the input stream with the server's response\n // we want to catch IOException because HttpUrlConnection throws these for non-success\n // responses (eg 404 throws a FileNotFoundException) but we need to map to our own\n // specific exceptions\n try {\n try {\n connection = connection.execute();\n } catch (HttpConnectionInterceptorException e) {\n CouchDbException exception = new CouchDbException(connection.getConnection()\n .getResponseMessage(), connection.getConnection().getResponseCode());\n if (e.deserialize) {\n try {\n JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject\n .class);\n exception.error = getAsString(errorResponse, \"error\");\n exception.reason = getAsString(errorResponse, \"reason\");\n } catch (JsonParseException jpe) {\n exception.error = e.error;\n }\n } else {\n exception.error = e.error;\n exception.reason = e.reason;\n }\n throw exception;\n }\n int code = connection.getConnection().getResponseCode();\n String response = connection.getConnection().getResponseMessage();\n // everything ok? return the stream\n if (code / 100 == 2) { // success [200,299]\n return connection;\n } else {\n final CouchDbException ex;\n switch (code) {\n case HttpURLConnection.HTTP_NOT_FOUND: //404\n ex = new NoDocumentException(response);\n break;\n case HttpURLConnection.HTTP_CONFLICT: //409\n ex = new DocumentConflictException(response);\n break;\n case HttpURLConnection.HTTP_PRECON_FAILED: //412\n ex = new PreconditionFailedException(response);\n break;\n case 429:\n // If a Replay429Interceptor is present it will check for 429 and retry at\n // intervals. If the retries do not succeed or no 429 replay was configured\n // we end up here and throw a TooManyRequestsException.\n ex = new TooManyRequestsException(response);\n break;\n default:\n ex = new CouchDbException(response, code);\n break;\n }\n es = connection.getConnection().getErrorStream();\n //if there is an error stream try to deserialize into the typed exception\n if (es != null) {\n try {\n //read the error stream into memory\n byte[] errorResponse = IOUtils.toByteArray(es);\n\n Class<? extends CouchDbException> exceptionClass = ex.getClass();\n //treat the error as JSON and try to deserialize\n try {\n // Register an InstanceCreator that returns the existing exception so\n // we can just populate the fields, but not ignore the constructor.\n // Uses a new Gson so we don't accidentally recycle an exception.\n Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new\n CouchDbExceptionInstanceCreator(ex)).create();\n // Now populate the exception with the error/reason other info from JSON\n g.fromJson(new InputStreamReader(new ByteArrayInputStream\n (errorResponse),\n \"UTF-8\"), exceptionClass);\n } catch (JsonParseException e) {\n // The error stream was not JSON so just set the string content as the\n // error field on ex before we throw it\n ex.error = new String(errorResponse, \"UTF-8\");\n }\n } finally {\n close(es);\n }\n }\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n } catch (IOException ioe) {\n CouchDbException ex = new CouchDbException(\"Error retrieving server response\", ioe);\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n }" ]
[ "private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action) {\r\n return createRetentionPolicy(api, name, type, length, action, null);\r\n }", "public Double score(final String member) {\n return doWithJedis(new JedisCallable<Double>() {\n @Override\n public Double call(Jedis jedis) {\n return jedis.zscore(getKey(), member);\n }\n });\n }", "public byte[] keyToStorageFormat(byte[] key) {\n\n switch(getReadOnlyStorageFormat()) {\n case READONLY_V0:\n case READONLY_V1:\n return ByteUtils.md5(key);\n case READONLY_V2:\n return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT);\n default:\n throw new VoldemortException(\"Unknown read-only storage format\");\n }\n }", "protected void deleteConflictingResources(CmsObject cms, CmsModule module, Map<CmsUUID, CmsUUID> conflictingIds)\n throws CmsException, Exception {\n\n CmsProject conflictProject = cms.createProject(\n \"Deletion of conflicting resources for \" + module.getName(),\n \"Deletion of conflicting resources for \" + module.getName(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n CmsObject deleteCms = OpenCms.initCmsObject(cms);\n deleteCms.getRequestContext().setCurrentProject(conflictProject);\n for (CmsUUID vfsId : conflictingIds.values()) {\n CmsResource toDelete = deleteCms.readResource(vfsId, CmsResourceFilter.ALL);\n lock(deleteCms, toDelete);\n deleteCms.deleteResource(toDelete, CmsResource.DELETE_PRESERVE_SIBLINGS);\n }\n OpenCms.getPublishManager().publishProject(deleteCms);\n OpenCms.getPublishManager().waitWhileRunning();\n }", "private String readHeaderString(BufferedInputStream stream) throws IOException\n {\n int bufferSize = 100;\n stream.mark(bufferSize);\n byte[] buffer = new byte[bufferSize];\n stream.read(buffer);\n Charset charset = CharsetHelper.UTF8;\n String header = new String(buffer, charset);\n int prefixIndex = header.indexOf(\"PPX!!!!|\");\n int suffixIndex = header.indexOf(\"|!!!!XPP\");\n\n if (prefixIndex != 0 || suffixIndex == -1)\n {\n throw new IOException(\"File format not recognised\");\n }\n\n int skip = suffixIndex + 9;\n stream.reset();\n stream.skip(skip);\n\n return header.substring(prefixIndex + 8, suffixIndex);\n }", "public String nstring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n String value = atom(request);\n if (\"NIL\".equals(value)) {\n return null;\n } else {\n throw new ProtocolException(\"Invalid nstring value: valid values are '\\\"...\\\"', '{12} CRLF *CHAR8', and 'NIL'.\");\n }\n }\n }", "public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) {\n Preconditions.checkArgumentNotNull(target, \"target\");\n boolean modified = false;\n while (iterator.hasNext()) {\n modified |= target.add(iterator.next());\n }\n return modified;\n }", "private static void bodyWithConcatenation(\n SourceBuilder code,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n String typename) {\n code.add(\" return \\\"%s{\", typename);\n String prefix = \"\";\n for (Property property : generatorsByProperty.keySet()) {\n PropertyCodeGenerator generator = generatorsByProperty.get(property);\n code.add(\"%s%s=\\\" + %s + \\\"\",\n prefix, property.getName(), (Excerpt) generator::addToStringValue);\n prefix = \", \";\n }\n code.add(\"}\\\";%n\");\n }", "@Deprecated\n\tpublic void setResolutions(List<Double> resolutions) {\n\t\tgetZoomLevels().clear();\n\t\tfor (Double resolution : resolutions) {\n\t\t\tgetZoomLevels().add(new ScaleInfo(1. / resolution));\n\t\t}\n\t}" ]
Converts a sequence of Java characters to a sequence of unicode code points. @return the number of code points written to the destination buffer
[ "public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int codePointCount = 0;\n for (int i = 0; i < srcLen; ) {\n final int cp = codePointAt(src, srcOff + i, srcOff + srcLen);\n final int charCount = Character.charCount(cp);\n dest[destOff + codePointCount++] = cp;\n i += charCount;\n }\n return codePointCount;\n }" ]
[ "public boolean decompose(DMatrixRMaj mat , int indexStart , int n ) {\n double m[] = mat.data;\n\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = m[indexStart+i*mat.numCols+j];\n\n int iEl = i*n;\n int jEl = j*n;\n int end = iEl+i;\n // k = 0:i-1\n for( ; iEl<end; iEl++,jEl++ ) {\n// sum -= el[i*n+k]*el[j*n+k];\n sum -= el[iEl]*el[jEl];\n }\n\n if( i == j ) {\n // is it positive-definate?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n el[i*n+i] = el_ii;\n m[indexStart+i*mat.numCols+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n double v = sum*div_el_ii;\n el[j*n+i] = v;\n m[indexStart+j*mat.numCols+i] = v;\n }\n }\n }\n\n return true;\n }", "public void process(Connection connection, String directory) throws Exception\n {\n connection.setAutoCommit(true);\n\n //\n // Retrieve meta data about the connection\n //\n DatabaseMetaData dmd = connection.getMetaData();\n\n String[] types =\n {\n \"TABLE\"\n };\n\n FileWriter fw = new FileWriter(directory);\n PrintWriter pw = new PrintWriter(fw);\n\n pw.println(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n pw.println();\n pw.println(\"<database>\");\n\n ResultSet tables = dmd.getTables(null, null, null, types);\n while (tables.next() == true)\n {\n processTable(pw, connection, tables.getString(\"TABLE_NAME\"));\n }\n\n pw.println(\"</database>\");\n\n pw.close();\n\n tables.close();\n }", "public static appqoepolicy[] get(nitro_service service) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tappqoepolicy[] response = (appqoepolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void writeProcessorOutputToValues(\n final Object output,\n final Processor<?, ?> processor,\n final Values values) {\n Map<String, String> mapper = processor.getOutputMapperBiMap();\n if (mapper == null) {\n mapper = Collections.emptyMap();\n }\n\n final Collection<Field> fields = getAllAttributes(output.getClass());\n for (Field field: fields) {\n String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);\n try {\n final Object value = field.get(output);\n if (value != null) {\n values.put(name, value);\n } else {\n values.remove(name);\n }\n } catch (IllegalAccessException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }\n }", "public void appointTempoMaster(int deviceNumber) throws IOException {\n final DeviceUpdate update = getLatestStatusFor(deviceNumber);\n if (update == null) {\n throw new IllegalArgumentException(\"Device \" + deviceNumber + \" not found on network.\");\n }\n appointTempoMaster(update);\n }", "public String haikunate() {\n if (tokenHex) {\n tokenChars = \"0123456789abcdef\";\n }\n\n String adjective = randomString(adjectives);\n String noun = randomString(nouns);\n\n StringBuilder token = new StringBuilder();\n if (tokenChars != null && tokenChars.length() > 0) {\n for (int i = 0; i < tokenLength; i++) {\n token.append(tokenChars.charAt(random.nextInt(tokenChars.length())));\n }\n }\n\n return Stream.of(adjective, noun, token.toString())\n .filter(s -> s != null && !s.isEmpty())\n .collect(joining(delimiter));\n }", "public Date getBaselineFinish()\n {\n Object result = getCachedValue(TaskField.BASELINE_FINISH);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_FINISH);\n }\n\n if (!(result instanceof Date))\n {\n result = null;\n }\n return (Date) result;\n }", "private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }", "private void handleUpdate(final int player) {\n final TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n final WaveformDetail waveformDetail = WaveformFinder.getInstance().getLatestDetailFor(player);\n final BeatGrid beatGrid = BeatGridFinder.getInstance().getLatestBeatGridFor(player);\n if (metadata != null && waveformDetail != null && beatGrid != null) {\n final String signature = computeTrackSignature(metadata.getTitle(), metadata.getArtist(),\n metadata.getDuration(), waveformDetail, beatGrid);\n if (signature != null) {\n signatures.put(player, signature);\n deliverSignatureUpdate(player, signature);\n }\n }\n }" ]
Read metadata by populating an instance of the target class using SAXParser.
[ "private Object readMetadataFromXML(InputSource source, Class target)\r\n throws MalformedURLException, ParserConfigurationException, SAXException, IOException\r\n {\r\n // TODO: make this configurable\r\n boolean validate = false;\r\n \r\n // get a xml reader instance:\r\n SAXParserFactory factory = SAXParserFactory.newInstance();\r\n log.info(\"RepositoryPersistor using SAXParserFactory : \" + factory.getClass().getName());\r\n if (validate)\r\n {\r\n factory.setValidating(true);\r\n }\r\n SAXParser p = factory.newSAXParser();\r\n XMLReader reader = p.getXMLReader();\r\n if (validate)\r\n {\r\n reader.setErrorHandler(new OJBErrorHandler());\r\n }\r\n\r\n Object result;\r\n if (DescriptorRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n DescriptorRepository repository = new DescriptorRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new RepositoryXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n result = repository;\r\n }\r\n else if (ConnectionRepository.class.equals(target))\r\n {\r\n // create an empty repository:\r\n ConnectionRepository repository = new ConnectionRepository();\r\n // create handler for building the repository structure\r\n ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);\r\n // tell parser to use our handler:\r\n reader.setContentHandler(handler);\r\n reader.parse(source);\r\n //LoggerFactory.getBootLogger().info(\"loading XML took \" + (stop - start) + \" msecs\");\r\n result = repository;\r\n }\r\n else\r\n throw new MetadataException(\"Could not build a repository instance for '\" + target +\r\n \"', using source \" + source);\r\n return result;\r\n }" ]
[ "public static AppDescriptor deserializeFrom(byte[] bytes) {\n try {\n ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n return (AppDescriptor) ois.readObject();\n } catch (IOException e) {\n throw E.ioException(e);\n } catch (ClassNotFoundException e) {\n throw E.unexpected(e);\n }\n }", "protected VelocityContext createContext()\n {\n VelocityContext context = new VelocityContext();\n context.put(META_KEY, META);\n context.put(UTILS_KEY, UTILS);\n context.put(MESSAGES_KEY, MESSAGES);\n return context;\n }", "private String validatePattern() {\n\n String error = null;\n switch (getPatternType()) {\n case DAILY:\n error = isEveryWorkingDay() ? null : validateInterval();\n break;\n case WEEKLY:\n error = validateInterval();\n if (null == error) {\n error = validateWeekDaySet();\n }\n break;\n case MONTHLY:\n error = validateInterval();\n if (null == error) {\n error = validateMonthSet();\n if (null == error) {\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n }\n }\n break;\n case YEARLY:\n error = isWeekDaySet() ? validateWeekOfMonthSet() : validateDayOfMonth();\n break;\n case INDIVIDUAL:\n case NONE:\n default:\n }\n return error;\n }", "private void increaseBeliefCount(String bName) {\n Object belief = this.getBelief(bName);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n this.setBelief(bName, count + 1);\n }", "public static byte[] getContentBytes(String stringUrl) throws IOException {\n URL url = new URL(stringUrl);\n byte[] data = MyStreamUtils.readContentBytes(url.openStream());\n return data;\n }", "public static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) {\n Node parent = childElement.unwrap().getParentNode();\n if (parent == null || !parentElement.unwrap().isEqualNode(parent)) {\n throw LOG.elementIsNotChildOfThisElement(childElement, parentElement);\n }\n }", "public static appfwlearningdata[] get(nitro_service service, appfwlearningdata_args args) throws Exception{\n\t\tappfwlearningdata obj = new appfwlearningdata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tappfwlearningdata[] response = (appfwlearningdata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public static void checkArrayLength(String parameterName, int actualLength,\n int expectedLength) {\n if (actualLength != expectedLength) {\n throw Exceptions.IllegalArgument(\n \"Array %s should have %d elements, not %d\", parameterName,\n expectedLength, actualLength);\n }\n }", "public void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }" ]
Detect numbers using comma as a decimal separator and replace with period. @param value original numeric value @return corrected numeric value
[ "private static final String correctNumberFormat(String value)\n {\n String result;\n int index = value.indexOf(',');\n if (index == -1)\n {\n result = value;\n }\n else\n {\n char[] chars = value.toCharArray();\n chars[index] = '.';\n result = new String(chars);\n }\n return result;\n }" ]
[ "protected void setupRegistration() {\n if (isServiceWorkerSupported()) {\n Navigator.serviceWorker.register(getResource()).then(object -> {\n logger.info(\"Service worker has been successfully registered\");\n registration = (ServiceWorkerRegistration) object;\n\n onRegistered(new ServiceEvent(), registration);\n\n // Observe service worker lifecycle\n observeLifecycle(registration);\n\n // Setup Service Worker events events\n setupOnControllerChangeEvent();\n setupOnMessageEvent();\n setupOnErrorEvent();\n return null;\n }, error -> {\n logger.info(\"ServiceWorker registration failed: \" + error);\n return null;\n });\n } else {\n logger.info(\"Service worker is not supported by this browser.\");\n }\n }", "public void dispatchKeyEvent(int code, int action) {\n int keyCode = 0;\n int keyAction = 0;\n if (code == BUTTON_1) {\n keyCode = KeyEvent.KEYCODE_BUTTON_1;\n } else if (code == BUTTON_2) {\n keyCode = KeyEvent.KEYCODE_BUTTON_2;\n }\n\n if (action == ACTION_DOWN) {\n keyAction = KeyEvent.ACTION_DOWN;\n } else if (action == ACTION_UP) {\n keyAction = KeyEvent.ACTION_UP;\n }\n\n KeyEvent keyEvent = new KeyEvent(keyAction, keyCode);\n setKeyEvent(keyEvent);\n }", "public Result cmd(String cliCommand) {\n try {\n // The intent here is to return a Response when this is doable.\n if (ctx.isWorkflowMode() || ctx.isBatchMode()) {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx);\n if (handler.getFormat() == OperationFormat.INSTANCE) {\n ModelNode request = ctx.buildRequest(cliCommand);\n ModelNode response = ctx.execute(request, cliCommand);\n return new Result(cliCommand, request, response);\n } else {\n ctx.handle(cliCommand);\n return new Result(cliCommand, ctx.getExitCode());\n }\n } catch (CommandLineException cfe) {\n throw new IllegalArgumentException(\"Error handling command: \"\n + cliCommand, cfe);\n } catch (IOException ioe) {\n throw new IllegalStateException(\"Unable to send command \"\n + cliCommand + \" to server.\", ioe);\n }\n }", "public void setHeader(String header, String value) {\n StringValidator.throwIfEmptyOrNull(\"header\", header);\n StringValidator.throwIfEmptyOrNull(\"value\", value);\n\n if (headers == null) {\n headers = new HashMap<String, String>();\n }\n\n headers.put(header, value);\n }", "public ItemRequest<ProjectStatus> createInProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"POST\");\n }", "public Map<String, SetAndCount> getAggregateResultFullSummary() {\n\n Map<String, SetAndCount> summaryMap = new ConcurrentHashMap<String, SetAndCount>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), new SetAndCount(entry.getValue()));\n }\n\n return summaryMap;\n }", "private static String getHostname() {\n if (Hostname == null) {\n try {\n Hostname = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n Hostname = \"default\";\n LOGGER.warn(\"Can not get current hostname\", e);\n }\n }\n return Hostname;\n }", "public int[] getTenors() {\r\n\t\tSet<Integer> setTenors\t= new HashSet<>();\r\n\r\n\t\tfor(int moneyness : getGridNodesPerMoneyness().keySet()) {\r\n\t\t\tsetTenors.addAll(Arrays.asList((IntStream.of(keyMap.get(moneyness)[1]).boxed().toArray(Integer[]::new))));\r\n\t\t}\r\n\t\treturn setTenors.stream().sorted().mapToInt(Integer::intValue).toArray();\r\n\t}", "public static void copyProperties(Object dest, Object orig){\n\t\ttry {\n\t\t\tif (orig != null && dest != null){\n\t\t\t\tBeanUtils.copyProperties(dest, orig);\n\n\t\t\t\tPropertyUtils putils = new PropertyUtils();\n\t PropertyDescriptor origDescriptors[] = putils.getPropertyDescriptors(orig);\n\n\t\t\t\tfor (PropertyDescriptor origDescriptor : origDescriptors) {\n\t\t\t\t\tString name = origDescriptor.getName();\n\t\t\t\t\tif (\"class\".equals(name)) {\n\t\t\t\t\t\tcontinue; // No point in trying to set an object's class\n\t\t\t\t\t}\n\n\t\t\t\t\tClass propertyType = origDescriptor.getPropertyType();\n\t\t\t\t\tif (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType)))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (!putils.isReadable(orig, name)) { //because of bad convention\n\t\t\t\t\t\tMethod m = orig.getClass().getMethod(\"is\" + name.substring(0, 1).toUpperCase() + name.substring(1), (Class<?>[]) null);\n\t\t\t\t\t\tObject value = m.invoke(orig, (Object[]) null);\n\n\t\t\t\t\t\tif (putils.isWriteable(dest, name)) {\n\t\t\t\t\t\t\tBeanUtilsBean.getInstance().copyProperty(dest, name, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new DJException(\"Could not copy properties for shared object: \" + orig +\", message: \" + e.getMessage(),e);\n\t\t}\n\t}" ]
Callback when each frame in the indicator animation should be drawn.
[ "private void animateIndicatorInvalidate() {\n if (mIndicatorScroller.computeScrollOffset()) {\n mIndicatorOffset = mIndicatorScroller.getCurr();\n invalidate();\n\n if (!mIndicatorScroller.isFinished()) {\n postOnAnimation(mIndicatorRunnable);\n return;\n }\n }\n\n completeAnimatingIndicator();\n }" ]
[ "public boolean remove(long key) {\n int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n Entry previous = null;\n Entry entry = table[index];\n while (entry != null) {\n Entry next = entry.next;\n if (entry.key == key) {\n if (previous == null) {\n table[index] = next;\n } else {\n previous.next = next;\n }\n size--;\n return true;\n }\n previous = entry;\n entry = next;\n }\n return false;\n }", "@Beta\n public MSICredentials withObjectId(String objectId) {\n this.objectId = objectId;\n this.clientId = null;\n this.identityId = null;\n return this;\n }", "public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }", "private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)\r\n {\r\n FieldDescriptor fields[] = cld.getLockingFields();\r\n\r\n for (int i=0; i<fields.length; i++)\r\n {\r\n PersistentField field = fields[i].getPersistentField();\r\n Object lockVal = oldLockingValues[i].getValue();\r\n\r\n field.set(obj, lockVal);\r\n }\r\n }", "public void setRGB(int red, int green, int blue) throws Exception {\r\n\r\n CmsColor color = new CmsColor();\r\n color.setRGB(red, green, blue);\r\n\r\n m_red = red;\r\n m_green = green;\r\n m_blue = blue;\r\n m_hue = color.getHue();\r\n m_saturation = color.getSaturation();\r\n m_brightness = color.getValue();\r\n\r\n m_tbRed.setText(Integer.toString(m_red));\r\n m_tbGreen.setText(Integer.toString(m_green));\r\n m_tbBlue.setText(Integer.toString(m_blue));\r\n m_tbHue.setText(Integer.toString(m_hue));\r\n m_tbSaturation.setText(Integer.toString(m_saturation));\r\n m_tbBrightness.setText(Integer.toString(m_brightness));\r\n m_tbHexColor.setText(color.getHex());\r\n setPreview(color.getHex());\r\n\r\n updateSliders();\r\n }", "public static double elementMin( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a minimum.\n // Otherwise zero needs to be considered\n double min = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val < min ) {\n min = val;\n }\n }\n\n return min;\n }", "private static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(OP_ADDR));\n PathAddress validationAddress = pa.subAddress(0, pa.size() - 1);\n\n return Util.getEmptyOperation(\"validate-cache\", validationAddress.toModelNode());\n }", "public AT_Row setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public StateVertex crawlIndex() {\n\t\tLOG.debug(\"Setting up vertex of the index page\");\n\n\t\tif (basicAuthUrl != null) {\n\t\t\tbrowser.goToUrl(basicAuthUrl);\n\t\t}\n\n\t\tbrowser.goToUrl(url);\n\n\t\t// Run url first load plugin to clear the application state\n\t\tplugins.runOnUrlFirstLoadPlugins(context);\n\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tStateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),\n\t\t\t\tstateComparator.getStrippedDom(browser), browser);\n\t\tPreconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,\n\t\t\t\t\"It seems some the index state is crawled more than once.\");\n\n\t\tLOG.debug(\"Parsing the index for candidate elements\");\n\t\tImmutableList<CandidateElement> extract = candidateExtractor.extract(index);\n\n\t\tplugins.runPreStateCrawlingPlugins(context, extract, index);\n\n\t\tcandidateActionCache.addActions(extract, index);\n\n\t\treturn index;\n\n\t}" ]
Visit this and all child nodes. @param visitor The visitor to use.
[ "public final void visit(final Visitor visitor)\n\t{\n\t\tfinal Visit visit = new Visit();\n\t\ttry\n\t\t{\n\t\t\tvisit(visitor, visit);\n\t\t}\n\t\tcatch (final StopVisitationException ignored)\n\t\t{\n\t\t}\n\t}" ]
[ "public static BoxLegalHoldAssignment.Info create(BoxAPIConnection api,\n String policyID, String resourceType, String resourceID) {\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n JsonObject requestJSON = new JsonObject()\n .add(\"policy_id\", policyID)\n .add(\"assign_to\", new JsonObject()\n .add(\"type\", resourceType)\n .add(\"id\", resourceID));\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxLegalHoldAssignment createdAssignment = new BoxLegalHoldAssignment(api, responseJSON.get(\"id\").asString());\n return createdAssignment.new Info(responseJSON);\n }", "public static vpnglobal_auditnslogpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnglobal_auditnslogpolicy_binding[] response = (vpnglobal_auditnslogpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public final void notifyFooterItemInserted(int position) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n// if (position < 0 || position >= newFooterItemCount) {\n// throw new IndexOutOfBoundsException(\"The given position \" + position\n// + \" is not within the position bounds for footer items [0 - \"\n// + (newFooterItemCount - 1) + \"].\");\n// }\n notifyItemInserted(position + newHeaderItemCount + newContentItemCount);\n }", "public static Expression type(String lhs, Type rhs) {\n return new Expression(lhs, \"$type\", rhs.toString());\n }", "public static vpnclientlessaccesspolicy get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy response = (vpnclientlessaccesspolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unchecked\")\n public static <E> String serialize(E object, ParameterizedType<E> parameterizedType) throws IOException {\n return mapperFor(parameterizedType).serialize(object);\n }", "private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }", "public static base_responses add(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver addresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new ntpserver();\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].minpoll = resources[i].minpoll;\n\t\t\t\taddresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\taddresources[i].autokey = resources[i].autokey;\n\t\t\t\taddresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) {\n ClassFileServices classFileServices = services.get(ClassFileServices.class);\n if (classFileServices != null) {\n final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class);\n try {\n final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods());\n services.add(FastProcessAnnotatedTypeResolver.class, resolver);\n } catch (UnsupportedObserverMethodException e) {\n BootstrapLogger.LOG.notUsingFastResolver(e.getObserver());\n return;\n }\n }\n }" ]
Executes the API action "wbsetaliases" for the given parameters. @param id the id of the entity to be edited; if used, the site and title parameters must be null @param site when selecting an entity by title, the site key for the title, e.g., "enwiki"; if used, title must also be given but id must be null @param title string used to select an entity by title; if used, site must also be given but id must be null @param newEntity used for creating a new entity of a given type; the value indicates the intended entity type; possible values include "item" and "property"; if used, the parameters id, site, and title must be null @param language the language code for the label @param add the values of the aliases to add. They will be merged with the existing aliases. This parameter cannot be used in conjunction with "set". @param remove the values of the aliases to remove. Other aliases will be retained. This parameter cannot be used in conjunction with "set". @param set the values of the aliases to set. This will erase any existing aliases in this language and replace them by the given list. @param bot if true, edits will be flagged as "bot edits" provided that the logged in user is in the bot group; for regular users, the flag will just be ignored @param baserevid the revision of the data that the edit refers to or 0 if this should not be submitted; when used, the site will ensure that no edit has happened since this revision to detect edit conflicts; it is recommended to use this whenever in all operations where the outcome depends on the state of the online data @param summary summary for the edit; will be prepended by an automatically generated comment; the length limit of the autocomment together with the summary is 260 characters: everything above that limit will be cut off @return the JSON response from the API @throws IOException if there was an IO problem. such as missing network connection @throws MediaWikiApiErrorException if the API returns an error @throws IOException @throws MediaWikiApiErrorException
[ "public JsonNode wbSetAliases(String id, String site, String title,\n\t\t\tString newEntity, String language, List<String> add,\n\t\t\tList<String> remove, List<String> set,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting aliases\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (set != null) {\n\t\t\tif (add != null || remove != null) {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Cannot use parameters \\\"add\\\" or \\\"remove\\\" when using \\\"set\\\" to edit aliases\");\n\t\t\t}\n\t\t\tparameters.put(\"set\", ApiConnection.implodeObjects(set));\n\t\t}\n\t\tif (add != null) {\n\t\t\tparameters.put(\"add\", ApiConnection.implodeObjects(add));\n\t\t}\n\t\tif (remove != null) {\n\t\t\tparameters.put(\"remove\", ApiConnection.implodeObjects(remove));\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetaliases\", id, site, title, newEntity, parameters, summary, baserevid, bot);\n\t\treturn response;\n\t}" ]
[ "public int getIgnoredCount() {\n int count = 0;\n for (AggregatedTestResultEvent t : getTests()) {\n if (t.getStatus() == TestStatus.IGNORED ||\n t.getStatus() == TestStatus.IGNORED_ASSUMPTION) {\n count++;\n }\n }\n return count;\n }", "public static base_responses delete(nitro_service client, String fipskeyname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (fipskeyname != null && fipskeyname.length > 0) {\n\t\t\tsslfipskey deleteresources[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslfipskey();\n\t\t\t\tdeleteresources[i].fipskeyname = fipskeyname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "protected Path normalizePath(final Path parent, final String path) {\n return parent.resolve(path).toAbsolutePath().normalize();\n }", "public static base_response update(nitro_service client, snmpoption resource) throws Exception {\n\t\tsnmpoption updateresource = new snmpoption();\n\t\tupdateresource.snmpset = resource.snmpset;\n\t\tupdateresource.snmptraplogging = resource.snmptraplogging;\n\t\treturn updateresource.update_resource(client);\n\t}", "@Override\n public List<JobInstance> getJobs(Query query)\n {\n return JqmClientFactory.getClient().getJobs(query);\n }", "public PBKey getPBKey()\r\n {\r\n if (pbKey == null)\r\n {\r\n this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());\r\n }\r\n return pbKey;\r\n }", "public static boolean isAssignable(Type lhsType, Type rhsType) {\n\t\tAssert.notNull(lhsType, \"Left-hand side type must not be null\");\n\t\tAssert.notNull(rhsType, \"Right-hand side type must not be null\");\n\n\t\t// all types are assignable to themselves and to class Object\n\t\tif (lhsType.equals(rhsType) || lhsType.equals(Object.class)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (lhsType instanceof Class<?>) {\n\t\t\tClass<?> lhsClass = (Class<?>) lhsType;\n\n\t\t\t// just comparing two classes\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\treturn ClassUtils.isAssignable(lhsClass, (Class<?>) rhsType);\n\t\t\t}\n\n\t\t\tif (rhsType instanceof ParameterizedType) {\n\t\t\t\tType rhsRaw = ((ParameterizedType) rhsType).getRawType();\n\n\t\t\t\t// a parameterized type is always assignable to its raw class type\n\t\t\t\tif (rhsRaw instanceof Class<?>) {\n\t\t\t\t\treturn ClassUtils.isAssignable(lhsClass, (Class<?>) rhsRaw);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (lhsClass.isArray() && rhsType instanceof GenericArrayType) {\n\t\t\t\tType rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();\n\n\t\t\t\treturn isAssignable(lhsClass.getComponentType(), rhsComponent);\n\t\t\t}\n\t\t}\n\n\t\t// parameterized types are only assignable to other parameterized types and class types\n\t\tif (lhsType instanceof ParameterizedType) {\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\tType lhsRaw = ((ParameterizedType) lhsType).getRawType();\n\n\t\t\t\tif (lhsRaw instanceof Class<?>) {\n\t\t\t\t\treturn ClassUtils.isAssignable((Class<?>) lhsRaw, (Class<?>) rhsType);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rhsType instanceof ParameterizedType) {\n\t\t\t\treturn isAssignable((ParameterizedType) lhsType, (ParameterizedType) rhsType);\n\t\t\t}\n\t\t}\n\n\t\tif (lhsType instanceof GenericArrayType) {\n\t\t\tType lhsComponent = ((GenericArrayType) lhsType).getGenericComponentType();\n\n\t\t\tif (rhsType instanceof Class<?>) {\n\t\t\t\tClass<?> rhsClass = (Class<?>) rhsType;\n\n\t\t\t\tif (rhsClass.isArray()) {\n\t\t\t\t\treturn isAssignable(lhsComponent, rhsClass.getComponentType());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rhsType instanceof GenericArrayType) {\n\t\t\t\tType rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();\n\n\t\t\t\treturn isAssignable(lhsComponent, rhsComponent);\n\t\t\t}\n\t\t}\n\n\t\tif (lhsType instanceof WildcardType) {\n\t\t\treturn isAssignable((WildcardType) lhsType, rhsType);\n\t\t}\n\n\t\treturn false;\n\t}", "public static int findVerticalOffset(JRDesignBand band) {\n\t\tint finalHeight = 0;\n\t\tif (band != null) {\n\t\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\t\tJRDesignElement element = (JRDesignElement) jrChild;\n\t\t\t\tint currentHeight = element.getY() + element.getHeight();\n\t\t\t\tif (currentHeight > finalHeight) finalHeight = currentHeight;\n\t\t\t}\n\t\t\treturn finalHeight;\n\t\t}\n\t\treturn finalHeight;\n\t}", "protected static List<String> parseMandatoryStringValues(JSONObject json, String key) throws JSONException {\n\n List<String> list = null;\n JSONArray array = json.getJSONArray(key);\n list = new ArrayList<String>(array.length());\n for (int i = 0; i < array.length(); i++) {\n try {\n String entry = array.getString(i);\n list.add(entry);\n } catch (JSONException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_STRING_ENTRY_UNPARSABLE_1, key), e);\n }\n }\n return list;\n }" ]
We want to get the best result possible as this value is used to determine what work needs to be recovered. @return
[ "public Long getOldestTaskCreatedTime(){\n\t Timer.Context ctx = getOldestTaskTimeTimer.time();\n\t try {\n \t long oldest = Long.MAX_VALUE;\n \t \n \t /*\n \t * I am asking this question first, because if I ask it after I could\n \t * miss the oldest time if the oldest is polled and worked on\n \t */\n \t Long oldestQueueTime = this.taskQueue.getOldestQueueTime();\n \t if(oldestQueueTime != null)\n \t oldest = oldestQueueTime;\n \t \n \t //there is a tiny race condition here... but we just want to make our best attempt\n \t long inProgressOldestTime = tasksInProgressTracker.getOldestTime();\n \t \n \t if(inProgressOldestTime < oldest)\n \t oldest = inProgressOldestTime;\n \t \n \t return oldest;\n\t } finally {\n\t ctx.stop();\n\t }\n\t}" ]
[ "@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }", "protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) {\n Object returnObject = invokeJavascript(function);\n if (returnObject instanceof JSObject) {\n try {\n Constructor<T> constructor = returnType.getConstructor(JSObject.class);\n return constructor.newInstance((JSObject) returnObject);\n } catch (Exception ex) {\n throw new IllegalStateException(ex);\n }\n } else {\n return (T) returnObject;\n }\n }", "public void actionPerformed(java.awt.event.ActionEvent e)\r\n {\r\n System.out.println(\"Action Command: \" + e.getActionCommand());\r\n System.out.println(\"Action Params : \" + e.paramString());\r\n System.out.println(\"Action Source : \" + e.getSource());\r\n System.out.println(\"Action SrcCls : \" + e.getSource().getClass().getName());\r\n org.apache.ojb.broker.metadata.ClassDescriptor cld =\r\n new org.apache.ojb.broker.metadata.ClassDescriptor(rootNode.getRepository());\r\n // cld.setClassNameOfObject(\"New Class\");\r\n cld.setTableName(\"New Table\");\r\n rootNode.addClassDescriptor(cld);\r\n }", "public static ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,\n final DomainController domainController, final ExpressionResolver expressionResolver) {\n final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,\n hostModel, domainController, expressionResolver);\n\n\n return factory.getBootUpdates();\n }", "public Profile findProfile(int profileId) throws Exception {\n Profile profile = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, profileId);\n results = statement.executeQuery();\n if (results.next()) {\n profile = this.getProfileFromResultSet(results);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n return profile;\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void recordScreen(String screenName){\n if(screenName == null || (!currentScreenName.isEmpty() && currentScreenName.equals(screenName))) return;\n getConfigLogger().debug(getAccountId(), \"Screen changed to \" + screenName);\n currentScreenName = screenName;\n recordPageEventWithExtras(null);\n }", "private void populateResourceAssignmentWorkgroupFields(Record record, ResourceAssignmentWorkgroupFields workgroup) throws MPXJException\n {\n workgroup.setMessageUniqueID(record.getString(0));\n workgroup.setConfirmed(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setResponsePending(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setUpdateStart(record.getDateTime(3));\n workgroup.setUpdateFinish(record.getDateTime(4));\n workgroup.setScheduleID(record.getString(5));\n }", "public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }", "protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}" ]
Enqueues a message for sending on the send thread. @param serialMessage the serial message to enqueue.
[ "public void enqueue(SerialMessage serialMessage) {\n\t\tthis.sendQueue.add(serialMessage);\n\t\tlogger.debug(\"Enqueueing message. Queue length = {}\", this.sendQueue.size());\n\t}" ]
[ "public static String getStatusForItem(Long lastActivity) {\n\n if (lastActivity.longValue() < CmsSessionsTable.INACTIVE_LIMIT) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_BROADCAST_COLS_STATUS_ACTIVE_0);\n }\n return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_BROADCAST_COLS_STATUS_INACTIVE_0);\n }", "public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }", "private void resetCalendar() {\n _calendar = getCalendar();\n if (_defaultTimeZone != null) {\n _calendar.setTimeZone(_defaultTimeZone);\n }\n _currentYear = _calendar.get(Calendar.YEAR);\n }", "public static vpnvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationradiuspolicy_binding obj = new vpnvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationradiuspolicy_binding response[] = (vpnvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static OgmCollectionPersister getInverseCollectionPersister(OgmCollectionPersister mainSidePersister) {\n\t\tif ( mainSidePersister.isInverse() || !mainSidePersister.isManyToMany() || !mainSidePersister.getElementType().isEntityType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tEntityPersister inverseSidePersister = mainSidePersister.getElementPersister();\n\n\t\t// process collection-typed properties of inverse side and try to find association back to main side\n\t\tfor ( Type type : inverseSidePersister.getPropertyTypes() ) {\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( mainSidePersister.getFactory(), (CollectionType) type );\n\t\t\t\tif ( isCollectionMatching( mainSidePersister, inverseCollectionPersister ) ) {\n\t\t\t\t\treturn inverseCollectionPersister;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "private void readTable(InputStream is, SynchroTable table) throws IOException\n {\n int skip = table.getOffset() - m_offset;\n if (skip != 0)\n {\n StreamHelper.skip(is, skip);\n m_offset += skip;\n }\n\n String tableName = DatatypeConverter.getString(is);\n int tableNameLength = 2 + tableName.length();\n m_offset += tableNameLength;\n\n int dataLength;\n if (table.getLength() == -1)\n {\n dataLength = is.available();\n }\n else\n {\n dataLength = table.getLength() - tableNameLength;\n }\n\n SynchroLogger.log(\"READ\", tableName);\n\n byte[] compressedTableData = new byte[dataLength];\n is.read(compressedTableData);\n m_offset += dataLength;\n\n Inflater inflater = new Inflater();\n inflater.setInput(compressedTableData);\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedTableData.length);\n byte[] buffer = new byte[1024];\n while (!inflater.finished())\n {\n int count;\n\n try\n {\n count = inflater.inflate(buffer);\n }\n catch (DataFormatException ex)\n {\n throw new IOException(ex);\n }\n outputStream.write(buffer, 0, count);\n }\n outputStream.close();\n byte[] uncompressedTableData = outputStream.toByteArray();\n\n SynchroLogger.log(uncompressedTableData);\n\n m_tableData.put(table.getName(), uncompressedTableData);\n }", "public void addNode(NodeT node) {\n node.setOwner(this);\n nodeTable.put(node.key(), node);\n }", "private Date getTimeFromInteger(Integer time)\n {\n Date result = null;\n\n if (time != null)\n {\n int minutes = time.intValue();\n int hours = minutes / 60;\n minutes -= (hours * 60);\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.HOUR_OF_DAY, hours);\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n\n return (result);\n }", "private void readSubProjects(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n while (uniqueIDOffset < filePathOffset)\n {\n readSubProject(data, uniqueIDOffset, filePathOffset, fileNameOffset, subprojectIndex++);\n uniqueIDOffset += 4;\n }\n }" ]
Use this API to unset the properties of snmpoption resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, snmpoption resource, String[] args) throws Exception{\n\t\tsnmpoption unsetresource = new snmpoption();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "public void setLabel(String label) {\n\n int ix = lstSizes.indexOf(label);\n if (ix != -1) {\n setLabel(ix);\n }\n }", "public UpdateDescription merge(@Nullable final UpdateDescription otherDescription) {\n if (otherDescription != null) {\n for (final Map.Entry<String, BsonValue> entry : this.updatedFields.entrySet()) {\n if (otherDescription.removedFields.contains(entry.getKey())) {\n this.updatedFields.remove(entry.getKey());\n }\n }\n for (final String removedField : this.removedFields) {\n if (otherDescription.updatedFields.containsKey(removedField)) {\n this.removedFields.remove(removedField);\n }\n }\n\n this.removedFields.addAll(otherDescription.removedFields);\n this.updatedFields.putAll(otherDescription.updatedFields);\n }\n\n return this;\n }", "public static double[][] toDouble(int[][] array) {\n double[][] n = new double[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (double) array[i][j];\n }\n }\n return n;\n }", "public static Identity fromByteArray(final byte[] anArray) throws PersistenceBrokerException\r\n {\r\n // reverse of the serialize() algorithm:\r\n // read from byte[] with a ByteArrayInputStream, decompress with\r\n // a GZIPInputStream and then deserialize by reading from the ObjectInputStream\r\n try\r\n {\r\n final ByteArrayInputStream bais = new ByteArrayInputStream(anArray);\r\n final GZIPInputStream gis = new GZIPInputStream(bais);\r\n final ObjectInputStream ois = new ObjectInputStream(gis);\r\n final Identity result = (Identity) ois.readObject();\r\n ois.close();\r\n gis.close();\r\n bais.close();\r\n return result;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n }", "public static Configuration loadFromString(String config)\n throws IOException, SAXException {\n ConfigurationImpl cfg = new ConfigurationImpl();\n\n XMLReader parser = XMLReaderFactory.createXMLReader();\n parser.setContentHandler(new ConfigHandler(cfg, null));\n Reader reader = new StringReader(config);\n parser.parse(new InputSource(reader));\n return cfg;\n }", "protected MappedPreparedStmt<T, ID> prepareStatement(Long limit, boolean cacheStore) throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\tString statement = buildStatementString(argList);\n\t\tArgumentHolder[] selectArgs = argList.toArray(new ArgumentHolder[argList.size()]);\n\t\tFieldType[] resultFieldTypes = getResultFieldTypes();\n\t\tFieldType[] argFieldTypes = new FieldType[argList.size()];\n\t\tfor (int selectC = 0; selectC < selectArgs.length; selectC++) {\n\t\t\targFieldTypes[selectC] = selectArgs[selectC].getFieldType();\n\t\t}\n\t\tif (!type.isOkForStatementBuilder()) {\n\t\t\tthrow new IllegalStateException(\"Building a statement from a \" + type + \" statement is not allowed\");\n\t\t}\n\t\treturn new MappedPreparedStmt<T, ID>(dao, tableInfo, statement, argFieldTypes, resultFieldTypes, selectArgs,\n\t\t\t\t(databaseType.isLimitSqlSupported() ? null : limit), type, cacheStore);\n\t}", "protected void propagateOnMotionOutside(MotionEvent event)\n {\n if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n getGVRContext().getEventManager().sendEvent(this, ITouchEvents.class, \"onMotionOutside\", this, event);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n getGVRContext().getEventManager().sendEvent(mScene, ITouchEvents.class, \"onMotionOutside\", this, event);\n }\n }\n }", "public SerialMessage setValueMessage(int level) {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_SET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_SET,\r\n\t\t\t\t\t\t\t\t(byte) level\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "private List<TokenStream> collectTokenStreams(TokenStream stream) {\n \n // walk through the token stream and build a collection \n // of sub token streams that represent possible date locations\n List<Token> currentGroup = null;\n List<List<Token>> groups = new ArrayList<List<Token>>();\n Token currentToken;\n int currentTokenType;\n StringBuilder tokenString = new StringBuilder();\n while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) {\n currentTokenType = currentToken.getType();\n tokenString.append(DateParser.tokenNames[currentTokenType]).append(\" \");\n\n // we're currently NOT collecting for a possible date group\n if(currentGroup == null) {\n // skip over white space and known tokens that cannot be the start of a date\n if(currentTokenType != DateLexer.WHITE_SPACE &&\n DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) {\n\n currentGroup = new ArrayList<Token>();\n currentGroup.add(currentToken);\n }\n }\n\n // we're currently collecting\n else {\n // preserve white space\n if(currentTokenType == DateLexer.WHITE_SPACE) {\n currentGroup.add(currentToken);\n }\n\n else {\n // if this is an unknown token, we'll close out the current group\n if(currentTokenType == DateLexer.UNKNOWN) {\n addGroup(currentGroup, groups);\n currentGroup = null;\n }\n // otherwise, the token is known and we're currently collecting for\n // a group, so we'll add it to the current group\n else {\n currentGroup.add(currentToken);\n }\n }\n }\n }\n\n if(currentGroup != null) {\n addGroup(currentGroup, groups);\n }\n \n _logger.info(\"STREAM: \" + tokenString.toString());\n List<TokenStream> streams = new ArrayList<TokenStream>();\n for(List<Token> group:groups) {\n if(!group.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"GROUP: \");\n for (Token token : group) {\n builder.append(DateParser.tokenNames[token.getType()]).append(\" \");\n }\n _logger.info(builder.toString());\n\n streams.add(new CommonTokenStream(new NattyTokenSource(group)));\n }\n }\n\n return streams;\n }" ]
Get the SuggestionsInterface. @return The SuggestionsInterface
[ "@Override\n public SuggestionsInterface getSuggestionsInterface() {\n if (suggestionsInterface == null) {\n suggestionsInterface = new SuggestionsInterface(apiKey, sharedSecret, transport);\n }\n return suggestionsInterface;\n }" ]
[ "public static Record getRecord(String text)\n {\n Record root;\n\n try\n {\n root = new Record(text);\n }\n\n //\n // I've come across invalid calendar data in an otherwise fine Primavera\n // database belonging to a customer. We deal with this gracefully here\n // rather than propagating an exception.\n //\n catch (Exception ex)\n {\n root = null;\n }\n\n return root;\n }", "protected static Map<String, String> getHeadersAsMap(ResponseEntity response) {\n\n Map<String, List<String>> headers = new HashMap<>(response.getHeaders());\n Map<String, String> map = new HashMap<>();\n\n for ( Map.Entry<String, List<String>> header :headers.entrySet() ) {\n String headerValue = Joiner.on(\",\").join(header.getValue());\n map.put(header.getKey(), headerValue);\n }\n\n return map;\n }", "public static gslbrunningconfig get(nitro_service service) throws Exception{\n\t\tgslbrunningconfig obj = new gslbrunningconfig();\n\t\tgslbrunningconfig[] response = (gslbrunningconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private void computeUnnamedParams() {\n unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList()));\n }", "public String getUrl(){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(\"http://\");\n\t\tsb.append(getHttpConfiguration().getBindHost().get());\n\t\tsb.append(\":\");\n\t\tsb.append(getHttpConfiguration().getPort());\n\t\t\n\t\treturn sb.toString();\n\t}", "private void addApiDocRoots(String packageListUrl) {\n\tBufferedReader br = null;\n\tpackageListUrl = fixApiDocRoot(packageListUrl);\n\ttry {\n\t URL url = new URL(packageListUrl + \"/package-list\");\n\t br = new BufferedReader(new InputStreamReader(url.openStream()));\n\t String line;\n\t while((line = br.readLine()) != null) {\n\t\tline = line + \".\";\n\t\tPattern pattern = Pattern.compile(line.replace(\".\", \"\\\\.\") + \"[^\\\\.]*\");\n\t\tapiDocMap.put(pattern, packageListUrl);\n\t }\n\t} catch(IOException e) {\n\t System.err.println(\"Errors happened while accessing the package-list file at \"\n\t\t + packageListUrl);\n\t} finally {\n\t if(br != null)\n\t\ttry {\n\t\t br.close();\n\t\t} catch (IOException e) {}\n\t}\n\t\n }", "public static boolean oracleExists(CuratorFramework curator) {\n boolean exists = false;\n try {\n exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null\n && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty();\n } catch (Exception nne) {\n if (nne instanceof KeeperException.NoNodeException) {\n // you'll do nothing\n } else {\n throw new RuntimeException(nne);\n }\n }\n return exists;\n }", "public StandaloneCommandBuilder setDebug(final boolean suspend, final int port) {\n debugArg = String.format(DEBUG_FORMAT, (suspend ? \"y\" : \"n\"), port);\n return this;\n }", "private void createSuiteList(List<ISuite> suites,\n File outputDirectory,\n boolean onlyFailures) throws Exception\n {\n VelocityContext context = createContext();\n context.put(SUITES_KEY, suites);\n context.put(ONLY_FAILURES_KEY, onlyFailures);\n generateFile(new File(outputDirectory, SUITES_FILE),\n SUITES_FILE + TEMPLATE_EXTENSION,\n context);\n }" ]
Apply aliases to task and resource fields. @param aliases map of aliases
[ "private void applyAliases(Map<FieldType, String> aliases)\n {\n CustomFieldContainer fields = m_project.getCustomFields();\n for (Map.Entry<FieldType, String> entry : aliases.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }" ]
[ "public static double KumarJohnsonDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n r += Math.pow(p[i] * p[i] - q[i] * q[i], 2) / 2 * Math.pow(p[i] * q[i], 1.5);\n }\n }\n return r;\n }", "public void setReadTimeout(int millis) {\n\t\t// Hack to get round Spring's dynamic loading of http client stuff\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis);\n\t\t}\n\t}", "public static MediaType binary( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, true );\n }", "public List<I_CmsEditableGroupRow> getRows() {\n\n List<I_CmsEditableGroupRow> result = Lists.newArrayList();\n for (Component component : m_container) {\n if (component instanceof I_CmsEditableGroupRow) {\n result.add((I_CmsEditableGroupRow)component);\n }\n }\n return result;\n }", "public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }", "private JSONObject getARP(final Context context) {\n try {\n final String nameSpaceKey = getNamespaceARPKey();\n if (nameSpaceKey == null) return null;\n\n final SharedPreferences prefs = StorageHelper.getPreferences(context, nameSpaceKey);\n final Map<String, ?> all = prefs.getAll();\n final Iterator<? extends Map.Entry<String, ?>> iter = all.entrySet().iterator();\n\n while (iter.hasNext()) {\n final Map.Entry<String, ?> kv = iter.next();\n final Object o = kv.getValue();\n if (o instanceof Number && ((Number) o).intValue() == -1) {\n iter.remove();\n }\n }\n final JSONObject ret = new JSONObject(all);\n getConfigLogger().verbose(getAccountId(), \"Fetched ARP for namespace key: \" + nameSpaceKey + \" values: \" + all.toString());\n return ret;\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Failed to construct ARP object\", t);\n return null;\n }\n }", "@RequestMapping(value = \"/api/profile\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addProfile(Model model, String name) throws Exception {\n logger.info(\"Should be adding the profile name when I hit the enter button={}\", name);\n return Utils.getJQGridJSON(profileService.add(name), \"profile\");\n }", "public static Span prefix(Bytes rowPrefix) {\n Objects.requireNonNull(rowPrefix);\n Bytes fp = followingPrefix(rowPrefix);\n return new Span(rowPrefix, true, fp == null ? Bytes.EMPTY : fp, false);\n }", "public static void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }" ]
Use this API to fetch appfwpolicylabel_binding resource of given name .
[ "public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "private <T> T populateBean(final T resultBean, final String[] nameMapping) {\n\t\t\n\t\t// map each column to its associated field on the bean\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\t\n\t\t\tfinal Object fieldValue = processedColumns.get(i);\n\t\t\t\n\t\t\t// don't call a set-method in the bean if there is no name mapping for the column or no result to store\n\t\t\tif( nameMapping[i] == null || fieldValue == null ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// invoke the setter on the bean\n\t\t\tMethod setMethod = cache.getSetMethod(resultBean, nameMapping[i], fieldValue.getClass());\n\t\t\tinvokeSetter(resultBean, setMethod, fieldValue);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn resultBean;\n\t}", "public static <T> T createProxy(final Class<T> proxyInterface) {\n\t\tif( proxyInterface == null ) {\n\t\t\tthrow new NullPointerException(\"proxyInterface should not be null\");\n\t\t}\n\t\treturn proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(),\n\t\t\tnew Class[] { proxyInterface }, new BeanInterfaceProxy()));\n\t}", "protected void appendFacetOption(StringBuffer query, final String name, final String value) {\n\n query.append(\" facet.\").append(name).append(\"=\").append(value);\n }", "public User getLimits() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_LIMITS);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element userElement = response.getPayload();\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n NodeList photoNodes = userElement.getElementsByTagName(\"photos\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element plElement = (Element) photoNodes.item(i);\r\n PhotoLimits pl = new PhotoLimits();\r\n user.setPhotoLimits(pl);\r\n pl.setMaxDisplay(plElement.getAttribute(\"maxdisplaypx\"));\r\n pl.setMaxUpload(plElement.getAttribute(\"maxupload\"));\r\n }\r\n NodeList videoNodes = userElement.getElementsByTagName(\"videos\");\r\n for (int i = 0; i < videoNodes.getLength(); i++) {\r\n Element vlElement = (Element) videoNodes.item(i);\r\n VideoLimits vl = new VideoLimits();\r\n user.setPhotoLimits(vl);\r\n vl.setMaxDuration(vlElement.getAttribute(\"maxduration\"));\r\n vl.setMaxUpload(vlElement.getAttribute(\"maxupload\"));\r\n }\r\n return user;\r\n }", "void applyFreshParticleOffScreen(\n @NonNull final Scene scene,\n final int position) {\n final int w = scene.getWidth();\n final int h = scene.getHeight();\n if (w == 0 || h == 0) {\n throw new IllegalStateException(\n \"Cannot generate particles if scene width or height is 0\");\n }\n\n float x = random.nextInt(w);\n float y = random.nextInt(h);\n\n // The offset to make when creating point of out bounds\n final short offset = (short) (scene.getParticleRadiusMin() + scene.getLineLength());\n\n // Point angle range\n final float startAngle;\n float endAngle;\n\n // Make random offset and calulate angles so that the direction of travel will always be\n // towards our View\n switch (random.nextInt(4)) {\n case 0:\n // offset to left\n x = (short) -offset;\n startAngle = angleDeg(pcc, pcc, x, y);\n endAngle = angleDeg(pcc, h - pcc, x, y);\n break;\n\n case 1:\n // offset to top\n y = (short) -offset;\n startAngle = angleDeg(w - pcc, pcc, x, y);\n endAngle = angleDeg(pcc, pcc, x, y);\n break;\n\n case 2:\n // offset to right\n x = (short) (w + offset);\n startAngle = angleDeg(w - pcc, h - pcc, x, y);\n endAngle = angleDeg(w - pcc, pcc, x, y);\n break;\n\n case 3:\n // offset to bottom\n y = (short) (h + offset);\n startAngle = angleDeg(pcc, h - pcc, x, y);\n endAngle = angleDeg(w - pcc, h - pcc, x, y);\n break;\n\n default:\n throw new IllegalArgumentException(\"Supplied value out of range\");\n }\n\n if (endAngle < startAngle) {\n endAngle += 360;\n }\n\n // Get random angle from angle range\n final float randomAngleInRange = startAngle + (random\n .nextInt((int) Math.abs(endAngle - startAngle)));\n final double direction = Math.toRadians(randomAngleInRange);\n\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float speedFactor = newRandomIndividualParticleSpeedFactor();\n final float radius = newRandomIndividualParticleRadius(scene);\n\n scene.setParticleData(\n position,\n x,\n y,\n dCos,\n dSin,\n radius,\n speedFactor);\n }", "public static Diagram parseJson(String json,\n Boolean keepGlossaryLink) throws JSONException {\n JSONObject modelJSON = new JSONObject(json);\n return parseJson(modelJSON,\n keepGlossaryLink);\n }", "protected boolean isNetworkSection(int networkPrefixLength, boolean withPrefixLength) {\n\t\tint segmentCount = getSegmentCount();\n\t\tif(segmentCount == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tint bitsPerSegment = getBitsPerSegment();\n\t\tint prefixedSegmentIndex = getNetworkSegmentIndex(networkPrefixLength, getBytesPerSegment(), bitsPerSegment);\n\t\tif(prefixedSegmentIndex + 1 < segmentCount) {\n\t\t\treturn false; //not the right number of segments\n\t\t}\n\t\t//the segment count matches, now compare the prefixed segment\n\t\tint segPrefLength = getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex);\n\t\treturn !getSegment(segmentCount - 1).isNetworkChangedByPrefix(segPrefLength, withPrefixLength);\n\t}", "public CollectionRequest<Tag> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/tags\", workspace);\n return new CollectionRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }" ]
Try to fire a given event on the Browser. @param eventable the eventable to fire @return true iff the event is fired
[ "private boolean fireEvent(Eventable eventable) {\n\t\tEventable eventToFire = eventable;\n\t\tif (eventable.getIdentification().getHow().toString().equals(\"xpath\")\n\t\t\t\t&& eventable.getRelatedFrame().equals(\"\")) {\n\t\t\teventToFire = resolveByXpath(eventable, eventToFire);\n\t\t}\n\t\tboolean isFired = false;\n\t\ttry {\n\t\t\tisFired = browser.fireEventAndWait(eventToFire);\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tif (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null\n\t\t\t\t\t&& \"A\".equals(eventToFire.getElement().getTag())) {\n\t\t\t\tisFired = visitAnchorHrefIfPossible(eventToFire);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Ignoring invisible element {}\", eventToFire.getElement());\n\t\t\t}\n\t\t} catch (InterruptedException e) {\n\t\t\tLOG.debug(\"Interrupted during fire event\");\n\t\t\tinterruptThread();\n\t\t\treturn false;\n\t\t}\n\n\t\tLOG.debug(\"Event fired={} for eventable {}\", isFired, eventable);\n\n\t\tif (isFired) {\n\t\t\t// Let the controller execute its specified wait operation on the browser thread safe.\n\t\t\twaitConditionChecker.wait(browser);\n\t\t\tbrowser.closeOtherWindows();\n\t\t\treturn true;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath\n\t\t\t * removed 1 state to represent the path TO here.\n\t\t\t */\n\t\t\tplugins.runOnFireEventFailedPlugins(context, eventable,\n\t\t\t\t\tcrawlpath.immutableCopyWithoutLast());\n\t\t\treturn false; // no event fired\n\t\t}\n\t}" ]
[ "public boolean assertValidPkForDelete(ClassDescriptor cld, Object obj)\r\n {\r\n if(!ProxyHelper.isProxy(obj))\r\n {\r\n FieldDescriptor fieldDescriptors[] = cld.getPkFields();\r\n int fieldDescriptorSize = fieldDescriptors.length;\r\n for(int i = 0; i < fieldDescriptorSize; i++)\r\n {\r\n FieldDescriptor fd = fieldDescriptors[i];\r\n Object pkValue = fd.getPersistentField().get(obj);\r\n if (representsNull(fd, pkValue))\r\n {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }", "public static base_response add(nitro_service client, onlinkipv6prefix resource) throws Exception {\n\t\tonlinkipv6prefix addresource = new onlinkipv6prefix();\n\t\taddresource.ipv6prefix = resource.ipv6prefix;\n\t\taddresource.onlinkprefix = resource.onlinkprefix;\n\t\taddresource.autonomusprefix = resource.autonomusprefix;\n\t\taddresource.depricateprefix = resource.depricateprefix;\n\t\taddresource.decrementprefixlifetimes = resource.decrementprefixlifetimes;\n\t\taddresource.prefixvalidelifetime = resource.prefixvalidelifetime;\n\t\taddresource.prefixpreferredlifetime = resource.prefixpreferredlifetime;\n\t\treturn addresource.add_resource(client);\n\t}", "public void setDefaults(Annotation[] defaultAnnotations) {\n if (defaultAnnotations == null) {\n return;\n }\n for (Annotation each : defaultAnnotations) {\n Class<? extends Annotation> key = each.annotationType();\n if (Title.class.equals(key) || Description.class.equals(key)) {\n continue;\n }\n if (!annotations.containsKey(key)) {\n annotations.put(key, each);\n }\n }\n }", "@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}", "public static final BigInteger printTimeUnit(TimeUnit value)\n {\n return (BigInteger.valueOf(value == null ? TimeUnit.DAYS.getValue() + 1 : value.getValue() + 1));\n }", "public void setAlias(UserAlias userAlias)\r\n\t{\r\n\t\tm_alias = userAlias.getName();\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(userAlias);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public static void initializeDomainRegistry(final TransformerRegistry registry) {\n\n //The chains for transforming will be as follows\n //For JBoss EAP: 8.0.0 -> 5.0.0 -> 4.0.0 -> 1.8.0 -> 1.7.0 -> 1.6.0 -> 1.5.0\n\n registerRootTransformers(registry);\n registerChainedManagementTransformers(registry);\n registerChainedServerGroupTransformers(registry);\n registerProfileTransformers(registry);\n registerSocketBindingGroupTransformers(registry);\n registerDeploymentTransformers(registry);\n }", "public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tFV fieldValue = (FV) extractJavaFieldValue(object);\n\t\tif (isFieldValueDefault(fieldValue)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldValue;\n\t\t}\n\t}", "public void mergeSubsystem(final GlobalTransformerRegistry registry, String subsystemName, ModelVersion version) {\n final PathElement element = PathElement.pathElement(SUBSYSTEM, subsystemName);\n registry.mergeSubtree(this, PathAddress.EMPTY_ADDRESS.append(element), version);\n }" ]
This method is called to alert project listeners to the fact that a resource has been read from a project file. @param resource resource instance
[ "public void fireResourceReadEvent(Resource resource)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.resourceRead(resource);\n }\n }\n }" ]
[ "public static <T> DatabaseTableConfig<T> fromClass(DatabaseType databaseType, Class<T> clazz) throws SQLException {\n\t\tString tableName = extractTableName(databaseType, clazz);\n\t\tif (databaseType.isEntityNamesMustBeUpCase()) {\n\t\t\ttableName = databaseType.upCaseEntityName(tableName);\n\t\t}\n\t\treturn new DatabaseTableConfig<T>(databaseType, clazz, tableName,\n\t\t\t\textractFieldTypes(databaseType, clazz, tableName));\n\t}", "public void addExportedPackages(Set<String> packages) {\n\t\tString s = (String) getMainAttributes().get(EXPORT_PACKAGE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, packages, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(EXPORT_PACKAGE, result);\n\t}", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n // Calculate summaries.\n summaryListener.suiteSummary(e);\n\n Description suiteDescription = e.getDescription();\n String displayName = suiteDescription.getDisplayName();\n if (displayName.trim().isEmpty()) {\n junit4.log(\"Could not emit XML report for suite (null description).\", \n Project.MSG_WARN);\n return;\n }\n\n if (!suiteCounts.containsKey(displayName)) {\n suiteCounts.put(displayName, 1);\n } else {\n int newCount = suiteCounts.get(displayName) + 1;\n suiteCounts.put(displayName, newCount);\n if (!ignoreDuplicateSuites && newCount == 2) {\n junit4.log(\"Duplicate suite name used with XML reports: \"\n + displayName + \". This may confuse tools that process XML reports. \"\n + \"Set 'ignoreDuplicateSuites' to true to skip this message.\", Project.MSG_WARN);\n }\n displayName = displayName + \"-\" + newCount;\n }\n \n try {\n File reportFile = new File(dir, \"TEST-\" + displayName + \".xml\");\n RegistryMatcher rm = new RegistryMatcher();\n rm.bind(String.class, new XmlStringTransformer());\n Persister persister = new Persister(rm);\n persister.write(buildModel(e), reportFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize report for suite \"\n + displayName + \": \" + x.toString(), x, Project.MSG_WARN);\n }\n }", "private void checkForUnknownVariables(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD )\n throw new ParseError(\"Unknown variable on right side. \"+t.getWord());\n t = t.next;\n }\n }", "protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }", "private String escapeText(StringBuilder sb, String text)\n {\n int length = text.length();\n char c;\n\n sb.setLength(0);\n\n for (int loop = 0; loop < length; loop++)\n {\n c = text.charAt(loop);\n\n switch (c)\n {\n case '<':\n {\n sb.append(\"&lt;\");\n break;\n }\n\n case '>':\n {\n sb.append(\"&gt;\");\n break;\n }\n\n case '&':\n {\n sb.append(\"&amp;\");\n break;\n }\n\n default:\n {\n if (validXMLCharacter(c))\n {\n if (c > 127)\n {\n sb.append(\"&#\" + (int) c + \";\");\n }\n else\n {\n sb.append(c);\n }\n }\n\n break;\n }\n }\n }\n\n return (sb.toString());\n }", "private List<CmsSearchField> getFields() {\n\n CmsSearchManager manager = OpenCms.getSearchManager();\n I_CmsSearchFieldConfiguration fieldConfig = manager.getFieldConfiguration(getParamFieldconfiguration());\n List<CmsSearchField> result;\n if (fieldConfig != null) {\n result = fieldConfig.getFields();\n } else {\n result = Collections.emptyList();\n if (LOG.isErrorEnabled()) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_SEARCHINDEX_EDIT_MISSING_PARAM_1,\n A_CmsFieldConfigurationDialog.PARAM_FIELDCONFIGURATION));\n }\n }\n return result;\n }", "public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) {\n \tCollection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size());\n \t\n \tMap<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members);\n \tfor(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) {\n \t\tFuture<T> future = futureEntry.getValue();\n \t\tMember member = futureEntry.getKey();\n \t\t\n \t\ttry {\n if(maxWaitTime > 0) {\n \tresult.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit)));\n } else {\n \tresult.add(new MemberResponse<T>(member, future.get()));\n } \n //ignore exceptions... return what you can\n } catch (InterruptedException e) {\n \tThread.currentThread().interrupt(); //restore interrupted status and return what we have\n \treturn result;\n } catch (MemberLeftException e) {\n \tlog.warn(\"Member {} left while trying to get a distributed callable result\", member);\n } catch (ExecutionException e) {\n \tif(e.getCause() instanceof InterruptedException) {\n \t //restore interrupted state and return\n \t Thread.currentThread().interrupt();\n \t return result;\n \t} else {\n \t log.warn(\"Unable to execute callable on \"+member+\". There was an error.\", e);\n \t}\n } catch (TimeoutException e) {\n \tlog.error(\"Unable to execute task on \"+member+\" within 10 seconds.\");\n } catch (RuntimeException e) {\n \tlog.error(\"Unable to execute task on \"+member+\". An unexpected error occurred.\", e);\n }\n \t}\n \n return result;\n }" ]
Overridden to do only the clean-part of the linking but not the actual linking. This is deferred until someone wants to access the content of the resource.
[ "@Override\n\tprotected void doLinking() {\n\t\tIParseResult parseResult = getParseResult();\n\t\tif (parseResult == null || parseResult.getRootASTElement() == null)\n\t\t\treturn;\n\n\t\tXtextLinker castedLinker = (XtextLinker) getLinker();\n\t\tcastedLinker.discardGeneratedPackages(parseResult.getRootASTElement());\n\t}" ]
[ "private void writeExceptions9(List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n for (ProjectCalendarException exception : exceptions)\n {\n boolean working = exception.getWorking();\n\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BIGINTEGER_ZERO);\n day.setDayWorking(Boolean.valueOf(working));\n\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod period = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayTimePeriod();\n day.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }", "public static void waitForDomain(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForDomain(null, client, startupTimeout);\n }", "private static boolean getSystemConnectivity(Context context) {\n try {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (cm == null) {\n return false;\n }\n\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n return activeNetwork.isConnectedOrConnecting();\n } catch (Exception exception) {\n return false;\n }\n }", "private Layout getActiveLayout(Project phoenixProject)\n {\n //\n // Start with the first layout we find\n //\n Layout activeLayout = phoenixProject.getLayouts().getLayout().get(0);\n\n //\n // If this isn't active, find one which is... and if none are,\n // we'll just use the first.\n //\n if (!activeLayout.isActive().booleanValue())\n {\n for (Layout layout : phoenixProject.getLayouts().getLayout())\n {\n if (layout.isActive().booleanValue())\n {\n activeLayout = layout;\n break;\n }\n }\n }\n\n return activeLayout;\n }", "public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n // load parameters\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n\n // execute command\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n doMetaCheckVersion(adminClient);\n }", "public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}", "public ItemRequest<Task> findById(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }", "public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }", "public static int cudnnConvolutionBackwardBias(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dbDesc, \n Pointer db)\n {\n return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db));\n }" ]
seeks to a particular month @param direction the direction to seek: two possibilities '<' go backward '>' go forward @param seekAmount the amount to seek. Must be guaranteed to parse as an integer @param month the month to seek to. Must be guaranteed to parse as an integer between 1 and 12
[ "public void seekToMonth(String direction, String seekAmount, String month) {\n int seekAmountInt = Integer.parseInt(seekAmount);\n int monthInt = Integer.parseInt(month);\n assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT));\n assert(monthInt >= 1 && monthInt <= 12);\n \n markDateInvocation();\n \n // set the day to the first of month. This step is necessary because if we seek to the \n // current day of a month whose number of days is less than the current day, we will \n // pushed into the next month.\n _calendar.set(Calendar.DAY_OF_MONTH, 1);\n \n // seek to the appropriate year\n if(seekAmountInt > 0) {\n int currentMonth = _calendar.get(Calendar.MONTH) + 1;\n int sign = direction.equals(DIR_RIGHT) ? 1 : -1;\n int numYearsToShift = seekAmountInt +\n (currentMonth == monthInt ? 0 : (currentMonth < monthInt ? sign > 0 ? -1 : 0 : sign > 0 ? 0 : -1));\n\n _calendar.add(Calendar.YEAR, (numYearsToShift * sign));\n }\n \n // now set the month\n _calendar.set(Calendar.MONTH, monthInt - 1);\n }" ]
[ "Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }", "@Deprecated\n public String get(String path) {\n final JsonValue value = this.values.get(this.pathToProperty(path));\n if (value == null) {\n return null;\n }\n if (!value.isString()) {\n return value.toString();\n }\n return value.asString();\n }", "private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }", "public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {\n final TestSpecification testSpecification = new TestSpecification();\n // Sort buckets by value ascending\n final Map<String,Integer> buckets = Maps.newLinkedHashMap();\n final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {\n @Override\n public int compare(final TestBucket lhs, final TestBucket rhs) {\n return Ints.compare(lhs.getValue(), rhs.getValue());\n }\n }).immutableSortedCopy(testDefinition.getBuckets());\n int fallbackValue = -1;\n if(testDefinitionBuckets.size() > 0) {\n final TestBucket firstBucket = testDefinitionBuckets.get(0);\n fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value\n\n final PayloadSpecification payloadSpecification = new PayloadSpecification();\n if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {\n final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());\n payloadSpecification.setType(payloadType.payloadTypeName);\n if (payloadType == PayloadType.MAP) {\n final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();\n for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {\n payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);\n }\n payloadSpecification.setSchema(payloadSpecificationSchema);\n }\n testSpecification.setPayload(payloadSpecification);\n }\n\n for (int i = 0; i < testDefinitionBuckets.size(); i++) {\n final TestBucket bucket = testDefinitionBuckets.get(i);\n buckets.put(bucket.getName(), bucket.getValue());\n }\n }\n testSpecification.setBuckets(buckets);\n testSpecification.setDescription(testDefinition.getDescription());\n testSpecification.setFallbackValue(fallbackValue);\n return testSpecification;\n }", "public boolean attachComponent(GVRComponent component) {\n if (component.getNative() != 0) {\n NativeSceneObject.attachComponent(getNative(), component.getNative());\n }\n synchronized (mComponents) {\n long type = component.getType();\n if (!mComponents.containsKey(type)) {\n mComponents.put(type, component);\n component.setOwnerObject(this);\n return true;\n }\n }\n return false;\n }", "public boolean isEUI64(boolean partial) {\n\t\tint segmentCount = getSegmentCount();\n\t\tint endIndex = addressSegmentIndex + segmentCount;\n\t\tif(addressSegmentIndex <= 5) {\n\t\t\tif(endIndex > 6) {\n\t\t\t\tint index3 = 5 - addressSegmentIndex;\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(index3);\n\t\t\t\tIPv6AddressSegment seg4 = getSegment(index3 + 1);\n\t\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00) && seg3.matchesWithMask(0xff, 0xff);\n\t\t\t} else if(partial && endIndex == 6) {\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(5 - addressSegmentIndex);\n\t\t\t\treturn seg3.matchesWithMask(0xff, 0xff);\n\t\t\t}\n\t\t} else if(partial && addressSegmentIndex == 6 && endIndex > 6) {\n\t\t\tIPv6AddressSegment seg4 = getSegment(6 - addressSegmentIndex);\n\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00);\n\t\t}\n\t\treturn partial;\n\t}", "private void recordMount(SlotReference slot) {\n if (mediaMounts.add(slot)) {\n deliverMountUpdate(slot, true);\n }\n if (!mediaDetails.containsKey(slot)) {\n try {\n VirtualCdj.getInstance().sendMediaQuery(slot);\n } catch (Exception e) {\n logger.warn(\"Problem trying to request media details for \" + slot, e);\n }\n }\n }", "private static LblTree createTree(TreeWalker walker) {\n\t\tNode parent = walker.getCurrentNode();\n\t\tLblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1\n\t\tfor (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {\n\t\t\tnode.add(createTree(walker));\n\t\t}\n\t\twalker.setCurrentNode(parent);\n\t\treturn node;\n\t}", "public static long wrapped(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n double valA;\n int indexCbase= 0;\n int endOfKLoop = b.numRows*b.numCols;\n\n for( int i = 0; i < a.numRows; i++ ) {\n int indexA = i*a.numCols;\n\n // need to assign dataC to a value initially\n int indexB = 0;\n int indexC = indexCbase;\n int end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) {\n c.set( indexC++ , valA*b.get(indexB++));\n }\n\n // now add to it\n while( indexB != endOfKLoop ) { // k loop\n indexC = indexCbase;\n end = indexB + b.numCols;\n\n valA = a.get(indexA++);\n\n while( indexB < end ) { // j loop\n c.plus( indexC++ , valA*b.get(indexB++));\n }\n }\n indexCbase += c.numCols;\n }\n\n return System.currentTimeMillis() - timeBefore;\n }" ]
Initial random seed used for shuffling test suites and other sources of pseudo-randomness. If not set, any random value is set. <p>The seed's format is compatible with {@link RandomizedRunner} so that seed can be fixed for suites and methods alike.
[ "public void setSeed(String randomSeed) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) {\n String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED());\n if (!userProperty.equals(randomSeed)) {\n log(\"Ignoring seed attribute because it is overridden by user properties.\", Project.MSG_WARN);\n }\n } else if (!Strings.isNullOrEmpty(randomSeed)) {\n this.random = randomSeed;\n }\n }" ]
[ "public void localCommit()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"commit was called\");\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new TransactionNotInProgressException(\"Not in transaction, call begin() before commit()\");\r\n }\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.commit();\r\n }\r\n else if (con != null)\r\n {\r\n con.commit();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Connection.commit() call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Commit on underlying connection failed, try to rollback connection\", e);\r\n this.localRollback();\r\n throw new TransactionAbortedException(\"Commit on connection failed\", e);\r\n }\r\n finally\r\n {\r\n this.isInLocalTransaction = false;\r\n restoreAutoCommitState();\r\n this.releaseConnection();\r\n }\r\n }", "private void createPropertyVfsBundleFiles() throws CmsIllegalArgumentException, CmsLoaderException, CmsException {\n\n String bundleFileBasePath = m_sitepath + m_basename + \"_\";\n for (Locale l : m_localizations.keySet()) {\n CmsResource res = m_cms.createResource(\n bundleFileBasePath + l.toString(),\n OpenCms.getResourceManager().getResourceType(\n CmsMessageBundleEditorTypes.BundleType.PROPERTY.toString()));\n m_bundleFiles.put(l, res);\n LockedFile file = LockedFile.lockResource(m_cms, res);\n file.setCreated(true);\n m_lockedBundleFiles.put(l, file);\n m_changedTranslations.add(l);\n }\n\n }", "public Object get(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\treturn convertedObjects.get(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}", "public static synchronized void unregister(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n l.remove( factory );\n }\n }\n }", "public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {\n Map<String, Object> metadata = new HashMap<String, Object>();\n metadata.put(Constants.DEVICE_ID, deviceId);\n metadata.put(Constants.DEVICE_TYPE, deviceType);\n metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);\n metadata.put(\"scope\", \"generic\");\n ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();\n\n importDeclarations.put(deviceId, declaration);\n\n registerImportDeclaration(declaration);\n }", "public static base_responses kill(nitro_service client, systemsession resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemsession killresources[] = new systemsession[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tkillresources[i] = new systemsession();\n\t\t\t\tkillresources[i].sid = resources[i].sid;\n\t\t\t\tkillresources[i].all = resources[i].all;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, killresources,\"kill\");\n\t\t}\n\t\treturn result;\n\t}", "public void setFirstOccurence(int min, int max) throws ParseException {\n if (fullCondition == null) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n firstOptional = true;\n }\n firstMinimumOccurence = Math.max(1, min);\n firstMaximumOccurence = max;\n } else {\n throw new ParseException(\"fullCondition already generated\");\n }\n }", "@Override\n\tpublic void visit(FeatureTypeStyle fts) {\n\n\t\tFeatureTypeStyle copy = new FeatureTypeStyleImpl(\n\t\t\t\t(FeatureTypeStyleImpl) fts);\n\t\tRule[] rules = fts.getRules();\n\t\tint length = rules.length;\n\t\tRule[] rulesCopy = new Rule[length];\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tif (rules[i] != null) {\n\t\t\t\trules[i].accept(this);\n\t\t\t\trulesCopy[i] = (Rule) pages.pop();\n\t\t\t}\n\t\t}\n\t\tcopy.setRules(rulesCopy);\n\t\tif (fts.getTransformation() != null) {\n\t\t\tcopy.setTransformation(copy(fts.getTransformation()));\n\t\t}\n\t\tif (STRICT && !copy.equals(fts)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided FeatureTypeStyle:\" + fts);\n\t\t}\n\t\tpages.push(copy);\n\t}", "public static void rebuild(final MODE newMode) {\n if (mode != newMode) {\n mode = newMode;\n TYPE type;\n switch (mode) {\n case DEBUG:\n type = TYPE.ANDROID;\n Log.startFullLog();\n break;\n case DEVELOPER:\n type = TYPE.PERSISTENT;\n Log.stopFullLog();\n break;\n case USER:\n type = TYPE.ANDROID;\n break;\n default:\n type = DEFAULT_TYPE;\n Log.stopFullLog();\n break;\n }\n currentLog = getLog(type);\n }\n }" ]
Give an embedded association, creates all the nodes and relationships required to represent it. It assumes that the entity node containing the association already exists in the db. @param executionEngine the {@link GraphDatabaseService} to run the query @param associationKey the {@link AssociationKey} identifying the association @param embeddedKey the {@link EntityKey} identifying the embedded component @return the created {@link Relationship} that represents the association
[ "public Relationship createRelationshipForEmbeddedAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey, EntityKey embeddedKey) {\n\t\tString query = initCreateEmbeddedAssociationQuery( associationKey, embeddedKey );\n\t\tObject[] queryValues = createRelationshipForEmbeddedQueryValues( associationKey, embeddedKey );\n\t\treturn executeQuery( executionEngine, query, queryValues );\n\t}" ]
[ "public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) {\n assertNumericArgument(timeout, true);\n this.requestTimeout = unit.toMillis(timeout);\n return this;\n }", "public static boolean isQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return false;\n }\n return (str.startsWith(\"\\\"\") && str.endsWith(\"\\\"\"));\n }", "public Search counts(String[] countsfields) {\r\n assert (countsfields.length > 0);\r\n JsonArray countsJsonArray = new JsonArray();\r\n for(String countsfield : countsfields) {\r\n JsonPrimitive element = new JsonPrimitive(countsfield);\r\n countsJsonArray.add(element);\r\n }\r\n databaseHelper.query(\"counts\", countsJsonArray);\r\n return this;\r\n }", "public Column getColumn(String columnName) {\n if (columnName == null) {\n return null;\n }\n for (Column column : columns) {\n if (columnName.equals(column.getData())) {\n return column;\n }\n }\n return null;\n }", "private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }", "public boolean runOnMainThreadNext(Runnable r) {\n assert handler != null;\n\n if (!sanityCheck(\"runOnMainThreadNext \" + r)) {\n return false;\n }\n return handler.post(r);\n }", "public ItemRequest<Task> removeDependencies(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependencies\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "public void setSpecularIntensity(float r, float g, float b, float a) {\n setVec4(\"specular_intensity\", r, g, b, a);\n }", "public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }" ]
Populate a milestone from a Row instance. @param row Row instance @param task Task instance
[ "private void populateMilestone(Row row, Task task)\n {\n task.setMilestone(true);\n //PROJID\n task.setUniqueID(row.getInteger(\"MILESTONEID\"));\n task.setStart(row.getDate(\"GIVEN_DATE_TIME\"));\n task.setFinish(row.getDate(\"GIVEN_DATE_TIME\"));\n //PROGREST_PERIOD\n //SYMBOL_APPEARANCE\n //MILESTONE_TYPE\n //PLACEMENU\n task.setPercentageComplete(row.getBoolean(\"COMPLETED\") ? COMPLETE : INCOMPLETE);\n //INTERRUPTIBLE_X\n //ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n //ACTUAL_DURATIONHOURS\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //EFFORT_BUDGET\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n //OVERALL_PERCENV_COMPLETE\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n //NOTET\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n //STARZ\n //ENJ\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n task.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }" ]
[ "SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }", "public Tokenizer<Tree> getTokenizer(final Reader r) {\r\n return new AbstractTokenizer<Tree>() {\r\n TreeReader tr = trf.newTreeReader(r);\r\n @Override\r\n public Tree getNext() {\r\n try {\r\n return tr.readTree();\r\n }\r\n catch(IOException e) {\r\n System.err.println(\"Error in reading tree.\");\r\n return null;\r\n }\r\n }\r\n };\r\n }", "public void finishFlow(final String code, final String state) throws ApiException {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (codeVerifier == null)\n throw new IllegalArgumentException(\"code_verifier is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(\"grant_type=\");\n builder.append(encode(\"authorization_code\"));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&code=\");\n builder.append(encode(code));\n builder.append(\"&code_verifier=\");\n builder.append(encode(codeVerifier));\n update(account, builder.toString());\n }", "public void setRightTableModel(TableModel model)\n {\n TableModel old = m_rightTable.getModel();\n m_rightTable.setModel(model);\n firePropertyChange(\"rightTableModel\", old, model);\n }", "public void setStringValue(String value) {\n\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {\n try {\n m_editValue = CmsLocationValue.parse(value);\n m_currentValue = m_editValue.cloneValue();\n displayValue();\n if ((m_popup != null) && m_popup.isVisible()) {\n m_popupContent.displayValues(m_editValue);\n updateMarkerPosition();\n }\n } catch (Exception e) {\n CmsLog.log(e.getLocalizedMessage() + \"\\n\" + CmsClientStringUtil.getStackTrace(e, \"\\n\"));\n }\n } else {\n m_currentValue = null;\n displayValue();\n }\n }", "public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }", "public Organization getModuleOrganization(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModuleOrganizationPath(moduleName, moduleVersion));\n final ClientResponse response = resource\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get module's organization\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(Organization.class);\n\n }", "public void logout() throws IOException {\n\t\tif (this.loggedIn) {\n\t\t\tMap<String, String> params = new HashMap<>();\n\t\t\tparams.put(\"action\", \"logout\");\n\t\t\tparams.put(\"format\", \"json\"); // reduce the output\n\t\t\ttry {\n\t\t\t\tsendJsonRequest(\"POST\", params);\n\t\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\t\tthrow new IOException(e.getMessage(), e); //TODO: we should throw a better exception\n\t\t\t}\n\n\t\t\tthis.loggedIn = false;\n\t\t\tthis.username = \"\";\n\t\t\tthis.password = \"\";\n\t\t}\n\t}", "public URL buildWithQuery(String base, String queryString, Object... values) {\n String urlString = String.format(base + this.template, values) + queryString;\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n assert false : \"An invalid URL template indicates a bug in the SDK.\";\n }\n\n return url;\n }" ]
Set the order in which sets are returned for the user. This method requires authentication with 'write' permission. @param photosetIds An array of Ids @throws FlickrException
[ "public void orderSets(String[] photosetIds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ORDER_SETS);\r\n ;\r\n\r\n parameters.put(\"photoset_ids\", StringUtilities.join(photosetIds, \",\"));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
[ "public static void main(String[] args) {\n if(args.length != 2) {\n System.out.println(\"Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema\");\n return;\n }\n\n Schema oldSchema;\n Schema newSchema;\n\n try {\n oldSchema = Schema.parse(new File(args[0]));\n } catch(Exception ex) {\n oldSchema = null;\n System.out.println(\"Could not open or parse the old schema (\" + args[0] + \") due to \"\n + ex);\n }\n\n try {\n newSchema = Schema.parse(new File(args[1]));\n } catch(Exception ex) {\n newSchema = null;\n System.out.println(\"Could not open or parse the new schema (\" + args[1] + \") due to \"\n + ex);\n }\n\n if(oldSchema == null || newSchema == null) {\n return;\n }\n\n System.out.println(\"Comparing: \");\n System.out.println(\"\\t\" + args[0]);\n System.out.println(\"\\t\" + args[1]);\n\n List<Message> messages = SchemaEvolutionValidator.checkBackwardCompatibility(oldSchema,\n newSchema,\n oldSchema.getName());\n Level maxLevel = Level.ALL;\n for(Message message: messages) {\n System.out.println(message.getLevel() + \": \" + message.getMessage());\n if(message.getLevel().isGreaterOrEqual(maxLevel)) {\n maxLevel = message.getLevel();\n }\n }\n\n if(maxLevel.isGreaterOrEqual(Level.ERROR)) {\n System.out.println(Level.ERROR\n + \": The schema is not backward compatible. New clients will not be able to read existing data.\");\n } else if(maxLevel.isGreaterOrEqual(Level.WARN)) {\n System.out.println(Level.WARN\n + \": The schema is partially backward compatible, but old clients will not be able to read data serialized in the new format.\");\n } else {\n System.out.println(Level.INFO\n + \": The schema is backward compatible. Old and new clients will be able to read records serialized by one another.\");\n }\n }", "List<Message> getFullTrackList(final CdjStatus.TrackSourceSlot slot, final Client client, final int sortOrder)\n throws IOException, InterruptedException, TimeoutException {\n // Send the metadata menu request\n if (client.tryLockingForMenuOperations(MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n Message response = client.menuRequest(Message.KnownType.TRACK_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slot,\n new NumberField(sortOrder));\n final long count = response.getMenuResultsCount();\n if (count == Message.NO_MENU_RESULTS_AVAILABLE || count == 0) {\n return Collections.emptyList();\n }\n\n // Gather all the metadata menu items\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, response);\n }\n finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock the player for menu operations\");\n }\n }", "public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,\n\t\t\t\t\t\t\t\t\t\t\t\tCrawlerContext context) {\n\t\tStateVertex cloneState = this.addStateToCurrentState(newState, event);\n\n\t\trunOnInvariantViolationPlugins(context);\n\n\t\tif (cloneState == null) {\n\t\t\tchangeState(newState);\n\t\t\tplugins.runOnNewStatePlugins(context, newState);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tchangeState(cloneState);\n\t\t\treturn false;\n\t\t}\n\t}", "public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n\n for( int i = 0; i < a.numRows; i++ ) {\n\n for( int j = 0; j < b.numCols; j++ ) {\n c.set(i,j,a.get(i,0)*b.get(0,j));\n }\n\n for( int k = 1; k < b.numRows; k++ ) {\n for( int j = 0; j < b.numCols; j++ ) {\n// c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j));\n c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j);\n }\n }\n }\n\n return System.currentTimeMillis() - timeBefore;\n }", "public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\n }", "public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "protected void writeBody(HttpURLConnection connection, ProgressListener listener) {\n if (this.body == null) {\n return;\n }\n\n connection.setDoOutput(true);\n try {\n OutputStream output = connection.getOutputStream();\n if (listener != null) {\n output = new ProgressOutputStream(output, listener, this.bodyLength);\n }\n int b = this.body.read();\n while (b != -1) {\n output.write(b);\n b = this.body.read();\n }\n output.close();\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n }", "@Deprecated\r\n public void setViews(String views) {\r\n if (views != null) {\r\n try {\r\n setViews(Integer.parseInt(views));\r\n } catch (NumberFormatException e) {\r\n setViews(-1);\r\n }\r\n }\r\n }", "public void stop(int waitMillis) throws InterruptedException {\n try {\n if (!isDone()) {\n setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format(\"Stopped by user: waiting for %d ms\", waitMillis)));\n }\n if (!waitForFinish(waitMillis)) {\n logger.warn(\"{} Client thread failed to finish in {} millis\", name, waitMillis);\n }\n } finally {\n rateTracker.shutdown();\n }\n }" ]
Removes a node meta data entry. @param key - the meta data key @throws GroovyBugError if the key is null
[ "public void removeNodeMetaData(Object key) {\n if (key==null) throw new GroovyBugError(\"Tried to remove meta data with null key \"+this+\".\");\n if (metaDataMap == null) {\n return;\n }\n metaDataMap.remove(key);\n }" ]
[ "String buildProjectEndpoint(DatastoreOptions options) {\n if (options.getProjectEndpoint() != null) {\n return options.getProjectEndpoint();\n }\n // DatastoreOptions ensures either project endpoint or project ID is set.\n String projectId = checkNotNull(options.getProjectId());\n if (options.getHost() != null) {\n return validateUrl(String.format(\"https://%s/%s/projects/%s\",\n options.getHost(), VERSION, projectId));\n } else if (options.getLocalHost() != null) {\n return validateUrl(String.format(\"http://%s/%s/projects/%s\",\n options.getLocalHost(), VERSION, projectId));\n }\n return validateUrl(String.format(\"%s/%s/projects/%s\",\n DEFAULT_HOST, VERSION, projectId));\n }", "public static BoxStoragePolicyAssignment.Info getAssignmentForTarget(final BoxAPIConnection api,\n String resolvedForType, String resolvedForID) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"resolved_for_type\", resolvedForType)\n .appendParam(\"resolved_for_id\", resolvedForID);\n URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,\n response.getJsonObject().get(\"entries\").asArray().get(0).asObject().get(\"id\").asString());\n BoxStoragePolicyAssignment.Info info = storagePolicyAssignment.new\n Info(response.getJsonObject().get(\"entries\").asArray().get(0).asObject());\n\n return info;\n }", "private void pushDeviceToken(final String token, final boolean register, final PushType type) {\n pushDeviceToken(this.context, token, register, type);\n }", "protected void mergeSameWork(LinkedList<TimephasedWork> list)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n TimephasedWork previousAssignment = null;\n for (TimephasedWork assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Duration previousAssignmentWork = previousAssignment.getAmountPerDay();\n Duration assignmentWork = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentWork.getDuration(), assignmentWork.getDuration(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().getDuration();\n total += assignmentWork.getDuration();\n Duration totalWork = Duration.getInstance(total, TimeUnit.MINUTES);\n\n TimephasedWork merged = new TimephasedWork();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentWork);\n merged.setTotalAmount(totalWork);\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }", "public static String getCorrelationId(Message message) {\n String correlationId = (String) message.get(CORRELATION_ID_KEY);\n if(null == correlationId) {\n correlationId = readCorrelationId(message);\n }\n if(null == correlationId) {\n correlationId = readCorrelationIdSoap(message);\n }\n return correlationId;\n }", "private boolean evaluateLogicalOperator(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = false;\n\n if (m_criteriaList.size() == 0)\n {\n result = true;\n }\n else\n {\n for (GenericCriteria criteria : m_criteriaList)\n {\n result = criteria.evaluate(container, promptValues);\n if ((m_operator == TestOperator.AND && !result) || (m_operator == TestOperator.OR && result))\n {\n break;\n }\n }\n }\n\n return result;\n }", "public int createPartitions(String topic, int partitionNum, boolean enlarge) throws IOException {\n KV<Receive, ErrorMapping> response = send(new CreaterRequest(topic, partitionNum, enlarge));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }", "static void showWarning(final String caption, final String description) {\n\n Notification warning = new Notification(caption, description, Type.WARNING_MESSAGE, true);\n warning.setDelayMsec(-1);\n warning.show(UI.getCurrent().getPage());\n\n }", "public static IndexedContainer getGroupsOfUser(\n CmsObject cms,\n CmsUser user,\n String caption,\n String iconProp,\n String ou,\n String propStatus,\n Function<CmsGroup, CmsCssIcon> iconProvider) {\n\n IndexedContainer container = new IndexedContainer();\n container.addContainerProperty(caption, String.class, \"\");\n container.addContainerProperty(ou, String.class, \"\");\n container.addContainerProperty(propStatus, Boolean.class, new Boolean(true));\n if (iconProvider != null) {\n container.addContainerProperty(iconProp, CmsCssIcon.class, null);\n }\n try {\n for (CmsGroup group : cms.getGroupsOfUser(user.getName(), true)) {\n Item item = container.addItem(group);\n item.getItemProperty(caption).setValue(group.getSimpleName());\n item.getItemProperty(ou).setValue(group.getOuFqn());\n if (iconProvider != null) {\n item.getItemProperty(iconProp).setValue(iconProvider.apply(group));\n }\n }\n } catch (CmsException e) {\n LOG.error(\"Unable to read groups from user\", e);\n }\n return container;\n }" ]
Gets the bytes for the highest address in the range represented by this address. @return
[ "protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}" ]
[ "private Collection<Locale> initLocales() {\n\n Collection<Locale> locales = null;\n switch (m_bundleType) {\n case DESCRIPTOR:\n locales = new ArrayList<Locale>(1);\n locales.add(Descriptor.LOCALE);\n break;\n case XML:\n case PROPERTY:\n locales = OpenCms.getLocaleManager().getAvailableLocales(m_cms, m_resource);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return locales;\n\n }", "public void addChildTaskBefore(Task child, Task previousSibling)\n {\n int index = m_children.indexOf(previousSibling);\n if (index == -1)\n {\n m_children.add(child);\n }\n else\n {\n m_children.add(index, child);\n }\n\n child.m_parent = this;\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }", "public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {\n Class<?> javaClass = annotatedType.getJavaClass();\n return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)\n && Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)\n && hasSimpleCdiConstructor(annotatedType);\n }", "public static void mergeHints(InputStream is, Map<String,List<Long>> hints) throws IOException {\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(is, Charsets.UTF_8));\n \n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\"))\n continue;\n\n final int equals = line.indexOf('=');\n if (equals <= 0) {\n throw new IOException(\"No '=' character on a non-comment line?: \" + line);\n } else {\n String key = line.substring(0, equals);\n List<Long> values = hints.get(key);\n if (values == null) {\n hints.put(key, values = new ArrayList<>());\n }\n for (String v : line.substring(equals + 1).split(\"[\\\\,]\")) {\n if (!v.isEmpty()) values.add(Long.parseLong(v));\n }\n }\n }\n }", "private List<String> generateDateTimePatterns(String datePattern, String[] timePatterns)\n {\n List<String> patterns = new ArrayList<String>();\n for (String timePattern : timePatterns)\n {\n patterns.add(datePattern + \" \" + timePattern);\n }\n\n // Always fall back on the date-only pattern\n patterns.add(datePattern);\n\n return patterns;\n }", "public static base_response add(nitro_service client, cmppolicylabel resource) throws Exception {\n\t\tcmppolicylabel addresource = new cmppolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}", "public static RgbaColor fromRgb(String rgb) {\n if (rgb.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbParts(rgb).split(\",\");\n if (parts.length == 3) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]));\n }\n else {\n return getDefaultColor();\n }\n }", "private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }", "public void populateFromAttributes(\n @Nonnull final Template template,\n @Nonnull final Map<String, Attribute> attributes,\n @Nonnull final PObject requestJsonAttributes) {\n if (requestJsonAttributes.has(JSON_REQUEST_HEADERS) &&\n requestJsonAttributes.getObject(JSON_REQUEST_HEADERS).has(JSON_REQUEST_HEADERS) &&\n !attributes.containsKey(JSON_REQUEST_HEADERS)) {\n attributes.put(JSON_REQUEST_HEADERS, new HttpRequestHeadersAttribute());\n }\n for (Map.Entry<String, Attribute> attribute: attributes.entrySet()) {\n try {\n put(attribute.getKey(),\n attribute.getValue().getValue(template, attribute.getKey(), requestJsonAttributes));\n } catch (ObjectMissingException | IllegalArgumentException e) {\n throw e;\n } catch (Throwable e) {\n String templateName = \"unknown\";\n for (Map.Entry<String, Template> entry: template.getConfiguration().getTemplates()\n .entrySet()) {\n if (entry.getValue() == template) {\n templateName = entry.getKey();\n break;\n }\n }\n\n String defaults = \"\";\n\n if (attribute instanceof ReflectiveAttribute<?>) {\n ReflectiveAttribute<?> reflectiveAttribute = (ReflectiveAttribute<?>) attribute;\n defaults = \"\\n\\n The attribute defaults are: \" + reflectiveAttribute.getDefaultValue();\n }\n\n String errorMsg = \"An error occurred when creating a value from the '\" + attribute.getKey() +\n \"' attribute for the '\" +\n templateName + \"' template.\\n\\nThe JSON is: \\n\" + requestJsonAttributes + defaults +\n \"\\n\" +\n e.toString();\n\n throw new AttributeParsingException(errorMsg, e);\n }\n }\n\n if (template.getConfiguration().isThrowErrorOnExtraParameters()) {\n final List<String> extraProperties = new ArrayList<>();\n for (Iterator<String> it = requestJsonAttributes.keys(); it.hasNext(); ) {\n final String attributeName = it.next();\n if (!attributes.containsKey(attributeName)) {\n extraProperties.add(attributeName);\n }\n }\n\n if (!extraProperties.isEmpty()) {\n throw new ExtraPropertyException(\"Extra properties found in the request attributes\",\n extraProperties, attributes.keySet());\n }\n }\n }" ]
When the JRField needs properties, use this method. @param propertyName @param value @return
[ "public ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}" ]
[ "public void show() {\n if (!(container instanceof RootPanel)) {\n if (!(container instanceof MaterialDialog)) {\n container.getElement().getStyle().setPosition(Style.Position.RELATIVE);\n }\n div.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);\n }\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.HIDDEN);\n }\n if (type == LoaderType.CIRCULAR) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.LOADER_WRAPPER);\n div.add(preLoader);\n } else if (type == LoaderType.PROGRESS) {\n div.setStyleName(CssName.VALIGN_WRAPPER + \" \" + CssName.PROGRESS_WRAPPER);\n progress.getElement().getStyle().setProperty(\"margin\", \"auto\");\n div.add(progress);\n }\n container.add(div);\n }", "public int indexOfKey(Object key) {\n return key == null ? indexOfNull() : indexOf(key, key.hashCode());\n }", "public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {\n\t\tCheck.notNull(code, \"code\");\n\t\tfinal ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, \"settings\"));\n\n\t\tfinal InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);\n\t\tfinal Clazz clazz = scaffoldClazz(analysis, settings);\n\n\t\t// immutable settings\n\t\tsettingsBuilder.fields(clazz.getFields());\n\t\tsettingsBuilder.immutableName(clazz.getName());\n\t\tsettingsBuilder.imports(clazz.getImports());\n\t\tfinal Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));\n\t\tsettingsBuilder.mainInterface(definition);\n\t\tsettingsBuilder.interfaces(clazz.getInterfaces());\n\t\tsettingsBuilder.packageDeclaration(clazz.getPackage());\n\n\t\tfinal String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));\n\t\tfinal String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));\n\t\treturn new Result(implementationCode, testCode);\n\t}", "@Deprecated\r\n private BufferedImage getOriginalImage(String suffix) throws IOException, FlickrException {\r\n StringBuffer buffer = getOriginalBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }", "public void visitExport(String packaze, int access, String... modules) {\n if (mv != null) {\n mv.visitExport(packaze, access, modules);\n }\n }", "public PayloadBuilder customField(final String key, final Object value) {\n root.put(key, value);\n return this;\n }", "public ClassDescriptor getSuperClassDescriptor()\r\n {\r\n if (!m_superCldSet)\r\n {\r\n if(getBaseClass() != null)\r\n {\r\n m_superCld = getRepository().getDescriptorFor(getBaseClass());\r\n if(m_superCld.isAbstract() || m_superCld.isInterface())\r\n {\r\n throw new MetadataException(\"Super class mapping only work for real class, but declared super class\" +\r\n \" is an interface or is abstract. Declared class: \" + m_superCld.getClassNameOfObject());\r\n }\r\n }\r\n m_superCldSet = true;\r\n }\r\n\r\n return m_superCld;\r\n }", "public List<String> getMultiSelect(String path) {\n List<String> values = new ArrayList<String>();\n for (JsonValue val : this.getValue(path).asArray()) {\n values.add(val.asString());\n }\n\n return values;\n }", "public Iterator getReportQueryIteratorByQuery(Query query) throws PersistenceBrokerException\n {\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return getReportQueryIteratorFromQuery(query, cld);\n }" ]
Handle a simple ping request. @param channel the channel @param header the protocol header @throws IOException for any error
[ "private static void handlePing(final Channel channel, final ManagementProtocolHeader header) throws IOException {\n final ManagementProtocolHeader response = new ManagementPongHeader(header.getVersion());\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }" ]
[ "public AccessAssertion unmarshal(final JSONObject encodedAssertion) {\n final String className;\n try {\n className = encodedAssertion.getString(JSON_CLASS_NAME);\n final Class<?> assertionClass =\n Thread.currentThread().getContextClassLoader().loadClass(className);\n final AccessAssertion assertion =\n (AccessAssertion) this.applicationContext.getBean(assertionClass);\n assertion.unmarshal(encodedAssertion);\n\n return assertion;\n } catch (JSONException | ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }", "public double getValue(ForwardCurveInterface forwardCurve, double swaprateVolatility) {\n\t\tdouble swaprate = swaprates[0];\n\t\tfor (double swaprate1 : swaprates) {\n\t\t\tif (swaprate1 != swaprate) {\n\t\t\t\tthrow new RuntimeException(\"Uneven swaprates not allows for analytical pricing.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(new TimeDiscretization(swapTenor), new TimeDiscretization(swapTenor), forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretization(swapTenor), forwardCurve);\n\n\t\treturn AnalyticFormulas.blackModelSwaptionValue(forwardSwapRate, swaprateVolatility, exerciseDate, swaprate, swapAnnuity);\n\t}", "public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }", "public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}", "private void emitSuiteStart(Description description, long startTimestamp) throws IOException {\n String suiteName = description.getDisplayName();\n if (useSimpleNames) {\n if (suiteName.lastIndexOf('.') >= 0) {\n suiteName = suiteName.substring(suiteName.lastIndexOf('.') + 1);\n }\n }\n logShort(shortTimestamp(startTimestamp) +\n \"Suite: \" +\n FormattingUtils.padTo(maxClassNameColumns, suiteName, \"[...]\"));\n }", "public void setScriptText(String scriptText, String language)\n {\n GVRScriptFile newScript = new GVRJavascriptScriptFile(getGVRContext(), scriptText);\n mLanguage = GVRScriptManager.LANG_JAVASCRIPT;\n setScriptFile(newScript);\n }", "public void useNewRESTServiceWithOldClient() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/new-rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n \n // The outgoing old Customer data needs to be transformed for \n // the new service to understand it and the response from the new service\n // needs to be transformed for this old client to understand it.\n ClientConfiguration config = WebClient.getConfig(customerService);\n addTransformInterceptors(config.getInInterceptors(),\n config.getOutInterceptors(),\n false);\n \n \n System.out.println(\"Using new RESTful CustomerService with old Client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old to New REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old to New REST\");\n printOldCustomerDetails(customer);\n }", "public boolean hasChanged(MediaDetails originalMedia) {\n if (!hashKey().equals(originalMedia.hashKey())) {\n throw new IllegalArgumentException(\"Can't compare media details with different hashKey values\");\n }\n return playlistCount != originalMedia.playlistCount || trackCount != originalMedia.trackCount;\n }", "public static Map<FieldType, String> getDefaultAliases()\n {\n Map<FieldType, String> map = new HashMap<FieldType, String>();\n\n map.put(TaskField.DATE1, \"Suspend Date\");\n map.put(TaskField.DATE2, \"Resume Date\");\n map.put(TaskField.TEXT1, \"Code\");\n map.put(TaskField.TEXT2, \"Activity Type\");\n map.put(TaskField.TEXT3, \"Status\");\n map.put(TaskField.NUMBER1, \"Primary Resource Unique ID\");\n\n return map;\n }" ]
Fetch JSON from RAW resource @param context Context @param resource Resource int of the RAW file @return JSON
[ "private static String getJsonFromRaw(Context context, int resource) {\n String json;\n try {\n InputStream inputStream = context.getResources().openRawResource(resource);\n int size = inputStream.available();\n byte[] buffer = new byte[size];\n inputStream.read(buffer);\n inputStream.close();\n json = new String(buffer, \"UTF-8\");\n } catch (IOException ex) {\n ex.printStackTrace();\n return null;\n }\n return json;\n }" ]
[ "public static String getDumpFileWebDirectory(\n\t\t\tDumpContentType dumpContentType, String projectName) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\tif (\"wikidatawiki\".equals(projectName)) {\n\t\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t\t+ \"wikidata\" + \"/\";\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Wikimedia Foundation uses non-systematic directory names for this type of dump file.\"\n\t\t\t\t\t\t\t\t+ \" I don't know where to find dumps of project \"\n\t\t\t\t\t\t\t\t+ projectName);\n\t\t\t}\n\t\t} else if (WmfDumpFile.WEB_DIRECTORY.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.DUMP_SITE_BASE_URL\n\t\t\t\t\t+ WmfDumpFile.WEB_DIRECTORY.get(dumpContentType)\n\t\t\t\t\t+ projectName + \"/\";\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}", "public IOrientationState getOrientationStateFromParam(int orientation) {\n switch (orientation) {\n case Orientation.ORIENTATION_HORIZONTAL_BOTTOM:\n return new OrientationStateHorizontalBottom();\n case Orientation.ORIENTATION_HORIZONTAL_TOP:\n return new OrientationStateHorizontalTop();\n case Orientation.ORIENTATION_VERTICAL_LEFT:\n return new OrientationStateVerticalLeft();\n case Orientation.ORIENTATION_VERTICAL_RIGHT:\n return new OrientationStateVerticalRight();\n default:\n return new OrientationStateHorizontalBottom();\n }\n }", "synchronized public void completeTask(int taskId, int partitionStoresMigrated) {\n tasksInFlight.remove(taskId);\n\n numTasksCompleted++;\n numPartitionStoresMigrated += partitionStoresMigrated;\n\n updateProgressBar();\n }", "public boolean getBoxBound(float[] corners)\n {\n int rc;\n if ((corners == null) || (corners.length != 6) ||\n ((rc = NativeVertexBuffer.getBoundingVolume(getNative(), corners)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy box bound into array provided\");\n }\n return rc != 0;\n }", "public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }", "public void setAngularLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularLowerLimits(getNative(), limitX, limitY, limitZ);\n }", "public static dnssuffix[] get(nitro_service service, String Dnssuffix[]) throws Exception{\n\t\tif (Dnssuffix !=null && Dnssuffix.length>0) {\n\t\t\tdnssuffix response[] = new dnssuffix[Dnssuffix.length];\n\t\t\tdnssuffix obj[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++) {\n\t\t\t\tobj[i] = new dnssuffix();\n\t\t\t\tobj[i].set_Dnssuffix(Dnssuffix[i]);\n\t\t\t\tresponse[i] = (dnssuffix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException\n {\n int unknown0Size = stream.getMajorVersion() > 5 ? 8 : 16;\n map.put(\"UNKNOWN0\", stream.readBytes(unknown0Size));\n map.put(\"UUID\", stream.readUUID()); \n }", "public void append(String str, String indentation) {\n\t\tif (indentation.isEmpty()) {\n\t\t\tappend(str);\n\t\t} else if (str != null)\n\t\t\tappend(indentation, str, segments.size());\n\t}" ]
Adds a filter definition to this project file. @param filter filter definition
[ "public void addFilter(Filter filter)\n {\n if (filter.isTaskFilter())\n {\n m_taskFilters.add(filter);\n }\n\n if (filter.isResourceFilter())\n {\n m_resourceFilters.add(filter);\n }\n\n m_filtersByName.put(filter.getName(), filter);\n m_filtersByID.put(filter.getID(), filter);\n }" ]
[ "protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }", "static void addOperationAddress(final ModelNode operation, final PathAddress base, final String key, final String value) {\n operation.get(OP_ADDR).set(base.append(key, value).toModelNode());\n }", "private void flushOutput() throws IOException {\n outStream.flush();\n outWriter.completeLine();\n errStream.flush();\n errWriter.completeLine();\n }", "public static boolean toBoolean(String value, boolean defaultValue)\r\n {\r\n return \"true\".equals(value) ? true : (\"false\".equals(value) ? false : defaultValue);\r\n }", "private Storepoint getCurrentStorepoint(Project phoenixProject)\n {\n List<Storepoint> storepoints = phoenixProject.getStorepoints().getStorepoint();\n Collections.sort(storepoints, new Comparator<Storepoint>()\n {\n @Override public int compare(Storepoint o1, Storepoint o2)\n {\n return DateHelper.compare(o2.getCreationTime(), o1.getCreationTime());\n }\n });\n return storepoints.get(0);\n }", "public static long bytesToNumber(byte[] buffer, int start, int length) {\n long result = 0;\n for (int index = start; index < start + length; index++) {\n result = (result << 8) + unsign(buffer[index]);\n }\n return result;\n }", "public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate(String templateID,\r\n MetadataFieldFilter... fieldFilters) {\r\n return BoxRetentionPolicyAssignment.createAssignmentToMetadata(this.getAPI(), this.getID(), templateID,\r\n fieldFilters);\r\n }", "public static boolean organizeAssociationMapByRowKey(\n\t\t\torg.hibernate.ogm.model.spi.Association association,\n\t\t\tAssociationKey key,\n\t\t\tAssociationContext associationContext) {\n\n\t\tif ( association.isEmpty() ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tObject valueOfFirstRow = association.get( association.getKeys().iterator().next() )\n\t\t\t\t.get( key.getMetadata().getRowKeyIndexColumnNames()[0] );\n\n\t\tif ( !( valueOfFirstRow instanceof String ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// The list style may be explicitly enforced for compatibility reasons\n\t\treturn getMapStorage( associationContext ) == MapStorageType.BY_KEY;\n\t}", "private boolean isAbandoned(final SubmittedPrintJob printJob) {\n final long duration = ThreadPoolJobManager.this.jobQueue.timeSinceLastStatusCheck(\n printJob.getEntry().getReferenceId());\n final boolean abandoned =\n duration > TimeUnit.SECONDS.toMillis(ThreadPoolJobManager.this.abandonedTimeout);\n if (abandoned) {\n LOGGER.info(\"Job {} is abandoned (no status check within the last {} seconds)\",\n printJob.getEntry().getReferenceId(), ThreadPoolJobManager.this.abandonedTimeout);\n }\n return abandoned;\n }" ]
Creates an element that represents an image drawn at the specified coordinates in the page. @param x the X coordinate of the image @param y the Y coordinate of the image @param width the width coordinate of the image @param height the height coordinate of the image @param type the image type: <code>"png"</code> or <code>"jpeg"</code> @param resource the image data depending on the specified type @return
[ "protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException\n {\n StringBuilder pstyle = new StringBuilder(\"position:absolute;\");\n pstyle.append(\"left:\").append(x).append(UNIT).append(';');\n pstyle.append(\"top:\").append(y).append(UNIT).append(';');\n pstyle.append(\"width:\").append(width).append(UNIT).append(';');\n pstyle.append(\"height:\").append(height).append(UNIT).append(';');\n //pstyle.append(\"border:1px solid red;\");\n \n Element el = doc.createElement(\"img\");\n el.setAttribute(\"style\", pstyle.toString());\n\n String imgSrc = config.getImageHandler().handleResource(resource);\n\n if (!disableImageData && !imgSrc.isEmpty())\n el.setAttribute(\"src\", imgSrc);\n else\n el.setAttribute(\"src\", \"\");\n \n return el;\n }" ]
[ "@Deprecated\n public static <T> T buildJsonResponse(Response response, Class<T> clazz) throws IOException, SlackApiException {\n if (response.code() == 200) {\n String body = response.body().string();\n DETAILED_LOGGER.accept(new HttpResponseListener.State(SlackConfig.DEFAULT, response, body));\n return GsonFactory.createSnakeCase().fromJson(body, clazz);\n } else {\n String body = response.body().string();\n throw new SlackApiException(response, body);\n }\n }", "public void unregisterComponent(java.awt.Component c)\r\n {\r\n java.awt.dnd.DragGestureRecognizer recognizer = \r\n (java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);\r\n if (recognizer != null)\r\n recognizer.setComponent(null);\r\n }", "public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers\n\t\t\t\t\t\t.openExampleFileOuputStream(\"life-expectancies.csv\"))) {\n\n\t\t\tfor (int i = 0; i < lifeSpans.length; i++) {\n\t\t\t\tif (peopleCount[i] != 0) {\n\t\t\t\t\tout.println(i + \",\" + (double) lifeSpans[i]\n\t\t\t\t\t\t\t/ peopleCount[i] + \",\" + peopleCount[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }", "public static final String getSelectedText(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getItemText(index) : null;\n }", "private void addCustomFields(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (CustomField field : file.getCustomFields())\n {\n final CustomField c = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n FieldType type = c.getFieldType();\n \n return type == null ? \"(unknown)\" : type.getFieldTypeClass() + \".\" + type.toString();\n }\n };\n parentNode.add(childNode);\n }\n }", "public Iterator getAllExtentClasses()\r\n {\r\n ArrayList subTypes = new ArrayList();\r\n\r\n subTypes.addAll(_extents);\r\n\r\n for (int idx = 0; idx < subTypes.size(); idx++)\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)subTypes.get(idx);\r\n\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n if (!subTypes.contains(curSubTypeDef))\r\n {\r\n subTypes.add(curSubTypeDef);\r\n }\r\n }\r\n }\r\n return subTypes.iterator();\r\n }", "public String[] init(String[] argv, int min, int max,\n Collection<CommandLineParser.Option> options)\n throws IOException, SAXException {\n // parse command line\n parser = new CommandLineParser();\n parser.setMinimumArguments(min);\n parser.setMaximumArguments(max);\n parser.registerOption(new CommandLineParser.BooleanOption(\"reindex\", 'I'));\n if (options != null)\n for (CommandLineParser.Option option : options)\n parser.registerOption(option);\n\n try {\n argv = parser.parse(argv);\n } catch (CommandLineParser.CommandLineParserException e) {\n System.err.println(\"ERROR: \" + e.getMessage());\n usage();\n System.exit(1);\n }\n\n // do we need to reindex?\n boolean reindex = parser.getOptionState(\"reindex\");\n\n // load configuration\n config = ConfigLoader.load(argv[0]);\n database = config.getDatabase(reindex); // overwrite iff reindex\n if (database.isInMemory())\n reindex = true; // no other way to do it in this case\n\n // reindex, if requested\n if (reindex)\n reindex(config, database);\n\n return argv;\n }", "public JsonNode wbRemoveClaims(List<String> statementIds,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statementIds,\n\t\t\t\t\"statementIds parameter cannot be null when deleting statements\");\n\t\tValidate.notEmpty(statementIds,\n\t\t\t\t\"statement ids to delete must be non-empty when deleting statements\");\n\t\tValidate.isTrue(statementIds.size() <= 50,\n\t\t\t\t\"At most 50 statements can be deleted at once\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", String.join(\"|\", statementIds));\n\t\t\n\t\treturn performAPIAction(\"wbremoveclaims\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}" ]
Set the values of all the knots. This version does not require the "extra" knots at -1 and 256 @param x the knot positions @param rgb the knot colors @param types the knot types
[ "public void setKnots(int[] x, int[] rgb, byte[] types) {\n\t\tnumKnots = rgb.length+2;\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tif (x != null)\n\t\t\tSystem.arraycopy(x, 0, xKnots, 1, numKnots-2);\n\t\telse\n\t\t\tfor (int i = 1; i > numKnots-1; i++)\n\t\t\t\txKnots[i] = 255*i/(numKnots-2);\n\t\tSystem.arraycopy(rgb, 0, yKnots, 1, numKnots-2);\n\t\tif (types != null)\n\t\t\tSystem.arraycopy(types, 0, knotTypes, 1, numKnots-2);\n\t\telse\n\t\t\tfor (int i = 0; i > numKnots; i++)\n\t\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}" ]
[ "protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }", "private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }", "public int readFrom(ByteBuffer src, long destOffset) {\n if (src.remaining() + destOffset >= size())\n throw new BufferOverflowException();\n int readLen = src.remaining();\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src);\n return readLen;\n }", "private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}", "public static base_response update(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig updateresource = new nsconfig();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.nsvlan = resource.nsvlan;\n\t\tupdateresource.ifnum = resource.ifnum;\n\t\tupdateresource.tagged = resource.tagged;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.maxconn = resource.maxconn;\n\t\tupdateresource.maxreq = resource.maxreq;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.cookieversion = resource.cookieversion;\n\t\tupdateresource.securecookie = resource.securecookie;\n\t\tupdateresource.pmtumin = resource.pmtumin;\n\t\tupdateresource.pmtutimeout = resource.pmtutimeout;\n\t\tupdateresource.ftpportrange = resource.ftpportrange;\n\t\tupdateresource.crportrange = resource.crportrange;\n\t\tupdateresource.timezone = resource.timezone;\n\t\tupdateresource.grantquotamaxclient = resource.grantquotamaxclient;\n\t\tupdateresource.exclusivequotamaxclient = resource.exclusivequotamaxclient;\n\t\tupdateresource.grantquotaspillover = resource.grantquotaspillover;\n\t\tupdateresource.exclusivequotaspillover = resource.exclusivequotaspillover;\n\t\tupdateresource.nwfwmode = resource.nwfwmode;\n\t\treturn updateresource.update_resource(client);\n\t}", "public void setRGB(int red, int green, int blue) throws Exception {\r\n\r\n CmsColor color = new CmsColor();\r\n color.setRGB(red, green, blue);\r\n\r\n m_red = red;\r\n m_green = green;\r\n m_blue = blue;\r\n m_hue = color.getHue();\r\n m_saturation = color.getSaturation();\r\n m_brightness = color.getValue();\r\n\r\n m_tbRed.setText(Integer.toString(m_red));\r\n m_tbGreen.setText(Integer.toString(m_green));\r\n m_tbBlue.setText(Integer.toString(m_blue));\r\n m_tbHue.setText(Integer.toString(m_hue));\r\n m_tbSaturation.setText(Integer.toString(m_saturation));\r\n m_tbBrightness.setText(Integer.toString(m_brightness));\r\n m_tbHexColor.setText(color.getHex());\r\n setPreview(color.getHex());\r\n\r\n updateSliders();\r\n }", "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\n }", "private void clearDeck(TrackMetadataUpdate update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) {\n deliverBeatGridUpdate(update.player, null);\n }\n }", "private void addResources(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n final Resource r = resource;\n MpxjTreeNode childNode = new MpxjTreeNode(resource)\n {\n @Override public String toString()\n {\n return r.getName();\n }\n };\n parentNode.add(childNode);\n }\n }" ]
Sorts the given array into sorted order using the given comparator. @param self the array to be sorted @param comparator a Comparator used for the comparison @return the sorted array @since 1.5.5
[ "public static <T> T[] sort(T[] self, Comparator<T> comparator) {\n return sort(self, true, comparator);\n }" ]
[ "public static void symmLowerToFull( DMatrixRMaj A )\n {\n if( A.numRows != A.numCols )\n throw new MatrixDimensionException(\"Must be a square matrix\");\n\n final int cols = A.numCols;\n\n for (int row = 0; row < A.numRows; row++) {\n for (int col = row+1; col < cols; col++) {\n A.data[row*cols+col] = A.data[col*cols+row];\n }\n }\n }", "public InetAddress getRemoteAddress() {\n final Channel channel;\n try {\n channel = strategy.getChannel();\n } catch (IOException e) {\n return null;\n }\n final Connection connection = channel.getConnection();\n final InetSocketAddress peerAddress = connection.getPeerAddress(InetSocketAddress.class);\n return peerAddress == null ? null : peerAddress.getAddress();\n }", "private static boolean scanForEndSig(File file, FileChannel channel) throws IOException, NonScannableZipException {\n\n // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long start = channel.size();\n long end = Math.max(0, start - MAX_REVERSE_SCAN);\n long channelPos = Math.max(0, start - CHUNK_SIZE);\n long lastChannelPos = channelPos;\n boolean firstRead = true;\n while (lastChannelPos >= end) {\n\n read(bb, channel, channelPos);\n\n int actualRead = bb.limit();\n if (firstRead) {\n long expectedRead = Math.min(CHUNK_SIZE, start);\n if (actualRead > expectedRead) {\n // File is still growing\n return false;\n }\n firstRead = false;\n }\n\n int bufferPos = actualRead -1;\n while (bufferPos >= SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the pattern is static\n // b) the pattern has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && ENDSIG_PATTERN[patternPos] == bb.get(bufferPos - patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid end of central dir record\n long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;\n if (validateEndRecord(file, channel, startEndRecord)) {\n return true;\n }\n // wasn't a valid end record; continue scan\n bufferPos -= 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;\n bufferPos -= END_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos -= 4;\n }\n }\n\n // Move back a full chunk. If we didn't read a full chunk, that's ok,\n // it means we read all data and the outer while loop will terminate\n if (channelPos <= bufferPos) {\n break;\n }\n lastChannelPos = channelPos;\n channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);\n }\n\n return false;\n }", "protected void layoutGroupSubreports(DJGroup columnsGroup, JRDesignGroup jgroup) {\n\t\tlog.debug(\"Starting subreport layout...\");\n\t\tJRDesignBand footerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupFooterSection()).getBandsList().get(0);\n\t\tJRDesignBand headerBand = (JRDesignBand) ((JRDesignSection)jgroup.getGroupHeaderSection()).getBandsList().get(0);\n\n\t\tlayOutSubReportInBand(columnsGroup, headerBand, DJConstants.HEADER);\n\t\tlayOutSubReportInBand(columnsGroup, footerBand, DJConstants.FOOTER);\n\n\t}", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n protected void addStoreToSession(String store) {\n\n Exception initializationException = null;\n\n storeNames.add(store);\n\n for(Node node: nodesToStream) {\n\n SocketDestination destination = null;\n SocketAndStreams sands = null;\n\n try {\n destination = new SocketDestination(node.getHost(),\n node.getAdminPort(),\n RequestFormatType.ADMIN_PROTOCOL_BUFFERS);\n sands = streamingSocketPool.checkout(destination);\n DataOutputStream outputStream = sands.getOutputStream();\n DataInputStream inputStream = sands.getInputStream();\n\n nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination);\n nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream);\n nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream);\n nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands);\n nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);\n\n remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId())\n .getValue();\n\n } catch(Exception e) {\n logger.error(e);\n try {\n close(sands.getSocket());\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n\n if(!faultyNodes.contains(node.getId()))\n faultyNodes.add(node.getId());\n initializationException = e;\n }\n\n }\n\n if(initializationException != null)\n throw new VoldemortException(initializationException);\n\n if(store.equals(\"slop\"))\n return;\n\n boolean foundStore = false;\n\n for(StoreDefinition remoteStoreDef: remoteStoreDefs) {\n if(remoteStoreDef.getName().equals(store)) {\n RoutingStrategyFactory factory = new RoutingStrategyFactory();\n RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef,\n adminClient.getAdminClientCluster());\n\n storeToRoutingStrategy.put(store, storeRoutingStrategy);\n validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef);\n foundStore = true;\n break;\n }\n }\n if(!foundStore) {\n logger.error(\"Store Name not found on the cluster\");\n throw new VoldemortException(\"Store Name not found on the cluster\");\n\n }\n\n }", "private Object getUdfValue(UDFAssignmentType udf)\n {\n if (udf.getCostValue() != null)\n {\n return udf.getCostValue();\n }\n \n if (udf.getDoubleValue() != null)\n {\n return udf.getDoubleValue();\n }\n \n if (udf.getFinishDateValue() != null)\n {\n return udf.getFinishDateValue();\n }\n \n if (udf.getIndicatorValue() != null)\n {\n return udf.getIndicatorValue();\n }\n \n if (udf.getIntegerValue() != null)\n {\n return udf.getIntegerValue();\n }\n \n if (udf.getStartDateValue() != null)\n {\n return udf.getStartDateValue();\n }\n \n if (udf.getTextValue() != null)\n {\n return udf.getTextValue();\n }\n \n return null;\n }", "protected void fixIntegerPrecisions(ItemIdValue itemIdValue,\n\t\t\tString propertyId) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Get the current statements for the property we want to fix:\n\t\t\tStatementGroup editPropertyStatements = currentItemDocument\n\t\t\t\t\t.findStatementGroup(propertyId);\n\t\t\tif (editPropertyStatements == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" no longer has any statements for \" + propertyId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tPropertyIdValue property = Datamodel\n\t\t\t\t\t.makeWikidataPropertyIdValue(propertyId);\n\t\t\tList<Statement> updateStatements = new ArrayList<>();\n\t\t\tfor (Statement s : editPropertyStatements) {\n\t\t\t\tQuantityValue qv = (QuantityValue) s.getValue();\n\t\t\t\tif (qv != null && isPlusMinusOneValue(qv)) {\n\t\t\t\t\tQuantityValue exactValue = Datamodel.makeQuantityValue(\n\t\t\t\t\t\t\tqv.getNumericValue(), qv.getNumericValue(),\n\t\t\t\t\t\t\tqv.getNumericValue());\n\t\t\t\t\tStatement exactStatement = StatementBuilder\n\t\t\t\t\t\t\t.forSubjectAndProperty(itemIdValue, property)\n\t\t\t\t\t\t\t.withValue(exactValue).withId(s.getStatementId())\n\t\t\t\t\t\t\t.withQualifiers(s.getQualifiers())\n\t\t\t\t\t\t\t.withReferences(s.getReferences())\n\t\t\t\t\t\t\t.withRank(s.getRank()).build();\n\t\t\t\t\tupdateStatements.add(exactStatement);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (updateStatements.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** \" + qid + \" quantity values for \"\n\t\t\t\t\t\t+ propertyId + \" already fixed\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tupdateStatements, propertyId);\n\n\t\t\tdataEditor.updateStatements(currentItemDocument, updateStatements,\n\t\t\t\t\tCollections.<Statement> emptyList(),\n\t\t\t\t\t\"Set exact values for [[Property:\" + propertyId + \"|\"\n\t\t\t\t\t\t\t+ propertyId + \"]] integer quantities (Task MB2)\");\n\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "protected PrintResult withOpenOutputStream(final PrintAction function) throws Exception {\n final File reportFile = getReportFile();\n final Processor.ExecutionContext executionContext;\n try (FileOutputStream out = new FileOutputStream(reportFile);\n BufferedOutputStream bout = new BufferedOutputStream(out)) {\n executionContext = function.run(bout);\n }\n return new PrintResult(reportFile.length(), executionContext);\n }", "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean confirm = false;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Remove metadata related to rebalancing\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n if(allNodes) {\n System.out.println(\" node = all nodes\");\n } else {\n System.out.println(\" node = \" + Joiner.on(\", \").join(nodeIds));\n }\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm, \"remove metadata related to rebalancing\")) {\n return;\n }\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds);\n\n doMetaClearRebalance(adminClient, nodeIds);\n }" ]
Replace a single value at the appropriate location in the existing value array. @param index - location in the array list @param newValue - the new String
[ "public void set1Value(int index, String newValue) {\n try {\n value.set( index, newValue );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) exception \" + e);\n }\n }" ]
[ "public Profile[] getProfilesForServerName(String serverName) throws Exception {\n int profileId = -1;\n ArrayList<Profile> returnProfiles = new ArrayList<Profile>();\n\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.GENERIC_PROFILE_ID + \" FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ? GROUP BY \" +\n Constants.GENERIC_PROFILE_ID\n );\n queryStatement.setString(1, serverName);\n results = queryStatement.executeQuery();\n\n while (results.next()) {\n profileId = results.getInt(Constants.GENERIC_PROFILE_ID);\n\n Profile profile = ProfileService.getInstance().findProfile(profileId);\n\n returnProfiles.add(profile);\n }\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (returnProfiles.size() == 0) {\n return null;\n }\n return returnProfiles.toArray(new Profile[0]);\n }", "private void sortFields()\r\n {\r\n HashMap fields = new HashMap();\r\n ArrayList fieldsWithId = new ArrayList();\r\n ArrayList fieldsWithoutId = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext(); )\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n fields.put(fieldDef.getName(), fieldDef);\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_ID))\r\n {\r\n fieldsWithId.add(fieldDef.getName());\r\n }\r\n else\r\n {\r\n fieldsWithoutId.add(fieldDef.getName());\r\n }\r\n }\r\n\r\n Collections.sort(fieldsWithId, new FieldWithIdComparator(fields));\r\n\r\n ArrayList result = new ArrayList();\r\n\r\n for (Iterator it = fieldsWithId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n for (Iterator it = fieldsWithoutId.iterator(); it.hasNext();)\r\n {\r\n result.add(getField((String)it.next()));\r\n }\r\n\r\n _fields = result;\r\n }", "protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }", "public String getHealthMemory() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Logging JVM Stats\\n\");\n MonitorProvider mp = MonitorProvider.getInstance();\n PerformUsage perf = mp.getJVMMemoryUsage();\n sb.append(perf.toString());\n\n if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {\n sb.append(\"========= WARNING: MEM USAGE > \" + THRESHOLD_PERCENT\n + \"!!\");\n sb.append(\" !! Live Threads List=============\\n\");\n sb.append(mp.getThreadUsage().toString());\n sb.append(\"========================================\\n\");\n sb.append(\"========================JVM Thread Dump====================\\n\");\n ThreadInfo[] threadDump = mp.getThreadDump();\n for (ThreadInfo threadInfo : threadDump) {\n sb.append(threadInfo.toString() + \"\\n\");\n }\n sb.append(\"===========================================================\\n\");\n }\n sb.append(\"Logged JVM Stats\\n\");\n\n return sb.toString();\n }", "public void createAssignmentFieldMap(Props props)\n {\n //System.out.println(\"ASSIGN\");\n byte[] fieldMapData = null;\n for (Integer key : ASSIGNMENT_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultAssignmentData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public InputStream getStream(String url, RasterLayer layer) throws IOException {\n\t\tif (layer instanceof ProxyLayerSupport) {\n\t\t\tProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;\n\t\t\tif (proxyLayer.isUseCache() && null != cacheManagerService) {\n\t\t\t\tObject cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);\n\t\t\t\tif (null != cachedObject) {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) cachedObject);\n\t\t\t\t} else {\n\t\t\t\t\ttestRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);\n\t\t\t\t\tInputStream stream = super.getStream(url, proxyLayer);\n\t\t\t\t\tByteArrayOutputStream os = new ByteArrayOutputStream();\n\t\t\t\t\tint b;\n\t\t\t\t\twhile ((b = stream.read()) >= 0) {\n\t\t\t\t\t\tos.write(b);\n\t\t\t\t\t}\n\t\t\t\t\tcacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),\n\t\t\t\t\t\t\tgetLayerEnvelope(proxyLayer));\n\t\t\t\t\treturn new ByteArrayInputStream((byte[]) os.toByteArray());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn super.getStream(url, layer);\n\t}", "public static byte[] encode(byte[] ba, int offset, long v) {\n ba[offset + 0] = (byte) (v >>> 56);\n ba[offset + 1] = (byte) (v >>> 48);\n ba[offset + 2] = (byte) (v >>> 40);\n ba[offset + 3] = (byte) (v >>> 32);\n ba[offset + 4] = (byte) (v >>> 24);\n ba[offset + 5] = (byte) (v >>> 16);\n ba[offset + 6] = (byte) (v >>> 8);\n ba[offset + 7] = (byte) (v >>> 0);\n return ba;\n }", "private Date getTimeFromInteger(Integer time)\n {\n Date result = null;\n\n if (time != null)\n {\n int minutes = time.intValue();\n int hours = minutes / 60;\n minutes -= (hours * 60);\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.HOUR_OF_DAY, hours);\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n\n return (result);\n }", "public Where<T, ID> like(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LIKE_OPERATION));\n\t\treturn this;\n\t}" ]
Get the ActivityInterface. @return The ActivityInterface
[ "@Override\n public ActivityInterface getActivityInterface() {\n if (activityInterface == null) {\n activityInterface = new ActivityInterface(apiKey, sharedSecret, transport);\n }\n return activityInterface;\n }" ]
[ "public static final String printBookingType(BookingType value)\n {\n return (Integer.toString(value == null ? BookingType.COMMITTED.getValue() : value.getValue()));\n }", "private PersistenceBroker obtainBroker()\r\n {\r\n PersistenceBroker _broker;\r\n try\r\n {\r\n if (pbKey == null)\r\n {\r\n //throw new OJBRuntimeException(\"Not possible to do action, cause no tx runnning and no PBKey is set\");\r\n log.warn(\"No tx runnning and PBKey is null, try to use the default PB\");\r\n _broker = PersistenceBrokerFactory.defaultPersistenceBroker();\r\n }\r\n else\r\n {\r\n _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);\r\n }\r\n }\r\n catch (PBFactoryException e)\r\n {\r\n log.error(\"Could not obtain PB for PBKey \" + pbKey, e);\r\n throw new OJBRuntimeException(\"Unexpected micro-kernel exception\", e);\r\n }\r\n return _broker;\r\n }", "public final void setValue(String value) {\n\n if ((null == value) || value.isEmpty()) {\n setDefaultValue();\n } else {\n try {\n tryToSetParsedValue(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n CmsDebugLog.consoleLog(\"Could not set invalid serial date value: \" + value);\n setDefaultValue();\n }\n }\n notifyOnValueChange();\n }", "public byte[] getMessageBuffer() {\n\t\tByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();\n\t\tbyte[] result;\n\t\tresultByteBuffer.write((byte)0x01);\n\t\tint messageLength = messagePayload.length + \n\t\t\t\t(this.messageClass == SerialMessageClass.SendData && \n\t\t\t\tthis.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length\n\t\t\n\t\tresultByteBuffer.write((byte) messageLength);\n\t\tresultByteBuffer.write((byte) messageType.ordinal());\n\t\tresultByteBuffer.write((byte) messageClass.getKey());\n\t\t\n\t\ttry {\n\t\t\tresultByteBuffer.write(messagePayload);\n\t\t} catch (IOException e) {\n\t\t\t\n\t\t}\n\n\t\t// callback ID and transmit options for a Send Data message.\n\t\tif (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {\n\t\t\tresultByteBuffer.write(transmitOptions);\n\t\t\tresultByteBuffer.write(callbackId);\n\t\t}\n\t\t\n\t\tresultByteBuffer.write((byte) 0x00);\n\t\tresult = resultByteBuffer.toByteArray();\n\t\tresult[result.length - 1] = 0x01;\n\t\tresult[result.length - 1] = calculateChecksum(result);\n\t\tlogger.debug(\"Assembled message buffer = \" + SerialMessage.bb2hex(result));\n\t\treturn result;\n\t}", "public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,\r\n edu.stanford.nlp.sequences.FeatureFactory<IN> featureFactory) {\r\n pad.set(AnswerAnnotation.class, flags.backgroundSymbol);\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n ArrayList<List<String>> features = new ArrayList<List<String>>();\r\n\r\n // for (int i = 0; i < windowSize; i++) {\r\n // List featuresC = new ArrayList();\r\n // for (int j = 0; j < FeatureFactory.win[i].length; j++) {\r\n // featuresC.addAll(featureFactory.features(info, loc,\r\n // FeatureFactory.win[i][j]));\r\n // }\r\n // features.add(featuresC);\r\n // }\r\n\r\n Collection<Clique> done = new HashSet<Clique>();\r\n for (int i = 0; i < windowSize; i++) {\r\n List<String> featuresC = new ArrayList<String>();\r\n List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);\r\n windowCliques.removeAll(done);\r\n done.addAll(windowCliques);\r\n for (Clique c : windowCliques) {\r\n featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons\r\n }\r\n features.add(featuresC);\r\n }\r\n\r\n int[] labels = new int[windowSize];\r\n\r\n for (int i = 0; i < windowSize; i++) {\r\n String answer = pInfo.get(loc + i - windowSize + 1).get(AnswerAnnotation.class);\r\n labels[i] = classIndex.indexOf(answer);\r\n }\r\n\r\n printFeatureLists(pInfo.get(loc), features);\r\n\r\n CRFDatum<List<String>, CRFLabel> d = new CRFDatum<List<String>, CRFLabel>(features, new CRFLabel(labels));\r\n // System.err.println(d);\r\n return d;\r\n }", "public static nslimitidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tobj.set_name(name);\n\t\tnslimitidentifier_stats response = (nslimitidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public static base_response add(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction addresource = new tmtrafficaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.apptimeout = resource.apptimeout;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.formssoaction = resource.formssoaction;\n\t\taddresource.persistentcookie = resource.persistentcookie;\n\t\taddresource.initiatelogout = resource.initiatelogout;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn addresource.add_resource(client);\n\t}", "private void setExpressionForPrecalculatedTotalValue(\n\t\t\tDJCrosstabColumn[] auxCols, DJCrosstabRow[] auxRows, JRDesignExpression measureExp, DJCrosstabMeasure djmeasure,\n\t\t\tDJCrosstabColumn crosstabColumn, DJCrosstabRow crosstabRow, String meausrePrefix) {\n\n\t\tString rowValuesExp = \"new Object[]{\";\n\t\tString rowPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxRows.length; i++) {\n\t\t\tif (auxRows[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\trowValuesExp += \"$V{\" + auxRows[i].getProperty().getProperty() +\"}\";\n\t\t\trowPropsExp += \"\\\"\" + auxRows[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxRows.length && auxRows[i+1].getProperty()!= null){\n\t\t\t\trowValuesExp += \", \";\n\t\t\t\trowPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\trowValuesExp += \"}\";\n\t\trowPropsExp += \"}\";\n\n\t\tString colValuesExp = \"new Object[]{\";\n\t\tString colPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxCols.length; i++) {\n\t\t\tif (auxCols[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\tcolValuesExp += \"$V{\" + auxCols[i].getProperty().getProperty() +\"}\";\n\t\t\tcolPropsExp += \"\\\"\" + auxCols[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxCols.length && auxCols[i+1].getProperty()!= null){\n\t\t\t\tcolValuesExp += \", \";\n\t\t\t\tcolPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\tcolValuesExp += \"}\";\n\t\tcolPropsExp += \"}\";\n\n\t\tString measureProperty = meausrePrefix + djmeasure.getProperty().getProperty();\n\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_totalProvider}).getValueFor( \"\n\t\t+ colPropsExp +\", \"\n\t\t+ colValuesExp +\", \"\n\t\t+ rowPropsExp\n\t\t+ \", \"\n\t\t+ rowValuesExp\n\t\t+\" ))\";\n\n\t\tif (djmeasure.getValueFormatter() != null){\n\n\t\t\tString fieldsMap = ExpressionUtils.getTextForFieldsFromScriptlet();\n\t\t\tString parametersMap = ExpressionUtils.getTextForParametersFromScriptlet();\n\t\t\tString variablesMap = ExpressionUtils.getTextForVariablesFromScriptlet();\n\n\t\t\tString stringExpression = \"(((\"+DJValueFormatter.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_vf}).evaluate( \"\n\t\t\t\t+ \"(\"+expText+\"), \" + fieldsMap +\", \" + variablesMap + \", \" + parametersMap +\" ))\";\n\n\t\t\tmeasureExp.setText(stringExpression);\n\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t} else {\n\n//\t\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+djmeasure.getProperty().getProperty()+\"_totalProvider}).getValueFor( \"\n//\t\t\t+ colPropsExp +\", \"\n//\t\t\t+ colValuesExp +\", \"\n//\t\t\t+ rowPropsExp\n//\t\t\t+ \", \"\n//\t\t\t+ rowValuesExp\n//\t\t\t+\" ))\";\n//\n\t\t\tlog.debug(\"text for crosstab total provider is: \" + expText);\n\n\t\t\tmeasureExp.setText(expText);\n//\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t\tString valueClassNameForOperation = ExpressionUtils.getValueClassNameForOperation(djmeasure.getOperation(),djmeasure.getProperty());\n\t\t\tmeasureExp.setValueClassName(valueClassNameForOperation);\n\t\t}\n\n\t}", "public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) {\n Resources res = context.getResources();\n Duration duration = readableDuration.toDuration();\n\n final int hours = (int) duration.getStandardHours();\n if (hours != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours);\n }\n\n final int minutes = (int) duration.getStandardMinutes();\n if (minutes != 0) {\n return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes);\n }\n\n final int seconds = (int) duration.getStandardSeconds();\n return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds);\n }" ]
Returns an MBeanServer with the specified name @param name @return
[ "private MBeanServer getServerForName(String name) {\n try {\n MBeanServer mbeanServer = null;\n final ObjectName objectNameQuery = new ObjectName(name + \":type=Service,*\");\n\n for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {\n if (server.queryNames(objectNameQuery, null).size() > 0) {\n mbeanServer = server;\n // we found it, bail out\n break;\n }\n }\n\n return mbeanServer;\n } catch (Exception e) {\n }\n\n return null;\n }" ]
[ "public void setFarClippingDistance(float far) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setFarClippingDistance(far);\n centerCamera.setFarClippingDistance(far);\n ((GVRCameraClippingDistanceInterface)rightCamera).setFarClippingDistance(far);\n }\n }", "public Map<String, String> getParams() {\n\n Map<String, String> params = new HashMap<>(1);\n params.put(PARAM_COLLAPSED, Boolean.TRUE.toString());\n return params;\n }", "protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }", "private Integer getOutlineLevel(Task task)\n {\n String value = task.getWBS();\n Integer result = Integer.valueOf(1);\n if (value != null && value.length() > 0)\n {\n String[] path = WBS_SPLIT_REGEX.split(value);\n result = Integer.valueOf(path.length);\n }\n return result;\n }", "private Calendar cleanHistCalendar(Calendar cal) {\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.HOUR, 0);\n return cal;\n }", "public void updateStructure()\n {\n if (size() > 1)\n {\n Collections.sort(this);\n m_projectFile.getChildTasks().clear();\n\n Task lastTask = null;\n int lastLevel = -1;\n boolean autoWbs = m_projectFile.getProjectConfig().getAutoWBS();\n boolean autoOutlineNumber = m_projectFile.getProjectConfig().getAutoOutlineNumber();\n\n for (Task task : this)\n {\n task.clearChildTasks();\n Task parent = null;\n if (!task.getNull())\n {\n int level = NumberHelper.getInt(task.getOutlineLevel());\n\n if (lastTask != null)\n {\n if (level == lastLevel || task.getNull())\n {\n parent = lastTask.getParentTask();\n level = lastLevel;\n }\n else\n {\n if (level > lastLevel)\n {\n parent = lastTask;\n }\n else\n {\n while (level <= lastLevel)\n {\n parent = lastTask.getParentTask();\n\n if (parent == null)\n {\n break;\n }\n\n lastLevel = NumberHelper.getInt(parent.getOutlineLevel());\n lastTask = parent;\n }\n }\n }\n }\n\n lastTask = task;\n lastLevel = level;\n\n if (autoWbs || task.getWBS() == null)\n {\n task.generateWBS(parent);\n }\n\n if (autoOutlineNumber)\n {\n task.generateOutlineNumber(parent);\n }\n }\n\n if (parent == null)\n {\n m_projectFile.getChildTasks().add(task);\n }\n else\n {\n parent.addChildTask(task);\n }\n }\n }\n }", "protected boolean closeAtomically() {\n if (isClosed.compareAndSet(false, true)) {\n Closeable.closeQuietly(networkStatsListener);\n return true;\n } else {\n //was already closed.\n return false;\n }\n }", "public void setSchema(String schema)\n {\n if (schema.charAt(schema.length() - 1) != '.')\n {\n schema = schema + '.';\n }\n m_schema = schema;\n }", "private List<Variable> parseAssignRange(Sequence sequence, TokenList tokens, TokenList.Token t0) {\n // find assignment symbol\n TokenList.Token tokenAssign = t0.next;\n while( tokenAssign != null && tokenAssign.symbol != Symbol.ASSIGN ) {\n tokenAssign = tokenAssign.next;\n }\n\n if( tokenAssign == null )\n throw new ParseError(\"Can't find assignment operator\");\n\n // see if it is a sub matrix before\n if( tokenAssign.previous.symbol == Symbol.PAREN_RIGHT ) {\n TokenList.Token start = t0.next;\n if( start.symbol != Symbol.PAREN_LEFT )\n throw new ParseError((\"Expected left param for assignment\"));\n TokenList.Token end = tokenAssign.previous;\n TokenList subTokens = tokens.extractSubList(start,end);\n subTokens.remove(subTokens.getFirst());\n subTokens.remove(subTokens.getLast());\n\n handleParentheses(subTokens,sequence);\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(subTokens, sequence);\n\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n\n List<Variable> range = new ArrayList<>();\n addSubMatrixVariables(inputs, range);\n if( range.size() != 1 && range.size() != 2 ) {\n throw new ParseError(\"Unexpected number of range variables. 1 or 2 expected\");\n }\n return range;\n }\n\n return null;\n }" ]
This method takes an integer enumeration of a priority and returns an appropriate instance of this class. Note that unrecognised values are treated as medium priority. @param priority int version of the priority @return Priority class instance
[ "public static Priority getInstance(int priority)\n {\n Priority result;\n\n if (priority >= LOWEST && priority <= DO_NOT_LEVEL && (priority % 100 == 0))\n {\n result = VALUE[(priority / 100) - 1];\n }\n else\n {\n result = new Priority(priority);\n }\n\n return (result);\n }" ]
[ "public final Jar setAttribute(String section, String name, String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Manifest cannot be modified after entries are added.\");\n Attributes attr = getManifest().getAttributes(section);\n if (attr == null) {\n attr = new Attributes();\n getManifest().getEntries().put(section, attr);\n }\n attr.putValue(name, value);\n return this;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public TrackMetadata requestMetadataFrom(final CdjStatus status) {\n if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {\n return null;\n }\n final DataReference track = new DataReference(status.getTrackSourcePlayer(), status.getTrackSourceSlot(),\n status.getRekordboxId());\n return requestMetadataFrom(track, status.getTrackType());\n }", "public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,\n final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {\n\n return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);\n }", "public boolean invokeFunction(String funcName, Object[] args)\n {\n mLastError = null;\n if (mScriptFile != null)\n {\n if (mScriptFile.invokeFunction(funcName, args))\n {\n return true;\n }\n }\n mLastError = mScriptFile.getLastError();\n if ((mLastError != null) && !mLastError.contains(\"is not defined\"))\n {\n getGVRContext().logError(mLastError, this);\n }\n return false;\n }", "public void commandContinuationRequest()\r\n throws ProtocolException {\r\n try {\r\n output.write('+');\r\n output.write(' ');\r\n output.write('O');\r\n output.write('K');\r\n output.write('\\r');\r\n output.write('\\n');\r\n output.flush();\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Unexpected exception in sending command continuation request.\", e);\r\n }\r\n }", "public static double Y(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n double ans1 = x * (-0.4900604943e13 + y * (0.1275274390e13\r\n + y * (-0.5153438139e11 + y * (0.7349264551e9\r\n + y * (-0.4237922726e7 + y * 0.8511937935e4)))));\r\n double ans2 = 0.2499580570e14 + y * (0.4244419664e12\r\n + y * (0.3733650367e10 + y * (0.2245904002e8\r\n + y * (0.1020426050e6 + y * (0.3549632885e3 + y)))));\r\n return (ans1 / ans2) + 0.636619772 * (J(x) * Math.log(x) - 1.0 / x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 2.356194491;\r\n double ans1 = 1.0 + y * (0.183105e-2 + y * (-0.3516396496e-4\r\n + y * (0.2457520174e-5 + y * (-0.240337019e-6))));\r\n double ans2 = 0.04687499995 + y * (-0.2002690873e-3\r\n + y * (0.8449199096e-5 + y * (-0.88228987e-6\r\n + y * 0.105787412e-6)));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\n }", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "public static int validateZone(CharSequence zone) {\n\t\tfor(int i = 0; i < zone.length(); i++) {\n\t\t\tchar c = zone.charAt(i);\n\t\t\tif (c == IPAddress.PREFIX_LEN_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tif (c == IPv6Address.SEGMENT_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}", "public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) {\r\n sendMimeMessage(createTextEmail(to, from, subject, msg, setup));\r\n }" ]
adds a CmsJspImageBean as hi-DPI variant to this image @param factor the variant multiplier, e.g. "2x" (the common retina multiplier) @param image the image to be used for this variant
[ "public void addHiDpiImage(String factor, CmsJspImageBean image) {\n\n if (m_hiDpiImages == null) {\n m_hiDpiImages = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleHiDpiTransformer());\n }\n m_hiDpiImages.put(factor, image);\n }" ]
[ "private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }", "public int getChunkForKey(byte[] key) throws IllegalStateException {\n if(numChunks == 0) {\n throw new IllegalStateException(\"The ChunkedFileSet is closed.\");\n }\n\n switch(storageFormat) {\n case READONLY_V0: {\n return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks);\n }\n case READONLY_V1: {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n routingPartitionList.retainAll(nodePartitionIds);\n\n if(routingPartitionList.size() != 1) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n return chunkIdToChunkStart.get(routingPartitionList.get(0))\n + ReadOnlyUtils.chunk(ByteUtils.md5(key),\n chunkIdToNumChunks.get(routingPartitionList.get(0)));\n }\n case READONLY_V2: {\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n\n Pair<Integer, Integer> bucket = null;\n for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) {\n if(bucket == null) {\n bucket = Pair.create(routingPartitionList.get(0), replicaType);\n } else {\n throw new IllegalStateException(\"Found more than one replica for a given partition on the current node!\");\n }\n }\n }\n\n if(bucket == null) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n Integer chunkStart = chunkIdToChunkStart.get(bucket);\n\n if (chunkStart == null) {\n throw new IllegalStateException(\"chunkStart is null.\");\n }\n\n return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket));\n }\n default: {\n throw new IllegalStateException(\"Unsupported storageFormat: \" + storageFormat);\n }\n }\n\n }", "public static int cudnnReduceTensor(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n Pointer indices, \n long indicesSizeInBytes, \n Pointer workspace, \n long workspaceSizeInBytes, \n Pointer alpha, \n cudnnTensorDescriptor aDesc, \n Pointer A, \n Pointer beta, \n cudnnTensorDescriptor cDesc, \n Pointer C)\n {\n return checkResult(cudnnReduceTensorNative(handle, reduceTensorDesc, indices, indicesSizeInBytes, workspace, workspaceSizeInBytes, alpha, aDesc, A, beta, cDesc, C));\n }", "public static List<DbModule> getAllSubmodules(final DbModule module) {\n final List<DbModule> submodules = new ArrayList<DbModule>();\n submodules.addAll(module.getSubmodules());\n\n for(final DbModule submodule: module.getSubmodules()){\n submodules.addAll(getAllSubmodules(submodule));\n }\n\n return submodules;\n }", "public Long getLong(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }", "public static float gain(float a, float b) {\n/*\n\t\tfloat p = (float)Math.log(1.0 - b) / (float)Math.log(0.5);\n\n\t\tif (a < .001)\n\t\t\treturn 0.0f;\n\t\telse if (a > .999)\n\t\t\treturn 1.0f;\n\t\tif (a < 0.5)\n\t\t\treturn (float)Math.pow(2 * a, p) / 2;\n\t\telse\n\t\t\treturn 1.0f - (float)Math.pow(2 * (1. - a), p) / 2;\n*/\n\t\tfloat c = (1.0f/b-2.0f) * (1.0f-2.0f*a);\n\t\tif (a < 0.5)\n\t\t\treturn a/(c+1.0f);\n\t\telse\n\t\t\treturn (c-a)/(c-1.0f);\n\t}", "protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }", "public static String read(final File file) throws IOException {\n final StringBuilder sb = new StringBuilder();\n\n try (\n final FileReader fr = new FileReader(file);\n final BufferedReader br = new BufferedReader(fr);\n ) {\n\n String sCurrentLine;\n\n while ((sCurrentLine = br.readLine()) != null) {\n sb.append(sCurrentLine);\n }\n }\n\n return sb.toString();\n }" ]
Split a module Id to get the module version @param moduleId @return String
[ "public static String getModuleVersion(final String moduleId) {\n final int splitter = moduleId.lastIndexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(splitter+1);\n }" ]
[ "public Map<String, String> decompose(Frontier frontier, String modelText) {\r\n if (!(frontier instanceof SCXMLFrontier)) {\r\n return null;\r\n }\n\r\n TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState;\r\n Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables;\n\r\n Map<String, String> decomposition = new HashMap<String, String>();\r\n decomposition.put(\"target\", target.getId());\n\r\n StringBuilder packedVariables = new StringBuilder();\r\n for (Map.Entry<String, String> variable : variables.entrySet()) {\r\n packedVariables.append(variable.getKey());\r\n packedVariables.append(\"::\");\r\n packedVariables.append(variable.getValue());\r\n packedVariables.append(\";\");\r\n }\n\r\n decomposition.put(\"variables\", packedVariables.toString());\r\n decomposition.put(\"model\", modelText);\n\r\n return decomposition;\r\n }", "public ChangesResult getChanges() {\n final URI uri = this.databaseHelper.changesUri(\"feed\", \"normal\");\n return client.get(uri, ChangesResult.class);\n }", "public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException {\n\t\t// Calculate new derivatives. Note that this method is called only with\n\t\t// parameters = parameterCurrent, so we may use valueCurrent.\n\n\t\tVector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length);\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\tfinal double[] parametersNew\t= parameters.clone();\n\t\t\tfinal double[] derivative\t\t= derivatives[parameterIndex];\n\n\t\t\tfinal int workerParameterIndex = parameterIndex;\n\t\t\tCallable<double[]> worker = new Callable<double[]>() {\n\t\t\t\tpublic double[] call() {\n\t\t\t\t\tdouble parameterFiniteDifference;\n\t\t\t\t\tif(parameterSteps != null) {\n\t\t\t\t\t\tparameterFiniteDifference = parameterSteps[workerParameterIndex];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try to adaptively set a parameter shift. Note that in some\n\t\t\t\t\t\t * applications it may be important to set parameterSteps.\n\t\t\t\t\t\t * appropriately.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tparameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Shift parameter value\n\t\t\t\t\tparametersNew[workerParameterIndex] += parameterFiniteDifference;\n\n\t\t\t\t\t// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsetValues(parametersNew, derivative);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// We signal an exception to calculate the derivative as NaN\n\t\t\t\t\t\tArrays.fill(derivative, Double.NaN);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) {\n\t\t\t\t\t\tderivative[valueIndex] -= valueCurrent[valueIndex];\n\t\t\t\t\t\tderivative[valueIndex] /= parameterFiniteDifference;\n\t\t\t\t\t\tif(Double.isNaN(derivative[valueIndex])) {\n\t\t\t\t\t\t\tderivative[valueIndex] = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn derivative;\n\t\t\t\t}\n\t\t\t};\n\t\t\tif(executor != null) {\n\t\t\t\tFuture<double[]> valueFuture = executor.submit(worker);\n\t\t\t\tvalueFutures.add(parameterIndex, valueFuture);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tFutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker);\n\t\t\t\tvalueFutureTask.run();\n\t\t\t\tvalueFutures.add(parameterIndex, valueFutureTask);\n\t\t\t}\n\t\t}\n\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\ttry {\n\t\t\t\tderivatives[parameterIndex] = valueFutures.get(parameterIndex).get();\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t}\n\t\t}\n\t}", "public static systementitydata[] get(nitro_service service, systementitydata_args args) throws Exception{\n\t\tsystementitydata obj = new systementitydata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsystementitydata[] response = (systementitydata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public static void Forward(double[][] data) {\n double[][] result = new double[data.length][data[0].length];\n\n for (int m = 0; m < data.length; m++) {\n for (int n = 0; n < data[0].length; n++) {\n double sum = 0;\n for (int i = 0; i < result.length; i++) {\n for (int k = 0; k < data.length; k++) {\n sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n));\n }\n result[m][n] = (1.0 / data.length) * sum;\n }\n }\n }\n\n for (int i = 0; i < data.length; i++) {\n for (int j = 0; j < data[0].length; j++) {\n data[i][j] = result[i][j];\n }\n }\n }", "public JavadocComment toComment(String indentation) {\n for (char c : indentation.toCharArray()) {\n if (!Character.isWhitespace(c)) {\n throw new IllegalArgumentException(\"The indentation string should be composed only by whitespace characters\");\n }\n }\n StringBuilder sb = new StringBuilder();\n sb.append(EOL);\n final String text = toText();\n if (!text.isEmpty()) {\n for (String line : text.split(EOL)) {\n sb.append(indentation);\n sb.append(\" * \");\n sb.append(line);\n sb.append(EOL);\n }\n }\n sb.append(indentation);\n sb.append(\" \");\n return new JavadocComment(sb.toString());\n }", "public static byte numberOfBytesRequired(long number) {\n if(number < 0)\n number = -number;\n for(byte i = 1; i <= SIZE_OF_LONG; i++)\n if(number < (1L << (8 * i)))\n return i;\n throw new IllegalStateException(\"Should never happen.\");\n }", "public void configure(Configuration pConfig) throws ConfigurationException\r\n {\r\n if (pConfig instanceof PBPoolConfiguration)\r\n {\r\n PBPoolConfiguration conf = (PBPoolConfiguration) pConfig;\r\n this.setMaxActive(conf.getMaxActive());\r\n this.setMaxIdle(conf.getMaxIdle());\r\n this.setMaxWait(conf.getMaxWaitMillis());\r\n this.setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis());\r\n this.setTimeBetweenEvictionRunsMillis(conf.getTimeBetweenEvictionRunsMilli());\r\n this.setWhenExhaustedAction(conf.getWhenExhaustedAction());\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass().getName() +\r\n \" cannot read configuration properties, use default.\");\r\n }\r\n }", "String buildSelect(String htmlAttributes, SelectOptions options) {\n\n return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());\n }" ]
We have a non-null date, try each format in turn to see if it can be parsed. @param str date to parse @param pos position at which to start parsing @return Date instance
[ "protected Date parseNonNullDate(String str, ParsePosition pos)\n {\n Date result = null;\n for (int index = 0; index < m_formats.length; index++)\n {\n result = m_formats[index].parse(str, pos);\n if (pos.getIndex() != 0)\n {\n break;\n }\n result = null;\n }\n return result;\n }" ]
[ "public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "public byte[] keyToStorageFormat(byte[] key) {\n\n switch(getReadOnlyStorageFormat()) {\n case READONLY_V0:\n case READONLY_V1:\n return ByteUtils.md5(key);\n case READONLY_V2:\n return ByteUtils.copy(ByteUtils.md5(key), 0, 2 * ByteUtils.SIZE_OF_INT);\n default:\n throw new VoldemortException(\"Unknown read-only storage format\");\n }\n }", "public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }", "public static <A extends Annotation> EnhancedAnnotation<A> create(SlimAnnotatedType<A> annotatedType, ClassTransformer classTransformer) {\n\n Class<A> annotationType = annotatedType.getJavaClass();\n\n Map<Class<? extends Annotation>, Annotation> annotationMap = new HashMap<Class<? extends Annotation>, Annotation>();\n annotationMap.putAll(buildAnnotationMap(annotatedType.getAnnotations()));\n annotationMap.putAll(buildAnnotationMap(classTransformer.getTypeStore().get(annotationType)));\n // Annotations and declared annotations are the same for annotation type\n return new EnhancedAnnotationImpl<A>(annotatedType, annotationMap, annotationMap, classTransformer);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public Stream<ChangeEvent<DocumentT>> watch(final BsonValue... ids)\n throws InterruptedException, IOException {\n return operations.watch(\n new HashSet<>(Arrays.asList(ids)),\n false,\n documentClass\n ).execute(service);\n }", "public int getXForBeat(int beat) {\n BeatGrid grid = beatGrid.get();\n if (grid != null) {\n return millisecondsToX(grid.getTimeWithinTrack(beat));\n }\n return 0;\n }", "public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {\n return getSharedItem(api, sharedLink, null);\n }", "public static void generateJavaFiles(String requirementsFolder,\n String platformName, String src_test_dir, String tests_package,\n String casemanager_package, String loggingPropFile)\n throws Exception {\n\n File reqFolder = new File(requirementsFolder);\n if (reqFolder.isDirectory()) {\n for (File f : reqFolder.listFiles()) {\n if (f.getName().endsWith(\".story\")) {\n try {\n SystemReader.generateJavaFilesForOneStory(\n f.getCanonicalPath(), platformName,\n src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } catch (IOException e) {\n String message = \"ERROR: \" + e.getMessage();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n }\n for (File f : reqFolder.listFiles()) {\n if (f.isDirectory()) {\n SystemReader.generateJavaFiles(requirementsFolder\n + File.separator + f.getName(), platformName,\n src_test_dir, tests_package + \".\" + f.getName(),\n casemanager_package, loggingPropFile);\n }\n }\n } else if (reqFolder.getName().endsWith(\".story\")) {\n SystemReader.generateJavaFilesForOneStory(requirementsFolder,\n platformName, src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } else {\n String message = \"No story file found in \" + requirementsFolder;\n logger.severe(message);\n throw new BeastException(message);\n }\n\n }", "public void setSingletonVariable(String name, WindupVertexFrame frame)\n {\n setVariable(name, Collections.singletonList(frame));\n }" ]
Retrieves a timestamp from the property data. @param type Type identifier @return timestamp
[ "public Date getTime(Integer type)\n {\n Date result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getTime(item, 0);\n }\n\n return (result);\n }" ]
[ "public static base_response update(nitro_service client, bridgetable resource) throws Exception {\n\t\tbridgetable updateresource = new bridgetable();\n\t\tupdateresource.bridgeage = resource.bridgeage;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static String strMapToStr(Map<String, String> map) {\n\n StringBuilder sb = new StringBuilder();\n\n if (map == null || map.isEmpty())\n return sb.toString();\n\n for (Entry<String, String> entry : map.entrySet()) {\n\n sb.append(\"< \" + entry.getKey() + \", \" + entry.getValue() + \"> \");\n }\n return sb.toString();\n\n }", "public static String getJavaClassFromSchemaInfo(String schemaInfo) {\n final String ONLY_JAVA_CLIENTS_SUPPORTED = \"Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=foo.Bar</schema-info> where foo.Bar is the fully qualified name of the message.\";\n\n if(StringUtils.isEmpty(schemaInfo))\n throw new IllegalArgumentException(\"This serializer requires a non-empty schema-info.\");\n\n String[] languagePairs = StringUtils.split(schemaInfo, ',');\n if(languagePairs.length > 1)\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n String[] javaPair = StringUtils.split(languagePairs[0], '=');\n if(javaPair.length != 2 || !javaPair[0].trim().equals(\"java\"))\n throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);\n\n return javaPair[1].trim();\n }", "public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }", "public List<BoxTask.Info> getTasks(String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n URL url = GET_TASKS_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTask.Info> tasks = new ArrayList<BoxTask.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject taskJSON = value.asObject();\n BoxTask task = new BoxTask(this.getAPI(), taskJSON.get(\"id\").asString());\n BoxTask.Info info = task.new Info(taskJSON);\n tasks.add(info);\n }\n\n return tasks;\n }", "String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }", "private List<Entry> sortEntries(List<Entry> loadedEntries) {\n Collections.sort(loadedEntries, new Comparator<Entry>() {\n @Override\n public int compare(Entry entry1, Entry entry2) {\n int result = (int) (entry1.cuePosition - entry2.cuePosition);\n if (result == 0) {\n int h1 = (entry1.hotCueNumber != 0) ? 1 : 0;\n int h2 = (entry2.hotCueNumber != 0) ? 1 : 0;\n result = h1 - h2;\n }\n return result;\n }\n });\n return Collections.unmodifiableList(loadedEntries);\n }", "WaveformDetail getWaveformDetail(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n final NumberField idField = new NumberField(rekordboxId);\n\n // First try to get the NXS2-style color waveform if we are supposed to.\n if (preferColor.get()) {\n try {\n Message response = client.simpleRequest(Message.KnownType.ANLZ_TAG_REQ, Message.KnownType.ANLZ_TAG,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField,\n new NumberField(Message.ANLZ_FILE_TAG_COLOR_WAVEFORM_DETAIL), new NumberField(Message.ALNZ_FILE_TYPE_EXT));\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n } catch (Exception e) {\n logger.info(\"No color waveform available for slot \" + slot + \", id \" + rekordboxId + \"; requesting blue version.\", e);\n }\n }\n\n Message response = client.simpleRequest(Message.KnownType.WAVE_DETAIL_REQ, Message.KnownType.WAVE_DETAIL,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField, NumberField.WORD_0);\n return new WaveformDetail(new DataReference(slot, rekordboxId), response);\n }", "public static Document removeTags(Document dom, String tagName) {\n NodeList list;\n try {\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n\n while (list.getLength() > 0) {\n Node sc = list.item(0);\n\n if (sc != null) {\n sc.getParentNode().removeChild(sc);\n }\n\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n }\n } catch (XPathExpressionException e) {\n LOGGER.error(\"Error while removing tag \" + tagName, e);\n }\n\n return dom;\n\n }" ]
Returns the given text with the first letter in upper case. <h2>Examples:</h2> <pre> capitalize("hi") == "Hi" capitalize("Hi") == "Hi" capitalize("hi there") == "hi there" capitalize("") == "" capitalize(null) == null </pre> @param text the text to capitalize @return text with the first letter in upper case
[ "public static String capitalize( String text ) {\n if( text == null || text.isEmpty() ) {\n return text;\n }\n return text.substring( 0, 1 ).toUpperCase().concat( text.substring( 1, text.length() ) );\n }" ]
[ "public void reformatFile() throws IOException\n {\n List<LineNumberPosition> lineBrokenPositions = new ArrayList<>();\n List<String> brokenLines = breakLines(lineBrokenPositions);\n emitFormatted(brokenLines, lineBrokenPositions);\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal);\n }", "public T addFile(final String name, final List<String> path, final byte[] newHash, final boolean isDirectory) {\n return addFile(name, path, newHash, isDirectory, null);\n }", "public void writeNameValuePair(String name, Date value) throws IOException\n {\n internalWriteNameValuePair(name, m_format.format(value));\n }", "private void readResourceAssignments(Project gpProject)\n {\n Allocations allocations = gpProject.getAllocations();\n if (allocations != null)\n {\n for (Allocation allocation : allocations.getAllocation())\n {\n readResourceAssignment(allocation);\n }\n }\n }", "protected I_CmsFacetQueryItem parseFacetQueryItem(JSONObject item) {\n\n String query;\n try {\n query = item.getString(JSON_KEY_QUERY_FACET_QUERY_QUERY);\n } catch (JSONException e) {\n // TODO: Log\n return null;\n }\n String label = parseOptionalStringValue(item, JSON_KEY_QUERY_FACET_QUERY_LABEL);\n return new CmsFacetQueryItem(query, label);\n }", "@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new SingleInstanceWorkloadStrategy(job, name, arguments, endpointRegistry, execService));\n }\n }", "private void emitSuiteEnd(AggregatedSuiteResultEvent e, int suitesCompleted) throws IOException {\n assert showSuiteSummary;\n\n final StringBuilder b = new StringBuilder();\n final int totalErrors = this.totalErrors.addAndGet(e.isSuccessful() ? 0 : 1);\n b.append(String.format(Locale.ROOT, \"%sCompleted [%d/%d%s]%s in %.2fs, \",\n shortTimestamp(e.getStartTimestamp() + e.getExecutionTime()),\n suitesCompleted,\n totalSuites,\n totalErrors == 0 ? \"\" : \" (\" + totalErrors + \"!)\",\n e.getSlave().slaves > 1 ? \" on J\" + e.getSlave().id : \"\",\n e.getExecutionTime() / 1000.0d));\n b.append(e.getTests().size()).append(Pluralize.pluralize(e.getTests().size(), \" test\"));\n\n int failures = e.getFailureCount();\n if (failures > 0) {\n b.append(\", \").append(failures).append(Pluralize.pluralize(failures, \" failure\"));\n }\n\n int errors = e.getErrorCount();\n if (errors > 0) {\n b.append(\", \").append(errors).append(Pluralize.pluralize(errors, \" error\"));\n }\n\n int ignored = e.getIgnoredCount();\n if (ignored > 0) {\n b.append(\", \").append(ignored).append(\" skipped\");\n }\n\n if (!e.isSuccessful()) {\n b.append(FAILURE_STRING);\n }\n\n b.append(\"\\n\");\n logShort(b, false);\n }", "public float getPositionZ(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT);\n }" ]
Use this API to add sslaction resources.
[ "public static base_responses add(nitro_service client, sslaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslaction addresources[] = new sslaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].clientauth = resources[i].clientauth;\n\t\t\t\taddresources[i].clientcert = resources[i].clientcert;\n\t\t\t\taddresources[i].certheader = resources[i].certheader;\n\t\t\t\taddresources[i].clientcertserialnumber = resources[i].clientcertserialnumber;\n\t\t\t\taddresources[i].certserialheader = resources[i].certserialheader;\n\t\t\t\taddresources[i].clientcertsubject = resources[i].clientcertsubject;\n\t\t\t\taddresources[i].certsubjectheader = resources[i].certsubjectheader;\n\t\t\t\taddresources[i].clientcerthash = resources[i].clientcerthash;\n\t\t\t\taddresources[i].certhashheader = resources[i].certhashheader;\n\t\t\t\taddresources[i].clientcertissuer = resources[i].clientcertissuer;\n\t\t\t\taddresources[i].certissuerheader = resources[i].certissuerheader;\n\t\t\t\taddresources[i].sessionid = resources[i].sessionid;\n\t\t\t\taddresources[i].sessionidheader = resources[i].sessionidheader;\n\t\t\t\taddresources[i].cipher = resources[i].cipher;\n\t\t\t\taddresources[i].cipherheader = resources[i].cipherheader;\n\t\t\t\taddresources[i].clientcertnotbefore = resources[i].clientcertnotbefore;\n\t\t\t\taddresources[i].certnotbeforeheader = resources[i].certnotbeforeheader;\n\t\t\t\taddresources[i].clientcertnotafter = resources[i].clientcertnotafter;\n\t\t\t\taddresources[i].certnotafterheader = resources[i].certnotafterheader;\n\t\t\t\taddresources[i].owasupport = resources[i].owasupport;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "private void readHours(ProjectCalendar calendar, Day day, Integer hours)\n {\n int value = hours.intValue();\n int startHour = 0;\n ProjectCalendarHours calendarHours = null;\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n\n calendar.setWorkingDay(day, false);\n\n while (value != 0)\n {\n // Move forward until we find a working hour\n while (startHour < 24 && (value & 0x1) == 0)\n {\n value = value >> 1;\n ++startHour;\n }\n\n // No more working hours, bail out\n if (startHour >= 24)\n {\n break;\n }\n\n // Move forward until we find the end of the working hours\n int endHour = startHour;\n while (endHour < 24 && (value & 0x1) != 0)\n {\n value = value >> 1;\n ++endHour;\n }\n\n cal.set(Calendar.HOUR_OF_DAY, startHour);\n Date startDate = cal.getTime();\n cal.set(Calendar.HOUR_OF_DAY, endHour);\n Date endDate = cal.getTime();\n\n if (calendarHours == null)\n {\n calendarHours = calendar.addCalendarHours(day);\n calendar.setWorkingDay(day, true);\n }\n calendarHours.addRange(new DateRange(startDate, endDate));\n startHour = endHour;\n }\n \n DateHelper.pushCalendar(cal);\n }", "public void setConnection(JdbcConnectionDescriptor jcd) throws PlatformException\r\n {\r\n _jcd = jcd;\r\n\r\n String targetDatabase = (String)_dbmsToTorqueDb.get(_jcd.getDbms().toLowerCase());\r\n\r\n if (targetDatabase == null)\r\n {\r\n throw new PlatformException(\"Database \"+_jcd.getDbms()+\" is not supported by torque\");\r\n }\r\n if (!targetDatabase.equals(_targetDatabase))\r\n {\r\n _targetDatabase = targetDatabase;\r\n _creationScript = null;\r\n _initScripts.clear();\r\n }\r\n }", "protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) {\n lock.lock();\n try {\n // Check that we still allow registration\n // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses\n // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests\n // TODO WFCORE-845 consider using an IllegalStateException for this\n //assert ! shutdown;\n final Integer operationId;\n if(id == null) {\n // If we did not get an operationId, create a new one\n operationId = operationIdManager.createBatchId();\n } else {\n // Check that the operationId is not already taken\n if(! operationIdManager.lockBatchId(id)) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id);\n }\n operationId = id;\n }\n final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this);\n final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request);\n if(existing != null) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId);\n }\n ProtocolLogger.ROOT_LOGGER.tracef(\"Registered active operation %d\", operationId);\n activeCount++; // condition.signalAll();\n return request;\n } finally {\n lock.unlock();\n }\n }", "public static base_response export(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey exportresource = new sslfipskey();\n\t\texportresource.fipskeyname = resource.fipskeyname;\n\t\texportresource.key = resource.key;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}", "public static Transformers.ResourceIgnoredTransformationRegistry createServerIgnoredRegistry(final RequiredConfigurationHolder rc, final Transformers.ResourceIgnoredTransformationRegistry delegate) {\n return new Transformers.ResourceIgnoredTransformationRegistry() {\n @Override\n public boolean isResourceTransformationIgnored(PathAddress address) {\n final int length = address.size();\n if (length == 0) {\n return false;\n } else if (length >= 1) {\n if (delegate.isResourceTransformationIgnored(address)) {\n return true;\n }\n\n final PathElement element = address.getElement(0);\n final String type = element.getKey();\n switch (type) {\n case ModelDescriptionConstants.EXTENSION:\n // Don't ignore extensions for now\n return false;\n// if (local) {\n// return false; // Always include all local extensions\n// } else if (rc.getExtensions().contains(element.getValue())) {\n// return false;\n// }\n// break;\n case ModelDescriptionConstants.PROFILE:\n if (rc.getProfiles().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SERVER_GROUP:\n if (rc.getServerGroups().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SOCKET_BINDING_GROUP:\n if (rc.getSocketBindings().contains(element.getValue())) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n };\n }", "public void removeSource(GVRAudioSource audioSource)\n {\n synchronized (mAudioSources)\n {\n audioSource.setListener(null);\n mAudioSources.remove(audioSource);\n }\n }", "void setPaused(final boolean isPaused) {\n docLock.writeLock().lock();\n try {\n docsColl.updateOne(\n getDocFilter(namespace, documentId),\n new BsonDocument(\"$set\",\n new BsonDocument(\n ConfigCodec.Fields.IS_PAUSED,\n new BsonBoolean(isPaused))));\n this.isPaused = isPaused;\n } catch (IllegalStateException e) {\n // eat this\n } finally {\n docLock.writeLock().unlock();\n }\n }", "public static authenticationvserver_stats[] get(nitro_service service) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tauthenticationvserver_stats[] response = (authenticationvserver_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public void deleteShovel(String vhost, String shovelname) {\n\t this.deleteIgnoring404(uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(shovelname)));\n }" ]
Use this API to update vpnclientlessaccesspolicy.
[ "public static base_response update(nitro_service client, vpnclientlessaccesspolicy resource) throws Exception {\n\t\tvpnclientlessaccesspolicy updateresource = new vpnclientlessaccesspolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.profilename = resource.profilename;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
[ "public static Date getYearlyAbsoluteAsDate(RecurringData data)\n {\n Date result;\n Integer yearlyAbsoluteDay = data.getDayNumber();\n Integer yearlyAbsoluteMonth = data.getMonthNumber();\n Date startDate = data.getStartDate();\n\n if (yearlyAbsoluteDay == null || yearlyAbsoluteMonth == null || startDate == null)\n {\n result = null;\n }\n else\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n cal.set(Calendar.MONTH, yearlyAbsoluteMonth.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, yearlyAbsoluteDay.intValue());\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }", "public Map<BsonValue, ChangeEvent<BsonDocument>> getEventsForNamespace(\n final MongoNamespace namespace\n ) {\n this.instanceLock.readLock().lock();\n final NamespaceChangeStreamListener streamer;\n try {\n streamer = nsStreamers.get(namespace);\n } finally {\n this.instanceLock.readLock().unlock();\n }\n if (streamer == null) {\n return new HashMap<>();\n }\n return streamer.getEvents();\n }", "public void beforeClose(PBStateEvent event)\r\n {\r\n /*\r\n arminw:\r\n this is a workaround for use in managed environments. When a PB instance is used\r\n within a container a PB.close call is done when leave the container method. This close\r\n the PB handle (but the real instance is still in use) and the PB listener are notified.\r\n But the JTA tx was not committed at\r\n this point in time and the session cache should not be cleared, because the updated/new\r\n objects will be pushed to the real cache on commit call (if we clear, nothing to push).\r\n So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle\r\n is closed), if true we don't reset the session cache.\r\n */\r\n if(!broker.isInTransaction())\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clearing the session cache\");\r\n resetSessionCache();\r\n }\r\n }", "public String calculateLabelUnit(final CoordinateReferenceSystem mapCrs) {\n String unit;\n if (this.labelProjection != null) {\n unit = this.labelCRS.getCoordinateSystem().getAxis(0).getUnit().toString();\n } else {\n unit = mapCrs.getCoordinateSystem().getAxis(0).getUnit().toString();\n }\n\n return unit;\n }", "public synchronized void stopDebugServer() {\n if (mDebugServer == null) {\n Log.e(TAG, \"Debug server is not running.\");\n return;\n }\n\n mDebugServer.shutdown();\n mDebugServer = null;\n }", "public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent,\n boolean logMessageContentOverride) {\n\n /*\n * If controlling of logging behavior is not allowed externally\n * then log according to global property value\n */\n if (!logMessageContentOverride) {\n return logMessageContent;\n }\n\n Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME);\n\n if (null == logMessageContentExtObj) {\n\n return logMessageContent;\n\n } else if (logMessageContentExtObj instanceof Boolean) {\n\n return ((Boolean) logMessageContentExtObj).booleanValue();\n\n } else if (logMessageContentExtObj instanceof String) {\n\n String logMessageContentExtVal = (String) logMessageContentExtObj;\n\n if (logMessageContentExtVal.equalsIgnoreCase(\"true\")) {\n\n return true;\n\n } else if (logMessageContentExtVal.equalsIgnoreCase(\"false\")) {\n\n return false;\n\n } else {\n\n return logMessageContent;\n }\n } else {\n\n return logMessageContent;\n }\n }", "public static List<String> getValueList(List<String> valuePairs, String delim) {\n List<String> valueList = Lists.newArrayList();\n for(String valuePair: valuePairs) {\n String[] value = valuePair.split(delim, 2);\n if(value.length != 2)\n throw new VoldemortException(\"Invalid argument pair: \" + valuePair);\n valueList.add(value[0]);\n valueList.add(value[1]);\n }\n return valueList;\n }", "public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\n }", "protected void addPropertiesStart(String type) {\n putProperty(PropertyKey.Host.name(), IpUtils.getHostName());\n putProperty(PropertyKey.Type.name(), type);\n putProperty(PropertyKey.Status.name(), Status.Start.name());\n }" ]
This method attempts to locate a suitable directory by checking a number of different configuration sources. 1 - serverConfigUserDirPropertyName - This value is used to check it a matching system property has been set. 2 - suppliedConfigDir - If a path was specified on the command line it is expected to be passed in as this parameter. 3 - serverConfigDirPropertyName - This is a second system property to check. And finally if none of these match defaultBaseDir specifies the configuration being searched and is appended to the JBoss Home value discovered when the utility started.
[ "private File buildDirPath(final String serverConfigUserDirPropertyName, final String suppliedConfigDir,\n final String serverConfigDirPropertyName, final String serverBaseDirPropertyName, final String defaultBaseDir) {\n String propertyDir = System.getProperty(serverConfigUserDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n if (suppliedConfigDir != null) {\n return new File(suppliedConfigDir);\n }\n propertyDir = System.getProperty(serverConfigDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n\n propertyDir = System.getProperty(serverBaseDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n\n return new File(new File(stateValues.getOptions().getJBossHome(), defaultBaseDir), \"configuration\");\n }" ]
[ "public ItemRequest<Team> addUser(String team) {\n \n String path = String.format(\"/teams/%s/addUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }", "public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }", "public float getNormalX(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }", "public void setModel(Database databaseModel, DescriptorRepository objModel)\r\n {\r\n _dbModel = databaseModel;\r\n _preparedModel = new PreparedModel(objModel, databaseModel);\r\n }", "public List<TableProperty> getEditableColumns(CmsMessageBundleEditorTypes.EditMode mode) {\n\n return m_editorState.get(mode).getEditableColumns();\n }", "private int tryAcquireExclusiveTransaction(@NotNull final Thread thread, final int timeout) {\n long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);\n try (CriticalSection ignored = criticalSection.enter()) {\n if (getThreadPermits(thread) > 0) {\n throw new ExodusException(\"Exclusive transaction can't be nested\");\n }\n final Condition condition = criticalSection.newCondition();\n final long currentOrder = acquireOrder++;\n regularQueue.put(currentOrder, condition);\n while (acquiredPermits > 0 || regularQueue.firstKey() != currentOrder) {\n try {\n nanos = condition.awaitNanos(nanos);\n if (nanos < 0) {\n break;\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n break;\n }\n }\n if (acquiredPermits == 0 && regularQueue.firstKey() == currentOrder) {\n regularQueue.pollFirstEntry();\n acquiredPermits = availablePermits;\n threadPermits.put(thread, availablePermits);\n return availablePermits;\n }\n regularQueue.remove(currentOrder);\n notifyNextWaiters();\n }\n return 0;\n }", "public QueryBuilder useIndex(String designDocument, String indexName) {\n useIndex = new String[]{designDocument, indexName};\n return this;\n }", "public void initialize(FragmentManager fragmentManager) {\n AirMapInterface mapInterface = (AirMapInterface)\n fragmentManager.findFragmentById(R.id.map_frame);\n\n if (mapInterface != null) {\n initialize(fragmentManager, mapInterface);\n } else {\n initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build());\n }\n }", "public List<CmsCategory> getTopItems() {\n\n List<CmsCategory> categories = new ArrayList<CmsCategory>();\n String matcher = Pattern.quote(m_mainCategoryPath) + \"[^/]*/\";\n for (CmsCategory category : m_categories) {\n if (category.getPath().matches(matcher)) {\n categories.add(category);\n }\n }\n return categories;\n }" ]