query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Add a variable to the scripting context. @param varName The variable name. @param value The variable value.
[ "@Override\n public void addVariable(String varName, Object value) {\n synchronized (mGlobalVariables) {\n mGlobalVariables.put(varName, value);\n }\n refreshGlobalBindings();\n }" ]
[ "public static Cluster\n balanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster,\n final int maxContiguousPartitionsPerZone) {\n System.out.println(\"Balance number of contiguous partitions within a zone.\");\n System.out.println(\"numPartitionsPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \"\n + nextCandidateCluster.getNumberOfPartitionsInZone(zoneId));\n }\n System.out.println(\"numNodesPerZone\");\n for(int zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(zoneId + \" : \" + nextCandidateCluster.getNumberOfNodesInZone(zoneId));\n }\n\n // Break up contiguous partitions within each zone\n HashMap<Integer, List<Integer>> partitionsToRemoveFromZone = Maps.newHashMap();\n System.out.println(\"Contiguous partitions\");\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n System.out.println(\"\\tZone: \" + zoneId);\n Map<Integer, Integer> partitionToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(nextCandidateCluster,\n zoneId);\n\n List<Integer> partitionsToRemoveFromThisZone = new ArrayList<Integer>();\n for(Map.Entry<Integer, Integer> entry: partitionToRunLength.entrySet()) {\n if(entry.getValue() > maxContiguousPartitionsPerZone) {\n List<Integer> contiguousPartitions = new ArrayList<Integer>(entry.getValue());\n for(int partitionId = entry.getKey(); partitionId < entry.getKey()\n + entry.getValue(); partitionId++) {\n contiguousPartitions.add(partitionId\n % nextCandidateCluster.getNumberOfPartitions());\n }\n System.out.println(\"Contiguous partitions: \" + contiguousPartitions);\n partitionsToRemoveFromThisZone.addAll(Utils.removeItemsToSplitListEvenly(contiguousPartitions,\n maxContiguousPartitionsPerZone));\n }\n }\n\n partitionsToRemoveFromZone.put(zoneId, partitionsToRemoveFromThisZone);\n System.out.println(\"\\t\\tPartitions to remove: \" + partitionsToRemoveFromThisZone);\n }\n\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n\n Random r = new Random();\n for(int zoneId: returnCluster.getZoneIds()) {\n for(int partitionId: partitionsToRemoveFromZone.get(zoneId)) {\n // Pick a random other zone Id\n List<Integer> otherZoneIds = new ArrayList<Integer>();\n for(int otherZoneId: returnCluster.getZoneIds()) {\n if(otherZoneId != zoneId) {\n otherZoneIds.add(otherZoneId);\n }\n }\n int whichOtherZoneId = otherZoneIds.get(r.nextInt(otherZoneIds.size()));\n\n // Pick a random node from other zone ID\n int whichNodeOffset = r.nextInt(returnCluster.getNumberOfNodesInZone(whichOtherZoneId));\n int whichNodeId = new ArrayList<Integer>(returnCluster.getNodeIdsInZone(whichOtherZoneId)).get(whichNodeOffset);\n\n // Steal partition from one zone to another!\n returnCluster = UpdateClusterUtils.createUpdatedCluster(returnCluster,\n whichNodeId,\n Lists.newArrayList(partitionId));\n }\n }\n\n return returnCluster;\n\n }", "protected StrongCounter getCounterOrCreateIt(String counterName, int initialValue) {\n\t\tCounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager );\n\t\tif ( !counterManager.isDefined( counterName ) ) {\n\t\t\tLOG.tracef( \"Counter %s is not defined, creating it\", counterName );\n\n\t\t\t// global configuration is mandatory in order to define\n\t\t\t// a new clustered counter with persistent storage\n\t\t\tvalidateGlobalConfiguration();\n\n\t\t\tcounterManager.defineCounter( counterName,\n\t\t\t\tCounterConfiguration.builder(\n\t\t\t\t\tCounterType.UNBOUNDED_STRONG )\n\t\t\t\t\t\t.initialValue( initialValue )\n\t\t\t\t\t\t.storage( Storage.PERSISTENT )\n\t\t\t\t\t\t.build() );\n\t\t}\n\n\t\tStrongCounter strongCounter = counterManager.getStrongCounter( counterName );\n\t\treturn strongCounter;\n\t}", "private static float angleDeg(final float ax, final float ay,\n final float bx, final float by) {\n final double angleRad = Math.atan2(ay - by, ax - bx);\n double angle = Math.toDegrees(angleRad);\n if (angleRad < 0) {\n angle += 360;\n }\n return (float) angle;\n }", "Map<String, String> packageNameMap() {\n if (packageNames == null) {\n return emptyMap();\n }\n\n Map<String, String> names = new LinkedHashMap<String, String>();\n for (PackageName name : packageNames) {\n names.put(name.getUri(), name.getPackage());\n }\n return names;\n }", "public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) {\n Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year);\n return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0));\n }", "public static void validate(final License license) {\n // A license should have a name\n if(license.getName() == null ||\n license.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License name should not be empty!\")\n .build());\n }\n\n // A license should have a long name\n if(license.getLongName() == null ||\n license.getLongName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License long name should not be empty!\")\n .build());\n }\n\n // If there is a regexp, it should compile\n if(license.getRegexp() != null &&\n !license.getRegexp().isEmpty()){\n try{\n Pattern.compile(license.getRegexp());\n }\n catch (PatternSyntaxException e){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n Pattern regex = Pattern.compile(\"[&%//]\");\n if(regex.matcher(license.getRegexp()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"License regexp does not compile!\").build());\n }\n\n }\n }", "public void removeControl(String name) {\n Widget control = findChildByName(name);\n if (control != null) {\n removeChild(control);\n if (mBgResId != -1) {\n updateMesh();\n }\n }\n }", "@Deprecated\n public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {\n this.threadIdleMs = unit.toMillis(threadIdleTime);\n return this;\n }" ]
Returns a reasonable timeout duration for a watch request. @param expectedTimeoutMillis timeout duration that a user wants to use, in milliseconds @param bufferMillis buffer duration which needs to be added, in milliseconds @return timeout duration in milliseconds, between the specified {@code bufferMillis} and the {@link #MAX_MILLIS}.
[ "public static long makeReasonable(long expectedTimeoutMillis, long bufferMillis) {\n checkArgument(expectedTimeoutMillis > 0,\n \"expectedTimeoutMillis: %s (expected: > 0)\", expectedTimeoutMillis);\n checkArgument(bufferMillis >= 0,\n \"bufferMillis: %s (expected: > 0)\", bufferMillis);\n\n final long timeout = Math.min(expectedTimeoutMillis, MAX_MILLIS);\n if (bufferMillis == 0) {\n return timeout;\n }\n\n if (timeout > MAX_MILLIS - bufferMillis) {\n return MAX_MILLIS;\n } else {\n return bufferMillis + timeout;\n }\n }" ]
[ "public static Command newInsertElements(Collection objects, String outIdentifier, boolean returnObject, String entryPoint) {\n return getCommandFactoryProvider().newInsertElements( objects, outIdentifier, returnObject, entryPoint );\n }", "public List<DbModule> getAncestors(final String gavc, final FiltersHolder filters) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n return repositoryHandler.getAncestors(dbArtifact, filters);\n }", "protected void addFacetPart(CmsSolrQuery query) {\n\n StringBuffer value = new StringBuffer();\n value.append(\"{!key=\").append(m_config.getName());\n addFacetOptions(value);\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n value.append(\" ex=\").append(m_config.getIgnoreTags());\n }\n value.append(\"}\");\n value.append(m_config.getRange());\n query.add(\"facet.range\", value.toString());\n }", "public RedwoodConfiguration rootHandler(final LogRecordHandler handler){\r\n tasks.add(new Runnable(){ public void run(){ Redwood.appendHandler(handler); } });\r\n Redwood.appendHandler(handler);\r\n return this;\r\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 }", "private void clearMetadata(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverTrackMetadataUpdate(player, null); // Inform listeners the metadata is gone.\n }\n }\n }\n }", "public FormAction setValuesInForm(Form form) {\r\n\t\tFormAction formAction = new FormAction();\r\n\t\tform.setFormAction(formAction);\r\n\t\tthis.forms.add(form);\r\n\t\treturn formAction;\r\n\t}", "private void handleApplicationUpdateRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Update Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\t\n\t\tlogger.trace(\"Application Update Request from Node \" + nodeId);\n\t\tUpdateState updateState = UpdateState.getUpdateState(incomingMessage.getMessagePayloadByte(0));\n\t\t\n\t\tswitch (updateState) {\n\t\t\tcase NODE_INFO_RECEIVED:\n\t\t\t\tlogger.debug(\"Application update request, node information received.\");\t\t\t\n\t\t\t\tint length = incomingMessage.getMessagePayloadByte(2);\n\t\t\t\tZWaveNode node = getNode(nodeId);\n\t\t\t\t\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\tfor (int i = 6; i < length + 3; i++) {\n\t\t\t\t\tint data = incomingMessage.getMessagePayloadByte(i);\n\t\t\t\t\tif(data == 0xef ) {\n\t\t\t\t\t\t// TODO: Implement control command classes\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.debug(String.format(\"Adding command class 0x%02X to the list of supported command classes.\", data));\n\t\t\t\t\tZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(data, node, this);\n\t\t\t\t\tif (commandClass != null)\n\t\t\t\t\t\tnode.addCommandClass(commandClass);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// advance node stage.\n\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t\n\t\t\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase NODE_INFO_REQ_FAILED:\n\t\t\t\tlogger.debug(\"Application update request, Node Info Request Failed, re-request node info.\");\n\t\t\t\t\n\t\t\t\tSerialMessage requestInfoMessage = this.lastSentMessage;\n\t\t\t\t\n\t\t\t\tif (requestInfoMessage.getMessageClass() != SerialMessage.SerialMessageClass.RequestNodeInfo) {\n\t\t\t\t\tlogger.warn(\"Got application update request without node info request, ignoring.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\tif (--requestInfoMessage.attempts >= 0) {\n\t\t\t\t\tlogger.error(\"Got Node Info Request Failed while sending this serial message. Requeueing\");\n\t\t\t\t\tthis.enqueue(requestInfoMessage);\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tlogger.warn(\"Node Info Request Failed 3x. Discarding message: {}\", lastSentMessage.toString());\n\t\t\t\t}\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(String.format(\"TODO: Implement Application Update Request Handling of %s (0x%02X).\", updateState.getLabel(), updateState.getKey()));\n\t\t}\n\t}", "public static void Forward(double[][] data) {\n int rows = data.length;\n int cols = data[0].length;\n\n double[] row = new double[cols];\n double[] col = new double[rows];\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < row.length; j++)\n row[j] = data[i][j];\n\n Forward(row);\n\n for (int j = 0; j < row.length; j++)\n data[i][j] = row[j];\n }\n\n for (int j = 0; j < cols; j++) {\n for (int i = 0; i < col.length; i++)\n col[i] = data[i][j];\n\n Forward(col);\n\n for (int i = 0; i < col.length; i++)\n data[i][j] = col[i];\n }\n }" ]
Creates an operations that targets this handler. @param operationToValidate the operation that this handler will validate @return the validation operation
[ "static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(ModelDescriptionConstants.OP_ADDR));\n PathAddress realmPA = null;\n for (int i = pa.size() - 1; i > 0; i--) {\n PathElement pe = pa.getElement(i);\n if (SECURITY_REALM.equals(pe.getKey())) {\n realmPA = pa.subAddress(0, i + 1);\n break;\n }\n }\n assert realmPA != null : \"operationToValidate did not have an address that included a \" + SECURITY_REALM;\n return Util.getEmptyOperation(\"validate-authentication\", realmPA.toModelNode());\n }" ]
[ "public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(Object parent, FID id) throws SQLException {\n\t\t// this can happen if we have a foreign-auto-refresh scenario\n\t\tif (foreignFieldType == null) {\n\t\t\treturn null;\n\t\t}\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tif (!fieldConfig.isForeignCollectionEager()) {\n\t\t\t// we know this won't go recursive so no need for the counters\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\n\t\t// try not to create level counter objects unless we have to\n\t\tLevelCounters levelCounters = threadLevelCounters.get();\n\t\tif (levelCounters == null) {\n\t\t\tif (fieldConfig.getForeignCollectionMaxEagerLevel() == 0) {\n\t\t\t\t// then return a lazy collection instead\n\t\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(),\n\t\t\t\t\t\tfieldConfig.isForeignCollectionOrderAscending());\n\t\t\t}\n\t\t\tlevelCounters = new LevelCounters();\n\t\t\tthreadLevelCounters.set(levelCounters);\n\t\t}\n\n\t\tif (levelCounters.foreignCollectionLevel == 0) {\n\t\t\tlevelCounters.foreignCollectionLevelMax = fieldConfig.getForeignCollectionMaxEagerLevel();\n\t\t}\n\t\t// are we over our level limit?\n\t\tif (levelCounters.foreignCollectionLevel >= levelCounters.foreignCollectionLevelMax) {\n\t\t\t// then return a lazy collection instead\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\t\tlevelCounters.foreignCollectionLevel++;\n\t\ttry {\n\t\t\treturn new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t} finally {\n\t\t\tlevelCounters.foreignCollectionLevel--;\n\t\t}\n\t}", "public static DMatrixRMaj wrap(int numRows , int numCols , double []data ) {\n DMatrixRMaj s = new DMatrixRMaj();\n s.data = data;\n s.numRows = numRows;\n s.numCols = numCols;\n\n return s;\n }", "private void printClassRecord(PrintStream out, ClassRecord classRecord,\n\t\t\tEntityIdValue entityIdValue) {\n\t\tprintTerms(out, classRecord.itemDocument, entityIdValue, \"\\\"\"\n\t\t\t\t+ getClassLabel(entityIdValue) + \"\\\"\");\n\t\tprintImage(out, classRecord.itemDocument);\n\n\t\tout.print(\",\" + classRecord.itemCount + \",\" + classRecord.subclassCount);\n\n\t\tprintClassList(out, classRecord.superClasses);\n\n\t\tHashSet<EntityIdValue> superClasses = new HashSet<>();\n\t\tfor (EntityIdValue superClass : classRecord.superClasses) {\n\t\t\taddSuperClasses(superClass, superClasses);\n\t\t}\n\n\t\tprintClassList(out, superClasses);\n\n\t\tprintRelatedProperties(out, classRecord);\n\n\t\tout.println(\"\");\n\t}", "private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}", "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\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 Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }", "public Collection<Group> getPublicGroups(String userId) throws FlickrException {\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_GROUPS);\r\n\r\n parameters.put(\"user_id\", userId);\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 groupsElement = response.getPayload();\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"nsid\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setEighteenPlus(groupElement.getAttribute(\"eighteenplus\").equals(\"0\") ? false : true);\r\n groups.add(group);\r\n }\r\n return groups;\r\n }", "public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }" ]
Read the top level tasks from GanttProject. @param gpProject GanttProject project
[ "private void readTasks(Project gpProject)\n {\n Tasks tasks = gpProject.getTasks();\n readTaskCustomPropertyDefinitions(tasks);\n for (net.sf.mpxj.ganttproject.schema.Task task : tasks.getTask())\n {\n readTask(m_projectFile, task);\n }\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public static <E> E getObject(String className) {\n if (className == null) {\n return (E) null;\n }\n try {\n return (E) Class.forName(className).newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(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}", "private Boolean readOptionalBoolean(JSONValue val) {\n\n JSONBoolean b = null == val ? null : val.isBoolean();\n if (b != null) {\n return Boolean.valueOf(b.booleanValue());\n }\n return null;\n }", "public void setModelByInputFileStream(InputStream inputFileStream) {\r\n try {\r\n this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\n }", "protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }", "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 }", "private void tryRefreshAccessToken(final Long reqStartedAt) {\n authLock.writeLock().lock();\n try {\n if (!isLoggedIn()) {\n throw new StitchClientException(StitchClientErrorCode.LOGGED_OUT_DURING_REQUEST);\n }\n\n try {\n final Jwt jwt = Jwt.fromEncoded(getAuthInfo().getAccessToken());\n if (jwt.getIssuedAt() >= reqStartedAt) {\n return;\n }\n } catch (final IOException e) {\n // Swallow\n }\n\n // retry\n refreshAccessToken();\n } finally {\n authLock.writeLock().unlock();\n }\n }", "public static void main(String[] args) {\r\n TreebankLanguagePack tlp = new PennTreebankLanguagePack();\r\n System.out.println(\"Start symbol: \" + tlp.startSymbol());\r\n String start = tlp.startSymbol();\r\n System.out.println(\"Should be true: \" + (tlp.isStartSymbol(start)));\r\n String[] strs = {\"-\", \"-LLB-\", \"NP-2\", \"NP=3\", \"NP-LGS\", \"NP-TMP=3\"};\r\n for (String str : strs) {\r\n System.out.println(\"String: \" + str + \" basic: \" + tlp.basicCategory(str) + \" basicAndFunc: \" + tlp.categoryAndFunction(str));\r\n }\r\n }", "private void initUpperLeftComponent() {\n\n m_upperLeftComponent = new HorizontalLayout();\n m_upperLeftComponent.setHeight(\"100%\");\n m_upperLeftComponent.setSpacing(true);\n m_upperLeftComponent.setDefaultComponentAlignment(Alignment.MIDDLE_RIGHT);\n m_upperLeftComponent.addComponent(m_languageSwitch);\n m_upperLeftComponent.addComponent(m_filePathLabel);\n\n }" ]
Use this API to fetch a filterglobal_filterpolicy_binding resources.
[ "public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static int[] insertArray(int[] original, int index, int[] inserted) {\n int[] modified = new int[original.length + inserted.length];\n System.arraycopy(original, 0, modified, 0, index);\n System.arraycopy(inserted, 0, modified, index, inserted.length);\n System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);\n return modified;\n }", "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 }", "public static String blur(int radius, int sigma) {\n if (radius < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radius > 150) {\n throw new IllegalArgumentException(\"Radius must be lower or equal than 150.\");\n }\n if (sigma < 0) {\n throw new IllegalArgumentException(\"Sigma must be greater than zero.\");\n }\n return FILTER_BLUR + \"(\" + radius + \",\" + sigma + \")\";\n }", "private void stopDone() {\n synchronized (stopLock) {\n final StopContext stopContext = this.stopContext;\n this.stopContext = null;\n if (stopContext != null) {\n stopContext.complete();\n }\n stopLock.notifyAll();\n }\n }", "public static String toSafeFileName(String name) {\n int size = name.length();\n StringBuilder builder = new StringBuilder(size * 2);\n for (int i = 0; i < size; i++) {\n char c = name.charAt(i);\n boolean valid = c >= 'a' && c <= 'z';\n valid = valid || (c >= 'A' && c <= 'Z');\n valid = valid || (c >= '0' && c <= '9');\n valid = valid || (c == '_') || (c == '-') || (c == '.');\n\n if (valid) {\n builder.append(c);\n } else {\n // Encode the character using hex notation\n builder.append('x');\n builder.append(Integer.toHexString(i));\n }\n }\n return builder.toString();\n }", "public static<Z> Function0<Z> lift(Func0<Z> f) {\n\treturn bridge.lift(f);\n }", "public Diff compare(String left, String right) {\n\t\treturn compare(getCtType(left), getCtType(right));\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 Map<String, Automaton> createAutomatonMap(String prefix,\n List<String> valueList, Boolean filter) {\n HashMap<String, Automaton> automatonMap = new HashMap<>();\n if (valueList != null) {\n for (String item : valueList) {\n if (filter) {\n item = item.replaceAll(\"([\\\\\\\"\\\\)\\\\(\\\\<\\\\>\\\\.\\\\@\\\\#\\\\]\\\\[\\\\{\\\\}])\",\n \"\\\\\\\\$1\");\n }\n automatonMap.put(item,\n new RegExp(prefix + MtasToken.DELIMITER + item + \"\\u0000*\")\n .toAutomaton());\n }\n }\n return automatonMap;\n }" ]
Read the projects from a ConceptDraw PROJECT file as top level tasks. @param cdp ConceptDraw PROJECT file
[ "private void readTasks(Document cdp)\n {\n //\n // Sort the projects into the correct order\n //\n List<Project> projects = new ArrayList<Project>(cdp.getProjects().getProject());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(projects, new Comparator<Project>()\n {\n @Override public int compare(Project o1, Project o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n for (Project project : cdp.getProjects().getProject())\n {\n readProject(project);\n }\n }" ]
[ "public static base_responses unset(nitro_service client, String trapname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm unsetresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tunsetresources[i] = new snmpalarm();\n\t\t\t\tunsetresources[i].trapname = trapname[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "private void init_jdbcTypes() throws SQLException\r\n {\r\n ReportQuery q = (ReportQuery) getQueryObject().getQuery();\r\n m_jdbcTypes = new int[m_attributeCount];\r\n \r\n // try to get jdbcTypes from Query\r\n if (q.getJdbcTypes() != null)\r\n {\r\n m_jdbcTypes = q.getJdbcTypes();\r\n }\r\n else\r\n {\r\n ResultSetMetaData rsMetaData = getRsAndStmt().m_rs.getMetaData();\r\n for (int i = 0; i < m_attributeCount; i++)\r\n {\r\n m_jdbcTypes[i] = rsMetaData.getColumnType(i + 1);\r\n }\r\n \r\n }\r\n }", "private static void listTaskNotes(ProjectFile file)\n {\n for (Task task : file.getTasks())\n {\n String notes = task.getNotes();\n\n if (notes.length() != 0)\n {\n System.out.println(\"Notes for \" + task.getName() + \": \" + notes);\n }\n }\n\n System.out.println();\n }", "public static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {\n StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);\n for (String kp : keyPrefix) {\n prefix.append('.').append(kp);\n }\n return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, LoggingExtension.class.getClassLoader(), true, false) {\n @Override\n public String getOperationParameterDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDescription(operationName, paramName, locale, bundle);\n }\n\n @Override\n public String getOperationParameterValueTypeDescription(final String operationName, final String paramName, final Locale locale,\n final ResourceBundle bundle, final String... suffixes) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterValueTypeDescription(operationName, paramName, locale, bundle, suffixes);\n }\n\n @Override\n public String getOperationParameterDeprecatedDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDeprecatedDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDeprecatedDescription(operationName, paramName, locale, bundle);\n }\n };\n }", "public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable,\n final Collection<ControlFlowBlock> controlFlowBlocks) {\n return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks));\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 boolean startsWith(Bytes prefix) {\n Objects.requireNonNull(prefix, \"startWith(Bytes prefix) cannot have null parameter\");\n\n if (prefix.length > this.length) {\n return false;\n } else {\n int end = this.offset + prefix.length;\n for (int i = this.offset, j = prefix.offset; i < end; i++, j++) {\n if (this.data[i] != prefix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }", "private void populateDefaultData(FieldItem[] defaultData)\n {\n for (FieldItem item : defaultData)\n {\n m_map.put(item.getType(), item);\n }\n }", "@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\tthis.attributes = (Map) attributes;\n\t}" ]
Convert an integer value into a TimeUnit instance. @param value time unit value @return TimeUnit instance
[ "public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }" ]
[ "public static String generateQuery(final String key, final Object value) {\n\t\tfinal Map<String, Object> params = new HashMap<>();\n\t\tparams.put(key, value);\n\t\treturn generateQuery(params);\n\t}", "public static DMatrixRMaj[] span(int dimen, int numVectors , Random rand ) {\n if( dimen < numVectors )\n throw new IllegalArgumentException(\"The number of vectors must be less than or equal to the dimension\");\n\n DMatrixRMaj u[] = new DMatrixRMaj[numVectors];\n\n u[0] = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);\n NormOps_DDRM.normalizeF(u[0]);\n\n for( int i = 1; i < numVectors; i++ ) {\n// System.out.println(\" i = \"+i);\n DMatrixRMaj a = new DMatrixRMaj(dimen,1);\n DMatrixRMaj r=null;\n\n for( int j = 0; j < i; j++ ) {\n// System.out.println(\"j = \"+j);\n if( j == 0 )\n r = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);\n\n // find a vector that is normal to vector j\n // u[i] = (1/2)*(r + Q[j]*r)\n a.set(r);\n VectorVectorMult_DDRM.householder(-2.0,u[j],r,a);\n CommonOps_DDRM.add(r,a,a);\n CommonOps_DDRM.scale(0.5,a);\n\n// UtilEjml.print(a);\n\n DMatrixRMaj t = a;\n a = r;\n r = t;\n\n // normalize it so it doesn't get too small\n double val = NormOps_DDRM.normF(r);\n if( val == 0 || Double.isNaN(val) || Double.isInfinite(val))\n throw new RuntimeException(\"Failed sanity check\");\n CommonOps_DDRM.divide(r,val);\n }\n\n u[i] = r;\n }\n\n return u;\n }", "protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tboolean tryAgain = false;\r\n\t\tConnection result = null;\r\n\t\tConnection oldRawConnection = connectionHandle.getInternalConnection();\r\n\t\tString url = this.getConfig().getJdbcUrl();\r\n\t\t\r\n\t\tint acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts();\r\n\t\tlong acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs();\r\n\t\tAcquireFailConfig acquireConfig = new AcquireFailConfig();\r\n\t\tacquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));\r\n\t\tacquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs);\r\n\t\tacquireConfig.setLogMessage(\"Failed to acquire connection to \"+url);\r\n\t\tConnectionHook connectionHook = this.getConfig().getConnectionHook();\r\n\t\tdo{ \r\n\t\t\tresult = null;\r\n\t\t\ttry { \r\n\t\t\t\t// keep track of this hook.\r\n\t\t\t\tresult = this.obtainRawInternalConnection();\r\n\t\t\t\ttryAgain = false;\r\n\r\n\t\t\t\tif (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){\r\n\t\t\t\t\tlogger.info(\"Successfully re-established connection to \"+url);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tthis.getDbIsDown().set(false);\r\n\t\t\t\t\r\n\t\t\t\tconnectionHandle.setInternalConnection(result);\r\n\t\t\t\t\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\tconnectionHook.onAcquire(connectionHandle);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t\tConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL());\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\ttryAgain = connectionHook.onAcquireFail(e, acquireConfig);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlogger.error(String.format(\"Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d\", url, acquireRetryDelayInMs, acquireRetryAttempts), e);\r\n\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (acquireRetryAttempts > 0){\r\n\t\t\t\t\t\t\tThread.sleep(acquireRetryDelayInMs);\r\n\t \t\t\t\t\t}\r\n\t\t\t\t\t\ttryAgain = (acquireRetryAttempts--) > 0;\r\n\t\t\t\t\t} catch (InterruptedException e1) {\r\n\t\t\t\t\t\ttryAgain=false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (!tryAgain){\r\n\t\t\t\t\tif (oldRawConnection != null) {\r\n\t\t\t\t\t\toldRawConnection.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (result != null) {\r\n\t\t\t\t\t\tresult.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconnectionHandle.setInternalConnection(oldRawConnection);\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} while (tryAgain);\r\n\r\n\t\treturn result;\r\n\r\n\t}", "private void validateSegments(List<LogSegment> segments) {\n synchronized (lock) {\n for (int i = 0; i < segments.size() - 1; i++) {\n LogSegment curr = segments.get(i);\n LogSegment next = segments.get(i + 1);\n if (curr.start() + curr.size() != next.start()) {\n throw new IllegalStateException(\"The following segments don't validate: \" + curr.getFile()\n .getAbsolutePath() + \", \" + next.getFile().getAbsolutePath());\n }\n }\n }\n }", "private static void setupFlowId(SoapMessage message) {\n String flowId = FlowIdHelper.getFlowId(message);\n\n if (flowId == null) {\n flowId = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n flowId = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n Exchange ex = message.getExchange();\n if (null!=ex){\n Message reqMsg = ex.getOutMessage();\n if ( null != reqMsg) {\n flowId = FlowIdHelper.getFlowId(reqMsg);\n }\n }\n }\n\n if (flowId != null && !flowId.isEmpty()) {\n FlowIdHelper.setFlowId(message, flowId);\n }\n }", "public static void paintCheckedBackground(Component c, Graphics g, int x, int y, int width, int height) {\n\t\tif ( backgroundImage == null ) {\n\t\t\tbackgroundImage = new BufferedImage( 64, 64, BufferedImage.TYPE_INT_ARGB );\n\t\t\tGraphics bg = backgroundImage.createGraphics();\n\t\t\tfor ( int by = 0; by < 64; by += 8 ) {\n\t\t\t\tfor ( int bx = 0; bx < 64; bx += 8 ) {\n\t\t\t\t\tbg.setColor( ((bx^by) & 8) != 0 ? Color.lightGray : Color.white );\n\t\t\t\t\tbg.fillRect( bx, by, 8, 8 );\n\t\t\t\t}\n\t\t\t}\n\t\t\tbg.dispose();\n\t\t}\n\n\t\tif ( backgroundImage != null ) {\n\t\t\tShape saveClip = g.getClip();\n\t\t\tRectangle r = g.getClipBounds();\n\t\t\tif (r == null)\n\t\t\t\tr = new Rectangle(c.getSize());\n\t\t\tr = r.intersection(new Rectangle(x, y, width, height));\n\t\t\tg.setClip(r);\n\t\t\tint w = backgroundImage.getWidth();\n\t\t\tint h = backgroundImage.getHeight();\n\t\t\tif (w != -1 && h != -1) {\n\t\t\t\tint x1 = (r.x / w) * w;\n\t\t\t\tint y1 = (r.y / h) * h;\n\t\t\t\tint x2 = ((r.x + r.width + w - 1) / w) * w;\n\t\t\t\tint y2 = ((r.y + r.height + h - 1) / h) * h;\n\t\t\t\tfor (y = y1; y < y2; y += h)\n\t\t\t\t\tfor (x = x1; x < x2; x += w)\n\t\t\t\t\t\tg.drawImage(backgroundImage, x, y, c);\n\t\t\t}\n\t\t\tg.setClip(saveClip);\n\t\t}\n\t}", "public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {\n // Evaluate the target filter of the ImporterService on the Declaration\n Filter filter = bindersManager.getTargetFilter(declarationBinderRef);\n return filter.matches(declaration.getMetadata());\n }", "private <T> T readIntoBean(final T bean, final String[] nameMapping, final CellProcessor[] processors)\n\t\tthrows IOException {\n\t\t\n\t\tif( readRow() ) {\n\t\t\tif( nameMapping.length != length() ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\t\"the nameMapping array and the number of columns read \"\n\t\t\t\t\t\t+ \"should be the same size (nameMapping length = %d, columns = %d)\", nameMapping.length,\n\t\t\t\t\tlength()));\n\t\t\t}\n\t\t\t\n\t\t\tif( processors == null ) {\n\t\t\t\tprocessedColumns.clear();\n\t\t\t\tprocessedColumns.addAll(getColumns());\n\t\t\t} else {\n\t\t\t\texecuteProcessors(processedColumns, processors);\n\t\t\t}\n\t\t\t\n\t\t\treturn populateBean(bean, nameMapping);\n\t\t}\n\t\t\n\t\treturn null; // EOF\n\t}", "public static base_response add(nitro_service client, vpath resource) throws Exception {\n\t\tvpath addresource = new vpath();\n\t\taddresource.name = resource.name;\n\t\taddresource.destip = resource.destip;\n\t\taddresource.encapmode = resource.encapmode;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Initialize current thread's JobContext using specified copy @param origin the original job context
[ "static void loadFromOrigin(JobContext origin) {\n if (origin.bag_.isEmpty()) {\n return;\n }\n ActContext<?> actContext = ActContext.Base.currentContext();\n if (null != actContext) {\n Locale locale = (Locale) origin.bag_.get(\"locale\");\n if (null != locale) {\n actContext.locale(locale);\n }\n H.Session session = (H.Session) origin.bag_.get(\"session\");\n if (null != session) {\n actContext.attribute(\"__session\", session);\n }\n }\n }" ]
[ "public static base_response unset(nitro_service client, nstimeout resource, String[] args) throws Exception{\n\t\tnstimeout unsetresource = new nstimeout();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public void remove(RowKey key) {\n\t\tcurrentState.put( key, new AssociationOperation( key, null, REMOVE ) );\n\t}", "public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }", "@UiThread\n protected void parentExpandedFromViewHolder(int flatParentPosition) {\n ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition);\n updateExpandedParent(parentWrapper, flatParentPosition, true);\n }", "protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }", "protected TokenList.Token parseSubmatrixToExtract(TokenList.Token variableTarget,\n TokenList tokens, Sequence sequence) {\n\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(tokens, sequence);\n\n List<Variable> variables = new ArrayList<Variable>();\n\n // for the operation, the first variable must be the matrix which is being manipulated\n variables.add(variableTarget.getVariable());\n\n addSubMatrixVariables(inputs, variables);\n if( variables.size() != 2 && variables.size() != 3 ) {\n throw new ParseError(\"Unexpected number of variables. 1 or 2 expected\");\n }\n\n // first parameter is the matrix it will be extracted from. rest specify range\n Operation.Info info;\n\n // only one variable means its referencing elements\n // two variables means its referencing a sub matrix\n if( inputs.size() == 1 ) {\n Variable varA = variables.get(1);\n if( varA.getType() == VariableType.SCALAR ) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else if( inputs.size() == 2 ) {\n Variable varA = variables.get(1);\n Variable varB = variables.get(2);\n\n if( varA.getType() == VariableType.SCALAR && varB.getType() == VariableType.SCALAR) {\n info = functions.create(\"extractScalar\", variables);\n } else {\n info = functions.create(\"extract\", variables);\n }\n } else {\n throw new ParseError(\"Expected 2 inputs to sub-matrix\");\n }\n\n sequence.addOperation(info.op);\n\n return new TokenList.Token(info.output);\n }", "public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{\n\t\trnatparam unsetresource = new rnatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public void postProcess() {\n\t\tif (foreignColumnName != null) {\n\t\t\tforeignAutoRefresh = true;\n\t\t}\n\t\tif (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {\n\t\t\tmaxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;\n\t\t}\n\t}", "public static final BigDecimal printDurationInDecimalThousandthsOfMinutes(Duration duration)\n {\n BigDecimal result = null;\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigDecimal.valueOf(printDurationFractionsOfMinutes(duration, 1000));\n }\n return result;\n }" ]
Provide array of String results from inputOutput MFString field named string. @return value of string field
[ "public String[] getString() {\n String[] valueDestination = new String[ string.size() ];\n this.string.getValue(valueDestination);\n return valueDestination;\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 }", "public void removeVariable(String name)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n frame.remove(name);\n }", "@JmxOperation(description = \"swapFiles changes this store to use the new data directory\")\n public void swapFiles(String newStoreDirectory) {\n logger.info(\"Swapping files for store '\" + getName() + \"' to \" + newStoreDirectory);\n File newVersionDir = new File(newStoreDirectory);\n\n if(!newVersionDir.exists())\n throw new VoldemortException(\"File \" + newVersionDir.getAbsolutePath()\n + \" does not exist.\");\n\n if(!(newVersionDir.getParentFile().compareTo(storeDir.getAbsoluteFile()) == 0 && ReadOnlyUtils.checkVersionDirName(newVersionDir)))\n throw new VoldemortException(\"Invalid version folder name '\"\n + newVersionDir\n + \"'. Either parent directory is incorrect or format(version-n) is incorrect\");\n\n // retrieve previous version for (a) check if last write is winning\n // (b) if failure, rollback use\n File previousVersionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n if(previousVersionDir == null)\n throw new VoldemortException(\"Could not find any latest directory to swap with in store '\"\n + getName() + \"'\");\n\n long newVersionId = ReadOnlyUtils.getVersionId(newVersionDir);\n long previousVersionId = ReadOnlyUtils.getVersionId(previousVersionDir);\n if(newVersionId == -1 || previousVersionId == -1)\n throw new VoldemortException(\"Unable to parse folder names (\" + newVersionDir.getName()\n + \",\" + previousVersionDir.getName()\n + \") since format(version-n) is incorrect\");\n\n // check if we're greater than latest since we want last write to win\n if(previousVersionId > newVersionId) {\n logger.info(\"No swap required since current latest version \" + previousVersionId\n + \" is greater than swap version \" + newVersionId);\n deleteBackups();\n return;\n }\n\n logger.info(\"Acquiring write lock on '\" + getName() + \"':\");\n fileModificationLock.writeLock().lock();\n boolean success = false;\n try {\n close();\n logger.info(\"Opening primary files for store '\" + getName() + \"' at \"\n + newStoreDirectory);\n\n // open the latest store\n open(newVersionDir);\n success = true;\n } finally {\n try {\n // we failed to do the swap, attempt a rollback to last version\n if(!success)\n rollback(previousVersionDir);\n\n } finally {\n fileModificationLock.writeLock().unlock();\n if(success)\n logger.info(\"Swap operation completed successfully on store \" + getName()\n + \", releasing lock.\");\n else\n logger.error(\"Swap operation failed.\");\n }\n }\n\n // okay we have released the lock and the store is now open again, it is\n // safe to do a potentially slow delete if we have one too many backups\n deleteBackups();\n }", "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 }", "boolean callbackUnregistered(final TransactionalProtocolClient old, final boolean shuttingDown) {\n // Disconnect the remote connection.\n // WFCORE-196 Do this out of the sync block to avoid deadlocks where in-flight requests can't\n // be informed that the channel has closed\n protocolClient.disconnected(old);\n\n synchronized (this) {\n // If the connection dropped without us stopping the process ask for reconnection\n if (!shuttingDown && requiredState == InternalState.SERVER_STARTED) {\n final InternalState state = internalState;\n if (state == InternalState.PROCESS_STOPPED\n || state == InternalState.PROCESS_STOPPING\n || state == InternalState.STOPPED) {\n // In case it stopped we don't reconnect\n return true;\n }\n // In case we are reloading, it will reconnect automatically\n if (state == InternalState.RELOADING) {\n return true;\n }\n try {\n ROOT_LOGGER.logf(DEBUG_LEVEL, \"trying to reconnect to %s current-state (%s) required-state (%s)\", serverName, state, requiredState);\n internalSetState(new ReconnectTask(), state, InternalState.SEND_STDIN);\n } catch (Exception e) {\n ROOT_LOGGER.logf(DEBUG_LEVEL, e, \"failed to send reconnect task\");\n }\n return false;\n } else {\n return true;\n }\n }\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 void deleteServerGroup(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = \" + id);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\n }", "public static Object setProperty( String key, String value ) {\n return prp.setProperty( key, value );\n }" ]
Sign in a group of connections to the registry by key @param key the key @param connections a collection of websocket connections
[ "public void signIn(String key, Collection<WebSocketConnection> connections) {\n if (connections.isEmpty()) {\n return;\n }\n Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>();\n for (WebSocketConnection conn : connections) {\n newMap.put(conn, conn);\n }\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.putAll(newMap);\n }" ]
[ "public Channel sessionConnectGenerateChannel(Session session)\n throws JSchException {\n \t// set timeout\n session.connect(sshMeta.getSshConnectionTimeoutMillis());\n \n ChannelExec channel = (ChannelExec) session.openChannel(\"exec\");\n channel.setCommand(sshMeta.getCommandLine());\n\n // if run as super user, assuming the input stream expecting a password\n if (sshMeta.isRunAsSuperUser()) {\n \ttry {\n channel.setInputStream(null, true);\n\n OutputStream out = channel.getOutputStream();\n channel.setOutputStream(System.out, true);\n channel.setExtOutputStream(System.err, true);\n channel.setPty(true);\n channel.connect();\n \n\t out.write((sshMeta.getPassword()+\"\\n\").getBytes());\n\t out.flush();\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"error in sessionConnectGenerateChannel for super user\", e);\n\t\t\t}\n } else {\n \tchannel.setInputStream(null);\n \tchannel.connect();\n }\n\n return channel;\n\n }", "static Shell createTelnetConsoleShell(String prompt, String appName,\n ShellCommandHandler mainHandler, InputStream input, OutputStream output) {\n try {\n // Set up nvt4j; ignore the initial clear & reposition\n final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input, output) {\n private boolean cleared;\n private boolean moved;\n\n @Override\n public void clear() throws IOException {\n if (this.cleared)\n super.clear();\n this.cleared = true;\n }\n\n @Override\n public void move(int row, int col) throws IOException {\n if (this.moved)\n super.move(row, col);\n this.moved = true;\n }\n };\n nvt4jTerminal.put(nvt4j.impl.Terminal.AUTO_WRAP_ON);\n nvt4jTerminal.setCursor(true);\n\n // Have JLine do input & output through telnet terminal\n final InputStream jlineInput = new InputStream() {\n @Override\n public int read() throws IOException {\n return nvt4jTerminal.get();\n }\n };\n final OutputStream jlineOutput = new OutputStream() {\n @Override\n public void write(int value) throws IOException {\n nvt4jTerminal.put(value);\n }\n };\n\n return createTerminalConsoleShell(prompt, appName, mainHandler, jlineInput, jlineOutput);\n } catch (Exception e) {\n // Failover: use default shell\n BufferedReader in = new BufferedReader(new InputStreamReader(input));\n PrintStream out = new PrintStream(output);\n\n return createConsoleShell(prompt, appName, mainHandler, in, out, out, null);\n }\n }", "public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }", "protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) {\n routingFor(routable1)\n .routees()\n .forEach(routee -> routee.receiveCommand(action, routable1));\n }", "public static boolean isTrue(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression\r\n && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"TRUE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isTrueExpression()) ||\r\n \"Boolean.TRUE\".equals(expression.getText());\r\n }", "public static boolean isFalse(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"FALSE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression())\r\n || \"Boolean.FALSE\".equals(expression.getText());\r\n }", "public byte[] getValueAsArray() {\n ByteBuffer buffer = getValue();\n byte[] result = new byte[buffer.remaining()];\n buffer.get(result);\n return result;\n }", "public boolean containsNonZeroHosts(IPAddressSection other) {\n\t\tif(!other.isPrefixed()) {\n\t\t\treturn contains(other);\n\t\t}\n\t\tint otherPrefixLength = other.getNetworkPrefixLength();\n\t\tif(otherPrefixLength == other.getBitCount()) {\n\t\t\treturn contains(other);\n\t\t}\n\t\treturn containsNonZeroHostsImpl(other, otherPrefixLength);\n\t}", "private float[] generateParticleVelocities()\n {\n float [] particleVelocities = new float[mEmitRate * 3];\n Vector3f temp = new Vector3f(0,0,0);\n for ( int i = 0; i < mEmitRate * 3 ; i +=3 )\n {\n temp.x = mParticlePositions[i];\n temp.y = mParticlePositions[i+1];\n temp.z = mParticlePositions[i+2];\n\n\n float velx = mRandom.nextFloat() * (maxVelocity.x- minVelocity.x)\n + minVelocity.x;\n\n float vely = mRandom.nextFloat() * (maxVelocity.y - minVelocity.y)\n + minVelocity.y;\n float velz = mRandom.nextFloat() * (maxVelocity.z - minVelocity.z)\n + minVelocity.z;\n\n temp = temp.normalize();\n temp.mul(velx, vely, velz, temp);\n\n particleVelocities[i] = temp.x;\n particleVelocities[i+1] = temp.y;\n particleVelocities[i+2] = temp.z;\n }\n\n return particleVelocities;\n\n }" ]
This essentially ensures that we only store a single Vertex for each unique "Set" of tags.
[ "public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags)\n {\n Map<Set<String>, Vertex> cache = getCache(event);\n Vertex vertex = cache.get(tags);\n if (vertex == null)\n {\n TagSetModel model = create();\n model.setTags(tags);\n cache.put(tags, model.getElement());\n return model;\n }\n else\n {\n return frame(vertex);\n }\n }" ]
[ "public Set<? extends Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n all.put(this.getProcessor(), null);\n for (ProcessorGraphNode<?, ?> dependency: this.dependencies) {\n for (Processor<?, ?> p: dependency.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }", "private static long getVersionId(String versionDir) {\n try {\n return Long.parseLong(versionDir.replace(\"version-\", \"\"));\n } catch(NumberFormatException e) {\n logger.trace(\"Cannot parse version directory to obtain id \" + versionDir);\n return -1;\n }\n }", "public static void reset() {\n for (Object name : Collections.list(MAP_KEY_TO_SCOPE.keys())) {\n closeScope(name);\n }\n ConfigurationHolder.configuration.onScopeForestReset();\n ScopeImpl.resetUnBoundProviders();\n }", "public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }", "public DocumentReaderAndWriter<IN> makeReaderAndWriter() {\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>)\r\n Class.forName(flags.readerAndWriter).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.readerAndWriter: '%s'\", flags.readerAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }", "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 }", "public static base_responses unset(nitro_service client, Long clid[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance unsetresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tunsetresources[i] = new clusterinstance();\n\t\t\t\tunsetresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "private void calculateMenuItemPosition() {\n\n float itemRadius = (expandedRadius + collapsedRadius) / 2, f;\n RectF area = new RectF(\n center.x - itemRadius,\n center.y - itemRadius,\n center.x + itemRadius,\n center.y + itemRadius);\n Path path = new Path();\n path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));\n PathMeasure measure = new PathMeasure(path, false);\n float len = measure.getLength();\n int divisor = getChildCount();\n float divider = len / divisor;\n\n for (int i = 0; i < getChildCount(); i++) {\n float[] coords = new float[2];\n measure.getPosTan(i * divider + divider * .5f, coords, null);\n FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();\n item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);\n item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);\n }\n }", "public String pop() {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.spop(getKey());\n }\n });\n }" ]
Add a calendar day node. @param parentNode parent node @param calendar ProjectCalendar instance @param day calendar day
[ "private void addCalendarDay(MpxjTreeNode parentNode, ProjectCalendar calendar, final Day day)\n {\n MpxjTreeNode dayNode = new MpxjTreeNode(day)\n {\n @Override public String toString()\n {\n return day.name();\n }\n };\n parentNode.add(dayNode);\n addHours(dayNode, calendar.getHours(day));\n }" ]
[ "public final List<MtasSolrStatus> checkForExceptions() {\n List<MtasSolrStatus> statusWithException = null;\n for (MtasSolrStatus item : data) {\n if (item.checkResponseForException()) {\n if (statusWithException == null) {\n statusWithException = new ArrayList<>();\n }\n statusWithException.add(item);\n }\n }\n return statusWithException;\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 double computeLikelihoodP() {\n double ret = 1.0;\n\n for( int i = 0; i < r.numRows; i++ ) {\n double a = r.get(i,0);\n\n ret *= Math.exp(-a*a/2.0);\n }\n\n return ret;\n }", "@Override\n public Integer getMasterPartition(byte[] key) {\n return abs(hash.hash(key)) % (Math.max(1, this.partitionToNode.length));\n }", "public void updateInfo(Info info) {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"PUT\");\n request.setBody(info.getPendingChanges());\n BoxAPIResponse boxAPIResponse = request.send();\n\n if (boxAPIResponse instanceof BoxJSONResponse) {\n BoxJSONResponse response = (BoxJSONResponse) boxAPIResponse;\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }\n }", "public boolean changeState(StateVertex nextState) {\n\t\tif (nextState == null) {\n\t\t\tLOGGER.info(\"nextState given is null\");\n\t\t\treturn false;\n\t\t}\n\t\tLOGGER.debug(\"Trying to change to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\tcurrentState.getName());\n\n\t\tif (stateFlowGraph.canGoTo(currentState, nextState)) {\n\n\t\t\tLOGGER.debug(\"Changed to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\t\tcurrentState.getName());\n\n\t\t\tsetCurrentState(nextState);\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\tLOGGER.info(\"Cannot go to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\t\tcurrentState.getName());\n\t\t\treturn false;\n\t\t}\n\t}", "private ModelNode createJVMNode() throws OperationFailedException {\n ModelNode jvm = new ModelNode().setEmptyObject();\n jvm.get(NAME).set(getProperty(\"java.vm.name\"));\n jvm.get(JAVA_VERSION).set(getProperty(\"java.vm.specification.version\"));\n jvm.get(JVM_VERSION).set(getProperty(\"java.version\"));\n jvm.get(JVM_VENDOR).set(getProperty(\"java.vm.vendor\"));\n jvm.get(JVM_HOME).set(getProperty(\"java.home\"));\n return jvm;\n }", "public String getEditedFilePath() {\n\n switch (getBundleType()) {\n case DESCRIPTOR:\n return m_cms.getSitePath(m_desc);\n case PROPERTY:\n return null != m_lockedBundleFiles.get(getLocale())\n ? m_cms.getSitePath(m_lockedBundleFiles.get(getLocale()).getFile())\n : m_cms.getSitePath(m_resource);\n case XML:\n return m_cms.getSitePath(m_resource);\n default:\n throw new IllegalArgumentException();\n }\n }", "private Iterable<BoxRetentionPolicyAssignment.Info> getAssignments(String type, int limit, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (type != null) {\r\n queryString.appendParam(\"type\", type);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString(), getID());\r\n return new BoxResourceIterable<BoxRetentionPolicyAssignment.Info>(getAPI(), url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicyAssignment assignment\r\n = new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get(\"id\").asString());\r\n return assignment.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }" ]
Entry point for processing filter definitions. @param properties project properties @param filters project filters @param fixedData filter fixed data @param varData filter var data
[ "public void process(ProjectProperties properties, FilterContainer filters, FixedData fixedData, Var2Data varData)\n {\n int filterCount = fixedData.getItemCount();\n boolean[] criteriaType = new boolean[2];\n CriteriaReader criteriaReader = getCriteriaReader();\n\n for (int filterLoop = 0; filterLoop < filterCount; filterLoop++)\n {\n byte[] filterFixedData = fixedData.getByteArrayValue(filterLoop);\n if (filterFixedData == null || filterFixedData.length < 4)\n {\n continue;\n }\n\n Filter filter = new Filter();\n filter.setID(Integer.valueOf(MPPUtility.getInt(filterFixedData, 0)));\n filter.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(filterFixedData, 4)));\n byte[] filterVarData = varData.getByteArray(filter.getID(), getVarDataType());\n if (filterVarData == null)\n {\n continue;\n }\n\n //System.out.println(ByteArrayHelper.hexdump(filterVarData, true, 16, \"\"));\n List<GenericCriteriaPrompt> prompts = new LinkedList<GenericCriteriaPrompt>();\n\n filter.setShowRelatedSummaryRows(MPPUtility.getByte(filterVarData, 4) != 0);\n filter.setCriteria(criteriaReader.process(properties, filterVarData, 0, -1, prompts, null, criteriaType));\n\n filter.setIsTaskFilter(criteriaType[0]);\n filter.setIsResourceFilter(criteriaType[1]);\n filter.setPrompts(prompts);\n\n filters.addFilter(filter);\n //System.out.println(filter);\n }\n }" ]
[ "public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException {\n // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation.\n // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client\n // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to\n // have this issue.\n\n // First shutdown the servers\n final ModelNode stopServersOp = Operations.createOperation(\"stop-servers\");\n stopServersOp.get(\"blocking\").set(true);\n stopServersOp.get(\"timeout\").set(timeout);\n ModelNode response = client.execute(stopServersOp);\n if (!Operations.isSuccessfulOutcome(response)) {\n throw new OperationExecutionException(\"Failed to stop servers.\", stopServersOp, response);\n }\n\n // Now shutdown the host\n final ModelNode address = determineHostAddress(client);\n final ModelNode shutdownOp = Operations.createOperation(\"shutdown\", address);\n response = client.execute(shutdownOp);\n if (Operations.isSuccessfulOutcome(response)) {\n // Wait until the process has died\n while (true) {\n if (isDomainRunning(client, true)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(\"Failed to shutdown host.\", shutdownOp, response);\n }\n }", "@UiThread\n protected void expandView() {\n setExpanded(true);\n onExpansionToggled(false);\n\n if (mParentViewHolderExpandCollapseListener != null) {\n mParentViewHolderExpandCollapseListener.onParentExpanded(getAdapterPosition());\n }\n }", "private WaveformPreview requestPreviewInternal(final DataReference trackReference, final boolean failIfPassive) {\n\n // First check if we are using cached data for this slot\n MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(trackReference));\n if (cache != null) {\n return cache.getWaveformPreview(null, trackReference);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(trackReference.getSlotReference());\n if (sourceDetails != null) {\n final WaveformPreview provided = MetadataFinder.getInstance().allMetadataProviders.getWaveformPreview(sourceDetails, trackReference);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (MetadataFinder.getInstance().isPassive() && failIfPassive && trackReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // We have to actually request the preview using the dbserver protocol.\n ConnectionManager.ClientTask<WaveformPreview> task = new ConnectionManager.ClientTask<WaveformPreview>() {\n @Override\n public WaveformPreview useClient(Client client) throws Exception {\n return getWaveformPreview(trackReference.rekordboxId, SlotReference.getSlotReference(trackReference), client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(trackReference.player, task, \"requesting waveform preview\");\n } catch (Exception e) {\n logger.error(\"Problem requesting waveform preview, returning null\", e);\n }\n return null;\n }", "private void addModuleToGraph(final DbModule module, final AbstractGraph graph, final int depth) {\n if (graph.isTreated(graph.getId(module))) {\n return;\n }\n\n final String moduleElementId = graph.getId(module);\n graph.addElement(moduleElementId, module.getVersion(), depth == 0);\n\n if (filters.getDepthHandler().shouldGoDeeper(depth)) {\n for (final DbDependency dep : DataUtils.getAllDbDependencies(module)) {\n if(filters.shouldBeInReport(dep)){\n addDependencyToGraph(dep, graph, depth + 1, moduleElementId);\n }\n }\n }\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 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 }", "public static Collection<Field> getAllAttributes(final Class<?> classToInspect) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), field -> true);\n return allFields;\n }", "public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) {\n String key = registerEventHandler(h);\n String mcall = \"google.maps.event.addListener(\" + obj.getVariableName() + \", '\" + type.name() + \"', \"\n + \"function(event) {document.jsHandlers.handleUIEvent('\" + key + \"', event);});\";//.latLng\n //System.out.println(\"addUIEventHandler mcall: \" + mcall);\n runtime.execute(mcall);\n }", "protected Element createLineElement(float x1, float y1, float x2, float y2)\n {\n HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2);\n String color = colorString(getGraphicsState().getStrokingColor());\n\n StringBuilder pstyle = new StringBuilder(50);\n pstyle.append(\"left:\").append(style.formatLength(line.getLeft())).append(';');\n pstyle.append(\"top:\").append(style.formatLength(line.getTop())).append(';');\n pstyle.append(\"width:\").append(style.formatLength(line.getWidth())).append(';');\n pstyle.append(\"height:\").append(style.formatLength(line.getHeight())).append(';');\n pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(\" solid \").append(color).append(';');\n if (line.getAngleDegrees() != 0)\n pstyle.append(\"transform:\").append(\"rotate(\").append(line.getAngleDegrees()).append(\"deg);\");\n\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }" ]
Requests the waveform detail for a specific track ID, given a connection to a player that has already been set up. @param rekordboxId the track whose waveform detail is desired @param slot identifies the media slot we are querying @param client the dbserver client that is communicating with the appropriate player @return the retrieved waveform detail, or {@code null} if none was available @throws IOException if there is a communication problem
[ "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 }" ]
[ "protected void createSequence(PersistenceBroker broker, FieldDescriptor field,\r\n String sequenceName, long maxKey) throws Exception\r\n {\r\n Statement stmt = null;\r\n try\r\n {\r\n stmt = broker.serviceStatementManager().getGenericStatement(field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n stmt.execute(sp_createSequenceQuery(sequenceName, maxKey));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(e);\r\n throw new SequenceManagerException(\"Could not create new row in \"+SEQ_TABLE_NAME+\" table - TABLENAME=\" +\r\n sequenceName + \" field=\" + field.getColumnName(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (stmt != null) stmt.close();\r\n }\r\n catch (SQLException sqle)\r\n {\r\n if(log.isDebugEnabled())\r\n log.debug(\"Threw SQLException while in createSequence and closing stmt\", sqle);\r\n // ignore it\r\n }\r\n }\r\n }", "public static Method getSAMMethod(Class<?> c) {\n // SAM = single public abstract method\n // if the class is not abstract there is no abstract method\n if (!Modifier.isAbstract(c.getModifiers())) return null;\n if (c.isInterface()) {\n Method[] methods = c.getMethods();\n // res stores the first found abstract method\n Method res = null;\n for (Method mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (mi.getAnnotation(Traits.Implemented.class)!=null) continue;\n try {\n Object.class.getMethod(mi.getName(), mi.getParameterTypes());\n continue;\n } catch (NoSuchMethodException e) {/*ignore*/}\n\n // we have two methods, so no SAM\n if (res!=null) return null;\n res = mi;\n }\n return res;\n\n } else {\n\n LinkedList<Method> methods = new LinkedList();\n getAbstractMethods(c, methods);\n if (methods.isEmpty()) return null;\n ListIterator<Method> it = methods.listIterator();\n while (it.hasNext()) {\n Method m = it.next();\n if (hasUsableImplementation(c, m)) it.remove();\n }\n return getSingleNonDuplicateMethod(methods);\n }\n }", "public void associateTypeJndiResource(JNDIResourceModel resource, String type)\n {\n if (type == null || resource == null)\n {\n return;\n }\n\n if (StringUtils.equals(type, \"javax.sql.DataSource\") && !(resource instanceof DataSourceModel))\n {\n DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);\n }\n else if (StringUtils.equals(type, \"javax.jms.Queue\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.QueueConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.QUEUE);\n }\n else if (StringUtils.equals(type, \"javax.jms.Topic\") && !(resource instanceof JmsDestinationModel))\n {\n JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);\n jms.setDestinationType(JmsDestinationType.TOPIC);\n }\n else if (StringUtils.equals(type, \"javax.jms.TopicConnectionFactory\") && !(resource instanceof JmsConnectionFactoryModel))\n {\n JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);\n jms.setConnectionFactoryType(JmsDestinationType.TOPIC);\n }\n }", "private boolean validate(CmsFavoriteEntry entry) {\n\n try {\n String siteRoot = entry.getSiteRoot();\n if (!m_okSiteRoots.contains(siteRoot)) {\n m_rootCms.readResource(siteRoot);\n m_okSiteRoots.add(siteRoot);\n }\n CmsUUID project = entry.getProjectId();\n if (!m_okProjects.contains(project)) {\n m_cms.readProject(project);\n m_okProjects.add(project);\n }\n for (CmsUUID id : Arrays.asList(entry.getDetailId(), entry.getStructureId())) {\n if ((id != null) && !m_okStructureIds.contains(id)) {\n m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n m_okStructureIds.add(id);\n }\n }\n return true;\n\n } catch (Exception e) {\n LOG.info(\"Favorite entry validation failed: \" + e.getLocalizedMessage(), e);\n return false;\n }\n\n }", "public void useXopAttachmentServiceWithWebClient() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments/xop\";\n \n JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean();\n factoryBean.setAddress(serviceURI);\n factoryBean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, \n (Object)\"true\"));\n WebClient client = factoryBean.createWebClient();\n WebClient.getConfig(client).getRequestContext().put(\"support.type.as.multipart\", \n \"true\"); \n client.type(\"multipart/related\").accept(\"multipart/related\");\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a WebClient\");\n \n XopBean xopResponse = client.post(xop, XopBean.class);\n \n verifyXopResponse(xop, xopResponse);\n }", "public void setHostName(String hostName) {\n if (hostName == null || hostName.contains(\":\")) {\n return;\n }\n ODO_HOST = hostName;\n BASE_URL = \"http://\" + ODO_HOST + \":\" + API_PORT + \"/\" + API_BASE + \"/\";\n }", "public void addControllerType(GVRControllerType controllerType)\n {\n if (cursorControllerTypes == null)\n {\n cursorControllerTypes = new ArrayList<GVRControllerType>();\n }\n else if (cursorControllerTypes.contains(controllerType))\n {\n return;\n }\n cursorControllerTypes.add(controllerType);\n }", "private boolean initRequestHandler(SelectionKey selectionKey) {\n ByteBuffer inputBuffer = inputStream.getBuffer();\n int remaining = inputBuffer.remaining();\n\n // Don't have enough bytes to determine the protocol yet...\n if(remaining < 3)\n return true;\n\n byte[] protoBytes = { inputBuffer.get(0), inputBuffer.get(1), inputBuffer.get(2) };\n\n try {\n String proto = ByteUtils.getString(protoBytes, \"UTF-8\");\n inputBuffer.clear();\n RequestFormatType requestFormatType = RequestFormatType.fromCode(proto);\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"Protocol negotiated for \" + socketChannel.socket() + \": \"\n + requestFormatType.getDisplayName());\n\n // The protocol negotiation is the first request, so respond by\n // sticking the bytes in the output buffer, signaling the Selector,\n // and returning false to denote no further processing is needed.\n outputStream.getBuffer().put(ByteUtils.getBytes(\"ok\", \"UTF-8\"));\n prepForWrite(selectionKey);\n\n return false;\n } catch(IllegalArgumentException e) {\n // okay we got some nonsense. For backwards compatibility,\n // assume this is an old client who does not know how to negotiate\n RequestFormatType requestFormatType = RequestFormatType.VOLDEMORT_V0;\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"No protocol proposal given for \" + socketChannel.socket()\n + \", assuming \" + requestFormatType.getDisplayName());\n\n return true;\n }\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 }" ]
bind attribute and value @param stmt @param index @param attributeOrQuery @param value @param cld @return @throws SQLException
[ "private int bindStatementValue(PreparedStatement stmt, int index, Object attributeOrQuery, Object value, ClassDescriptor cld)\r\n throws SQLException\r\n {\r\n FieldDescriptor fld = null;\r\n // if value is a subQuery bind it\r\n if (value instanceof Query)\r\n {\r\n Query subQuery = (Query) value;\r\n return bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n\r\n // if attribute is a subQuery bind it\r\n if (attributeOrQuery instanceof Query)\r\n {\r\n Query subQuery = (Query) attributeOrQuery;\r\n bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);\r\n }\r\n else\r\n {\r\n fld = cld.getFieldDescriptorForPath((String) attributeOrQuery);\r\n }\r\n\r\n if (fld != null)\r\n {\r\n // BRJ: use field conversions and platform\r\n if (value != null)\r\n {\r\n m_platform.setObjectForStatement(stmt, index, fld.getFieldConversion().javaToSql(value), fld.getJdbcType().getType());\r\n }\r\n else\r\n {\r\n m_platform.setNullForStatement(stmt, index, fld.getJdbcType().getType());\r\n }\r\n }\r\n else\r\n {\r\n if (value != null)\r\n {\r\n stmt.setObject(index, value);\r\n }\r\n else\r\n {\r\n stmt.setNull(index, Types.NULL);\r\n }\r\n }\r\n\r\n return ++index; // increment before return\r\n }" ]
[ "public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() {\n\n if (null == m_allSubCategories) {\n m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n @Override\n public Object transform(Object categoryPath) {\n\n try {\n List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories(\n m_cms,\n (String)categoryPath,\n true,\n m_cms.getRequestContext().getUri());\n CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean(\n m_cms,\n categories,\n (String)categoryPath);\n return result;\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n\n });\n }\n return m_allSubCategories;\n }", "void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException {\n persist(key, value, enableDisableMode, disable, file, null);\n }", "public void setSingletonVariable(String name, WindupVertexFrame frame)\n {\n setVariable(name, Collections.singletonList(frame));\n }", "private static CustomInfoType convertCustomInfo(Map<String, String> customInfo) {\n if (customInfo == null) {\n return null;\n }\n\n CustomInfoType ciType = new CustomInfoType();\n for (Entry<String, String> entry : customInfo.entrySet()) {\n CustomInfoType.Item cItem = new CustomInfoType.Item();\n cItem.setKey(entry.getKey());\n cItem.setValue(entry.getValue());\n ciType.getItem().add(cItem);\n }\n\n return ciType;\n }", "private void processCalendarException(ProjectCalendar calendar, Row row)\n {\n Date fromDate = row.getDate(\"CD_FROM_DATE\");\n Date toDate = row.getDate(\"CD_TO_DATE\");\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME1\"), row.getDate(\"CD_TO_TIME1\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME2\"), row.getDate(\"CD_TO_TIME2\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME3\"), row.getDate(\"CD_TO_TIME3\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME4\"), row.getDate(\"CD_TO_TIME4\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME5\"), row.getDate(\"CD_TO_TIME5\")));\n }\n }", "public void setHtml(String html) {\n this.html = html;\n\n if (widget != null) {\n if (widget.isAttached()) {\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\");\n } else {\n widget.addAttachHandler(event ->\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\"));\n }\n } else {\n GWT.log(\"Please initialize the Target widget.\", new IllegalStateException());\n }\n }", "public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }", "protected void progressInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n long totalTimeS = (System.currentTimeMillis() - startTimeMs) / Time.MS_PER_SECOND;\n\n logger.info(tag + \" : scanned \" + scanned + \" and fetched \" + fetched + \" for store '\"\n + storageEngine.getName() + \"' partitionIds:\" + partitionIds + \" in \"\n + totalTimeS + \" s\");\n }\n }", "public Object get(int dataSet) throws SerializationException {\r\n\t\tObject result = null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult = getData(ds);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}" ]
Convert JsonString to Object of Clazz @param json @param clazz @return Object of Clazz
[ "protected <T> T fromJsonString(String json, Class<T> clazz) {\n\t\treturn _gsonParser.fromJson(json, clazz);\n\t}" ]
[ "private <T extends ProgramElementDoc> List<T> filterByVisibility(T[] docs, Visibility visibility) {\n\tif (visibility == Visibility.PRIVATE)\n\t return Arrays.asList(docs);\n\n\tList<T> filtered = new ArrayList<T>();\n\tfor (T doc : docs) {\n\t if (Visibility.get(doc).compareTo(visibility) > 0)\n\t\tfiltered.add(doc);\n\t}\n\treturn filtered;\n }", "private Map<UUID, FieldType> populateCustomFieldMap()\n {\n byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);\n int length = MPPUtility.getInt(data, 0);\n int index = length + 36;\n\n // 4 byte record count\n int recordCount = MPPUtility.getInt(data, index);\n index += 4;\n\n // 8 bytes per record\n index += (8 * recordCount);\n \n Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();\n while (index < data.length)\n {\n int blockLength = MPPUtility.getInt(data, index); \n if (blockLength <= 0 || index + blockLength > data.length)\n {\n break;\n }\n \n int fieldID = MPPUtility.getInt(data, index + 4);\n FieldType field = FieldTypeHelper.getInstance(fieldID);\n UUID guid = MPPUtility.getGUID(data, index + 160);\n map.put(guid, field);\n index += blockLength;\n }\n return map;\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}", "@SuppressWarnings(\"unused\")\n public String getDevicePushToken(final PushType type) {\n switch (type) {\n case GCM:\n return getCachedGCMToken();\n case FCM:\n return getCachedFCMToken();\n default:\n return null;\n }\n }", "public void setInitialSequence(int[] sequence) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].setInitialSequence(sequence);\r\n return;\r\n }\r\n model1.setInitialSequence(sequence);\r\n model2.setInitialSequence(sequence);\r\n }", "public boolean process(DMatrixRMaj A , int numSingularValues, DMatrixRMaj nullspace ) {\n decomposition.decompose(A);\n\n if( A.numRows > A.numCols ) {\n Q.reshape(A.numCols,Math.min(A.numRows,A.numCols));\n decomposition.getQ(Q, true);\n } else {\n Q.reshape(A.numCols, A.numCols);\n decomposition.getQ(Q, false);\n }\n\n nullspace.reshape(Q.numRows,numSingularValues);\n CommonOps_DDRM.extract(Q,0,Q.numRows,Q.numCols-numSingularValues,Q.numCols,nullspace,0,0);\n\n return true;\n }", "private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)\n {\n //Rates rates = m_factory.createProjectResourcesResourceRates();\n //xml.setRates(rates);\n //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();\n\n List<Project.Resources.Resource.Rates.Rate> ratesList = null;\n\n for (int tableIndex = 0; tableIndex < 5; tableIndex++)\n {\n CostRateTable table = mpx.getCostRateTable(tableIndex);\n if (table != null)\n {\n Date from = DateHelper.FIRST_DATE;\n for (CostRateTableEntry entry : table)\n {\n if (costRateTableWriteRequired(entry, from))\n {\n if (ratesList == null)\n {\n Rates rates = m_factory.createProjectResourcesResourceRates();\n xml.setRates(rates);\n ratesList = rates.getRate();\n }\n\n Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();\n ratesList.add(rate);\n\n rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));\n rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));\n rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));\n rate.setRatesFrom(from);\n from = entry.getEndDate();\n rate.setRatesTo(from);\n rate.setRateTable(BigInteger.valueOf(tableIndex));\n rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));\n rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));\n }\n }\n }\n }\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 static StoreDefinition getStoreDef(List<StoreDefinition> list, String name) {\n for(StoreDefinition def: list)\n if(def.getName().equals(name))\n return def;\n return null;\n }" ]
Returns the list of module dependencies regarding the provided filters @param moduleId String @param filters FiltersHolder @return List<Dependency>
[ "public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n return getModuleDependencies(module, filters, 1, new ArrayList<String>());\n }" ]
[ "public static base_response unset(nitro_service client, nsdiameter resource, String[] args) throws Exception{\n\t\tnsdiameter unsetresource = new nsdiameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public boolean process( DMatrixSparseCSC A ) {\n init(A);\n\n TriangularSolver_DSCC.eliminationTree(A,true,parent,gwork);\n\n countNonZeroInR(parent);\n countNonZeroInV(parent);\n\n // if more columns than rows it's possible that Q*R != A. That's because a householder\n // would need to be created that's outside the m by m Q matrix. In reality it has\n // a partial solution. Column pivot are needed.\n if( m < n ) {\n for (int row = 0; row <m; row++) {\n if( gwork.data[head+row] < 0 ) {\n return false;\n }\n }\n }\n return true;\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 EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n }\n } catch (Exception e) {\n e.printStackTrace();\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\n return endpoint;\n }", "public <T> InternalEjbDescriptor<T> get(String beanName) {\n return cast(ejbByName.get(beanName));\n }", "private String stripLineBreaks(String text, String replacement)\n {\n if (text.indexOf('\\r') != -1 || text.indexOf('\\n') != -1)\n {\n StringBuilder sb = new StringBuilder(text);\n\n int index;\n\n while ((index = sb.indexOf(\"\\r\\n\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\\r\")) != -1)\n {\n sb.replace(index, index + 2, replacement);\n }\n\n while ((index = sb.indexOf(\"\\r\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n while ((index = sb.indexOf(\"\\n\")) != -1)\n {\n sb.replace(index, index + 1, replacement);\n }\n\n text = sb.toString();\n }\n\n return (text);\n }", "public Bundler put(String key, CharSequence value) {\n delegate.putCharSequence(key, value);\n return this;\n }", "private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) {\n\n\t\tif(forwardCurveName != null) {\n\n\t\t\t//determine average fixing offset and period length\n\t\t\tdouble fixingOffset = 0;\n\t\t\tdouble periodLength = 0;\n\n\t\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i++) {\n\t\t\t\tfixingOffset *= ((double) i) / (i+1);\n\t\t\t\tfixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1);\n\n\t\t\t\tperiodLength *= ((double) i) / (i+1);\n\t\t\t\tperiodLength += schedule.getPeriodLength(i) / (i+1);\n\t\t\t}\n\n\t\t\treturn new LIBORIndex(forwardCurveName, fixingOffset, periodLength);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}", "protected <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {\r\n\r\n return ensureHandlers().addHandlerToSource(type, this, handler);\r\n }" ]
Returns the URL of the first route. @return URL backed by the first route.
[ "public Optional<URL> getRoute() {\n Optional<Route> optionalRoute = getClient().routes().inNamespace(namespace)\n .list().getItems()\n .stream()\n .findFirst();\n\n return optionalRoute\n .map(OpenShiftRouteLocator::createUrlFromRoute);\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}", "private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "private void forward() {\n\n Set<String> selected = new HashSet<>();\n\n for (CheckBox checkbox : m_componentCheckboxes) {\n CmsSetupComponent component = (CmsSetupComponent)(checkbox.getData());\n if (checkbox.getValue().booleanValue()) {\n selected.add(component.getId());\n }\n }\n String error = null;\n for (String compId : selected) {\n CmsSetupComponent component = m_componentMap.get(compId);\n for (String dep : component.getDependencies()) {\n if (!selected.contains(dep)) {\n error = \"Unfulfilled dependency: The component \"\n + component.getName()\n + \" can not be installed because its dependency \"\n + m_componentMap.get(dep).getName()\n + \" is not selected\";\n break;\n }\n }\n }\n if (error == null) {\n Set<String> modules = new HashSet<>();\n\n for (CmsSetupComponent component : m_componentMap.values()) {\n\n if (selected.contains(component.getId())) {\n\n for (CmsModule module : m_context.getSetupBean().getAvailableModules().values()) {\n if (component.match(module.getName())) {\n modules.add(module.getName());\n }\n }\n }\n }\n List<String> moduleList = new ArrayList<>(modules);\n m_context.getSetupBean().setInstallModules(CmsStringUtil.listAsString(moduleList, \"|\"));\n m_context.stepForward();\n } else {\n CmsSetupErrorDialog.showErrorDialog(error, error);\n }\n }", "@Override\r\n public synchronized long skip(final long length) throws IOException {\r\n final long skip = super.skip(length);\r\n this.count += skip;\r\n return skip;\r\n }", "private void getMonthlyRelativeDates(Calendar calendar, int frequency, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }", "public AsciiTable setPaddingTopChar(Character paddingTopChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTopChar(paddingTopChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }", "public Object copy(Object obj, PersistenceBroker broker)\r\n\t\t\tthrows ObjectCopyException\r\n\t{\r\n\t\tif (obj instanceof OjbCloneable)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\treturn ((OjbCloneable) obj).ojbClone();\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new ObjectCopyException(\"Object must implement OjbCloneable in order to use the\"\r\n\t\t\t\t\t\t\t\t\t\t + \" CloneableObjectCopyStrategy\");\r\n\t\t}\r\n\t}", "public void addClass(ClassNode node) {\n node = node.redirect();\n String name = node.getName();\n ClassNode stored = classes.get(name);\n if (stored != null && stored != node) {\n // we have a duplicate class!\n // One possibility for this is, that we declared a script and a\n // class in the same file and named the class like the file\n SourceUnit nodeSource = node.getModule().getContext();\n SourceUnit storedSource = stored.getModule().getContext();\n String txt = \"Invalid duplicate class definition of class \" + node.getName() + \" : \";\n if (nodeSource == storedSource) {\n // same class in same source\n txt += \"The source \" + nodeSource.getName() + \" contains at least two definitions of the class \" + node.getName() + \".\\n\";\n if (node.isScriptBody() || stored.isScriptBody()) {\n txt += \"One of the classes is an explicit generated class using the class statement, the other is a class generated from\" +\n \" the script body based on the file name. Solutions are to change the file name or to change the class name.\\n\";\n }\n } else {\n txt += \"The sources \" + nodeSource.getName() + \" and \" + storedSource.getName() + \" each contain a class with the name \" + node.getName() + \".\\n\";\n }\n nodeSource.getErrorCollector().addErrorAndContinue(\n new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()), nodeSource)\n );\n }\n classes.put(name, node);\n\n if (classesToCompile.containsKey(name)) {\n ClassNode cn = classesToCompile.get(name);\n cn.setRedirect(node);\n classesToCompile.remove(name);\n }\n }" ]
Matches the styles and adjusts the size. This needs to be called after the input is added to the DOM, so we do it in onLoad.
[ "@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }" ]
[ "public void setConvergence( int maxIterations , double ftol , double gtol ) {\n this.maxIterations = maxIterations;\n this.ftol = ftol;\n this.gtol = gtol;\n }", "public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }", "public void setAutoClose(boolean autoClose) {\n this.autoClose = autoClose;\n\n if (autoCloseHandlerRegistration != null) {\n autoCloseHandlerRegistration.removeHandler();\n autoCloseHandlerRegistration = null;\n }\n\n if (autoClose) {\n autoCloseHandlerRegistration = registerHandler(addValueChangeHandler(event -> close()));\n }\n }", "public final File getTaskDirectory() {\n createIfMissing(this.working, \"Working\");\n try {\n return Files.createTempDirectory(this.working.toPath(), TASK_DIR_PREFIX).toFile();\n } catch (IOException e) {\n throw new AssertionError(\"Unable to create temporary directory in '\" + this.working + \"'\");\n }\n }", "public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }", "private boolean hasBidirectionalAssociation(Class clazz)\r\n {\r\n ClassDescriptor cdesc;\r\n Collection refs;\r\n boolean hasBidirAssc;\r\n\r\n if (_withoutBidirAssc.contains(clazz))\r\n {\r\n return false;\r\n }\r\n\r\n if (_withBidirAssc.contains(clazz))\r\n {\r\n return true;\r\n }\r\n\r\n // first time we meet this class, let's look at metadata\r\n cdesc = _pb.getClassDescriptor(clazz);\r\n refs = cdesc.getObjectReferenceDescriptors();\r\n hasBidirAssc = false;\r\n REFS_CYCLE:\r\n for (Iterator it = refs.iterator(); it.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor ord;\r\n ClassDescriptor relCDesc;\r\n Collection relRefs;\r\n\r\n ord = (ObjectReferenceDescriptor) it.next();\r\n relCDesc = _pb.getClassDescriptor(ord.getItemClass());\r\n relRefs = relCDesc.getObjectReferenceDescriptors();\r\n for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )\r\n {\r\n ObjectReferenceDescriptor relOrd;\r\n\r\n relOrd = (ObjectReferenceDescriptor) relIt.next();\r\n if (relOrd.getItemClass().equals(clazz))\r\n {\r\n hasBidirAssc = true;\r\n break REFS_CYCLE;\r\n }\r\n }\r\n }\r\n if (hasBidirAssc)\r\n {\r\n _withBidirAssc.add(clazz);\r\n }\r\n else\r\n {\r\n _withoutBidirAssc.add(clazz);\r\n }\r\n\r\n return hasBidirAssc;\r\n }", "public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void rotateWithPivot(float quatW, float quatX, float quatY,\n float quatZ, float pivotX, float pivotY, float pivotZ) {\n NativeTransform.rotateWithPivot(getNative(), quatW, quatX, quatY,\n quatZ, pivotX, pivotY, pivotZ);\n }", "private boolean isBundleProperty(Object property) {\n\n return (property.equals(TableProperty.KEY) || property.equals(TableProperty.TRANSLATION));\n }" ]
Handle a whole day change event. @param event the change event.
[ "@UiHandler(\"m_wholeDayCheckBox\")\n void onWholeDayChange(ValueChangeEvent<Boolean> event) {\n\n //TODO: Improve - adjust time selections?\n if (handleChange()) {\n m_controller.setWholeDay(event.getValue());\n }\n }" ]
[ "public void handleChannelClosed(final Channel closed, final IOException e) {\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n if (activeOperation.getChannel() == closed) {\n // Only call cancel, to also interrupt still active threads\n activeOperation.getResultHandler().cancel();\n }\n }\n }", "public void addNotBetween(Object attribute, Object value1, Object value2)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }", "public void forObjectCache(String template, Properties attributes) throws XDocletException\r\n {\r\n _curObjectCacheDef = _curClassDef.getObjectCache();\r\n if (_curObjectCacheDef != null)\r\n {\r\n generate(template);\r\n _curObjectCacheDef = null;\r\n }\r\n }", "private void updateGhostStyle() {\n\n if (CmsStringUtil.isEmpty(m_realValue)) {\n if (CmsStringUtil.isEmpty(m_ghostValue)) {\n updateTextArea(m_realValue);\n return;\n }\n if (!m_focus) {\n setGhostStyleEnabled(true);\n updateTextArea(m_ghostValue);\n } else {\n // don't show ghost mode while focused\n setGhostStyleEnabled(false);\n }\n } else {\n setGhostStyleEnabled(false);\n updateTextArea(m_realValue);\n }\n }", "public static base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {\n final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);\n return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));\n }", "public static String soundex(String str) {\n if (str.length() < 1)\n return \"\"; // no soundex key for the empty string (could use 000)\n \n char[] key = new char[4];\n key[0] = str.charAt(0);\n int pos = 1;\n char prev = '0';\n for (int ix = 1; ix < str.length() && pos < 4; ix++) {\n char ch = str.charAt(ix);\n int charno;\n if (ch >= 'A' && ch <= 'Z')\n charno = ch - 'A';\n else if (ch >= 'a' && ch <= 'z')\n charno = ch - 'a';\n else\n continue;\n\n if (number[charno] != '0' && number[charno] != prev)\n key[pos++] = number[charno];\n prev = number[charno];\n }\n\n for ( ; pos < 4; pos++)\n key[pos] = '0';\n\n return new String(key);\n }", "public TwoDHashMap<K2, K3, V> getAs2d(final K1 firstKey) {\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 != null ) {\n\t\t\treturn new TwoDHashMap<K2, K3, V>(innerMap1);\n\t\t} else {\n\t\t\treturn new TwoDHashMap<K2, K3, V>();\n\t\t}\n\t\t\n\t}", "@Deprecated\r\n private BufferedImage getImage(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }" ]
Converts the paged list. @param uList the resource list to convert from @return the converted list
[ "public PagedList<V> convert(final PagedList<U> uList) {\n if (uList == null || uList.isEmpty()) {\n return new PagedList<V>() {\n @Override\n public Page<V> nextPage(String s) throws RestException, IOException {\n return null;\n }\n };\n }\n Page<U> uPage = uList.currentPage();\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return new PagedList<V>(vPage) {\n @Override\n public Page<V> nextPage(String nextPageLink) throws RestException, IOException {\n Page<U> uPage = uList.nextPage(nextPageLink);\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return vPage;\n }\n };\n }" ]
[ "public List<Tag> getRootTags()\n {\n return this.definedTags.values().stream()\n .filter(Tag::isRoot)\n .collect(Collectors.toList());\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 HandlerRegistration addSearchFinishHandler(final SearchFinishEvent.SearchFinishHandler handler) {\n return addHandler(handler, SearchFinishEvent.TYPE);\n }", "public <V> V getObject(final String key, final Class<V> type) {\n final Object obj = this.values.get(key);\n return type.cast(obj);\n }", "public static boolean isConstant(Expression expression, Object expected) {\r\n return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue());\r\n }", "public int setPageCount(final int num) {\n int diff = num - getCheckableCount();\n if (diff > 0) {\n addIndicatorChildren(diff);\n } else if (diff < 0) {\n removeIndicatorChildren(-diff);\n }\n if (mCurrentPage >=num ) {\n mCurrentPage = 0;\n }\n setCurrentPage(mCurrentPage);\n return diff;\n }", "@RequestMapping(value = \"/legendgraphic\", method = RequestMethod.GET)\n\tpublic ModelAndView getGraphic(@RequestParam(\"layerId\") String layerId,\n\t\t\t@RequestParam(value = \"styleName\", required = false) String styleName,\n\t\t\t@RequestParam(value = \"ruleIndex\", required = false) Integer ruleIndex,\n\t\t\t@RequestParam(value = \"format\", required = false) String format,\n\t\t\t@RequestParam(value = \"width\", required = false) Integer width,\n\t\t\t@RequestParam(value = \"height\", required = false) Integer height,\n\t\t\t@RequestParam(value = \"scale\", required = false) Double scale,\n\t\t\t@RequestParam(value = \"allRules\", required = false) Boolean allRules, HttpServletRequest request)\n\t\t\tthrows GeomajasException {\n\t\tif (!allRules) {\n\t\t\treturn getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);\n\t\t} else {\n\t\t\treturn getGraphics(layerId, styleName, format, width, height, scale);\n\t\t}\n\t}", "public void addAll(@NonNull final Collection<T> collection) {\n final int length = collection.size();\n if (length == 0) {\n return;\n }\n synchronized (mLock) {\n final int position = getItemCount();\n mObjects.addAll(collection);\n notifyItemRangeInserted(position, length);\n }\n }", "public static synchronized Class< ? > locate(final String serviceName) {\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 && !l.isEmpty() ) {\n Callable<Class< ? >> c = l.get( l.size() - 1 );\n try {\n return c.call();\n } catch ( Exception e ) {\n }\n }\n }\n return null;\n }" ]
Sets the invalid values for the TextBox @param invalidValues @param isCaseSensitive @param invalidValueErrorMessage
[ "public void setInvalidValues(final Set<String> invalidValues,\n final boolean isCaseSensitive,\n final String invalidValueErrorMessage) {\n if (isCaseSensitive) {\n this.invalidValues = invalidValues;\n } else {\n this.invalidValues = new HashSet<String>();\n for (String value : invalidValues) {\n this.invalidValues.add(value.toLowerCase());\n }\n }\n this.isCaseSensitive = isCaseSensitive;\n this.invalidValueErrorMessage = invalidValueErrorMessage;\n }" ]
[ "public static void main(String[] args) throws IOException {\n\t\tExampleHelpers.configureLogging();\n\t\tJsonSerializationProcessor.printDocumentation();\n\n\t\tJsonSerializationProcessor jsonSerializationProcessor = new JsonSerializationProcessor();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(jsonSerializationProcessor);\n\t\tjsonSerializationProcessor.close();\n\t}", "public static vpnsessionaction get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tobj.set_name(name);\n\t\tvpnsessionaction response = (vpnsessionaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setVariable(String name, Object value) {\n if (variables == null)\n variables = new LinkedHashMap();\n variables.put(name, value);\n }", "public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }", "static GVRPerspectiveCamera makePerspShadowCamera(GVRPerspectiveCamera centerCam, float coneAngle)\n {\n GVRPerspectiveCamera camera = new GVRPerspectiveCamera(centerCam.getGVRContext());\n float near = centerCam.getNearClippingDistance();\n float far = centerCam.getFarClippingDistance();\n\n camera.setNearClippingDistance(near);\n camera.setFarClippingDistance(far);\n camera.setFovY((float) Math.toDegrees(coneAngle));\n camera.setAspectRatio(1.0f);\n return camera;\n }", "private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {\n final ModelNode op = ServerOperations.createAddOperation(address);\n for (Map.Entry<String, String> prop : properties.entrySet()) {\n final String[] props = prop.getKey().split(\",\");\n if (props.length == 0) {\n throw new RuntimeException(\"Invalid property \" + prop);\n }\n ModelNode node = op;\n for (int i = 0; i < props.length - 1; ++i) {\n node = node.get(props[i]);\n }\n final String value = prop.getValue() == null ? \"\" : prop.getValue();\n if (value.startsWith(\"!!\")) {\n handleDmrString(node, props[props.length - 1], value);\n } else {\n node.get(props[props.length - 1]).set(value);\n }\n }\n return op;\n }", "private static void addVersionInfo(byte[] grid, int size, int version) {\n // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/\n long version_data = QR_ANNEX_D[version - 7];\n for (int i = 0; i < 6; i++) {\n grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;\n grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;\n grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;\n grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;\n }\n }", "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {\n int numSingular = Math.min(W.numRows,W.numCols);\n boolean compact = W.numRows == W.numCols;\n\n if( compact ) {\n if( U != null ) {\n if( tranU && U.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n else if( !tranU && U.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n }\n\n if( V != null ) {\n if( tranV && V.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n else if( !tranV && V.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n }\n } else {\n if( U != null && U.numRows != U.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n if( V != null && V.numRows != V.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n if( U != null && U.numRows != W.numRows )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n if( V != null && V.numRows != W.numCols )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n }\n }" ]
Use this API to fetch all the cmppolicylabel resources that are configured on netscaler.
[ "public static cmppolicylabel[] get(nitro_service service) throws Exception{\n\t\tcmppolicylabel obj = new cmppolicylabel();\n\t\tcmppolicylabel[] response = (cmppolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static NodeList evaluateXpathExpression(Document dom, String xpathExpr)\n\t\t\tthrows XPathExpressionException {\n\t\tXPathFactory factory = XPathFactory.newInstance();\n\t\tXPath xpath = factory.newXPath();\n\t\tXPathExpression expr = xpath.compile(xpathExpr);\n\t\tObject result = expr.evaluate(dom, XPathConstants.NODESET);\n\t\treturn (NodeList) result;\n\t}", "public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }", "public static byte[] storeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws IOException, OperationFailedException {\n if (!operation.hasDefined(CONTENT)) {\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final ModelNode content = operation.get(CONTENT).get(0);\n if (content.hasDefined(HASH)) {\n // This should be handled as part of the OSH\n throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());\n }\n final byte[] hash = storeDeploymentContent(context, operation, contentRepository);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }", "public static <T> T flattenOption(scala.Option<T> option) {\n if (option.isEmpty()) {\n return null;\n } else {\n return option.get();\n }\n }", "public static <GIVEN, WHEN, THEN> Scenario<GIVEN, WHEN, THEN> create( Class<GIVEN> givenClass, Class<WHEN> whenClass,\n Class<THEN> thenClass ) {\n return new Scenario<GIVEN, WHEN, THEN>( givenClass, whenClass, thenClass );\n }", "public void printRelations(ClassDoc c) {\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tif (hidden(c) || c.name().equals(\"\")) // avoid phantom classes, they may pop up when the source uses annotations\n\t return;\n\t// Print generalization (through the Java superclass)\n\tType s = c.superclassType();\n\tClassDoc sc = s != null && !s.qualifiedTypeName().equals(Object.class.getName()) ? s.asClassDoc() : null;\n\tif (sc != null && !c.isEnum() && !hidden(sc))\n\t relation(opt, RelationType.EXTENDS, c, sc, null, null, null);\n\t// Print generalizations (through @extends tags)\n\tfor (Tag tag : c.tags(\"extends\"))\n\t if (!hidden(tag.text()))\n\t\trelation(opt, RelationType.EXTENDS, c, c.findClass(tag.text()), null, null, null);\n\t// Print realizations (Java interfaces)\n\tfor (Type iface : c.interfaceTypes()) {\n\t ClassDoc ic = iface.asClassDoc();\n\t if (!hidden(ic))\n\t\trelation(opt, RelationType.IMPLEMENTS, c, ic, null, null, null);\n\t}\n\t// Print other associations\n\tallRelation(opt, RelationType.COMPOSED, c);\n\tallRelation(opt, RelationType.NAVCOMPOSED, c);\n\tallRelation(opt, RelationType.HAS, c);\n\tallRelation(opt, RelationType.NAVHAS, c);\n\tallRelation(opt, RelationType.ASSOC, c);\n\tallRelation(opt, RelationType.NAVASSOC, c);\n\tallRelation(opt, RelationType.DEPEND, c);\n }", "public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}", "public RedwoodConfiguration clear(){\r\n tasks = new LinkedList<Runnable>();\r\n tasks.add(new Runnable(){ public void run(){\r\n Redwood.clearHandlers();\r\n Redwood.restoreSystemStreams();\r\n Redwood.clearLoggingClasses();\r\n } });\r\n return this;\r\n }", "public void setWholeDay(Boolean isWholeDay) {\r\n\r\n if (m_model.isWholeDay() ^ ((null != isWholeDay) && isWholeDay.booleanValue())) {\r\n m_model.setWholeDay(isWholeDay);\r\n valueChanged();\r\n }\r\n }" ]
NOT IN Criteria with SubQuery @param attribute The field name to be used @param subQuery The subQuery
[ "public void addNotIn(String attribute, Query subQuery)\r\n {\r\n\t\t// PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));\r\n }" ]
[ "public void strokeRectangle(Rectangle rect, Color color, float linewidth) {\n\t\tstrokeRectangle(rect, color, linewidth, null);\n\t}", "public void switchDataSource(BoneCPConfig newConfig) throws SQLException {\n\t\tlogger.info(\"Switch to new datasource requested. New Config: \"+newConfig);\n\t\tDataSource oldDS = getTargetDataSource();\n \n\t\tif (!(oldDS instanceof BoneCPDataSource)){\n\t\t\tthrow new SQLException(\"Unknown datasource type! Was expecting BoneCPDataSource but received \"+oldDS.getClass()+\". Not switching datasource!\");\n\t\t}\n\t\t\n\t\tBoneCPDataSource newDS = new BoneCPDataSource(newConfig);\n\t\tnewDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool\n\t\t\n\t\t// force application to start using the new one \n\t\tsetTargetDataSource(newDS);\n\t\t\n\t\tlogger.info(\"Shutting down old datasource slowly. Old Config: \"+oldDS);\n\t\t// tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used.\n\t\t((BoneCPDataSource)oldDS).close();\n\t}", "public static <T> OptionalValue<T> ofNullable(T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);\n }", "public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }", "private void readCalendars(Storepoint phoenixProject)\n {\n Calendars calendars = phoenixProject.getCalendars();\n if (calendars != null)\n {\n for (Calendar calendar : calendars.getCalendar())\n {\n readCalendar(calendar);\n }\n\n ProjectCalendar defaultCalendar = m_projectFile.getCalendarByName(phoenixProject.getDefaultCalendar());\n if (defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(defaultCalendar.getName());\n }\n }\n }", "public JSONObject getJsonFormatted(Map<String, String> dataMap) {\r\n JSONObject oneRowJson = new JSONObject();\n\r\n for (int i = 0; i < outTemplate.length; i++) {\r\n oneRowJson.put(outTemplate[i], dataMap.get(outTemplate[i]));\r\n }\n\n\r\n return oneRowJson;\r\n }", "public static sslservicegroup_sslcertkey_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tsslservicegroup_sslcertkey_binding obj = new sslservicegroup_sslcertkey_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tsslservicegroup_sslcertkey_binding response[] = (sslservicegroup_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String calculateCacheKey(String sql, int autoGeneratedKeys) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\ttmp.append(autoGeneratedKeys);\r\n\t\treturn tmp.toString();\r\n\t}", "public final void setExceptions(SortedSet<Date> dates) {\n\n m_exceptions.clear();\n if (null != dates) {\n m_exceptions.addAll(dates);\n }\n\n }" ]
Edit the co-ordinates that the user shows in @param photoId @param userId @param bounds @throws FlickrException
[ "public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\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 }" ]
[ "public static final Duration getDuration(InputStream is) throws IOException\n {\n double durationInSeconds = getInt(is);\n durationInSeconds /= (60 * 60);\n return Duration.getInstance(durationInSeconds, TimeUnit.HOURS);\n }", "public static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}", "public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }", "public void updateEmbeddedColumn(GraphDatabaseService executionEngine, Object[] keyValues, String embeddedColumn, Object value) {\n\t\tString query = getUpdateEmbeddedColumnQuery( keyValues, embeddedColumn );\n\t\tMap<String, Object> params = params( ArrayHelper.concat( keyValues, value, value ) );\n\t\texecutionEngine.execute( query, params );\n\t}", "private String hibcProcess(String source) {\n\n // HIBC 2.6 allows up to 110 characters, not including the \"+\" prefix or the check digit\n if (source.length() > 110) {\n throw new OkapiException(\"Data too long for HIBC LIC\");\n }\n\n source = source.toUpperCase();\n if (!source.matches(\"[A-Z0-9-\\\\. \\\\$/+\\\\%]+?\")) {\n throw new OkapiException(\"Invalid characters in input\");\n }\n\n int counter = 41;\n for (int i = 0; i < source.length(); i++) {\n counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);\n }\n counter = counter % 43;\n\n char checkDigit = HIBC_CHAR_TABLE[counter];\n\n encodeInfo += \"HIBC Check Digit Counter: \" + counter + \"\\n\";\n encodeInfo += \"HIBC Check Digit: \" + checkDigit + \"\\n\";\n\n return \"+\" + source + checkDigit;\n }", "public void deletePersistent(Object object)\r\n {\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open\");\r\n }\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"No transaction in progress, cannot delete persistent\");\r\n }\r\n RuntimeObject rt = new RuntimeObject(object, tx);\r\n tx.deletePersistent(rt);\r\n// tx.moveToLastInOrderList(rt.getIdentity());\r\n }", "private boolean isDepOfIdlArtifact(Artifact artifact, Map<String, Artifact> depsMap) {\n List<String> depTrail = artifact.getDependencyTrail();\n // depTrail can be null sometimes, which seems like a maven bug\n if (depTrail != null) {\n for (String name : depTrail) {\n Artifact dep = depsMap.get(name);\n if (dep != null && isIdlCalssifier(dep, classifier)) {\n return true;\n }\n }\n }\n return false;\n }", "protected float getLayoutOffset() {\n //final int offsetSign = getOffsetSign();\n final float axisSize = getViewPortSize(getOrientationAxis());\n float layoutOffset = - axisSize / 2;\n Log.d(LAYOUT, TAG, \"getLayoutOffset(): dimension: %5.2f, layoutOffset: %5.2f\",\n axisSize, layoutOffset);\n\n return layoutOffset;\n }", "public String stripThreadName(String threadId)\n {\n if (threadId == null)\n {\n return null;\n }\n else\n {\n int index = threadId.lastIndexOf('@');\n return index >= 0 ? threadId.substring(0, index) : threadId;\n }\n }" ]
Generate node data map. @param task the job info
[ "public void genNodeDataMap(ParallelTask task) {\n\n TargetHostMeta targetHostMeta = task.getTargetHostMeta();\n HttpMeta httpMeta = task.getHttpMeta();\n\n String entityBody = httpMeta.getEntityBody();\n String requestContent = HttpMeta\n .replaceDefaultFullRequestContent(entityBody);\n\n Map<String, NodeReqResponse> parallelTaskResult = task\n .getParallelTaskResult();\n for (String fqdn : targetHostMeta.getHosts()) {\n NodeReqResponse nodeReqResponse = new NodeReqResponse(fqdn);\n nodeReqResponse.setDefaultReqestContent(requestContent);\n parallelTaskResult.put(fqdn, nodeReqResponse);\n }\n }" ]
[ "public static URL codeLocationFromURL(String url) {\n try {\n return new URL(url);\n } catch (Exception e) {\n throw new InvalidCodeLocation(url);\n }\n }", "public void setClassOfObject(Class c)\r\n {\r\n m_Class = c;\r\n isAbstract = Modifier.isAbstract(m_Class.getModifiers());\r\n // TODO : Shouldn't the HashMap in DescriptorRepository be updated as well?\r\n }", "public void startAnimation()\n {\n Date time = new Date();\n this.beginAnimation = time.getTime();\n this.endAnimation = beginAnimation + (long) (animationTime * 1000);\n this.animate = true;\n }", "public static AliasOperationTransformer replaceLastElement(final PathElement element) {\n return create(new AddressTransformer() {\n @Override\n public PathAddress transformAddress(final PathAddress original) {\n final PathAddress address = original.subAddress(0, original.size() -1);\n return address.append(element);\n }\n });\n }", "static boolean isInCircle(float x, float y, float centerX, float centerY, float\n radius) {\n return Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius;\n }", "public Object materializeObject(ClassDescriptor cld, Identity oid)\r\n throws PersistenceBrokerException\r\n {\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);\r\n Object result = null;\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getSelectByPKStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getSelectByPKStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getSelectByPKStatement returned a null statement\");\r\n }\r\n /*\r\n arminw: currently a select by PK could never be a stored procedure,\r\n thus we can always set 'false'. Is this correct??\r\n */\r\n sm.bindSelect(stmt, oid, cld, false);\r\n rs = stmt.executeQuery();\r\n // data available read object, else return null\r\n ResultSetAndStatement rs_stmt = new ResultSetAndStatement(broker.serviceStatementManager(), stmt, rs, sql);\r\n if (rs.next())\r\n {\r\n Map row = new HashMap();\r\n cld.getRowReader().readObjectArrayFrom(rs_stmt, row);\r\n result = cld.getRowReader().readObjectFrom(row);\r\n }\r\n // close resources\r\n rs_stmt.close();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of materializeObject: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger, null);\r\n }\r\n return result;\r\n }", "public void fireAssignmentReadEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentRead(resourceAssignment);\n }\n }\n }", "protected void sendEvent(final T event) {\n if (isStatic) {\n sendEvent(event, null, null);\n } else {\n CreationalContext<X> creationalContext = null;\n try {\n Object receiver = getReceiverIfExists(null);\n if (receiver == null && reception != Reception.IF_EXISTS) {\n // creational context is created only if we need it for obtaining receiver\n // ObserverInvocationStrategy takes care of creating CC for parameters, if needed\n creationalContext = beanManager.createCreationalContext(declaringBean);\n receiver = getReceiverIfExists(creationalContext);\n }\n if (receiver != null) {\n sendEvent(event, receiver, creationalContext);\n }\n } finally {\n if (creationalContext != null) {\n creationalContext.release();\n }\n }\n }\n }", "@Override\r\n public void processOutput(Map<String, String> resultsMap) {\r\n queue.add(resultsMap);\n\r\n if (queue.size() > 10000) {\r\n log.info(\"Queue size \" + queue.size() + \", waiting\");\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ex) {\r\n log.info(\"Interrupted \", ex);\r\n }\r\n }\r\n }" ]
Create a Renderer getting a copy from the prototypes collection. @param content to render. @param parent used to inflate the view. @return a new renderer.
[ "private Renderer createRenderer(T content, ViewGroup parent) {\n int prototypeIndex = getPrototypeIndex(content);\n Renderer renderer = getPrototypeByIndex(prototypeIndex).copy();\n renderer.onCreate(content, layoutInflater, parent);\n return renderer;\n }" ]
[ "private void rotatorPushRight( int m )\n {\n double b11 = off[m];\n double b21 = diag[m+1];\n\n computeRotator(b21,-b11);\n\n // apply rotator on the right\n off[m] = 0;\n diag[m+1] = b21*c-b11*s;\n\n if( m+2 < N) {\n double b22 = off[m+1];\n off[m+1] = b22*c;\n bulge = b22*s;\n } else {\n bulge = 0;\n }\n\n// SimpleMatrix Q = createQ(m,m+1, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+1,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }", "public ResourceAssignmentWorkgroupFields addWorkgroupAssignment() throws MPXJException\n {\n if (m_workgroup != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n m_workgroup = new ResourceAssignmentWorkgroupFields();\n\n return (m_workgroup);\n }", "public boolean isWorkingDate(Date date)\n {\n Calendar cal = DateHelper.popCalendar(date);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n DateHelper.pushCalendar(cal);\n return isWorkingDate(date, day);\n }", "private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }", "public GeoShapeMapper transform(GeoTransformation... transformations) {\n if (this.transformations == null) {\n this.transformations = Arrays.asList(transformations);\n } else {\n this.transformations.addAll(Arrays.asList(transformations));\n }\n return this;\n }", "private String getCurrencyFormat(CurrencySymbolPosition position)\n {\n String result;\n\n switch (position)\n {\n case AFTER:\n {\n result = \"1.1#\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"1.1 #\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"# 1.1\";\n break;\n }\n\n default:\n case BEFORE:\n {\n result = \"#1.1\";\n break;\n }\n }\n\n return result;\n }", "public PartialCollection<BoxItem.Info> getItemsRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"offset\", offset)\n .appendParam(\"limit\", limit);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), 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 String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> items = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n BoxItem.Info entryInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject());\n if (entryInfo != null) {\n items.add(entryInfo);\n }\n }\n return items;\n }", "public static boolean isTrue(Expression expression) {\r\n if (expression == null) {\r\n return false;\r\n }\r\n if (expression instanceof PropertyExpression\r\n && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) {\r\n if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression\r\n && \"TRUE\".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) {\r\n return true;\r\n }\r\n }\r\n return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isTrueExpression()) ||\r\n \"Boolean.TRUE\".equals(expression.getText());\r\n }", "public static Map<FieldType, String> getDefaultAssignmentFieldMap()\n {\n Map<FieldType, String> map = new LinkedHashMap<FieldType, String>();\n\n map.put(AssignmentField.UNIQUE_ID, \"taskrsrc_id\");\n map.put(AssignmentField.GUID, \"guid\");\n map.put(AssignmentField.REMAINING_WORK, \"remain_qty\");\n map.put(AssignmentField.BASELINE_WORK, \"target_qty\");\n map.put(AssignmentField.ACTUAL_OVERTIME_WORK, \"act_ot_qty\");\n map.put(AssignmentField.BASELINE_COST, \"target_cost\");\n map.put(AssignmentField.ACTUAL_OVERTIME_COST, \"act_ot_cost\");\n map.put(AssignmentField.REMAINING_COST, \"remain_cost\");\n map.put(AssignmentField.ACTUAL_START, \"act_start_date\");\n map.put(AssignmentField.ACTUAL_FINISH, \"act_end_date\");\n map.put(AssignmentField.BASELINE_START, \"target_start_date\");\n map.put(AssignmentField.BASELINE_FINISH, \"target_end_date\");\n map.put(AssignmentField.ASSIGNMENT_DELAY, \"target_lag_drtn_hr_cnt\");\n\n return map;\n }" ]
Inverts an upper or lower triangular block submatrix. @param blockLength @param upper Is it upper or lower triangular. @param T Triangular matrix that is to be inverted. Must be block aligned. Not Modified. @param T_inv Where the inverse is stored. This can be the same as T. Modified. @param temp Work space variable that is size blockLength*blockLength.
[ "public static void invert( final int blockLength ,\n final boolean upper ,\n final DSubmatrixD1 T ,\n final DSubmatrixD1 T_inv ,\n final double temp[] )\n {\n if( upper )\n throw new IllegalArgumentException(\"Upper triangular matrices not supported yet\");\n\n if( temp.length < blockLength*blockLength )\n throw new IllegalArgumentException(\"Temp must be at least blockLength*blockLength long.\");\n\n if( T.row0 != T_inv.row0 || T.row1 != T_inv.row1 || T.col0 != T_inv.col0 || T.col1 != T_inv.col1)\n throw new IllegalArgumentException(\"T and T_inv must be at the same elements in the matrix\");\n\n final int M = T.row1-T.row0;\n\n final double dataT[] = T.original.data;\n final double dataX[] = T_inv.original.data;\n\n final int offsetT = T.row0*T.original.numCols+M*T.col0;\n\n for( int i = 0; i < M; i += blockLength ) {\n int heightT = Math.min(T.row1-(i+T.row0),blockLength);\n\n int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);\n\n for( int j = 0; j < i; j += blockLength ) {\n int widthX = Math.min(T.col1-(j+T.col0),blockLength);\n\n for( int w = 0; w < temp.length; w++ ) {\n temp[w] = 0;\n }\n\n for( int k = j; k < i; k += blockLength ) {\n int widthT = Math.min(T.col1-(k+T.col0),blockLength);\n\n int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);\n int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);\n\n blockMultMinus(dataT,dataX,temp,indexL,indexX,0,heightT,widthT,widthX);\n }\n\n int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);\n\n InnerTriangularSolver_DDRB.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);\n System.arraycopy(temp,0,dataX,indexX,widthX*heightT);\n }\n InnerTriangularSolver_DDRB.invertLower(dataT,dataX,heightT,indexII,indexII);\n }\n }" ]
[ "public void useOldRESTService() throws Exception {\n List<Object> providers = createJAXRSProviders();\n\n com.example.customerservice.CustomerService customerService = JAXRSClientFactory\n .createFromModel(\"http://localhost:\" + port + \"/examples/direct/rest\", \n com.example.customerservice.CustomerService.class,\n \"classpath:/model/CustomerService-jaxrs.xml\", \n providers, \n null);\n\n System.out.println(\"Using old RESTful CustomerService with old client\");\n\n customer.v1.Customer customer = createOldCustomer(\"Smith Old REST\");\n customerService.updateCustomer(customer);\n\n customer = customerService.getCustomerByName(\"Smith Old REST\");\n printOldCustomerDetails(customer);\n }", "public static nsconfig diff(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig diffresource = new nsconfig();\n\t\tdiffresource.config1 = resource.config1;\n\t\tdiffresource.config2 = resource.config2;\n\t\tdiffresource.outtype = resource.outtype;\n\t\tdiffresource.template = resource.template;\n\t\tdiffresource.ignoredevicespecific = resource.ignoredevicespecific;\n\t\treturn (nsconfig)diffresource.perform_operationEx(client,\"diff\");\n\t}", "public static aaagroup_aaauser_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_aaauser_binding obj = new aaagroup_aaauser_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_aaauser_binding response[] = (aaagroup_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void addHandlerInitializerMethod(ClassFile proxyClassType, ClassMethod staticConstructor) throws Exception {\n ClassMethod classMethod = proxyClassType.addMethod(AccessFlag.PRIVATE, INIT_MH_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT);\n final CodeAttribute b = classMethod.getCodeAttribute();\n b.aload(0);\n StaticMethodInformation methodInfo = new StaticMethodInformation(INIT_MH_METHOD_NAME, new Class[] { Object.class }, void.class,\n classMethod.getClassFile().getName());\n invokeMethodHandler(classMethod, methodInfo, false, DEFAULT_METHOD_RESOLVER, staticConstructor);\n b.checkcast(MethodHandler.class);\n b.putfield(classMethod.getClassFile().getName(), METHOD_HANDLER_FIELD_NAME, DescriptorUtils.makeDescriptor(MethodHandler.class));\n b.returnInstruction();\n BeanLogger.LOG.createdMethodHandlerInitializerForDecoratorProxy(getBeanType());\n\n }", "public static base_responses unset(nitro_service client, String ipaddress[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ipaddress != null && ipaddress.length > 0) {\n\t\t\tnsrpcnode unsetresources[] = new nsrpcnode[ipaddress.length];\n\t\t\tfor (int i=0;i<ipaddress.length;i++){\n\t\t\t\tunsetresources[i] = new nsrpcnode();\n\t\t\t\tunsetresources[i].ipaddress = ipaddress[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "public static locationfile get(nitro_service service) throws Exception{\n\t\tlocationfile obj = new locationfile();\n\t\tlocationfile[] response = (locationfile[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) {\n try {\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying domain level boot operations provided by master\");\n SyncModelParameters parameters =\n new SyncModelParameters(domainController, ignoredDomainResourceRegistry,\n hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository);\n final SyncDomainModelOperationHandler handler =\n new SyncDomainModelOperationHandler(hostInfo, parameters);\n final ModelNode operation = APPLY_DOMAIN_MODEL.clone();\n operation.get(DOMAIN_MODEL).set(bootOperations);\n\n final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler);\n\n final String outcome = result.get(OUTCOME).asString();\n final boolean success = SUCCESS.equals(outcome);\n\n // check if anything we synced triggered reload-required or restart-required.\n // if they did we log a warning on the synced slave.\n if (result.has(RESPONSE_HEADERS)) {\n final ModelNode headers = result.get(RESPONSE_HEADERS);\n if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired();\n }\n if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) {\n HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired();\n }\n }\n if (!success) {\n ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode();\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc);\n return false;\n } else {\n return true;\n }\n } catch (Exception e) {\n HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e);\n return false;\n }\n }", "public static Thread newThread(String name, Runnable runnable, boolean daemon) {\n Thread thread = new Thread(runnable, name);\n thread.setDaemon(daemon);\n return thread;\n }" ]
Register the agent in the platform @param agent_name The name of the agent to be registered @param agent The agent to register. @throws FIPAException
[ "public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{\n DFAgentDescription dfd = new DFAgentDescription();\n ServiceDescription sd = new ServiceDescription();\n \n sd.setType(serviceType);\n sd.setName(serviceName);\n \n //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. \n // He escogido crear nombres en clave en jade.common.Definitions para este campo. \n //NOTE El serviceName es el nombre efectivo del servicio. \n // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. \n // sd.setType(agentType);\n // sd.setName(agent.getLocalName());\n \n //Add services??\n \n // Sets the agent description\n dfd.setName(agent.getAID());\n dfd.addServices(sd);\n \n // Register the agent\n DFService.register(agent, dfd);\n }" ]
[ "public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }", "public void setDirectory(final String directory) {\n this.directory = new File(this.configuration.getDirectory(), directory);\n if (!this.directory.exists()) {\n throw new IllegalArgumentException(String.format(\n \"Directory does not exist: %s.\\n\" +\n \"Configuration contained value %s which is supposed to be relative to \" +\n \"configuration directory.\",\n this.directory, directory));\n }\n\n if (!this.directory.getAbsolutePath()\n .startsWith(this.configuration.getDirectory().getAbsolutePath())) {\n throw new IllegalArgumentException(String.format(\n \"All files and directories must be contained in the configuration directory the \" +\n \"directory provided in the configuration breaks that contract: %s in config \" +\n \"file resolved to %s.\",\n directory, this.directory));\n }\n }", "public void checkAllRequirementsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (Field field: this.dependantsInJson) {\n final Collection<String> requirements = this.dependantToRequirementsMap.get(field);\n if (!requirements.isEmpty()) {\n errors.append(\"\\n\");\n String type = field.getType().getName();\n if (field.getType().isArray()) {\n type = field.getType().getComponentType().getName() + \"[]\";\n }\n errors.append(\"\\t* \").append(type).append(' ').append(field.getName()).append(\" depends on \")\n .append(requirements);\n }\n }\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @Requires dependencies of '\" +\n currentPath + \"': \" + errors);\n }", "public static int[] randomSubset(int k, int n) {\n assert(0 < k && k <= n);\n Random r = new Random();\n int t = 0, m = 0;\n int[] result = new int[k];\n\n while (m < k) {\n double u = r.nextDouble();\n if ( (n - t) * u < k - m ) {\n result[m] = t;\n m++;\n }\n t++;\n }\n return result;\n }", "public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException {\n Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames);\n Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create();\n if (deploymentNames.isEmpty()) {\n for (String s : runtimeNames) {\n ServerLogger.ROOT_LOGGER.debugf(\"We haven't found any deployment for %s in server-group %s\", s, deploymentsRootAddress.getLastElement().getValue());\n }\n }\n if(removeOperation != null) {\n opBuilder.addStep(removeOperation);\n }\n for (String deploymentName : deploymentNames) {\n opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName)));\n }\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n final ModelNode slave = opBuilder.build().getOperation();\n transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress()));\n }", "public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }", "private void enforceSrid(Object feature) throws LayerException {\n\t\tGeometry geom = getFeatureModel().getGeometry(feature);\n\t\tif (null != geom) {\n\t\t\tgeom.setSRID(srid);\n\t\t\tgetFeatureModel().setGeometry(feature, geom);\n\t\t}\n\t}", "public Object getFieldByAlias(String alias)\n {\n return getCachedValue(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias));\n }", "@Override\n\tpublic void processItemDocument(ItemDocument itemDocument) {\n\t\tthis.countItems++;\n\n\t\t// Do some printing for demonstration/debugging.\n\t\t// Only print at most 50 items (or it would get too slow).\n\t\tif (this.countItems < 10) {\n\t\t\tSystem.out.println(itemDocument);\n\t\t} else if (this.countItems == 10) {\n\t\t\tSystem.out.println(\"*** I won't print any further items.\\n\"\n\t\t\t\t\t+ \"*** We will never finish if we print all the items.\\n\"\n\t\t\t\t\t+ \"*** Maybe remove this debug output altogether.\");\n\t\t}\n\t}" ]
When it is time to actually close a client, do so, and clean up the related data structures. @param client the client which has been idle for long enough to be closed
[ "private void closeClient(Client client) {\n logger.debug(\"Closing client {}\", client);\n client.close();\n openClients.remove(client.targetPlayer);\n useCounts.remove(client);\n timestamps.remove(client);\n }" ]
[ "public void setSymbolPosition(CurrencySymbolPosition posn)\n {\n if (posn == null)\n {\n posn = DEFAULT_CURRENCY_SYMBOL_POSITION;\n }\n set(ProjectField.CURRENCY_SYMBOL_POSITION, posn);\n }", "public boolean removeReader(Object key, Object resourceId)\r\n {\r\n boolean result = false;\r\n ObjectLocks objectLocks = null;\r\n synchronized(locktable)\r\n {\r\n objectLocks = (ObjectLocks) locktable.get(resourceId);\r\n if(objectLocks != null)\r\n {\r\n /**\r\n * MBAIRD, last one out, close the door and turn off the lights.\r\n * if no locks (readers or writers) exist for this object, let's remove\r\n * it from the locktable.\r\n */\r\n Map readers = objectLocks.getReaders();\r\n result = readers.remove(key) != null;\r\n if((objectLocks.getWriter() == null) && (readers.size() == 0))\r\n {\r\n locktable.remove(resourceId);\r\n }\r\n }\r\n }\r\n return result;\r\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 int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {\n\n int i, j;\n QrMode currentMode;\n int inputLength = inputModeUnoptimized.length;\n int count = 0;\n int alphaLength;\n int percent = 0;\n\n // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave\n // the original array alone so that subsequent binary length checks don't irrevocably\n // optimize the mode array for the wrong QR Code version\n QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);\n\n currentMode = QrMode.NULL;\n\n if (gs1) {\n count += 4;\n }\n\n if (eciMode != 3) {\n count += 12;\n }\n\n for (i = 0; i < inputLength; i++) {\n if (inputMode[i] != currentMode) {\n count += 4;\n switch (inputMode[i]) {\n case KANJI:\n count += tribus(version, 8, 10, 12);\n count += (blockLength(i, inputMode) * 13);\n break;\n case BINARY:\n count += tribus(version, 8, 16, 16);\n for (j = i; j < (i + blockLength(i, inputMode)); j++) {\n if (inputData[j] > 0xff) {\n count += 16;\n } else {\n count += 8;\n }\n }\n break;\n case ALPHANUM:\n count += tribus(version, 9, 11, 13);\n alphaLength = blockLength(i, inputMode);\n // In alphanumeric mode % becomes %%\n if (gs1) {\n for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b\n if (inputData[j] == '%') {\n percent++;\n }\n }\n }\n alphaLength += percent;\n switch (alphaLength % 2) {\n case 0:\n count += (alphaLength / 2) * 11;\n break;\n case 1:\n count += ((alphaLength - 1) / 2) * 11;\n count += 6;\n break;\n }\n break;\n case NUMERIC:\n count += tribus(version, 10, 12, 14);\n switch (blockLength(i, inputMode) % 3) {\n case 0:\n count += (blockLength(i, inputMode) / 3) * 10;\n break;\n case 1:\n count += ((blockLength(i, inputMode) - 1) / 3) * 10;\n count += 4;\n break;\n case 2:\n count += ((blockLength(i, inputMode) - 2) / 3) * 10;\n count += 7;\n break;\n }\n break;\n }\n currentMode = inputMode[i];\n }\n }\n\n return count;\n }", "private synchronized void setInitializationMethod(Method newMethod)\r\n {\r\n if (newMethod != null)\r\n {\r\n // make sure it's a no argument method\r\n if (newMethod.getParameterTypes().length > 0)\r\n {\r\n throw new MetadataException(\r\n \"Initialization methods must be zero argument methods: \"\r\n + newMethod.getClass().getName()\r\n + \".\"\r\n + newMethod.getName());\r\n }\r\n\r\n // make it accessible if it's not already\r\n if (!newMethod.isAccessible())\r\n {\r\n newMethod.setAccessible(true);\r\n }\r\n }\r\n this.initializationMethod = newMethod;\r\n }", "public static void load(File file)\n {\n try(FileInputStream inputStream = new FileInputStream(file))\n {\n LineIterator it = IOUtils.lineIterator(inputStream, \"UTF-8\");\n while (it.hasNext())\n {\n String line = it.next();\n if (!line.startsWith(\"#\") && !line.trim().isEmpty())\n {\n add(line);\n }\n }\n }\n catch (Exception e)\n {\n throw new WindupException(\"Failed loading archive ignore patterns from [\" + file.toString() + \"]\", e);\n }\n }", "@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }", "public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }" ]
This method extracts a portion of a byte array and writes it into another byte array. @param data Source data @param offset Offset into source data @param size Required size to be extracted from the source data @param buffer Destination buffer @param bufferOffset Offset into destination buffer
[ "public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n System.arraycopy(data, offset, buffer, bufferOffset, size);\n }" ]
[ "protected int countedSize() throws PersistenceBrokerException\r\n {\r\n Query countQuery = getBroker().serviceBrokerHelper().getCountQuery(getQueryObject().getQuery());\r\n ResultSetAndStatement rsStmt;\r\n ClassDescriptor cld = getQueryObject().getClassDescriptor();\r\n int count = 0;\r\n\r\n // BRJ: do not use broker.getCount() because it's extent-aware\r\n // the count we need here must not include extents !\r\n if (countQuery instanceof QueryBySQL)\r\n {\r\n String countSql = ((QueryBySQL) countQuery).getSql();\r\n rsStmt = getBroker().serviceJdbcAccess().executeSQL(countSql, cld, Query.NOT_SCROLLABLE);\r\n }\r\n else\r\n {\r\n rsStmt = getBroker().serviceJdbcAccess().executeQuery(countQuery, cld);\r\n }\r\n\r\n try\r\n {\r\n if (rsStmt.m_rs.next())\r\n {\r\n count = rsStmt.m_rs.getInt(1);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n finally\r\n {\r\n rsStmt.close();\r\n }\r\n\r\n return count;\r\n }", "public static ProctorLoadResult verify(\n @Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource,\n @Nonnull final Map<String, TestSpecification> requiredTests,\n @Nonnull final FunctionMapper functionMapper,\n final ProvidedContext providedContext,\n @Nonnull final Set<String> dynamicTests\n ) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());\n for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {\n final Map<Integer, String> bucketValueToName = Maps.newHashMap();\n for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {\n bucketValueToName.put(bucket.getValue(), bucket.getKey());\n }\n allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);\n }\n\n final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();\n final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());\n resultBuilder.recordAllMissing(missingTests);\n for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {\n final String testName = entry.getKey();\n\n final Map<Integer, String> knownBuckets;\n final TestSpecification specification;\n final boolean isRequired;\n if (allTestsKnownBuckets.containsKey(testName)) {\n // required in specification\n isRequired = true;\n knownBuckets = allTestsKnownBuckets.remove(testName);\n specification = requiredTests.get(testName);\n } else if (dynamicTests.contains(testName)) {\n // resolved by dynamic filter\n isRequired = false;\n knownBuckets = Collections.emptyMap();\n specification = new TestSpecification();\n } else {\n // we don't care about this test\n continue;\n }\n\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);\n\n } catch (IncompatibleTestMatrixException e) {\n if (isRequired) {\n LOGGER.error(String.format(\"Unable to load test matrix for a required test %s\", testName), e);\n resultBuilder.recordError(testName, e);\n } else {\n LOGGER.info(String.format(\"Unable to load test matrix for a dynamic test %s\", testName), e);\n resultBuilder.recordIncompatibleDynamicTest(testName, e);\n }\n }\n }\n\n // TODO mjs - is this check additive?\n resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());\n\n resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());\n\n final ProctorLoadResult loadResult = resultBuilder.build();\n\n return loadResult;\n }", "public double[] getTenors(double moneyness, double maturity) {\r\n\t\tint maturityInMonths\t= (int) Math.round(maturity * 12);\r\n\t\tint[] tenorsInMonths\t= getTenors(convertMoneyness(moneyness), maturityInMonths);\r\n\t\tdouble[] tenors\t\t\t= new double[tenorsInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < tenors.length; index++) {\r\n\t\t\ttenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]);\r\n\t\t}\r\n\t\treturn tenors;\r\n\t}", "protected void postLayoutChild(final int dataIndex) {\n if (!mContainer.isDynamic()) {\n boolean visibleInLayout = !mViewPort.isClippingEnabled() || inViewPort(dataIndex);\n ViewPortVisibility visibility = visibleInLayout ?\n ViewPortVisibility.FULLY_VISIBLE : ViewPortVisibility.INVISIBLE;\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onLayout: child with dataId [%d] viewportVisibility = %s\",\n dataIndex, visibility);\n\n Widget childWidget = mContainer.get(dataIndex);\n if (childWidget != null) {\n childWidget.setViewPortVisibility(visibility);\n }\n }\n }", "public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory,\n ResourcePoolConfig config) {\n return new QueuedKeyedResourcePool<K, V>(factory, config);\n }", "public void unlock() {\n\n for (Locale l : m_lockedBundleFiles.keySet()) {\n LockedFile f = m_lockedBundleFiles.get(l);\n f.tryUnlock();\n }\n if (null != m_descFile) {\n m_descFile.tryUnlock();\n }\n }", "private void cascadeMarkedForInsert()\r\n {\r\n // This list was used to avoid endless recursion on circular references\r\n List alreadyPrepared = new ArrayList();\r\n for(int i = 0; i < markedForInsertList.size(); i++)\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) markedForInsertList.get(i);\r\n // only if a new object was found we cascade to register the dependent objects\r\n if(mod.needsInsert())\r\n {\r\n cascadeInsertFor(mod, alreadyPrepared);\r\n alreadyPrepared.clear();\r\n }\r\n }\r\n markedForInsertList.clear();\r\n }", "private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) {\n MenuDrawer drawer;\n\n if (type == Type.STATIC) {\n drawer = new StaticDrawer(activity);\n\n } else if (type == Type.OVERLAY) {\n drawer = new OverlayDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n\n } else {\n drawer = new SlidingDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n }\n\n drawer.mDragMode = dragMode;\n drawer.setPosition(position);\n\n return drawer;\n }", "public void setValue(FieldContainer container, byte[] data)\n {\n if (data != null)\n {\n container.set(m_type, ((MPPUtility.getInt(data, m_offset) & m_mask) == 0) ? m_zeroValue : m_nonZeroValue);\n }\n }" ]
Creates the stats items. @param statsType the stats type @return the sorted set @throws IOException Signals that an I/O exception has occurred.
[ "static SortedSet<String> createStatsItems(String statsType)\n throws IOException {\n SortedSet<String> statsItems = new TreeSet<>();\n SortedSet<String> functionItems = new TreeSet<>();\n if (statsType != null) {\n Matcher m = fpStatsItems.matcher(statsType.trim());\n while (m.find()) {\n String tmpStatsItem = m.group(2).trim();\n if (STATS_TYPES.contains(tmpStatsItem)) {\n statsItems.add(tmpStatsItem);\n } else if (tmpStatsItem.equals(STATS_TYPE_ALL)) {\n for (String type : STATS_TYPES) {\n statsItems.add(type);\n }\n } else if (STATS_FUNCTIONS.contains(tmpStatsItem)) {\n if (m.group(3) == null) {\n throw new IOException(\"'\" + tmpStatsItem + \"' should be called as '\"\n + tmpStatsItem + \"()' with an optional argument\");\n } else {\n functionItems.add(m.group(1).trim());\n }\n } else {\n throw new IOException(\"unknown statsType '\" + tmpStatsItem + \"'\");\n }\n }\n }\n if (statsItems.size() == 0 && functionItems.size() == 0) {\n statsItems.add(STATS_TYPE_SUM);\n statsItems.add(STATS_TYPE_N);\n statsItems.add(STATS_TYPE_MEAN);\n }\n if (functionItems.size() > 0) {\n statsItems.addAll(functionItems);\n }\n return statsItems;\n }" ]
[ "public static <T> T load(String resourcePath, BeanSpec spec) {\n return load(resourcePath, spec, false);\n }", "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 IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }", "public void createEnvironment(@Observes(precedence = 10) BeforeClass event, OpenShiftAdapter client,\n CubeOpenShiftConfiguration cubeOpenShiftConfiguration) {\n final TestClass testClass = event.getTestClass();\n log.info(String.format(\"Creating environment for %s\", testClass.getName()));\n OpenShiftResourceFactory.createResources(testClass.getName(), client, testClass.getJavaClass(),\n cubeOpenShiftConfiguration.getProperties());\n classTemplateProcessor = new ClassTemplateProcessor(client, cubeOpenShiftConfiguration, testClass);\n final List<? extends OpenShiftResource> templateResources = classTemplateProcessor.processTemplateResources();\n templateDetailsProducer.set(() -> templateResources);\n }", "private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception\n {\n long start = System.currentTimeMillis();\n reader.setProjectID(projectID);\n ProjectFile projectFile = reader.read();\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading database completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }", "protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\n }", "public String getAttributeValue(String attributeName)\n throws JMException, UnsupportedEncodingException {\n String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding);\n return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName));\n }", "private void readZookeeperConfig() {\n\n try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {\n curator.start();\n\n accumuloInstance =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),\n StandardCharsets.UTF_8);\n accumuloInstanceID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),\n StandardCharsets.UTF_8);\n fluoApplicationID =\n new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),\n StandardCharsets.UTF_8);\n\n table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),\n StandardCharsets.UTF_8);\n\n observers = ObserverUtil.load(curator);\n\n config = FluoAdminImpl.mergeZookeeperConfig(config);\n\n // make sure not to include config passed to env, only want config from zookeeper\n appConfig = config.getAppConfiguration();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }", "@Override\n public void close() throws IOException {\n // Notify encoder of EOF (-1).\n if (doEncode) {\n baseNCodec.encode(singleByte, 0, EOF, context);\n } else {\n baseNCodec.decode(singleByte, 0, EOF, context);\n }\n flush();\n out.close();\n }" ]
Wait until a range has no notifications. @return true if notifications were ever seen while waiting
[ "private static boolean waitTillNoNotifications(Environment env, TableRange range)\n throws TableNotFoundException {\n boolean sawNotifications = false;\n long retryTime = MIN_SLEEP_MS;\n\n log.debug(\"Scanning tablet {} for notifications\", range);\n\n long start = System.currentTimeMillis();\n while (hasNotifications(env, range)) {\n sawNotifications = true;\n long sleepTime = Math.max(System.currentTimeMillis() - start, retryTime);\n log.debug(\"Tablet {} had notfications, will rescan in {}ms\", range, sleepTime);\n UtilWaitThread.sleep(sleepTime);\n retryTime = Math.min(MAX_SLEEP_MS, (long) (retryTime * 1.5));\n start = System.currentTimeMillis();\n }\n\n return sawNotifications;\n }" ]
[ "public static cachecontentgroup get(nitro_service service, String name) throws Exception{\n\t\tcachecontentgroup obj = new cachecontentgroup();\n\t\tobj.set_name(name);\n\t\tcachecontentgroup response = (cachecontentgroup) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void populateCalendar(Record record, ProjectCalendar calendar, boolean isBaseCalendar)\n {\n if (isBaseCalendar == true)\n {\n calendar.setName(record.getString(0));\n }\n else\n {\n calendar.setParent(m_projectFile.getCalendarByName(record.getString(0)));\n }\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.getInstance(record.getInteger(1)));\n calendar.setWorkingDay(Day.MONDAY, DayType.getInstance(record.getInteger(2)));\n calendar.setWorkingDay(Day.TUESDAY, DayType.getInstance(record.getInteger(3)));\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.getInstance(record.getInteger(4)));\n calendar.setWorkingDay(Day.THURSDAY, DayType.getInstance(record.getInteger(5)));\n calendar.setWorkingDay(Day.FRIDAY, DayType.getInstance(record.getInteger(6)));\n calendar.setWorkingDay(Day.SATURDAY, DayType.getInstance(record.getInteger(7)));\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }", "@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\tthis.attributes = (Map) attributes;\n\t}", "public static void setTranslucentStatusFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);\n }\n }", "public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "public void commit() {\n if (directory == null)\n return;\n\n try {\n if (reader != null)\n reader.close();\n\n // it turns out that IndexWriter.optimize actually slows\n // searches down, because it invalidates the cache. therefore\n // not calling it any more.\n // http://www.searchworkings.org/blog/-/blogs/uwe-says%3A-is-your-reader-atomic\n // iwriter.optimize();\n\n iwriter.commit();\n openSearchers();\n } catch (IOException e) {\n throw new DukeException(e);\n }\n }", "public static Command newInsert(Object object,\n String outIdentifier,\n boolean returnObject,\n String entryPoint ) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier,\n returnObject,\n entryPoint );\n }", "public void addModuleDir(final String moduleDir) {\n if (moduleDir == null) {\n throw LauncherMessages.MESSAGES.nullParam(\"moduleDir\");\n }\n // Validate the path\n final Path path = Paths.get(moduleDir).normalize();\n modulesDirs.add(path.toString());\n }", "public static base_response add(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute addresource = new lbroute();\n\t\taddresource.network = resource.network;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.gatewayname = resource.gatewayname;\n\t\treturn addresource.add_resource(client);\n\t}" ]
This method works as the one above, adding some properties to the message @param agent_name The id of the agents that receive the message @param msgtype @param message_content The content of the message @param properties to be added to the message @param connector The connector to get the external access
[ "public void sendMessageToAgentsWithExtraProperties(String[] agent_name,\n String msgtype, Object message_content,\n ArrayList<Object> properties, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n\n for (Object property : properties) {\n // Logger logger = Logger.getLogger(\"JadexMessenger\");\n // logger.info(\"Sending message with extra property: \"+property.get(0)+\", with value \"+property.get(1));\n hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));\n }\n\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }" ]
[ "public static final String decodePassword(byte[] data, byte encryptionCode)\n {\n String result;\n\n if (data.length < MINIMUM_PASSWORD_DATA_LENGTH)\n {\n result = null;\n }\n else\n {\n MPPUtility.decodeBuffer(data, encryptionCode);\n\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int i = 0; i < PASSWORD_MASK.length; i++)\n {\n int index = PASSWORD_MASK[i];\n c = (char) data[index];\n\n if (c == 0)\n {\n break;\n }\n buffer.append(c);\n }\n\n result = buffer.toString();\n }\n\n return (result);\n }", "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "MongoCollection<BsonDocument> getLocalCollection(final MongoNamespace namespace) {\n return getLocalCollection(\n namespace,\n BsonDocument.class,\n MongoClientSettings.getDefaultCodecRegistry());\n }", "@SuppressWarnings(\"deprecation\")\n public ResponseFromManager sendTaskToExecutionManager(ParallelTask task) {\n\n ResponseFromManager commandResponseFromManager = null;\n ActorRef executionManager = null;\n try {\n // Start new job\n logger.info(\"!!STARTED sendAgentCommandToManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr());\n\n executionManager = ActorConfig.createAndGetActorSystem().actorOf(\n Props.create(ExecutionManager.class, task),\n \"ExecutionManager-\" + task.getTaskId());\n\n final FiniteDuration duration = Duration.create(task.getConfig()\n .getTimeoutAskManagerSec(), TimeUnit.SECONDS);\n // Timeout timeout = new\n // Timeout(FiniteDuration.parse(\"300 seconds\"));\n Future<Object> future = Patterns.ask(executionManager,\n new InitialRequestToManager(task), new Timeout(duration));\n\n // set ref\n task.executionManager = executionManager;\n\n commandResponseFromManager = (ResponseFromManager) Await.result(\n future, duration);\n\n logger.info(\"!!COMPLETED sendTaskToExecutionManager : \"\n + task.getTaskId() + \" at \"\n + PcDateUtils.getNowDateTimeStr()\n + \" \\t\\t GenericResponseMap in future size: \"\n + commandResponseFromManager.getResponseCount());\n\n } catch (Exception ex) {\n logger.error(\"Exception in sendTaskToExecutionManager {} details {}: \",\n ex, ex);\n\n } finally {\n // stop the manager\n if (executionManager != null && !executionManager.isTerminated()) {\n ActorConfig.createAndGetActorSystem().stop(executionManager);\n }\n\n if (task.getConfig().isAutoSaveLogToLocal()) {\n task.saveLogToLocal();\n }\n\n }\n\n return commandResponseFromManager;\n\n }", "private boolean isInInnerCircle(float x, float y) {\n return GearWearableUtility.isInCircle(x, y, CENTER_X, CENTER_Y, INNER_RADIUS);\n }", "public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}", "public final List<PrintJobStatusExtImpl> poll(final int size) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<PrintJobStatusExtImpl> criteria =\n builder.createQuery(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n root.alias(\"pj\");\n criteria.where(builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING));\n criteria.orderBy(builder.asc(root.get(\"entry\").get(\"startTime\")));\n final Query<PrintJobStatusExtImpl> query = getSession().createQuery(criteria);\n query.setMaxResults(size);\n // LOCK but don't wait for release (since this is run continuously\n // anyway, no wait prevents deadlock)\n query.setLockMode(\"pj\", LockMode.UPGRADE_NOWAIT);\n try {\n return query.getResultList();\n } catch (PessimisticLockException ex) {\n // Another process was polling at the same time. We can ignore this error\n return Collections.emptyList();\n }\n }", "public static base_response update(nitro_service client, sslparameter resource) throws Exception {\n\t\tsslparameter updateresource = new sslparameter();\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.crlmemorysizemb = resource.crlmemorysizemb;\n\t\tupdateresource.strictcachecks = resource.strictcachecks;\n\t\tupdateresource.ssltriggertimeout = resource.ssltriggertimeout;\n\t\tupdateresource.sendclosenotify = resource.sendclosenotify;\n\t\tupdateresource.encrypttriggerpktcount = resource.encrypttriggerpktcount;\n\t\tupdateresource.denysslreneg = resource.denysslreneg;\n\t\tupdateresource.insertionencoding = resource.insertionencoding;\n\t\tupdateresource.ocspcachesize = resource.ocspcachesize;\n\t\tupdateresource.pushflag = resource.pushflag;\n\t\tupdateresource.dropreqwithnohostheader = resource.dropreqwithnohostheader;\n\t\tupdateresource.pushenctriggertimeout = resource.pushenctriggertimeout;\n\t\tupdateresource.undefactioncontrol = resource.undefactioncontrol;\n\t\tupdateresource.undefactiondata = resource.undefactiondata;\n\t\treturn updateresource.update_resource(client);\n\t}", "private void buildJoinTree(Criteria crit)\r\n {\r\n Enumeration e = crit.getElements();\r\n\r\n while (e.hasMoreElements())\r\n {\r\n Object o = e.nextElement();\r\n if (o instanceof Criteria)\r\n {\r\n buildJoinTree((Criteria) o);\r\n }\r\n else\r\n {\r\n SelectionCriteria c = (SelectionCriteria) o;\r\n \r\n // BRJ skip SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n continue;\r\n }\r\n \r\n // BRJ: Outer join for OR\r\n boolean useOuterJoin = (crit.getType() == Criteria.OR);\r\n\r\n // BRJ: do not build join tree for subQuery attribute \r\n if (c.getAttribute() != null && c.getAttribute() instanceof String)\r\n {\r\n\t\t\t\t\t//buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getAlias(), c.getPathClasses());\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n if (c instanceof FieldCriteria)\r\n {\r\n FieldCriteria cc = (FieldCriteria) c;\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) cc.getValue(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n }\r\n }\r\n }" ]
Returns the number of consecutive trailing one or zero bits. If network is true, returns the number of consecutive trailing zero bits. Otherwise, returns the number of consecutive trailing one bits. @param network @return
[ "public int getTrailingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong back = network ? 0 : getDivision(0).getMaxValue();\n\t\tint bitLen = 0;\n\t\tfor(int i = count - 1; i >= 0; i--) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != back) {\n\t\t\t\treturn bitLen + seg.getTrailingBitCount(network);\n\t\t\t}\n\t\t\tbitLen += seg.getBitCount();\n\t\t}\n\t\treturn bitLen;\n\t}" ]
[ "public static gslbdomain_stats get(nitro_service service, String name) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tobj.set_name(name);\n\t\tgslbdomain_stats response = (gslbdomain_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public double[] Kernel1D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n int r = size / 2;\n // kernel\n double[] kernel = new double[size];\n\n // compute kernel\n for (int x = -r, i = 0; i < size; x++, i++) {\n kernel[i] = Function1D(x);\n }\n\n return kernel;\n }", "public File curDir() {\n File file = session().attribute(ATTR_PWD);\n if (null == file) {\n file = new File(System.getProperty(\"user.dir\"));\n session().attribute(ATTR_PWD, file);\n }\n return file;\n }", "private void handleSerialAPIGetCapabilitiesResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Serial API Get Capabilities\");\n\n\t\tthis.serialAPIVersion = String.format(\"%d.%d\", incomingMessage.getMessagePayloadByte(0), incomingMessage.getMessagePayloadByte(1));\n\t\tthis.manufactureId = ((incomingMessage.getMessagePayloadByte(2)) << 8) | (incomingMessage.getMessagePayloadByte(3));\n\t\tthis.deviceType = ((incomingMessage.getMessagePayloadByte(4)) << 8) | (incomingMessage.getMessagePayloadByte(5));\n\t\tthis.deviceId = (((incomingMessage.getMessagePayloadByte(6)) << 8) | (incomingMessage.getMessagePayloadByte(7)));\n\t\t\n\t\tlogger.debug(String.format(\"API Version = %s\", this.getSerialAPIVersion()));\n\t\tlogger.debug(String.format(\"Manufacture ID = 0x%x\", this.getManufactureId()));\n\t\tlogger.debug(String.format(\"Device Type = 0x%x\", this.getDeviceType()));\n\t\tlogger.debug(String.format(\"Device ID = 0x%x\", this.getDeviceId()));\n\t\t\n\t\t// Ready to get information on Serial API\t\t\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessagePriority.High));\n\t}", "public int addPathnameToProfile(int id, String pathname, String actualPath) throws Exception {\n int pathOrder = getPathOrder(id).size() + 1;\n int pathId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PATH\n + \"(\" + Constants.PATH_PROFILE_PATHNAME + \",\"\n + Constants.PATH_PROFILE_ACTUAL_PATH + \",\"\n + Constants.PATH_PROFILE_GROUP_IDS + \",\"\n + Constants.PATH_PROFILE_PROFILE_ID + \",\"\n + Constants.PATH_PROFILE_PATH_ORDER + \",\"\n + Constants.PATH_PROFILE_CONTENT_TYPE + \",\"\n + Constants.PATH_PROFILE_REQUEST_TYPE + \",\"\n + Constants.PATH_PROFILE_GLOBAL + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\",\n PreparedStatement.RETURN_GENERATED_KEYS\n );\n statement.setString(1, pathname);\n statement.setString(2, actualPath);\n statement.setString(3, \"\");\n statement.setInt(4, id);\n statement.setInt(5, pathOrder);\n statement.setString(6, Constants.PATH_PROFILE_DEFAULT_CONTENT_TYPE); // should be set by UI/API\n statement.setInt(7, Constants.REQUEST_TYPE_GET); // should be set by UI/API\n statement.setBoolean(8, false);\n statement.executeUpdate();\n\n // execute statement and get resultSet which will have the generated path ID as the first field\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n pathId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\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 (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // need to add to request response table for all clients\n for (Client client : ClientService.getInstance().findAllClients(id)) {\n this.addPathToRequestResponseTable(id, client.getUUID(), pathId);\n }\n\n return pathId;\n }", "public int findAnimation(GVRAnimation findme)\n {\n int index = 0;\n for (GVRAnimation anim : mAnimations)\n {\n if (anim == findme)\n {\n return index;\n }\n ++index;\n }\n return -1;\n }", "void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }", "private void handleGetVersionResponse(SerialMessage incomingMessage) {\n\t\tthis.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);\n\t\tthis.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));\n\t\tlogger.debug(String.format(\"Got MessageGetVersion response. Version = %s, Library Type = 0x%02X\", zWaveVersion, ZWaveLibraryType));\n\t}", "@Override\n public void registerCapabilities(ManagementResourceRegistration resourceRegistration) {\n if (capabilities!=null) {\n for (RuntimeCapability c : capabilities) {\n resourceRegistration.registerCapability(c);\n }\n }\n if (incorporatingCapabilities != null) {\n resourceRegistration.registerIncorporatingCapabilities(incorporatingCapabilities);\n }\n assert requirements != null;\n resourceRegistration.registerRequirements(requirements);\n }" ]
Verifies application name. Avoids characters that Zookeeper does not like in nodes & Hadoop does not like in HDFS paths. @param name Application name @throws IllegalArgumentException If name contains illegal characters
[ "private void verifyApplicationName(String name) {\n if (name == null) {\n throw new IllegalArgumentException(\"Application name cannot be null\");\n }\n if (name.isEmpty()) {\n throw new IllegalArgumentException(\"Application name length must be > 0\");\n }\n String reason = null;\n char[] chars = name.toCharArray();\n char c;\n for (int i = 0; i < chars.length; i++) {\n c = chars[i];\n if (c == 0) {\n reason = \"null character not allowed @\" + i;\n break;\n } else if (c == '/' || c == '.' || c == ':') {\n reason = \"invalid character '\" + c + \"'\";\n break;\n } else if (c > '\\u0000' && c <= '\\u001f' || c >= '\\u007f' && c <= '\\u009F'\n || c >= '\\ud800' && c <= '\\uf8ff' || c >= '\\ufff0' && c <= '\\uffff') {\n reason = \"invalid character @\" + i;\n break;\n }\n }\n if (reason != null) {\n throw new IllegalArgumentException(\n \"Invalid application name \\\"\" + name + \"\\\" caused by \" + reason);\n }\n }" ]
[ "public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }", "private GridLines getGridLines(byte[] data, int offset)\n {\n Color normalLineColor = ColorType.getInstance(data[offset]).getColor();\n LineStyle normalLineStyle = LineStyle.getInstance(data[offset + 3]);\n int intervalNumber = data[offset + 4];\n LineStyle intervalLineStyle = LineStyle.getInstance(data[offset + 5]);\n Color intervalLineColor = ColorType.getInstance(data[offset + 6]).getColor();\n return new GridLines(normalLineColor, normalLineStyle, intervalNumber, intervalLineStyle, intervalLineColor);\n }", "public com.cloudant.client.api.model.ReplicationResult trigger() {\r\n ReplicationResult couchDbReplicationResult = replication.trigger();\r\n com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant\r\n .client.api.model.ReplicationResult(couchDbReplicationResult);\r\n return replicationResult;\r\n }", "@Override\n public String getName() {\n CommonProfile profile = this.getProfile();\n if(null == principalNameAttribute) {\n return profile.getId();\n }\n Object attrValue = profile.getAttribute(principalNameAttribute);\n return (null == attrValue) ? null : String.valueOf(attrValue);\n }", "private void countKey(Map<String, Integer> map, String key, int count) {\n\t\tif (map.containsKey(key)) {\n\t\t\tmap.put(key, map.get(key) + count);\n\t\t} else {\n\t\t\tmap.put(key, count);\n\t\t}\n\t}", "protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n long result;\r\n // lookup sequence name\r\n String sequenceName = calculateSequenceName(field);\r\n try\r\n {\r\n result = buildNextSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Throwable e)\r\n {\r\n // maybe the sequence was not created\r\n try\r\n {\r\n log.info(\"Create DB sequence key '\"+sequenceName+\"'\");\r\n createSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Exception e1)\r\n {\r\n throw new SequenceManagerException(\r\n SystemUtils.LINE_SEPARATOR +\r\n \"Could not grab next id, failed with \" + SystemUtils.LINE_SEPARATOR +\r\n e.getMessage() + SystemUtils.LINE_SEPARATOR +\r\n \"Creation of new sequence failed with \" +\r\n SystemUtils.LINE_SEPARATOR + e1.getMessage() + SystemUtils.LINE_SEPARATOR\r\n , e1);\r\n }\r\n try\r\n {\r\n result = buildNextSequence(field.getClassDescriptor(), sequenceName);\r\n }\r\n catch (Throwable e1)\r\n {\r\n throw new SequenceManagerException(\"Could not grab next id, sequence seems to exist\", e);\r\n }\r\n }\r\n return result;\r\n }", "public static void writeHints(File file, Map<String,List<Long>> hints) throws IOException {\n Closer closer = Closer.create();\n try {\n BufferedWriter w = closer.register(Files.newWriter(file, Charsets.UTF_8));\n if (!(hints instanceof SortedMap)) {\n hints = new TreeMap<String,List<Long>>(hints);\n }\n \n Joiner joiner = Joiner.on(',');\n for (Map.Entry<String,List<Long>> e : hints.entrySet()) {\n w.write(e.getKey());\n w.write(\"=\");\n joiner.appendTo(w, e.getValue());\n w.write(\"\\n\");\n }\n } catch (Throwable t) {\n throw closer.rethrow(t);\n } finally {\n closer.close();\n }\n }", "private long recover() throws IOException {\n checkMutable();\n long len = channel.size();\n ByteBuffer buffer = ByteBuffer.allocate(4);\n long validUpTo = 0;\n long next = 0L;\n do {\n next = validateMessage(channel, validUpTo, len, buffer);\n if (next >= 0) validUpTo = next;\n } while (next >= 0);\n channel.truncate(validUpTo);\n setSize.set(validUpTo);\n setHighWaterMark.set(validUpTo);\n logger.info(\"recover high water mark:\" + highWaterMark());\n /* This should not be necessary, but fixes bug 6191269 on some OSs. */\n channel.position(validUpTo);\n needRecover.set(false);\n return len - validUpTo;\n }", "static InstalledIdentity load(final InstalledImage image, final ProductConfig productConfig, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n\n // build the identity information\n final String productVersion = productConfig.resolveVersion();\n final String productName = productConfig.resolveName();\n final Identity identity = new AbstractLazyIdentity() {\n @Override\n public String getName() {\n return productName;\n }\n\n @Override\n public String getVersion() {\n return productVersion;\n }\n\n @Override\n public InstalledImage getInstalledImage() {\n return image;\n }\n };\n\n final Properties properties = PatchUtils.loadProperties(identity.getDirectoryStructure().getInstallationInfo());\n final List<String> allPatches = PatchUtils.readRefs(properties, Constants.ALL_PATCHES);\n\n // Step 1 - gather the installed layers data\n final InstalledConfiguration conf = createInstalledConfig(image);\n // Step 2 - process the actual module and bundle roots\n final ProcessedLayers processedLayers = process(conf, moduleRoots, bundleRoots);\n final InstalledConfiguration config = processedLayers.getConf();\n\n // Step 3 - create the actual config objects\n // Process layers\n final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl(identity, allPatches, image);\n for (final LayerPathConfig layer : processedLayers.getLayers().values()) {\n final String name = layer.name;\n installedIdentity.putLayer(name, createPatchableTarget(name, layer, config.getLayerMetadataDir(name), image));\n }\n // Process add-ons\n for (final LayerPathConfig addOn : processedLayers.getAddOns().values()) {\n final String name = addOn.name;\n installedIdentity.putAddOn(name, createPatchableTarget(name, addOn, config.getAddOnMetadataDir(name), image));\n }\n return installedIdentity;\n }" ]
Specify the string and the int identifying which word shaper to use and this returns the result of using that wordshaper on the String. @param inStr String to calculate word shape of @param wordShaper Constant for which shaping formula to use @param knownLCWords A Collection of known lowercase words, which some shapers use to decide the class of capitalized words. <i>Note: while this code works with any Collection, you should provide a Set for decent performance.</i> If this parameter is null or empty, then this option is not used (capitalized words are treated the same, regardless of whether the lowercased version of the String has been seen). @return The wordshape String
[ "public static String wordShape(String inStr, int wordShaper, Collection<String> knownLCWords) {\r\n // this first bit is for backwards compatibility with how things were first\r\n // implemented, where the word shaper name encodes whether to useLC.\r\n // If the shaper is in the old compatibility list, then a specified\r\n // list of knownLCwords is ignored\r\n if (knownLCWords != null && dontUseLC(wordShaper)) {\r\n knownLCWords = null;\r\n }\r\n switch (wordShaper) {\r\n case NOWORDSHAPE:\r\n return inStr;\r\n case WORDSHAPEDAN1:\r\n return wordShapeDan1(inStr);\r\n case WORDSHAPECHRIS1:\r\n return wordShapeChris1(inStr);\r\n case WORDSHAPEDAN2:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2USELC:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIO:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIOUSELC:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1USELC:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPECHRIS2:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS2USELC:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS3:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS3USELC:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS4:\r\n return wordShapeChris4(inStr, false, knownLCWords);\r\n case WORDSHAPEDIGITS:\r\n return wordShapeDigits(inStr);\r\n default:\r\n throw new IllegalStateException(\"Bad WordShapeClassifier\");\r\n }\r\n }" ]
[ "public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {\n\n final Set<String> keys = request.keys();\n if (keys.size() == 2) { // no props\n return null;\n }\n ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE);\n if (outcome == null) {\n outcome = retrieveDescription(ctx, request, true);\n if (outcome == null) {\n return null;\n } else {\n ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome);\n }\n }\n if(!outcome.has(Util.RESULT)) {\n throw new CommandFormatException(\"Failed to perform \" + Util.READ_OPERATION_DESCRIPTION + \" to validate the request: result is not available.\");\n }\n\n final String operationName = request.get(Util.OPERATION).asString();\n\n final ModelNode result = outcome.get(Util.RESULT);\n final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet();\n if(definedProps.isEmpty()) {\n if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) {\n throw new CommandFormatException(\"Operation '\" + operationName + \"' does not expect any property.\");\n }\n } else {\n int skipped = 0;\n for(String prop : keys) {\n if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) {\n ++skipped;\n continue;\n }\n if(!definedProps.contains(prop)) {\n if(!Util.OPERATION_HEADERS.equals(prop)) {\n throw new CommandFormatException(\"'\" + prop + \"' is not found among the supported properties: \" + definedProps);\n }\n }\n }\n }\n return outcome;\n }", "public static sslciphersuite[] get(nitro_service service, options option) throws Exception{\n\t\tsslciphersuite obj = new sslciphersuite();\n\t\tsslciphersuite[] response = (sslciphersuite[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public void propagateAsErrorIfCancelException(final Throwable t) {\n if ((t instanceof OperationCanceledError)) {\n throw ((OperationCanceledError)t);\n }\n final RuntimeException opCanceledException = this.getPlatformOperationCanceledException(t);\n if ((opCanceledException != null)) {\n throw new OperationCanceledError(opCanceledException);\n }\n }", "private boolean keyAlreadyExists(String newKey) {\n\n Collection<?> itemIds = m_table.getItemIds();\n for (Object itemId : itemIds) {\n if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {\n return true;\n }\n }\n return false;\n }", "public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }", "public static<A, B, C, D, Z> Function4<A, B, C, D, Z> lift(Func4<A, B, C, D, Z> f) {\n\treturn bridge.lift(f);\n }", "public void setControllerModel(GVRSceneObject controllerModel)\n {\n if (mControllerModel != null)\n {\n mControllerGroup.removeChildObject(mControllerModel);\n }\n mControllerModel = controllerModel;\n mControllerGroup.addChildObject(mControllerModel);\n mControllerModel.setEnable(mShowControllerModel);\n }", "public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid);\n return resp.getData();\n }", "protected void processAssignmentBaseline(Row row)\n {\n Integer id = row.getInteger(\"ASSN_UID\");\n ResourceAssignment assignment = m_assignmentMap.get(id);\n if (assignment != null)\n {\n int index = row.getInt(\"AB_BASE_NUM\");\n\n assignment.setBaselineStart(index, row.getDate(\"AB_BASE_START\"));\n assignment.setBaselineFinish(index, row.getDate(\"AB_BASE_FINISH\"));\n assignment.setBaselineWork(index, row.getDuration(\"AB_BASE_WORK\"));\n assignment.setBaselineCost(index, row.getCurrency(\"AB_BASE_COST\"));\n }\n }" ]
Handle a "current till end" change event. @param event the change event.
[ "@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\n }\n }" ]
[ "public static String getPrefixFromValue(String value) {\n if (value == null) {\n return null;\n } else if (value.contains(DELIMITER)) {\n String[] list = value.split(DELIMITER);\n if (list != null && list.length > 0) {\n return list[0].replaceAll(\"\\u0000\", \"\");\n } else {\n return null;\n }\n } else {\n return value.replaceAll(\"\\u0000\", \"\");\n }\n }", "public void setAccordion(boolean accordion) {\n getElement().setAttribute(\"data-collapsible\", accordion ? CssName.ACCORDION : CssName.EXPANDABLE);\n reload();\n }", "public Permissions 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\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 Element permissionsElement = response.getPayload();\r\n Permissions permissions = new Permissions();\r\n permissions.setId(permissionsElement.getAttribute(\"id\"));\r\n permissions.setPublicFlag(\"1\".equals(permissionsElement.getAttribute(\"ispublic\")));\r\n permissions.setFamilyFlag(\"1\".equals(permissionsElement.getAttribute(\"isfamily\")));\r\n permissions.setFriendFlag(\"1\".equals(permissionsElement.getAttribute(\"isfriend\")));\r\n permissions.setComment(permissionsElement.getAttribute(\"permcomment\"));\r\n permissions.setAddmeta(permissionsElement.getAttribute(\"permaddmeta\"));\r\n return permissions;\r\n }", "public static int[] binaryToRgb(boolean[] binaryArray) {\n int[] rgbArray = new int[binaryArray.length];\n\n for (int i = 0; i < binaryArray.length; i++) {\n if (binaryArray[i]) {\n rgbArray[i] = 0x00000000;\n } else {\n rgbArray[i] = 0x00FFFFFF;\n }\n }\n return rgbArray;\n }", "public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }", "public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }", "public static final String getSelectedText(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getItemText(index) : null;\n }", "@SuppressWarnings(\"WeakerAccess\")\n public int getPlayerDBServerPort(int player) {\n ensureRunning();\n Integer result = dbServerPorts.get(player);\n if (result == null) {\n return -1;\n }\n return result;\n }", "public Record findRecordById(String id) {\n if (directory == null)\n init();\n\n Property idprop = config.getIdentityProperties().iterator().next();\n for (Record r : lookup(idprop, id))\n if (r.getValue(idprop.getName()).equals(id))\n return r;\n\n return null; // not found\n }" ]
Indicates if this file represents a file on the underlying file system. @param filePath @return
[ "public static boolean isFileExist(String filePath) {\r\n if (StringUtils.isEmpty(filePath)) {\r\n return false;\r\n }\r\n\r\n File file = new File(filePath);\r\n return (file.exists() && file.isFile());\r\n }" ]
[ "public static void checkFloatNotNaNOrInfinity(String parameterName,\n float data) {\n if (Float.isNaN(data) || Float.isInfinite(data)) {\n throw Exceptions.IllegalArgument(\n \"%s should never be NaN or Infinite.\", parameterName);\n }\n }", "public static tmglobal_binding get(nitro_service service) throws Exception{\n\t\ttmglobal_binding obj = new tmglobal_binding();\n\t\ttmglobal_binding response = (tmglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public List<GanttDesignerRemark.Task> getTask()\n {\n if (task == null)\n {\n task = new ArrayList<GanttDesignerRemark.Task>();\n }\n return this.task;\n }", "public List<Module> getModules(final Map<String, String> filters) throws GrapesCommunicationException {\n final Client client = getClient();\n WebResource resource = client.resource(serverURL).path(RequestUtils.getAllModulesPath());\n for(final Map.Entry<String,String> queryParam: filters.entrySet()){\n resource = resource.queryParam(queryParam.getKey(), queryParam.getValue());\n }\n\n final ClientResponse response = resource.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 filtered modules.\";\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(new GenericType<List<Module>>(){});\n }", "private void fireEventForNonWebModules(Type eventType, Object event, Annotation... qualifiers) {\n try {\n BeanDeploymentModules modules = deploymentManager.getServices().get(BeanDeploymentModules.class);\n if (modules != null) {\n // fire event for non-web modules\n // web modules are handled by HttpContextLifecycle\n for (BeanDeploymentModule module : modules) {\n if (!module.isWebModule()) {\n module.fireEvent(eventType, event, qualifiers);\n }\n }\n }\n } catch (Exception ignored) {\n }\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 }", "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 }", "public void loadClass(String className) throws Exception {\n ClassInformation classInfo = classInformation.get(className);\n\n logger.info(\"Loading plugin.: {}, {}\", className, classInfo.pluginPath);\n\n // get URL for proxylib\n // need to load this also otherwise the annotations cannot be found later on\n File libFile = new File(proxyLibPath);\n URL libUrl = libFile.toURI().toURL();\n\n // store the last modified time of the plugin\n File pluginDirectoryFile = new File(classInfo.pluginPath);\n classInfo.lastModified = pluginDirectoryFile.lastModified();\n\n // load the plugin directory\n URL classURL = new File(classInfo.pluginPath).toURI().toURL();\n\n URL[] urls = new URL[] {classURL};\n URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());\n\n // load the class\n Class<?> cls = child.loadClass(className);\n\n // put loaded class into classInfo\n classInfo.loadedClass = cls;\n classInfo.loaded = true;\n\n classInformation.put(className, classInfo);\n\n logger.info(\"Loaded plugin: {}, {} method(s)\", cls.toString(), cls.getDeclaredMethods().length);\n }", "public static vpnsessionpolicy_aaauser_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionpolicy_aaauser_binding obj = new vpnsessionpolicy_aaauser_binding();\n\t\tobj.set_name(name);\n\t\tvpnsessionpolicy_aaauser_binding response[] = (vpnsessionpolicy_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Retrieve the value of a UDF. @param udf UDF value holder @return UDF value
[ "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 }" ]
[ "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }", "private Integer mapTaskID(Integer id)\n {\n Integer mappedID = m_clashMap.get(id);\n if (mappedID == null)\n {\n mappedID = id;\n }\n return (mappedID);\n }", "public void update(Object feature) throws LayerException {\n\t\tSession session = getSessionFactory().getCurrentSession();\n\t\tsession.update(feature);\n\t}", "@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }", "public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\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 }", "public void linkOneToOne(Object obj, ClassDescriptor cld, ObjectReferenceDescriptor rds, boolean insert)\n {\n storeAndLinkOneToOne(true, obj, cld, rds, true);\n }", "public void setWriteTimeout(int writeTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n m_project.getProjectProperties().setFileApplication(\"Synchro\");\n m_project.getProjectProperties().setFileType(\"SP\");\n\n CustomFieldContainer fields = m_project.getCustomFields();\n fields.getCustomField(TaskField.TEXT1).setAlias(\"Code\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n processCalendars();\n processResources();\n processTasks();\n processPredecessors();\n\n return m_project;\n }" ]
Add a console pipeline to the Redwood handler tree, printing to stdout. Calling this multiple times will result in messages being printed multiple times. @return this
[ "public RedwoodConfiguration stdout(){\r\n LogRecordHandler visibility = new VisibilityHandler();\r\n LogRecordHandler console = Redwood.ConsoleHandler.out();\r\n return this\r\n .rootHandler(visibility)\r\n .handler(visibility, console);\r\n }" ]
[ "private void readCalendars()\n {\n Table cal = m_tables.get(\"CAL\");\n for (MapRow row : cal)\n {\n ProjectCalendar calendar = m_projectFile.addCalendar();\n m_calendarMap.put(row.getInteger(\"CALENDAR_ID\"), calendar);\n Integer[] days =\n {\n row.getInteger(\"SUNDAY_HOURS\"),\n row.getInteger(\"MONDAY_HOURS\"),\n row.getInteger(\"TUESDAY_HOURS\"),\n row.getInteger(\"WEDNESDAY_HOURS\"),\n row.getInteger(\"THURSDAY_HOURS\"),\n row.getInteger(\"FRIDAY_HOURS\"),\n row.getInteger(\"SATURDAY_HOURS\")\n };\n\n calendar.setName(row.getString(\"NAME\"));\n readHours(calendar, Day.SUNDAY, days[0]);\n readHours(calendar, Day.MONDAY, days[1]);\n readHours(calendar, Day.TUESDAY, days[2]);\n readHours(calendar, Day.WEDNESDAY, days[3]);\n readHours(calendar, Day.THURSDAY, days[4]);\n readHours(calendar, Day.FRIDAY, days[5]);\n readHours(calendar, Day.SATURDAY, days[6]);\n\n int workingDaysPerWeek = 0;\n for (Day day : Day.values())\n {\n if (calendar.isWorkingDay(day))\n {\n ++workingDaysPerWeek;\n }\n }\n\n Integer workingHours = null;\n for (int index = 0; index < 7; index++)\n {\n if (days[index].intValue() != 0)\n {\n workingHours = days[index];\n break;\n }\n }\n\n if (workingHours != null)\n {\n int workingHoursPerDay = countHours(workingHours);\n int minutesPerDay = workingHoursPerDay * 60;\n int minutesPerWeek = minutesPerDay * workingDaysPerWeek;\n int minutesPerMonth = 4 * minutesPerWeek;\n int minutesPerYear = 52 * minutesPerWeek;\n\n calendar.setMinutesPerDay(Integer.valueOf(minutesPerDay));\n calendar.setMinutesPerWeek(Integer.valueOf(minutesPerWeek));\n calendar.setMinutesPerMonth(Integer.valueOf(minutesPerMonth));\n calendar.setMinutesPerYear(Integer.valueOf(minutesPerYear));\n }\n }\n }", "public final SimpleFeatureCollection treatStringAsURL(final Template template, final String geoJsonUrl)\n throws IOException {\n URL url;\n try {\n url = FileUtils.testForLegalFileUrl(template.getConfiguration(), new URL(geoJsonUrl));\n } catch (MalformedURLException e) {\n return null;\n }\n\n final String geojsonString;\n if (url.getProtocol().equalsIgnoreCase(\"file\")) {\n geojsonString = IOUtils.toString(url, Constants.DEFAULT_CHARSET.name());\n } else {\n geojsonString = URIUtils.toString(this.httpRequestFactory, url);\n }\n\n return treatStringAsGeoJson(geojsonString);\n }", "private void initializeQueue() {\n this.queue.clear();\n for (Map.Entry<String, NodeT> entry: nodeTable.entrySet()) {\n if (!entry.getValue().hasDependencies()) {\n this.queue.add(entry.getKey());\n }\n }\n if (queue.isEmpty()) {\n throw new IllegalStateException(\"Detected circular dependency\");\n }\n }", "public Token add( Variable variable ) {\n Token t = new Token(variable);\n push( t );\n return t;\n }", "public StringBuilder getSQLCondition(StringBuilder builder, String columnName) {\n\t\tString string = networkString.getString();\n\t\tif(isEntireAddress) {\n\t\t\tmatchString(builder, columnName, string);\n\t\t} else {\n\t\t\tmatchSubString(\n\t\t\t\t\tbuilder,\n\t\t\t\t\tcolumnName,\n\t\t\t\t\tnetworkString.getTrailingSegmentSeparator(),\n\t\t\t\t\tnetworkString.getTrailingSeparatorCount() + 1,\n\t\t\t\t\tstring);\n\t\t}\n\t\treturn builder;\n\t}", "public void onDrawerOpened(View drawerView) {\n super.onDrawerOpened(drawerView);\n if (listener != null) listener.onDrawerClosed(drawerView);\n }", "public static int cudnnBatchNormalizationBackward(\n cudnnHandle handle, \n int mode, \n Pointer alphaDataDiff, \n Pointer betaDataDiff, \n Pointer alphaParamDiff, \n Pointer betaParamDiff, \n cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */\n Pointer x, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor dxDesc, \n Pointer dx, \n /** Shared tensor desc for the 4 tensors below */\n cudnnTensorDescriptor dBnScaleBiasDesc, \n Pointer bnScale, /** bnBias doesn't affect backpropagation */\n /** scale and bias diff are not backpropagated below this layer */\n Pointer dBnScaleResult, \n Pointer dBnBiasResult, \n /** Same epsilon as forward pass */\n double epsilon, \n /** Optionally cached intermediate results from\n forward pass */\n Pointer savedMean, \n Pointer savedInvVariance)\n {\n return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageUnreadCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.unreadCount();\n } else {\n getConfigLogger().debug(getAccountId(), \"Notification Inbox not initialized\");\n return -1;\n }\n }\n }", "public static base_response reset(nitro_service client, Interface resource) throws Exception {\n\t\tInterface resetresource = new Interface();\n\t\tresetresource.id = resource.id;\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}" ]
Check whether the URL contains one of the patterns. @param uri URI @param patterns possible patterns @return true when URL contains one of the patterns
[ "public boolean checkContains(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.contains(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}" ]
[ "private void checkAllEnvelopes(PersistenceBroker broker)\r\n {\r\n Iterator iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n // only non transient objects should be performed\r\n if(!mod.getModificationState().isTransient())\r\n {\r\n mod.markReferenceElements(broker);\r\n }\r\n }\r\n }", "static <K, V> ViewQueryParameters<K, V> forwardPaginationQueryParameters\n (ViewQueryParameters<K, V> initialQueryParameters, K startkey, String startkey_docid) {\n\n // Copy the initial query parameters\n ViewQueryParameters<K, V> pageParameters = initialQueryParameters.copy();\n\n // Now override with the start keys provided\n pageParameters.setStartKey(startkey);\n pageParameters.setStartKeyDocId(startkey_docid);\n\n return pageParameters;\n }", "public long indexOf(final String element) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return doIndexOf(jedis, element);\n }\n });\n }", "public String getPermalinkForCurrentPage(CmsObject cms) {\n\n return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId());\n }", "public static String getContent(String stringUrl) throws IOException {\n InputStream stream = getContentStream(stringUrl);\n return MyStreamUtils.readContent(stream);\n }", "public static base_responses add(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice addresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbservice();\n\t\t\t\taddresources[i].servicename = resources[i].servicename;\n\t\t\t\taddresources[i].cnameentry = resources[i].cnameentry;\n\t\t\t\taddresources[i].ip = resources[i].ip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].servicetype = resources[i].servicetype;\n\t\t\t\taddresources[i].port = resources[i].port;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].publicport = resources[i].publicport;\n\t\t\t\taddresources[i].maxclient = resources[i].maxclient;\n\t\t\t\taddresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].cip = resources[i].cip;\n\t\t\t\taddresources[i].cipheader = resources[i].cipheader;\n\t\t\t\taddresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\taddresources[i].cookietimeout = resources[i].cookietimeout;\n\t\t\t\taddresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\taddresources[i].clttimeout = resources[i].clttimeout;\n\t\t\t\taddresources[i].svrtimeout = resources[i].svrtimeout;\n\t\t\t\taddresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\taddresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\taddresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\taddresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\taddresources[i].hashid = resources[i].hashid;\n\t\t\t\taddresources[i].comment = resources[i].comment;\n\t\t\t\taddresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "@UiHandler(\"m_atNumber\")\r\n void onWeekOfMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekOfMonth(event.getValue());\r\n }\r\n }", "protected void init(EnhancedAnnotation<T> annotatedAnnotation) {\n initType(annotatedAnnotation);\n initValid(annotatedAnnotation);\n check(annotatedAnnotation);\n }", "private void deleteLinks(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final LinksTable links = getLinksTable(txn, entityTypeId);\n final IntHashSet deletedLinks = new IntHashSet();\n try (Cursor cursor = links.getFirstIndexCursor(envTxn)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, 0))) != null;\n success; success = cursor.getNext()) {\n final ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final ByteIterable valueEntry = cursor.getValue();\n if (links.delete(envTxn, keyEntry, valueEntry)) {\n int linkId = key.getPropertyId();\n if (getLinkName(txn, linkId) != null) {\n deletedLinks.add(linkId);\n final LinkValue linkValue = LinkValue.entryToLinkValue(valueEntry);\n txn.linkDeleted(entity.getId(), (PersistentEntityId) linkValue.getEntityId(), linkValue.getLinkId());\n }\n }\n }\n }\n for (Integer linkId : deletedLinks) {\n links.deleteAllIndex(envTxn, linkId, entityLocalId);\n }\n }" ]
Replaces an existing metadata value. @param path the path that designates the key. Must be prefixed with a "/". @param value the value. @return this metadata object.
[ "public Metadata replace(String path, String value) {\n this.values.set(this.pathToProperty(path), value);\n this.addOp(\"replace\", path, value);\n return this;\n }" ]
[ "private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\n }", "public ModelNode buildRequest() throws OperationFormatException {\n\n ModelNode address = request.get(Util.ADDRESS);\n if(prefix.isEmpty()) {\n address.setEmptyList();\n } else {\n Iterator<Node> iterator = prefix.iterator();\n while (iterator.hasNext()) {\n OperationRequestAddress.Node node = iterator.next();\n if (node.getName() != null) {\n address.add(node.getType(), node.getName());\n } else if (iterator.hasNext()) {\n throw new OperationFormatException(\n \"The node name is not specified for type '\"\n + node.getType() + \"'\");\n }\n }\n }\n\n if(!request.hasDefined(Util.OPERATION)) {\n throw new OperationFormatException(\"The operation name is missing or the format of the operation request is wrong.\");\n }\n\n return request;\n }", "public static String getPrefixFromValue(String value) {\n if (value == null) {\n return null;\n } else if (value.contains(DELIMITER)) {\n String[] list = value.split(DELIMITER);\n if (list != null && list.length > 0) {\n return list[0].replaceAll(\"\\u0000\", \"\");\n } else {\n return null;\n }\n } else {\n return value.replaceAll(\"\\u0000\", \"\");\n }\n }", "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 }", "public void addHandlerFactory(ManagementRequestHandlerFactory factory) {\n for (;;) {\n final ManagementRequestHandlerFactory[] snapshot = updater.get(this);\n final int length = snapshot.length;\n final ManagementRequestHandlerFactory[] newVal = new ManagementRequestHandlerFactory[length + 1];\n System.arraycopy(snapshot, 0, newVal, 0, length);\n newVal[length] = factory;\n if (updater.compareAndSet(this, snapshot, newVal)) {\n return;\n }\n }\n }", "@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }", "public static <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException {\n return InterconnectMapper.mapper.readValue(data, clazz);\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}", "public void set(float val, Layout.Axis axis) {\n switch (axis) {\n case X:\n x = val;\n break;\n case Y:\n y = val;\n break;\n case Z:\n z = val;\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }" ]
Method indicating whether a day is a working or non-working day. @param day required day @return true if this is a working day
[ "public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\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 Statement open(String jndiPath) {\n try {\n Context ctx = new InitialContext();\n DataSource ds = (DataSource) ctx.lookup(jndiPath);\n Connection conn = ds.getConnection();\n return conn.createStatement();\n } catch (NamingException e) {\n throw new DukeException(\"No database configuration found via JNDI at \" +\n jndiPath, e);\n } catch (SQLException e) {\n throw new DukeException(\"Error connecting to database via \" +\n jndiPath, e);\n }\n }", "public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }", "void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }", "public static sslcipher_individualcipher_binding[] get_filtered(nitro_service service, String ciphergroupname, filtervalue[] filter) throws Exception{\n\t\tsslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslcipher_individualcipher_binding[] response = (sslcipher_individualcipher_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "private ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }", "private static void setCmsOfflineProject(CmsObject cms) {\n\n if (null == cms) {\n return;\n }\n\n final CmsRequestContext cmsContext = cms.getRequestContext();\n final CmsProject cmsProject = cmsContext.getCurrentProject();\n\n if (cmsProject.isOnlineProject()) {\n CmsProject cmsOfflineProject;\n try {\n cmsOfflineProject = cms.readProject(\"Offline\");\n cmsContext.setCurrentProject(cmsOfflineProject);\n } catch (CmsException e) {\n LOG.warn(\"Could not set the current project to \\\"Offline\\\". \");\n }\n }\n }", "protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }", "private FieldDescriptorDef cloneField(FieldDescriptorDef fieldDef, String prefix)\r\n {\r\n FieldDescriptorDef copyFieldDef = new FieldDescriptorDef(fieldDef, prefix);\r\n\r\n copyFieldDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyFieldDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyFieldDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included field \"+\r\n copyFieldDef.getName()+\" from class \"+fieldDef.getOwner().getName()); \r\n }\r\n copyFieldDef.applyModifications(mod);\r\n }\r\n return copyFieldDef;\r\n }" ]
Retrieves state and metrics information for all client connections across the cluster. @return list of connections across the cluster
[ "public List<ConnectionInfo> getConnections() {\n final URI uri = uriWithPath(\"./connections/\");\n return Arrays.asList(this.rt.getForObject(uri, ConnectionInfo[].class));\n }" ]
[ "public Integer getNodesPartitionIdForKey(int nodeId, final byte[] key) {\n // this is all the partitions the key replicates to.\n List<Integer> partitionIds = getReplicatingPartitionList(key);\n for(Integer partitionId: partitionIds) {\n // check which of the replicating partitions belongs to the node in\n // question\n if(getNodeIdForPartitionId(partitionId) == nodeId) {\n return partitionId;\n }\n }\n return null;\n }", "public static Class<?> resolveReturnType(Method method, Class<?> clazz) {\n\t\tAssert.notNull(method, \"Method must not be null\");\n\t\tType genericType = method.getGenericReturnType();\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tMap<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);\n\t\tType rawType = getRawType(genericType, typeVariableMap);\n\t\treturn (rawType instanceof Class ? (Class<?>) rawType : method.getReturnType());\n\t}", "protected Object checkUndefined(Object val) {\n if (val instanceof String && ((String) val).equals(\"undefined\")) {\n return null;\n }\n return val;\n }", "public void printAnswers(List<CoreLabel> doc, PrintWriter out) {\r\n // boolean tagsMerged = flags.mergeTags;\r\n // boolean useHead = flags.splitOnHead;\r\n\r\n if ( ! \"iob1\".equalsIgnoreCase(flags.entitySubclassification)) {\r\n deEndify(doc);\r\n }\r\n\r\n for (CoreLabel fl : doc) {\r\n String word = fl.word();\r\n if (word == BOUNDARY) { // Using == is okay, because it is set to constant\r\n out.println();\r\n } else {\r\n String gold = fl.get(OriginalAnswerAnnotation.class);\r\n if(gold == null) gold = \"\";\r\n String guess = fl.get(AnswerAnnotation.class);\r\n // System.err.println(fl.word() + \"\\t\" + fl.get(AnswerAnnotation.class) + \"\\t\" + fl.get(AnswerAnnotation.class));\r\n String pos = fl.tag();\r\n String chunk = (fl.get(ChunkAnnotation.class) == null ? \"\" : fl.get(ChunkAnnotation.class));\r\n out.println(fl.word() + '\\t' + pos + '\\t' + chunk + '\\t' +\r\n gold + '\\t' + guess);\r\n }\r\n }\r\n }", "public static cmppolicy_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tcmppolicy_stats[] response = (cmppolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public Object newInstance(String resource) {\n try {\n String name = resource.startsWith(\"/\") ? resource : \"/\" + resource;\n File file = new File(this.getClass().getResource(name).toURI());\n return newInstance(classLoader.parseClass(new GroovyCodeSource(file), true));\n } catch (Exception e) {\n throw new GroovyClassInstantiationFailed(classLoader, resource, e);\n }\n }", "public List<T> parseList(JsonParser jsonParser) throws IOException {\n List<T> list = new ArrayList<>();\n if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n list.add(parse(jsonParser));\n }\n }\n return list;\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 }", "public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){\n\t\t\tdouble minDistance = Double.MAX_VALUE;\n\t\t\tPoint2D.Double minDistancePoint = null;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/nPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < nPointsPerSegment; j++){\n\t\t \t\tPoint2D.Double candidate = new Point2D.Double(x, spline.value(x));\n\t\t \t\tdouble d = p.distance(candidate);\n\t\t \t\tif(d<minDistance){\n\t\t \t\t\tminDistance = d;\n\t\t \t\t\tminDistancePoint = candidate;\n\t\t \t\t}\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t return minDistancePoint;\n\t}" ]
Starts given docker machine. @param cliPathExec location of docker-machine or null if it is on PATH. @param machineName to be started.
[ "public void startDockerMachine(String cliPathExec, String machineName) {\n commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec), \"start\", machineName);\n this.manuallyStarted = true;\n }" ]
[ "public boolean isWorkingDate(Date date)\n {\n Calendar cal = DateHelper.popCalendar(date);\n Day day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n DateHelper.pushCalendar(cal);\n return isWorkingDate(date, day);\n }", "public void setSessionFactory(SessionFactory sessionFactory) throws HibernateLayerException {\n\t\ttry {\n\t\t\tthis.sessionFactory = sessionFactory;\n\t\t\tif (null != layerInfo) {\n\t\t\t\tentityMetadata = sessionFactory.getClassMetadata(layerInfo.getFeatureInfo().getDataSourceName());\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_NO_SESSION_FACTORY);\n\t\t}\n\t}", "private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }", "synchronized ArrayList<CTMessageDAO> getMessages(String userId){\n final String tName = Table.INBOX_MESSAGES.getName();\n Cursor cursor;\n ArrayList<CTMessageDAO> messageDAOArrayList = new ArrayList<>();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n cursor= db.rawQuery(\"SELECT * FROM \"+tName+\" WHERE \" + USER_ID + \" = ? ORDER BY \" + KEY_CREATED_AT+ \" DESC\", new String[]{userId});\n if(cursor != null) {\n while(cursor.moveToNext()){\n CTMessageDAO ctMessageDAO = new CTMessageDAO();\n ctMessageDAO.setId(cursor.getString(cursor.getColumnIndex(_ID)));\n ctMessageDAO.setJsonData(new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA))));\n ctMessageDAO.setWzrkParams(new JSONObject(cursor.getString(cursor.getColumnIndex(WZRKPARAMS))));\n ctMessageDAO.setDate(cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT)));\n ctMessageDAO.setExpires(cursor.getLong(cursor.getColumnIndex(EXPIRES)));\n ctMessageDAO.setRead(cursor.getInt(cursor.getColumnIndex(IS_READ)));\n ctMessageDAO.setUserId(cursor.getString(cursor.getColumnIndex(USER_ID)));\n ctMessageDAO.setTags(cursor.getString(cursor.getColumnIndex(TAGS)));\n ctMessageDAO.setCampaignId(cursor.getString(cursor.getColumnIndex(CAMPAIGN)));\n messageDAOArrayList.add(ctMessageDAO);\n }\n cursor.close();\n }\n return messageDAOArrayList;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e);\n return null;\n } catch (JSONException e) {\n getConfigLogger().verbose(\"Error retrieving records from \" + tName, e.getMessage());\n return null;\n } finally {\n dbHelper.close();\n }\n }", "public static void columnMaxAbs( DMatrixSparseCSC A , double []values ) {\n if( values.length < A.numCols )\n throw new IllegalArgumentException(\"Array is too small. \"+values.length+\" < \"+A.numCols);\n\n for (int i = 0; i < A.numCols; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n double maxabs = 0;\n for (int j = idx0; j < idx1; j++) {\n double v = Math.abs(A.nz_values[j]);\n if( v > maxabs )\n maxabs = v;\n }\n values[i] = maxabs;\n }\n }", "public String getUncPath() {\n getUncPath0();\n if( share == null ) {\n return \"\\\\\\\\\" + url.getHost();\n }\n return \"\\\\\\\\\" + url.getHost() + canon.replace( '/', '\\\\' );\n }", "public static void removeColumns( DMatrixRMaj A , int col0 , int col1 )\n {\n if( col1 < col0 ) {\n throw new IllegalArgumentException(\"col1 must be >= col0\");\n } else if( col0 >= A.numCols || col1 >= A.numCols ) {\n throw new IllegalArgumentException(\"Columns which are to be removed must be in bounds\");\n }\n\n int step = col1-col0+1;\n int offset = 0;\n for (int row = 0, idx=0; row < A.numRows; row++) {\n for (int i = 0; i < col0; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n offset += step;\n for (int i = col1+1; i < A.numCols; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n }\n A.numCols -= step;\n }", "private void updateLetsEncrypt() {\n\n getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0));\n\n CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig();\n if ((config == null) || !config.isValidAndEnabled()) {\n return;\n }\n CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config);\n boolean ok = converter.run(getReport(), OpenCms.getSiteManager());\n if (ok) {\n getReport().println(\n org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0),\n I_CmsReport.FORMAT_OK);\n }\n\n }", "public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\n }" ]
Helper method that stores in a hash map how often a certain key occurs. If the key has not been encountered yet, a new entry is created for it in the map. Otherwise the existing value for the key is incremented. @param map the map where the counts are stored @param key the key to be counted @param count value by which the count should be incremented; 1 is the usual case
[ "private void countKey(Map<String, Integer> map, String key, int count) {\n\t\tif (map.containsKey(key)) {\n\t\t\tmap.put(key, map.get(key) + count);\n\t\t} else {\n\t\t\tmap.put(key, count);\n\t\t}\n\t}" ]
[ "public void propagateIfCancelException(final Throwable t) {\n final RuntimeException cancelException = this.getPlatformOperationCanceledException(t);\n if ((cancelException != null)) {\n throw cancelException;\n }\n }", "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public Map<Integer, RandomVariable> getGradient(){\r\n\r\n\t\tint numberOfCalculationSteps = getFunctionList().size();\r\n\r\n\t\tRandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\tomegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\tfor(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){\r\n\r\n\t\t\tomegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\tArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();\r\n\r\n\t\t\tfor(int functionIndex:childrenList){\r\n\t\t\t\tRandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);\r\n\t\t\t\tomegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();\r\n\r\n\t\tMap<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>();\r\n\r\n\t\tfor(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){\r\n\t\t\tgradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}", "public static final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }", "protected void addArguments(FieldDescriptor field[])\r\n {\r\n for (int i = 0; i < field.length; i++)\r\n {\r\n ArgumentDescriptor arg = new ArgumentDescriptor(this);\r\n arg.setValue(field[i].getAttributeName(), false);\r\n this.addArgument(arg);\r\n }\r\n }", "public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }", "public CSTNode get( int index ) \n {\n CSTNode element = null;\n\n if( index < size() ) \n {\n element = (CSTNode)elements.get( index );\n }\n\n return element;\n }", "public static <T extends Comparable<? super T>> List<T> sortInplace(List<T> list) {\n\t\tCollections.sort(list);\n\t\treturn list;\n\t}", "public ImageSource apply(ImageSource input) {\n ImageSource originalImage = input;\n\n int width = originalImage.getWidth();\n int height = originalImage.getHeight();\n\n boolean[][] matrix = new boolean[width][height]; // black n white boolean matrix; true = blck, false = white\n\n // Copy\n ImageSource filteredImage = new MatrixSource(input);\n\n int[] histogram = OtsuBinarize.imageHistogram(originalImage);\n\n int totalNumberOfpixels = height * width;\n\n int threshold = OtsuBinarize.threshold(histogram, totalNumberOfpixels);\n\n int black = 0;\n int white = 255;\n\n int gray;\n int alpha;\n int newColor;\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n\n if (gray > threshold) {\n matrix[i][j] = false;\n } else {\n matrix[i][j] = true;\n }\n\n }\n }\n\n int blackTreshold = letterThreshold(originalImage, matrix);\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n gray = originalImage.getGray(i, j);\n alpha = originalImage.getA(i, j);\n\n if (gray > blackTreshold) {\n newColor = white;\n } else {\n newColor = black;\n }\n\n newColor = ColorHelper.getARGB(newColor, newColor, newColor, alpha);\n filteredImage.setRGB(i, j, newColor);\n }\n }\n\n return filteredImage;\n }" ]
Download a file asynchronously. @param url the URL pointing to the file @param retrofit the retrofit client @return an Observable pointing to the content of the file
[ "public static Observable<byte[]> downloadFileAsync(String url, Retrofit retrofit) {\n FileService service = retrofit.create(FileService.class);\n Observable<ResponseBody> response = service.download(url);\n return response.map(new Func1<ResponseBody, byte[]>() {\n @Override\n public byte[] call(ResponseBody responseBody) {\n try {\n return responseBody.bytes();\n } catch (IOException e) {\n throw Exceptions.propagate(e);\n }\n }\n });\n }" ]
[ "@Override\n public Object[] getAgentPlans(String agent_name, Connector connector) {\n // Not supported in JADE\n connector.getLogger().warning(\"Non suported method for Jade Platform. There is no plans in Jade platform.\");\n throw new java.lang.UnsupportedOperationException(\"Non suported method for Jade Platform. There is no extra properties.\");\n }", "private Object mapToId(Object tmp) {\n if (tmp instanceof Double) {\n return new Integer(((Double)tmp).intValue());\n } else {\n return Context.toString(tmp);\n }\n }", "private static void listAssignmentsByResource(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Assignments for resource \" + resource.getName() + \":\");\n\n for (ResourceAssignment assignment : resource.getTaskAssignments())\n {\n Task task = assignment.getTask();\n System.out.println(\" \" + task.getName());\n }\n }\n\n System.out.println();\n }", "public void delete(Object element, boolean testForEquality) {\r\n\tint index = indexOfFromTo(element, 0, size-1, testForEquality);\r\n\tif (index>=0) removeFromTo(index,index);\r\n}", "public RasterLayerInfo asLayerInfo(TileMap tileMap) {\n\t\tRasterLayerInfo layerInfo = new RasterLayerInfo();\n\n\t\tlayerInfo.setCrs(tileMap.getSrs());\n\t\tlayerInfo.setDataSourceName(tileMap.getTitle());\n\t\tlayerInfo.setLayerType(LayerType.RASTER);\n\t\tlayerInfo.setMaxExtent(asBbox(tileMap.getBoundingBox()));\n\t\tlayerInfo.setTileHeight(tileMap.getTileFormat().getHeight());\n\t\tlayerInfo.setTileWidth(tileMap.getTileFormat().getWidth());\n\n\t\tList<ScaleInfo> zoomLevels = new ArrayList<ScaleInfo>(tileMap.getTileSets().getTileSets().size());\n\t\tfor (TileSet tileSet : tileMap.getTileSets().getTileSets()) {\n\t\t\tzoomLevels.add(asScaleInfo(tileSet));\n\t\t}\n\t\tlayerInfo.setZoomLevels(zoomLevels);\n\n\t\treturn layerInfo;\n\t}", "public static bridgetable[] get(nitro_service service) throws Exception{\n\t\tbridgetable obj = new bridgetable();\n\t\tbridgetable[] response = (bridgetable[])obj.get_resources(service);\n\t\treturn response;\n\t}", "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 Object convertStringToJavaField(String value, int columnPos) throws SQLException {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.resultStringToJava(this, value, columnPos);\n\t\t}\n\t}", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query, boolean lazy) throws PersistenceBrokerException\r\n {\r\n ManageableCollection result;\r\n\r\n try\r\n {\r\n // BRJ: return empty Collection for null query\r\n if (query == null)\r\n {\r\n result = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n else\r\n {\r\n if (lazy)\r\n {\r\n result = pb.getProxyFactory().createCollectionProxy(pb.getPBKey(), query, collectionClass);\r\n }\r\n else\r\n {\r\n result = getCollectionByQuery(collectionClass, query.getSearchClass(), query);\r\n }\r\n }\r\n return result;\r\n }\r\n catch (Exception e)\r\n {\r\n if(e instanceof PersistenceBrokerException)\r\n {\r\n throw (PersistenceBrokerException) e;\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n }\r\n }" ]
Calculates the tiles width and height. @param code The unique tile code. Determines what tile we're talking about. @param maxExtent The maximum extent of the grid to which this tile belongs. @param scale The current client side scale. @return Returns an array of double values where the first value is the tile width and the second value is the tile height.
[ "public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\n\t}" ]
[ "protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\n }\n }", "private void changeClusterAndStores(String clusterKey,\n final Cluster cluster,\n String storesKey,\n final List<StoreDefinition> storeDefs) {\n metadataStore.writeLock.lock();\n try {\n VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock));\n\n // now put new stores\n updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock));\n\n } catch(Exception e) {\n logger.info(\"Error while changing cluster to \" + cluster + \"for key \" + clusterKey);\n throw new VoldemortException(e);\n } finally {\n metadataStore.writeLock.unlock();\n }\n }", "public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory,\n ResourcePoolConfig config) {\n return new QueuedKeyedResourcePool<K, V>(factory, config);\n }", "public static void main(String[] args) {\r\n\r\n String[] s = {\"there once was a man\", \"this one is a manic\", \"hey there\", \"there once was a mane\", \"once in a manger.\", \"where is one match?\", \"Jo3seph Smarr!\", \"Joseph R Smarr\"};\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.println(\"s1: \" + s[i]);\r\n System.out.println(\"s2: \" + s[j]);\r\n System.out.println(\"edit distance: \" + editDistance(s[i], s[j]));\r\n System.out.println(\"LCS: \" + longestCommonSubstring(s[i], s[j]));\r\n System.out.println(\"LCCS: \" + longestCommonContiguousSubstring(s[i], s[j]));\r\n System.out.println();\r\n }\r\n }\r\n }", "void applyFreshParticleOnScreen(\n @NonNull final Scene scene,\n final int position\n ) {\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 final double direction = Math.toRadians(random.nextInt(360));\n final float dCos = (float) Math.cos(direction);\n final float dSin = (float) Math.sin(direction);\n final float x = random.nextInt(w);\n final float y = random.nextInt(h);\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 void clearSources()\n {\n synchronized (mAudioSources)\n {\n for (GVRAudioSource source : mAudioSources)\n {\n source.setListener(null);\n }\n mAudioSources.clear();\n }\n }", "public static void stopService() {\n DaemonStarter.currentPhase.set(LifecyclePhase.STOPPING);\n final CountDownLatch cdl = new CountDownLatch(1);\n Executors.newSingleThreadExecutor().execute(() -> {\n DaemonStarter.getLifecycleListener().stopping();\n DaemonStarter.daemon.stop();\n cdl.countDown();\n });\n\n try {\n int timeout = DaemonStarter.lifecycleListener.get().getShutdownTimeoutSeconds();\n if (!cdl.await(timeout, TimeUnit.SECONDS)) {\n DaemonStarter.rlog.error(\"Failed to stop gracefully\");\n DaemonStarter.abortSystem();\n }\n } catch (InterruptedException e) {\n DaemonStarter.rlog.error(\"Failure awaiting stop\", e);\n Thread.currentThread().interrupt();\n }\n\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 Iterable<BoxFileVersionLegalHold.Info> getFileVersionHolds(int limit, String ... fields) {\n QueryStringBuilder queryString = new QueryStringBuilder().appendParam(\"policy_id\", this.getID());\n if (fields.length > 0) {\n queryString.appendParam(\"fields\", fields);\n }\n URL url = LIST_OF_FILE_VERSION_HOLDS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString());\n return new BoxResourceIterable<BoxFileVersionLegalHold.Info>(getAPI(), url, limit) {\n\n @Override\n protected BoxFileVersionLegalHold.Info factory(JsonObject jsonObject) {\n BoxFileVersionLegalHold assignment\n = new BoxFileVersionLegalHold(getAPI(), jsonObject.get(\"id\").asString());\n return assignment.new Info(jsonObject);\n }\n\n };\n }" ]
Over simplistic helper to compare two strings to check radio buttons. @param value1 the first value @param value2 the second value @return "checked" if both values are equal, the empty String "" otherwise
[ "public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\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 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 void setStructuredAppendMessageId(String messageId) {\r\n if (messageId != null && !messageId.matches(\"^[\\\\x21-\\\\x7F]+$\")) {\r\n throw new IllegalArgumentException(\"Invalid Aztec Code structured append message ID: \" + messageId);\r\n }\r\n this.structuredAppendMessageId = messageId;\r\n }", "private PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>\n getMatchedDestination(List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations,\n HttpMethod targetHttpMethod, String requestUri) {\n\n LOG.trace(\"Routable destinations for request {}: {}\", requestUri, routableDestinations);\n Iterable<String> requestUriParts = splitAndOmitEmpty(requestUri, '/');\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = new ArrayList<>();\n long maxScore = 0;\n\n for (PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> destination : routableDestinations) {\n HttpResourceModel resourceModel = destination.getDestination();\n\n for (HttpMethod httpMethod : resourceModel.getHttpMethod()) {\n if (targetHttpMethod.equals(httpMethod)) {\n long score = getWeightedMatchScore(requestUriParts, splitAndOmitEmpty(resourceModel.getPath(), '/'));\n LOG.trace(\"Max score = {}. Weighted score for {} is {}. \", maxScore, destination, score);\n if (score > maxScore) {\n maxScore = score;\n matchedDestinations.clear();\n matchedDestinations.add(destination);\n } else if (score == maxScore) {\n matchedDestinations.add(destination);\n }\n }\n }\n }\n\n if (matchedDestinations.size() > 1) {\n throw new IllegalStateException(String.format(\"Multiple matched handlers found for request uri %s: %s\",\n requestUri, matchedDestinations));\n } else if (matchedDestinations.size() == 1) {\n return matchedDestinations.get(0);\n }\n return null;\n }", "public static void endTrack(final String title){\r\n if(isClosed){ return; }\r\n //--Make Task\r\n final long timestamp = System.currentTimeMillis();\r\n Runnable endTrack = new Runnable(){\r\n public void run(){\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n //(check name match)\r\n String expected = titleStack.pop();\r\n if(!expected.equalsIgnoreCase(title)){\r\n throw new IllegalArgumentException(\"Track names do not match: expected: \" + expected + \" found: \" + title);\r\n }\r\n //(decrement depth)\r\n depth -= 1;\r\n //(send signal)\r\n handlers.process(null, MessageType.END_TRACK, depth, timestamp);\r\n assert !isThreaded || control.isHeldByCurrentThread();\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n long threadId = Thread.currentThread().getId();\r\n attemptThreadControl( threadId, endTrack );\r\n } else {\r\n //(case: no threading)\r\n endTrack.run();\r\n }\r\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 static base_response unset(nitro_service client, aaaparameter resource, String[] args) throws Exception{\n\t\taaaparameter unsetresource = new aaaparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static <T> ManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new ManagedBean<T>(attributes, clazz, createId(attributes, clazz), beanManager);\n }", "public String get(final String key) {\n final Collection<Argument> args = map.get(key);\n if (args != null) {\n return args.iterator().hasNext() ? args.iterator().next().getValue() : null;\n }\n return null;\n }" ]
Use this API to fetch statistics of appfwpolicylabel_stats resource of given name .
[ "public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "public WebSocketContext sendToTagged(String message, String tag) {\n return sendToTagged(message, tag, false);\n }", "void addValue(V value, Resource resource) {\n\t\tthis.valueQueue.add(value);\n\t\tthis.valueSubjectQueue.add(resource);\n\t}", "public static appqoepolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "protected <T> T fromJsonString(String json, Class<T> clazz) {\n\t\treturn _gsonParser.fromJson(json, clazz);\n\t}", "protected Class getClassCacheEntry(String name) {\n if (name == null) return null;\n synchronized (classCache) {\n return classCache.get(name);\n }\n }", "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 }", "@Override\n public void setBody(String body) {\n super.setBody(body);\n this.jsonValue = JsonValue.readFrom(body);\n }", "public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }", "public void checkVersion(ZWaveCommandClass commandClass) {\r\n\t\tZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass)this.getNode().getCommandClass(CommandClass.VERSION);\r\n\t\t\r\n\t\tif (versionCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Version command class not supported on node %d,\" +\r\n\t\t\t\t\t\"reverting to version 1 for command class %s (0x%02x)\", \r\n\t\t\t\t\tthis.getNode().getNodeId(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getLabel(), \r\n\t\t\t\t\tcommandClass.getCommandClass().getKey()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tthis.getController().sendData(versionCommandClass.getCommandClassVersionMessage(commandClass.getCommandClass()));\r\n\t}" ]
Set dates with the provided check states. @param datesWithCheckInfo the dates to set, accompanied with the check state to set.
[ "public void setDatesWithCheckState(Collection<CmsPair<Date, Boolean>> datesWithCheckInfo) {\n\n SortedSet<Date> dates = new TreeSet<>();\n m_checkBoxes.clear();\n for (CmsPair<Date, Boolean> p : datesWithCheckInfo) {\n addCheckBox(p.getFirst(), p.getSecond().booleanValue());\n dates.add(p.getFirst());\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }" ]
[ "protected AbstractColumn buildExpressionColumn() {\n\t\tExpressionColumn column = new ExpressionColumn();\n\t\tpopulateCommonAttributes(column);\n\t\t\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\treturn column;\n\t}", "public static final String getUnicodeString(byte[] data, int offset)\n {\n int length = getUnicodeStringLengthInBytes(data, offset);\n return length == 0 ? \"\" : new String(data, offset, length, CharsetHelper.UTF16LE);\n }", "public static base_response delete(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute deleteresource = new lbroute();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static synchronized void clearDaoCache() {\n\t\tif (classMap != null) {\n\t\t\tclassMap.clear();\n\t\t\tclassMap = null;\n\t\t}\n\t\tif (tableConfigMap != null) {\n\t\t\ttableConfigMap.clear();\n\t\t\ttableConfigMap = null;\n\t\t}\n\t}", "public Duration getWork(Date date, TimeUnit format)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n long time = getTotalTime(ranges);\n return convertFormat(time, format);\n }", "boolean lockShared(final Integer permit, final long timeout, final TimeUnit unit) {\n boolean result = false;\n try {\n result = lockSharedInterruptibly(permit, timeout, unit);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return result;\n }", "public double Function1D(double x) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }", "public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }", "public static base_response unset(nitro_service client, sslparameter resource, String[] args) throws Exception{\n\t\tsslparameter unsetresource = new sslparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Updates the image information.
[ "private void updateImageInfo() {\n\n String crop = getCrop();\n String point = getPoint();\n m_imageInfoDisplay.fillContent(m_info, crop, point);\n }" ]
[ "private List<Row> createTimeEntryRowList(String shiftData) throws ParseException\n {\n List<Row> list = new ArrayList<Row>();\n String[] shifts = shiftData.split(\",|:\");\n int index = 1;\n while (index < shifts.length)\n {\n index += 2;\n int entryCount = Integer.parseInt(shifts[index]);\n index++;\n\n for (int entryIndex = 0; entryIndex < entryCount; entryIndex++)\n {\n Integer exceptionTypeID = Integer.valueOf(shifts[index + 0]);\n Date startTime = DatatypeConverter.parseBasicTime(shifts[index + 1]);\n Date endTime = DatatypeConverter.parseBasicTime(shifts[index + 2]);\n\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"START_TIME\", startTime);\n map.put(\"END_TIME\", endTime);\n map.put(\"EXCEPTIOP\", exceptionTypeID);\n\n list.add(new MapRow(map));\n\n index += 3;\n }\n }\n\n return list;\n }", "public static vpnvserver_responderpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_responderpolicy_binding obj = new vpnvserver_responderpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_responderpolicy_binding response[] = (vpnvserver_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "static GVROrthogonalCamera makeOrthoShadowCamera(GVRPerspectiveCamera centerCam)\n {\n GVROrthogonalCamera shadowCam = new GVROrthogonalCamera(centerCam.getGVRContext());\n float near = centerCam.getNearClippingDistance();\n float far = centerCam.getFarClippingDistance();\n float fovy = (float) Math.toRadians(centerCam.getFovY());\n float h = (float) (Math.atan(fovy / 2.0f) * far) / 2.0f;\n\n shadowCam.setLeftClippingDistance(-h);\n shadowCam.setRightClippingDistance(h);\n shadowCam.setTopClippingDistance(h);\n shadowCam.setBottomClippingDistance(-h);\n shadowCam.setNearClippingDistance(near);\n shadowCam.setFarClippingDistance(far);\n return shadowCam;\n }", "protected static boolean numericEquals(Field vector1, Field vector2) {\n\t\tif (vector1.size() != vector2.size())\n\t\t\treturn false;\n\t\tif (vector1.isEmpty())\n\t\t\treturn true;\n\n\t\tIterator<Object> it1 = vector1.iterator();\n\t\tIterator<Object> it2 = vector2.iterator();\n\n\t\twhile (it1.hasNext()) {\n\t\t\tObject obj1 = it1.next();\n\t\t\tObject obj2 = it2.next();\n\n\t\t\tif (!(obj1 instanceof Number && obj2 instanceof Number))\n\t\t\t\treturn false;\n\n\t\t\tif (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}", "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 }", "@Deprecated\r\n private BufferedImage getImage(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }", "public static String readFlowId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String flowId = null;\n Header hdFlowId = ((SoapMessage)message).getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n if (hdFlowId.getObject() instanceof String) {\n flowId = (String)hdFlowId.getObject();\n } else if (hdFlowId.getObject() instanceof Node) {\n Node headerNode = (Node)hdFlowId.getObject();\n flowId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found FlowId soap header but value is not a String or a Node! Value: \"\n + hdFlowId.getObject().toString());\n }\n }\n return flowId;\n }", "public void incrementVersion(int node, long time) {\n if(node < 0 || node > Short.MAX_VALUE)\n throw new IllegalArgumentException(node\n + \" is outside the acceptable range of node ids.\");\n\n this.timestamp = time;\n\n Long version = versionMap.get((short) node);\n if(version == null) {\n version = 1L;\n } else {\n version = version + 1L;\n }\n\n versionMap.put((short) node, version);\n if(versionMap.size() >= MAX_NUMBER_OF_VERSIONS) {\n throw new IllegalStateException(\"Vector clock is full!\");\n }\n\n }", "public synchronized void withTransaction(Closure closure) throws SQLException {\n boolean savedCacheConnection = cacheConnection;\n cacheConnection = true;\n Connection connection = null;\n boolean savedAutoCommit = true;\n try {\n connection = createConnection();\n savedAutoCommit = connection.getAutoCommit();\n connection.setAutoCommit(false);\n callClosurePossiblyWithConnection(closure, connection);\n connection.commit();\n } catch (SQLException e) {\n handleError(connection, e);\n throw e;\n } catch (RuntimeException e) {\n handleError(connection, e);\n throw e;\n } catch (Error e) {\n handleError(connection, e);\n throw e;\n } catch (Exception e) {\n handleError(connection, e);\n throw new SQLException(\"Unexpected exception during transaction\", e);\n } finally {\n if (connection != null) {\n try {\n connection.setAutoCommit(savedAutoCommit);\n }\n catch (SQLException e) {\n LOG.finest(\"Caught exception resetting auto commit: \" + e.getMessage() + \" - continuing\");\n }\n }\n cacheConnection = false;\n closeResources(connection, null);\n cacheConnection = savedCacheConnection;\n if (dataSource != null && !cacheConnection) {\n useConnection = null;\n }\n }\n }" ]
Use picasso to render the video thumbnail into the thumbnail widget using a temporal placeholder. @param video to get the rendered thumbnail.
[ "private void renderThumbnail(Video video) {\n Picasso.with(getContext()).cancelRequest(thumbnail);\n Picasso.with(getContext())\n .load(video.getThumbnail())\n .placeholder(R.drawable.placeholder)\n .into(thumbnail);\n }" ]
[ "protected void endPersistence(final BufferedWriter writer) throws IOException {\n // Append any additional users to the end of the file.\n for (Object currentKey : toSave.keySet()) {\n String key = (String) currentKey;\n if (!key.contains(DISABLE_SUFFIX_KEY)) {\n writeProperty(writer, key, null);\n }\n }\n\n toSave = null;\n }", "public static double[][] diag(double[] vector){\n\n\t\t// Note: According to the Java Language spec, an array is initialized with the default value, here 0.\n\t\tdouble[][] diagonalMatrix = new double[vector.length][vector.length];\n\n\t\tfor(int index = 0; index < vector.length; index++) {\n\t\t\tdiagonalMatrix[index][index] = vector[index];\n\t\t}\n\n\t\treturn diagonalMatrix;\n\t}", "public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }", "public static boolean canParseColor(final String colorString) {\n try {\n return ColorParser.toColor(colorString) != null;\n } catch (Exception exc) {\n return false;\n }\n }", "private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}", "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 }", "@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }", "private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) {\n\t\tfor (StyleFilter styleFilter : styles) {\n\t\t\tif (styleFilter.getFilter().evaluate(feature)) {\n\t\t\t\treturn styleFilter;\n\t\t\t}\n\t\t}\n\t\treturn new StyleFilterImpl();\n\t}" ]
Send message to socket's output stream. @param messageToSend message to send. @return {@code true} if message was sent successfully, {@code false} otherwise.
[ "@SuppressWarnings(\"checkstyle:illegalcatch\")\n private boolean sendMessage(final byte[] messageToSend) {\n try {\n connectionPool.execute(new PooledObjectConsumer<TcpConnection>() {\n @Override\n public void accept(final TcpConnection tcpConnection) throws IOException {\n tcpConnection.write(messageToSend);\n }\n });\n } catch (final Exception e) {\n addError(String.format(\"Error sending message via tcp://%s:%s\",\n getGraylogHost(), getGraylogPort()), e);\n\n return false;\n }\n\n return true;\n }" ]
[ "public void normalize() {\n double lenSqr = x * x + y * y + z * z;\n double err = lenSqr - 1;\n if (err > (2 * DOUBLE_PREC) || err < -(2 * DOUBLE_PREC)) {\n double len = Math.sqrt(lenSqr);\n x /= len;\n y /= len;\n z /= len;\n }\n }", "public void stopServer() throws Exception {\n if (!externalDatabaseHost) {\n try (Connection sqlConnection = getConnection()) {\n sqlConnection.prepareStatement(\"SHUTDOWN\").execute();\n } catch (Exception e) {\n }\n\n try {\n server.stop();\n } catch (Exception e) {\n }\n }\n }", "public Set<ConstraintViolation> validate(int record) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int ds = 0; ds < 250; ++ds) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds));\r\n\t\t\t\terrors.addAll(validate(dataSetInfo));\r\n\t\t\t} catch (InvalidDataSetException ignored) {\r\n\t\t\t\t// DataSetFactory doesn't know about this ds, so will skip it\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn errors;\r\n\t}", "public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){\n\n\t\tint numberOfStrikes = strikes.length;\n\t\tHashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>();\n\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tfor(int i = 0; i< numberOfStrikes; i++) {\n\t\t\tdescriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i]));\n\t\t}\n\n\t\treturn descriptors;\n\t}", "public static vlan[] get(nitro_service service) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tvlan[] response = (vlan[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static base_response update(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice updateresource = new gslbservice();\n\t\tupdateresource.servicename = resource.servicename;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.publicip = resource.publicip;\n\t\tupdateresource.publicport = resource.publicport;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.sitepersistence = resource.sitepersistence;\n\t\tupdateresource.siteprefix = resource.siteprefix;\n\t\tupdateresource.maxclient = resource.maxclient;\n\t\tupdateresource.healthmonitor = resource.healthmonitor;\n\t\tupdateresource.maxbandwidth = resource.maxbandwidth;\n\t\tupdateresource.downstateflush = resource.downstateflush;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.viewname = resource.viewname;\n\t\tupdateresource.viewip = resource.viewip;\n\t\tupdateresource.monthreshold = resource.monthreshold;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.monitor_name_svc = resource.monitor_name_svc;\n\t\tupdateresource.hashid = resource.hashid;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.appflowlog = resource.appflowlog;\n\t\treturn updateresource.update_resource(client);\n\t}", "public Range<Dyno> listDynos(String appName) {\n return connection.execute(new DynoList(appName), apiKey);\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 void setTabs(ArrayList<String>tabs) {\n if (tabs == null || tabs.size() <= 0) return;\n\n if (platformSupportsTabs) {\n ArrayList<String> toAdd;\n if (tabs.size() > MAX_TABS) {\n toAdd = new ArrayList<>(tabs.subList(0, MAX_TABS));\n } else {\n toAdd = tabs;\n }\n this.tabs = toAdd.toArray(new String[0]);\n } else {\n Logger.d(\"Please upgrade com.android.support:design library to v28.0.0 to enable Tabs for App Inbox, dropping Tabs\");\n }\n }" ]
Gets the or create protocol header. @param message the message @return the message headers map
[ "private static Map<String, List<String>> getOrCreateProtocolHeader(\n Message message) {\n Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message\n .get(Message.PROTOCOL_HEADERS));\n if (headers == null) {\n headers = new HashMap<String, List<String>>();\n message.put(Message.PROTOCOL_HEADERS, headers);\n }\n return headers;\n }" ]
[ "public List<String> getPropertyPaths() {\n List<String> result = new ArrayList<String>();\n\n for (String property : this.values.names()) {\n if (!property.startsWith(\"$\")) {\n result.add(this.propertyToPath(property));\n }\n }\n\n return result;\n }", "public long indexOf(final String element) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return doIndexOf(jedis, element);\n }\n });\n }", "public static boolean isBigInteger(CharSequence self) {\n try {\n new BigInteger(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) {\n\t\treturn (Statement) Proxy.newProxyInstance(\n\t\t\t\tStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {StatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "public Where<T, ID> in(String columnName, Iterable<?> objects) throws SQLException {\n\t\taddClause(new In(columnName, findColumnFieldType(columnName), objects, true));\n\t\treturn this;\n\t}", "public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }", "protected void processDeletions(CmsObject cms, List<CmsResource> toDelete) throws CmsException {\n\n Collections.sort(toDelete, (a, b) -> b.getRootPath().compareTo(a.getRootPath()));\n for (CmsResource deleteRes : toDelete) {\n m_report.print(\n org.opencms.importexport.Messages.get().container(org.opencms.importexport.Messages.RPT_DELFOLDER_0),\n I_CmsReport.FORMAT_NOTE);\n m_report.print(\n org.opencms.report.Messages.get().container(\n org.opencms.report.Messages.RPT_ARGUMENT_1,\n deleteRes.getRootPath()));\n CmsLock lock = cms.getLock(deleteRes);\n if (lock.isUnlocked()) {\n lock(cms, deleteRes);\n }\n cms.deleteResource(deleteRes, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_report.println(\n org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),\n I_CmsReport.FORMAT_OK);\n\n }\n }", "public static int scale(Double factor, int pixel) {\n return rgb(\n (int) Math.round(factor * red(pixel)),\n (int) Math.round(factor * green(pixel)),\n (int) Math.round(factor * blue(pixel))\n );\n }", "public static void doPriorityEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) {\n jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n jedis.lpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }" ]
returns whether masking with the given mask results in a valid contiguous range for this segment, and if it does, if it matches the range obtained when masking the given values with the same mask. @param lowerValue @param upperValue @param mask @return
[ "public boolean matchesWithMask(long lowerValue, long upperValue, long mask) {\n\t\tif(lowerValue == upperValue) {\n\t\t\treturn matchesWithMask(lowerValue, mask);\n\t\t}\n\t\tif(!isMultiple()) {\n\t\t\t//we know lowerValue and upperValue are not the same, so impossible to match those two values with a single value\n\t\t\treturn false;\n\t\t}\n\t\tlong thisValue = getDivisionValue();\n\t\tlong thisUpperValue = getUpperDivisionValue();\n\t\tif(!isMaskCompatibleWithRange(thisValue, thisUpperValue, mask, getMaxValue())) {\n\t\t\treturn false;\n\t\t}\n\t\treturn lowerValue == (thisValue & mask) && upperValue == (thisUpperValue & mask);\n\t}" ]
[ "protected BoxWatermark getWatermark(URLTemplate itemUrl, String... fields) {\n URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID());\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n URL url = WATERMARK_URL_TEMPLATE.buildWithQuery(watermarkUrl.toString(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new BoxWatermark(response.getJSON());\n }", "public static long getGcTimestamp(String zookeepers) {\n ZooKeeper zk = null;\n try {\n zk = new ZooKeeper(zookeepers, 30000, null);\n\n // wait until zookeeper is connected\n long start = System.currentTimeMillis();\n while (!zk.getState().isConnected() && System.currentTimeMillis() - start < 30000) {\n Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);\n }\n\n byte[] d = zk.getData(ZookeeperPath.ORACLE_GC_TIMESTAMP, false, null);\n return LongUtil.fromByteArray(d);\n } catch (KeeperException | InterruptedException | IOException e) {\n log.warn(\"Failed to get oldest timestamp of Oracle from Zookeeper\", e);\n return OLDEST_POSSIBLE;\n } finally {\n if (zk != null) {\n try {\n zk.close();\n } catch (InterruptedException e) {\n log.error(\"Failed to close zookeeper client\", e);\n }\n }\n }\n }", "public static base_responses delete(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 deleteresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new ntpserver();\n\t\t\t\tdeleteresources[i].serverip = resources[i].serverip;\n\t\t\t\tdeleteresources[i].servername = resources[i].servername;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\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 }", "PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\n }", "public synchronized void removeControlPoint(ControlPoint controlPoint) {\n if (controlPoint.decreaseReferenceCount() == 0) {\n ControlPointIdentifier id = new ControlPointIdentifier(controlPoint.getDeployment(), controlPoint.getEntryPoint());\n entryPoints.remove(id);\n }\n }", "protected AbstractBeanDeployer<E> deploySpecialized() {\n // ensure that all decorators are initialized before initializing\n // the rest of the beans\n for (DecoratorImpl<?> bean : getEnvironment().getDecorators()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addDecorator(bean);\n BootstrapLogger.LOG.foundDecorator(bean);\n }\n for (InterceptorImpl<?> bean : getEnvironment().getInterceptors()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addInterceptor(bean);\n BootstrapLogger.LOG.foundInterceptor(bean);\n }\n return this;\n }", "final public Boolean checkRealOffset() {\n if ((tokenRealOffset == null) || !provideRealOffset) {\n return false;\n } else if (tokenOffset == null) {\n return true;\n } else if (tokenOffset.getStart() == tokenRealOffset.getStart()\n && tokenOffset.getEnd() == tokenRealOffset.getEnd()) {\n return false;\n } else {\n return true;\n }\n }", "public static sslocspresponder[] get(nitro_service service) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tsslocspresponder[] response = (sslocspresponder[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Creates a PathAddress from the given ModelNode address. The given node is expected to be an address node. @param node the node (cannot be {@code null}) @return the update identifier
[ "public static PathAddress pathAddress(final ModelNode node) {\n if (node.isDefined()) {\n\n// final List<Property> props = node.asPropertyList();\n // Following bit is crap TODO; uncomment above and delete below\n // when bug is fixed\n final List<Property> props = new ArrayList<Property>();\n String key = null;\n for (ModelNode element : node.asList()) {\n Property prop = null;\n if (element.getType() == ModelType.PROPERTY || element.getType() == ModelType.OBJECT) {\n prop = element.asProperty();\n } else if (key == null) {\n key = element.asString();\n } else {\n prop = new Property(key, element);\n }\n if (prop != null) {\n props.add(prop);\n key = null;\n }\n\n }\n if (props.size() == 0) {\n return EMPTY_ADDRESS;\n } else {\n final Set<String> seen = new HashSet<String>();\n final List<PathElement> values = new ArrayList<PathElement>();\n int index = 0;\n for (final Property prop : props) {\n final String name = prop.getName();\n if (seen.add(name)) {\n values.add(new PathElement(name, prop.getValue().asString()));\n } else {\n throw duplicateElement(name);\n }\n if (index == 1 && name.equals(SERVER) && seen.contains(HOST)) {\n seen.clear();\n }\n index++;\n }\n return new PathAddress(Collections.unmodifiableList(values));\n }\n } else {\n return EMPTY_ADDRESS;\n }\n }" ]
[ "public static nsacl6[] get(nitro_service service, String acl6name[]) throws Exception{\n\t\tif (acl6name !=null && acl6name.length>0) {\n\t\t\tnsacl6 response[] = new nsacl6[acl6name.length];\n\t\t\tnsacl6 obj[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++) {\n\t\t\t\tobj[i] = new nsacl6();\n\t\t\t\tobj[i].set_acl6name(acl6name[i]);\n\t\t\t\tresponse[i] = (nsacl6) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public void addColumn(String columnName, boolean searchable, boolean orderable,\n String searchValue) {\n this.columns.add(new Column(columnName, \"\", searchable, orderable,\n new Search(searchValue, false)));\n }", "public void forceApply(String conflictResolution) {\n\n URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"conflict_resolution\", conflictResolution);\n request.setBody(requestJSON.toString());\n request.send();\n }", "public void setTexCoord(String texName, String texCoordAttr, String shaderVarName)\n {\n synchronized (textures)\n {\n GVRTexture tex = textures.get(texName);\n\n if (tex != null)\n {\n tex.setTexCoord(texCoordAttr, shaderVarName);\n }\n else\n {\n throw new UnsupportedOperationException(\"Texture must be set before updating texture coordinate information\");\n }\n }\n }", "void update(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n if (member.getValue().isNull()) {\n continue;\n }\n\n this.parseJSONMember(member);\n }\n\n this.clearPendingChanges();\n }", "public synchronized boolean isComplete(int requestId, boolean remove) {\n if (!operations.containsKey(requestId))\n throw new VoldemortException(\"No operation with id \" + requestId + \" found\");\n\n if (operations.get(requestId).getStatus().isComplete()) {\n if (logger.isDebugEnabled())\n logger.debug(\"Operation complete \" + requestId);\n\n if (remove)\n operations.remove(requestId);\n\n return true;\n }\n\n return false;\n }", "private PreparedStatement prepareBatchStatement(String sql)\r\n {\r\n String sqlCmd = sql.substring(0, 7);\r\n\r\n if (sqlCmd.equals(\"UPDATE \") || sqlCmd.equals(\"DELETE \") || (_useBatchInserts && sqlCmd.equals(\"INSERT \")))\r\n {\r\n PreparedStatement stmt = (PreparedStatement) _statements.get(sql);\r\n if (stmt == null)\r\n {\r\n // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement\r\n // interfaces, otherwise proxy.jar works incorrectly\r\n stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{\r\n PreparedStatement.class, Statement.class, BatchPreparedStatement.class},\r\n new PreparedStatementInvocationHandler(this, sql, m_jcd));\r\n _statements.put(sql, stmt);\r\n }\r\n return stmt;\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n }", "public static void main(String[] args) {\r\n try {\r\n TreeFactory tf = new LabeledScoredTreeFactory();\r\n Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), \"UTF-8\"));\r\n TreeReader tr = new PennTreeReader(r, tf);\r\n Tree t = tr.readTree();\r\n while (t != null) {\r\n System.out.println(t);\r\n System.out.println();\r\n t = tr.readTree();\r\n }\r\n r.close();\r\n } catch (IOException ioe) {\r\n ioe.printStackTrace();\r\n }\r\n }", "public void setParent(ProjectCalendar calendar)\n {\n // I've seen a malformed MSPDI file which sets the parent calendar to itself.\n // Silently ignore this here.\n if (calendar != this)\n {\n if (getParent() != null)\n {\n getParent().removeDerivedCalendar(this);\n }\n\n super.setParent(calendar);\n\n if (calendar != null)\n {\n calendar.addDerivedCalendar(this);\n }\n clearWorkingDateCache();\n }\n }" ]
Adds an ORDER BY item with a direction indicator. @param name Name of the column by which to sort. @param ascending If true, specifies the direction "asc", otherwise, specifies the direction "desc".
[ "public SelectBuilder orderBy(String name, boolean ascending) {\n if (ascending) {\n orderBys.add(name + \" asc\");\n } else {\n orderBys.add(name + \" desc\");\n }\n return this;\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 }", "private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }", "private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}", "protected TemporaryBrokerWrapper getBroker() throws PBFactoryException\r\n {\r\n PersistenceBrokerInternal broker;\r\n boolean needsClose = false;\r\n\r\n if (getBrokerKey() == null)\r\n {\r\n /*\r\n arminw:\r\n if no PBKey is set we throw an exception, because we don't\r\n know which PB (connection) should be used.\r\n */\r\n throw new OJBRuntimeException(\"Can't find associated PBKey. Need PBKey to obtain a valid\" +\r\n \"PersistenceBroker instance from intern resources.\");\r\n }\r\n // first try to use the current threaded broker to avoid blocking\r\n broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());\r\n // current broker not found, create a intern new one\r\n if ((broker == null) || broker.isClosed())\r\n {\r\n broker = (PersistenceBrokerInternal) PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());\r\n /** Specifies whether we obtained a fresh broker which we have to close after we used it */\r\n needsClose = true;\r\n }\r\n return new TemporaryBrokerWrapper(broker, needsClose);\r\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 void assertGLThread() {\n if (Thread.currentThread().getId() != mGLThreadID) {\n RuntimeException e = new RuntimeException(\n \"Should not run GL functions from a non-GL thread!\");\n e.printStackTrace();\n throw e;\n }\n }", "public static final String getString(byte[] data, int offset)\n {\n return getString(data, offset, data.length - offset);\n }", "public boolean start(SensorManager sensorManager) {\n // Already started?\n if (accelerometer != null) {\n return true;\n }\n\n accelerometer = sensorManager.getDefaultSensor(\n Sensor.TYPE_ACCELEROMETER);\n\n // If this phone has an accelerometer, listen to it.\n if (accelerometer != null) {\n this.sensorManager = sensorManager;\n sensorManager.registerListener(this, accelerometer,\n SensorManager.SENSOR_DELAY_FASTEST);\n }\n return accelerometer != null;\n }", "public int compare(Object objA, Object objB)\r\n {\r\n String idAStr = _table.getColumn((String)objA).getProperty(\"id\");\r\n String idBStr = _table.getColumn((String)objB).getProperty(\"id\");\r\n int idA;\r\n int idB;\r\n\r\n try {\r\n idA = Integer.parseInt(idAStr);\r\n }\r\n catch (Exception ex) {\r\n return 1;\r\n }\r\n try {\r\n idB = Integer.parseInt(idBStr);\r\n }\r\n catch (Exception ex) {\r\n return -1;\r\n }\r\n return idA < idB ? -1 : (idA > idB ? 1 : 0);\r\n }" ]
Helper method to add a Java integer value to a message digest. @param digest the message digest being built @param value the integer whose bytes should be included in the digest
[ "private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }" ]
[ "public void setLeftTableModel(TableModel model)\n {\n TableModel old = m_leftTable.getModel();\n m_leftTable.setModel(model);\n firePropertyChange(\"leftTableModel\", old, model);\n }", "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 }", "public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }", "protected void parseOperationsL(TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.SYMBOL && token.getSymbol() == Symbol.TRANSPOSE) {\n if( token.previous.getType() == Type.VARIABLE )\n token = insertTranspose(token.previous,tokens,sequence);\n else\n throw new ParseError(\"Expected variable before transpose\");\n }\n token = token.next;\n }\n }", "public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void paintCheckedBackground(Component c, Graphics g, int x, int y, int width, int height) {\n\t\tif ( backgroundImage == null ) {\n\t\t\tbackgroundImage = new BufferedImage( 64, 64, BufferedImage.TYPE_INT_ARGB );\n\t\t\tGraphics bg = backgroundImage.createGraphics();\n\t\t\tfor ( int by = 0; by < 64; by += 8 ) {\n\t\t\t\tfor ( int bx = 0; bx < 64; bx += 8 ) {\n\t\t\t\t\tbg.setColor( ((bx^by) & 8) != 0 ? Color.lightGray : Color.white );\n\t\t\t\t\tbg.fillRect( bx, by, 8, 8 );\n\t\t\t\t}\n\t\t\t}\n\t\t\tbg.dispose();\n\t\t}\n\n\t\tif ( backgroundImage != null ) {\n\t\t\tShape saveClip = g.getClip();\n\t\t\tRectangle r = g.getClipBounds();\n\t\t\tif (r == null)\n\t\t\t\tr = new Rectangle(c.getSize());\n\t\t\tr = r.intersection(new Rectangle(x, y, width, height));\n\t\t\tg.setClip(r);\n\t\t\tint w = backgroundImage.getWidth();\n\t\t\tint h = backgroundImage.getHeight();\n\t\t\tif (w != -1 && h != -1) {\n\t\t\t\tint x1 = (r.x / w) * w;\n\t\t\t\tint y1 = (r.y / h) * h;\n\t\t\t\tint x2 = ((r.x + r.width + w - 1) / w) * w;\n\t\t\t\tint y2 = ((r.y + r.height + h - 1) / h) * h;\n\t\t\t\tfor (y = y1; y < y2; y += h)\n\t\t\t\t\tfor (x = x1; x < x2; x += w)\n\t\t\t\t\t\tg.drawImage(backgroundImage, x, y, c);\n\t\t\t}\n\t\t\tg.setClip(saveClip);\n\t\t}\n\t}", "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 static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate(\n String listStr, boolean removeDuplicate) {\n\n List<String> nodes = new ArrayList<String>();\n\n for (String token : listStr.split(\"[\\\\r?\\\\n| +]+\")) {\n\n // 20131025: fix if fqdn has space in the end.\n if (token != null && !token.trim().isEmpty()) {\n nodes.add(token.trim());\n\n }\n }\n\n if (removeDuplicate) {\n removeDuplicateNodeList(nodes);\n }\n logger.info(\"Target hosts size : \" + nodes.size());\n\n return nodes;\n\n }", "protected int readShort(InputStream is) throws IOException\n {\n byte[] data = new byte[2];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getShort(data, 0));\n }" ]
Synchronize the geotools transaction with the platform transaction, if such a transaction is active. @param featureStore @param dataSource
[ "public void synchTransaction(SimpleFeatureStore featureStore) {\n\t\t// check if transaction is active, otherwise do nothing (auto-commit mode)\n\t\tif (TransactionSynchronizationManager.isActualTransactionActive()) {\n\t\t\tDataAccess<SimpleFeatureType, SimpleFeature> dataStore = featureStore.getDataStore();\n\t\t\tif (!transactions.containsKey(dataStore)) {\n\t\t\t\tTransaction transaction = null;\n\t\t\t\tif (dataStore instanceof JDBCDataStore) {\n\t\t\t\t\tJDBCDataStore jdbcDataStore = (JDBCDataStore) dataStore;\n\t\t\t\t\ttransaction = jdbcDataStore.buildTransaction(DataSourceUtils\n\t\t\t\t\t\t\t.getConnection(jdbcDataStore.getDataSource()));\n\t\t\t\t} else {\n\t\t\t\t\ttransaction = new DefaultTransaction();\n\t\t\t\t}\n\t\t\t\ttransactions.put(dataStore, transaction);\n\t\t\t}\n\t\t\tfeatureStore.setTransaction(transactions.get(dataStore));\n\t\t}\n\t}" ]
[ "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\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}", "public T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {\n return modifyFile(name, path, existingHash, newHash, isDirectory, null);\n }", "public void editMeta(String photosetId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_META);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"title\", title);\r\n if (description != null) {\r\n parameters.put(\"description\", description);\r\n }\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 }", "private static String preparePlaceHolders(int length) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < length; ) {\n builder.append(\"?\");\n if (++i < length) {\n builder.append(\",\");\n }\n }\n return builder.toString();\n }", "public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\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 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}", "@Override\n public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);\n for (ResourceRoot resourceRoot : resourceRoots) {\n if (IgnoreMetaInfMarker.isIgnoreMetaInf(resourceRoot)) {\n continue;\n }\n Manifest manifest = getManifest(resourceRoot);\n if (manifest != null)\n resourceRoot.putAttachment(Attachments.MANIFEST, manifest);\n }\n }", "private void merge(ExecutionStatistics otherStatistics) {\n for (String s : otherStatistics.executionInfo.keySet())\n {\n TimingData thisStats = this.executionInfo.get(s);\n TimingData otherStats = otherStatistics.executionInfo.get(s);\n if(thisStats == null) {\n this.executionInfo.put(s,otherStats);\n } else {\n thisStats.merge(otherStats);\n }\n\n }\n }" ]
Makes a DocumentReaderAndWriter based on the flags the CRFClassifier was constructed with. Will create the flags.readerAndWriter and initialize it with the CRFClassifier's flags.
[ "public DocumentReaderAndWriter<IN> makeReaderAndWriter() {\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>)\r\n Class.forName(flags.readerAndWriter).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.readerAndWriter: '%s'\", flags.readerAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }" ]
[ "public static final Duration getDuration(double value, TimeUnit type)\n {\n double duration;\n // Value is given in 1/10 of minute\n switch (type)\n {\n case MINUTES:\n case ELAPSED_MINUTES:\n {\n duration = value / 10;\n break;\n }\n\n case HOURS:\n case ELAPSED_HOURS:\n {\n duration = value / 600; // 60 * 10\n break;\n }\n\n case DAYS:\n {\n duration = value / 4800; // 8 * 60 * 10\n break;\n }\n\n case ELAPSED_DAYS:\n {\n duration = value / 14400; // 24 * 60 * 10\n break;\n }\n\n case WEEKS:\n {\n duration = value / 24000; // 5 * 8 * 60 * 10\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n duration = value / 100800; // 7 * 24 * 60 * 10\n break;\n }\n\n case MONTHS:\n {\n duration = value / 96000; // 4 * 5 * 8 * 60 * 10\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n duration = value / 432000; // 30 * 24 * 60 * 10\n break;\n }\n\n default:\n {\n duration = value;\n break;\n }\n }\n return (Duration.getInstance(duration, type));\n }", "private void processOutlineCodeFields(Row parentRow) throws SQLException\n {\n Integer entityID = parentRow.getInteger(\"CODE_REF_UID\");\n Integer outlineCodeEntityID = parentRow.getInteger(\"CODE_UID\");\n\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_OUTLINE_CODES WHERE CODE_UID=?\", outlineCodeEntityID))\n {\n processOutlineCodeField(entityID, row);\n }\n }", "public static TestCaseStartedEvent withExecutorInfo(TestCaseStartedEvent event) {\n event.getLabels().add(createHostLabel(getHostname()));\n event.getLabels().add(createThreadLabel(format(\"%s.%s(%s)\",\n ManagementFactory.getRuntimeMXBean().getName(),\n Thread.currentThread().getName(),\n Thread.currentThread().getId())\n ));\n return event;\n }", "public ManageableCollection createCollectionProxy(PBKey brokerKey, Query query, Class collectionClass)\r\n {\r\n Object args[] = {brokerKey, collectionClass, query};\r\n\r\n try\r\n {\r\n return (ManageableCollection) getCollectionProxyConstructor(collectionClass).newInstance(args);\r\n }\r\n catch(InstantiationException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(InvocationTargetException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n catch(IllegalAccessException ex)\r\n {\r\n throw new PersistenceBrokerException(\"Exception while creating a new collection proxy instance\", ex);\r\n }\r\n }", "public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\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 Integer getInteger(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Integer.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 static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }", "public static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\n }" ]
Use this API to fetch aaauser_vpntrafficpolicy_binding resources of given name .
[ "public static aaauser_vpntrafficpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_vpntrafficpolicy_binding obj = new aaauser_vpntrafficpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_vpntrafficpolicy_binding response[] = (aaauser_vpntrafficpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public CollectionRequest<Project> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/projects\", workspace);\n return new CollectionRequest<Project>(this, Project.class, path, \"GET\");\n }", "public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {\n\t\tDayCountConventionInterface daycountConvention = getDayCountConvention(convention);\n\t\treturn daycountConvention.getDaycount(startDate, endDate);\n\t}", "public static lbmonitor_binding get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonitor_binding obj = new lbmonitor_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonitor_binding response = (lbmonitor_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "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 unlock() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", \"lock\").toString();\n URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n\n JsonObject lockObject = new JsonObject();\n lockObject.add(\"lock\", JsonObject.NULL);\n\n request.setBody(lockObject.toString());\n request.send();\n }", "public static Info rand( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"rand-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n RandomMatrices_DDRM.fillUniform(output.matrix, 0,1,manager.getRandom());\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }", "public static java.sql.Timestamp getTimestamp(Object value) {\n try {\n return toTimestamp(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "static void endInitialization(WeldContainer container, boolean isShutdownHookEnabled) {\n container.complete();\n // If needed, register one shutdown hook for all containers\n if (shutdownHook == null && isShutdownHookEnabled) {\n synchronized (LOCK) {\n if (shutdownHook == null) {\n shutdownHook = new ShutdownHook();\n SecurityActions.addShutdownHook(shutdownHook);\n }\n }\n }\n container.fireContainerInitializedEvent();\n }", "public static Class<?> resolveReturnType(Method method, Class<?> clazz) {\n\t\tAssert.notNull(method, \"Method must not be null\");\n\t\tType genericType = method.getGenericReturnType();\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tMap<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);\n\t\tType rawType = getRawType(genericType, typeVariableMap);\n\t\treturn (rawType instanceof Class ? (Class<?>) rawType : method.getReturnType());\n\t}" ]
Writes and reads the XOP attachment using a CXF JAX-RS WebClient. Note that WebClient is created with the help of JAXRSClientFactoryBean. JAXRSClientFactoryBean can be used when neither of the WebClient factory methods is appropriate. For example, in this case, an "mtom-enabled" property is set on the factory bean first. @throws Exception
[ "public void useXopAttachmentServiceWithWebClient() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments/xop\";\n \n JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean();\n factoryBean.setAddress(serviceURI);\n factoryBean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, \n (Object)\"true\"));\n WebClient client = factoryBean.createWebClient();\n WebClient.getConfig(client).getRequestContext().put(\"support.type.as.multipart\", \n \"true\"); \n client.type(\"multipart/related\").accept(\"multipart/related\");\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a WebClient\");\n \n XopBean xopResponse = client.post(xop, XopBean.class);\n \n verifyXopResponse(xop, xopResponse);\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 }", "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }", "public final void loadCollection(\n\t\tfinal SharedSessionContractImplementor session,\n\t\tfinal Serializable id,\n\t\tfinal Type type) throws HibernateException {\n\n\t\tif ( log.isDebugEnabled() ) {\n\t\t\tlog.debug(\n\t\t\t\t\t\"loading collection: \" +\n\t\t\t\t\tMessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() )\n\t\t\t\t);\n\t\t}\n\n\t\tSerializable[] ids = new Serializable[]{id};\n\t\tQueryParameters qp = new QueryParameters( new Type[]{type}, ids, ids );\n\t\tdoQueryAndInitializeNonLazyCollections(\n\t\t\t\tsession,\n\t\t\t\tqp,\n\t\t\t\tOgmLoadingContext.EMPTY_CONTEXT,\n\t\t\t\ttrue\n\t\t\t);\n\n\t\tlog.debug( \"done loading collection\" );\n\n\t}", "synchronized boolean reload(int permit, boolean suspend) {\n return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);\n }", "private boolean isRelated(Task task, List<Relation> list)\n {\n boolean result = false;\n for (Relation relation : list)\n {\n if (relation.getTargetTask().getUniqueID().intValue() == task.getUniqueID().intValue())\n {\n result = true;\n break;\n }\n }\n return result;\n }", "private void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) {\r\n String getterName = \"get\" + MetaClassHelper.capitalize(propertyName);\r\n MethodNode setter = classNode.getSetterMethod(\"set\" + MetaClassHelper.capitalize(propertyName));\r\n\r\n if (setter != null) {\r\n // Get the existing code block\r\n Statement code = setter.getCode();\r\n\r\n Expression oldValue = varX(\"$oldValue\");\r\n Expression newValue = varX(\"$newValue\");\r\n Expression proposedValue = varX(setter.getParameters()[0].getName());\r\n BlockStatement block = new BlockStatement();\r\n\r\n // create a local variable to hold the old value from the getter\r\n block.addStatement(declS(oldValue, callThisX(getterName)));\r\n\r\n // add the fireVetoableChange method call\r\n block.addStatement(stmt(callThisX(\"fireVetoableChange\", args(\r\n constX(propertyName), oldValue, proposedValue))));\r\n\r\n // call the existing block, which will presumably set the value properly\r\n block.addStatement(code);\r\n\r\n if (bindable) {\r\n // get the new value to emit in the event\r\n block.addStatement(declS(newValue, callThisX(getterName)));\r\n\r\n // add the firePropertyChange method call\r\n block.addStatement(stmt(callThisX(\"firePropertyChange\", args(constX(propertyName), oldValue, newValue))));\r\n }\r\n\r\n // replace the existing code block with our new one\r\n setter.setCode(block);\r\n }\r\n }", "private String extractNumericVersion(Collection<String> versionStrings) {\n if (versionStrings == null) {\n return \"\";\n }\n for (String value : versionStrings) {\n String releaseValue = calculateReleaseVersion(value);\n if (!releaseValue.equals(value)) {\n return releaseValue;\n }\n }\n return \"\";\n }", "@Override\n public InternationalFixedDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "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 }" ]
Obtain newline-delimited headers from response @param response HttpServletResponse to scan @return newline-delimited headers
[ "public static String getHeaders(HttpServletResponse response) {\n String headerString = \"\";\n Collection<String> headerNames = response.getHeaderNames();\n for (String headerName : headerNames) {\n // there may be multiple headers per header name\n for (String headerValue : response.getHeaders(headerName)) {\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += headerName + \": \" + headerValue;\n }\n }\n\n return headerString;\n }" ]
[ "public Class getSearchClass()\r\n\t{\r\n\t\tObject obj = getExampleObject();\r\n\r\n\t\tif (obj instanceof Identity)\r\n\t\t{\r\n\t\t\treturn ((Identity) obj).getObjectsTopLevelClass();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn obj.getClass();\r\n\t\t}\r\n\t}", "public void generateWBS(Task parent)\n {\n String wbs;\n\n if (parent == null)\n {\n if (NumberHelper.getInt(getUniqueID()) == 0)\n {\n wbs = \"0\";\n }\n else\n {\n wbs = Integer.toString(getParentFile().getChildTasks().size() + 1);\n }\n }\n else\n {\n wbs = parent.getWBS();\n\n //\n // Apparently I added the next lines to support MPX files generated by Artemis, back in 2005\n // Unfortunately I have no test data which exercises this code, and it now breaks\n // otherwise valid WBS values read (in this case) from XER files. So it's commented out\n // until someone complains about their 2005-era Artemis MPX files not working!\n //\n // int index = wbs.lastIndexOf(\".0\");\n // if (index != -1)\n // {\n // wbs = wbs.substring(0, index);\n // }\n\n int childTaskCount = parent.getChildTasks().size() + 1;\n if (wbs.equals(\"0\"))\n {\n wbs = Integer.toString(childTaskCount);\n }\n else\n {\n wbs += (\".\" + childTaskCount);\n }\n }\n\n setWBS(wbs);\n }", "public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }", "public void set(int i, double value) {\n switch (i) {\n case 0: {\n x = value;\n break;\n }\n case 1: {\n y = value;\n break;\n }\n case 2: {\n z = value;\n break;\n }\n default: {\n throw new ArrayIndexOutOfBoundsException(i);\n }\n }\n }", "public void configure(@Observes(precedence = -200) ArquillianDescriptor arquillianDescriptor) {\n restAssuredConfigurationInstanceProducer.set(\n RestAssuredConfiguration.fromMap(arquillianDescriptor\n .extension(\"restassured\")\n .getExtensionProperties()));\n }", "static synchronized void clearLogContext() {\n final LogContext embeddedLogContext = Holder.LOG_CONTEXT;\n // Remove the configurator and clear the log context\n final Configurator configurator = embeddedLogContext.getLogger(\"\").detach(Configurator.ATTACHMENT_KEY);\n // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext\n if (configurator instanceof PropertyConfigurator) {\n final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();\n clearLogContext(logContextConfiguration);\n } else if (configurator instanceof LogContextConfiguration) {\n clearLogContext((LogContextConfiguration) configurator);\n } else {\n // Remove all the handlers and close them as well as reset the loggers\n final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());\n for (String name : loggerNames) {\n final Logger logger = embeddedLogContext.getLoggerIfExists(name);\n if (logger != null) {\n final Handler[] handlers = logger.clearHandlers();\n if (handlers != null) {\n for (Handler handler : handlers) {\n handler.close();\n }\n }\n logger.setFilter(null);\n logger.setUseParentFilters(false);\n logger.setUseParentHandlers(true);\n logger.setLevel(Level.INFO);\n }\n }\n }\n }", "public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public static appflowpolicy_appflowglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowglobal_binding obj = new appflowpolicy_appflowglobal_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowglobal_binding response[] = (appflowpolicy_appflowglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "synchronized void asyncReconnect(final URI reconnectUri, String authKey, final ReconnectCallback callback) {\n if (getState() != State.OPEN) {\n return;\n }\n // Update the configuration with the new credentials\n final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);\n config.setCallbackHandler(createClientCallbackHandler(userName, authKey));\n config.setUri(reconnectUri);\n this.configuration = config;\n\n final ReconnectRunner reconnectTask = this.reconnectRunner;\n if (reconnectTask == null) {\n final ReconnectRunner task = new ReconnectRunner();\n task.callback = callback;\n task.future = executorService.submit(task);\n } else {\n reconnectTask.callback = callback;\n }\n }" ]
Pump events from event stream.
[ "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 }" ]
[ "public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}", "public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) {\n if(!groupClass.isEnum()) {\n throw new IllegalArgumentException(\"The group class \"+groupClass+\" is not an enum\");\n }\n groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>());\n return this;\n }", "public static <IN extends CoreMap> CRFClassifier<IN> getClassifier(File file) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n CRFClassifier<IN> crf = new CRFClassifier<IN>();\r\n crf.loadClassifier(file);\r\n return crf;\r\n }", "public void setAngularLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularLowerLimits(getNative(), limitX, limitY, limitZ);\n }", "@NonNull public CharSequence getQuery() {\n if (searchView != null) {\n return searchView.getQuery();\n } else if (supportView != null) {\n return supportView.getQuery();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "public Set<DeviceAnnouncement> findUnreachablePlayers() {\n ensureRunning();\n Set<DeviceAnnouncement> result = new HashSet<DeviceAnnouncement>();\n for (DeviceAnnouncement candidate: DeviceFinder.getInstance().getCurrentDevices()) {\n if (!Util.sameNetwork(matchedAddress.getNetworkPrefixLength(), matchedAddress.getAddress(), candidate.getAddress())) {\n result.add(candidate);\n }\n }\n return Collections.unmodifiableSet(result);\n }", "private void addDateWithCheckState(Date date, boolean checkState) {\n\n addCheckBox(date, checkState);\n if (!m_dates.contains(date)) {\n m_dates.add(date);\n fireValueChange();\n }\n }", "private static Map<String, Object> processConf(Map<String, ?> conf) {\n Map<String, Object> m = new HashMap<String, Object>(conf.size());\n for (String s : conf.keySet()) {\n Object o = conf.get(s);\n if (s.startsWith(\"act.\")) s = s.substring(4);\n m.put(s, o);\n m.put(Config.canonical(s), o);\n }\n return m;\n }", "private QueueCursor updateCursorForDBObject(JSONObject dbObject, QueueCursor cursor) {\n\n if (dbObject == null) return cursor;\n\n Iterator<String> keys = dbObject.keys();\n if (keys.hasNext()) {\n String key = keys.next();\n cursor.setLastId(key);\n try {\n cursor.setData(dbObject.getJSONArray(key));\n } catch (JSONException e) {\n cursor.setLastId(null);\n cursor.setData(null);\n }\n }\n\n return cursor;\n }" ]
Use this API to fetch csvserver_cmppolicy_binding resources of given name .
[ "public static csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public long nextUniqueTransaction(long timeMs) {\n long id = timeMs;\n for (; ; ) {\n long old = transactionID.get();\n if (old >= id)\n id = old + 1;\n if (transactionID.compareAndSet(old, id))\n break;\n }\n return id;\n }", "public ItemRequest<Project> addCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/addCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "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 }", "public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\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 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}", "public static sslocspresponder get(nitro_service service, String name) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tobj.set_name(name);\n\t\tsslocspresponder response = (sslocspresponder) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void handleFailedSendDataRequest(SerialMessage originalMessage) {\n\t\tZWaveNode node = this.getNode(originalMessage.getMessageNode());\n\t\t\n\t\tif (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)\n\t\t\treturn;\n\t\t\n\t\tif (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {\n\t\t\tZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);\n\t\t\t\n\t\t\tif (wakeUpCommandClass != null) {\n\t\t\t\twakeUpCommandClass.setAwake(false);\n\t\t\t\twakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)\n\t\t\treturn;\n\t\t\n\t\tnode.incrementResendCount();\n\t\t\n\t\tlogger.error(\"Got an error while sending data to node {}. Resending message.\", node.getNodeId());\n\t\tthis.sendData(originalMessage);\n\t}", "private void verifyClusterStoreDefinition() {\n if(SystemStoreConstants.isSystemStore(storeDefinition.getName())) {\n // TODO: Once \"todo\" in StorageService.initSystemStores is complete,\n // this early return can be removed and verification can be enabled\n // for system stores.\n return;\n }\n\n Set<Integer> clusterZoneIds = cluster.getZoneIds();\n\n if(clusterZoneIds.size() > 1) { // Zoned\n Map<Integer, Integer> zoneRepFactor = storeDefinition.getZoneReplicationFactor();\n Set<Integer> storeDefZoneIds = zoneRepFactor.keySet();\n\n if(!clusterZoneIds.equals(storeDefZoneIds)) {\n throw new VoldemortException(\"Zone IDs in cluster (\" + clusterZoneIds\n + \") are incongruent with zone IDs in store defs (\"\n + storeDefZoneIds + \")\");\n }\n\n for(int zoneId: clusterZoneIds) {\n if(zoneRepFactor.get(zoneId) > cluster.getNumberOfNodesInZone(zoneId)) {\n throw new VoldemortException(\"Not enough nodes (\"\n + cluster.getNumberOfNodesInZone(zoneId)\n + \") in zone with id \" + zoneId\n + \" for replication factor of \"\n + zoneRepFactor.get(zoneId) + \".\");\n }\n }\n } else { // Non-zoned\n\n if(storeDefinition.getReplicationFactor() > cluster.getNumberOfNodes()) {\n System.err.println(storeDefinition);\n System.err.println(cluster);\n throw new VoldemortException(\"Not enough nodes (\" + cluster.getNumberOfNodes()\n + \") for replication factor of \"\n + storeDefinition.getReplicationFactor() + \".\");\n }\n }\n }" ]
Appends the String representation of the given operand to this CharSequence. @param left a CharSequence @param value any Object @return the original toString() of the CharSequence with the object appended @since 1.8.2
[ "public static String plus(CharSequence left, Object value) {\n return left + DefaultGroovyMethods.toString(value);\n }" ]
[ "public static boolean blockAligned( int blockLength , DSubmatrixD1 A ) {\n if( A.col0 % blockLength != 0 )\n return false;\n if( A.row0 % blockLength != 0 )\n return false;\n\n if( A.col1 % blockLength != 0 && A.col1 != A.original.numCols ) {\n return false;\n }\n\n if( A.row1 % blockLength != 0 && A.row1 != A.original.numRows) {\n return false;\n }\n\n return true;\n }", "public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception {\n HeaderMap headers = exchange.getRequestHeaders();\n String[] origins = headers.get(Headers.ORIGIN).toArray();\n if (allowedOrigins != null && !allowedOrigins.isEmpty()) {\n for (String allowedOrigin : allowedOrigins) {\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n }\n }\n String allowedOrigin = defaultOrigin(exchange);\n for (String origin : origins) {\n if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {\n return allowedOrigin;\n }\n }\n ROOT_LOGGER.debug(\"Request rejected due to HOST/ORIGIN mis-match.\");\n ResponseCodeHandler.HANDLE_403.handleRequest(exchange);\n return null;\n }", "@Override\n\tpublic ClosableIterator<Tuple> callStoredProcedure(String storedProcedureName, ProcedureQueryParameters params, TupleContext tupleContext) {\n\t\tvalidate( params );\n\t\tStringBuilder commandLine = createCallStoreProcedureCommand( storedProcedureName, params );\n\t\tDocument result = callStoredProcedure( commandLine );\n\t\tObject resultValue = result.get( \"retval\" );\n\t\tList<Tuple> resultTuples = extractTuples( storedProcedureName, resultValue );\n\t\treturn CollectionHelper.newClosableIterator( resultTuples );\n\t}", "public static base_response unset(nitro_service client, systemuser resource, String[] args) throws Exception{\n\t\tsystemuser unsetresource = new systemuser();\n\t\tunsetresource.username = resource.username;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public String toUriString(final java.net.URI uri) {\n return this.toUriString(URI.createURI(uri.normalize().toString()));\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 }", "GVRSceneObject makeParticleMesh(float[] vertices, float[] velocities,\n float[] particleTimeStamps )\n {\n mParticleMesh = new GVRMesh(mGVRContext);\n\n //pass the particle positions as vertices, velocities as normals, and\n //spawning times as texture coordinates.\n mParticleMesh.setVertices(vertices);\n mParticleMesh.setNormals(velocities);\n mParticleMesh.setTexCoords(particleTimeStamps);\n\n particleID = new GVRShaderId(ParticleShader.class);\n material = new GVRMaterial(mGVRContext, particleID);\n\n material.setVec4(\"u_color\", mColorMultiplier.x, mColorMultiplier.y,\n mColorMultiplier.z, mColorMultiplier.w);\n material.setFloat(\"u_particle_age\", mAge);\n material.setVec3(\"u_acceleration\", mAcceleration.x, mAcceleration.y, mAcceleration.z);\n material.setFloat(\"u_particle_size\", mSize);\n material.setFloat(\"u_size_change_rate\", mParticleSizeRate);\n material.setFloat(\"u_fade\", mFadeWithAge);\n material.setFloat(\"u_noise_factor\", mNoiseFactor);\n\n GVRRenderData renderData = new GVRRenderData(mGVRContext);\n renderData.setMaterial(material);\n renderData.setMesh(mParticleMesh);\n material.setMainTexture(mTexture);\n\n GVRSceneObject meshObject = new GVRSceneObject(mGVRContext);\n meshObject.attachRenderData(renderData);\n meshObject.getRenderData().setMaterial(material);\n\n // Set the draw mode to GL_POINTS, disable writing to depth buffer, enable depth testing\n // and set the rendering order to transparent.\n // Disabling writing to depth buffer ensure that the particles blend correctly\n // and keeping the depth test on along with rendering them\n // after the geometry queue makes sure they occlude, and are occluded, correctly.\n\n meshObject.getRenderData().setDrawMode(GL_POINTS);\n meshObject.getRenderData().setDepthTest(true);\n meshObject.getRenderData().setDepthMask(false);\n meshObject.getRenderData().setRenderingOrder(GVRRenderData.GVRRenderingOrder.TRANSPARENT);\n\n return meshObject;\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 void assertValidNode(MetadataStore metadataStore, Integer nodeId) {\n if(!metadataStore.getCluster().hasNodeWithId(nodeId)) {\n throw new InvalidMetadataException(\"NodeId \" + nodeId + \" is not or no longer in this cluster\");\n }\n }" ]
Find and return the appropriate setter method for field. @return Set method or null (or throws IllegalArgumentException) if none found.
[ "public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}" ]
[ "private Properties parseXML(Document doc, String sectionName) {\n\t\tint found = -1;\n\t\tProperties results = new Properties();\n\t\tNodeList config = null;\n\t\tif (sectionName == null){\n\t\t\tconfig = doc.getElementsByTagName(\"default-config\");\n\t\t\tfound = 0;\n\t\t} else {\n\t\t\tconfig = doc.getElementsByTagName(\"named-config\");\n\t\t\tif(config != null && config.getLength() > 0) {\n\t\t\t\tfor (int i = 0; i < config.getLength(); i++) {\n\t\t\t\t\tNode node = config.item(i);\n\t\t\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE ){\n\t\t\t\t\t\tNamedNodeMap attributes = node.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tNode name = attributes.getNamedItem(\"name\");\n\t\t\t\t\t\t\tif (name.getNodeValue().equalsIgnoreCase(sectionName)){\n\t\t\t\t\t\t\t\tfound = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found == -1){\n\t\t\t\tconfig = null;\n\t\t\t\tlogger.warn(\"Did not find \"+sectionName+\" section in config file. Reverting to defaults.\");\n\t\t\t}\n\t\t}\n\n\t\tif(config != null && config.getLength() > 0) {\n\t\t\tNode node = config.item(found);\n\t\t\tif(node.getNodeType() == Node.ELEMENT_NODE){\n\t\t\t\tElement elementEntry = (Element)node;\n\t\t\t\tNodeList childNodeList = elementEntry.getChildNodes();\n\t\t\t\tfor (int j = 0; j < childNodeList.getLength(); j++) {\n\t\t\t\t\tNode node_j = childNodeList.item(j);\n\t\t\t\t\tif (node_j.getNodeType() == Node.ELEMENT_NODE) {\n\t\t\t\t\t\tElement piece = (Element) node_j;\n\t\t\t\t\t\tNamedNodeMap attributes = piece.getAttributes();\n\t\t\t\t\t\tif (attributes != null && attributes.getLength() > 0){\n\t\t\t\t\t\t\tresults.put(attributes.item(0).getNodeValue(), piece.getTextContent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}", "public String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }", "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "private void addMetadataProviderForMedia(String key, MetadataProvider provider) {\n if (!metadataProviders.containsKey(key)) {\n metadataProviders.put(key, Collections.newSetFromMap(new ConcurrentHashMap<MetadataProvider, Boolean>()));\n }\n Set<MetadataProvider> providers = metadataProviders.get(key);\n providers.add(provider);\n }", "public Boolean getBoolean(String fieldName) {\n\t\treturn hasValue(fieldName) ? Boolean.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t}", "private void processKeyValue(Map<ConfigurationKey, Object> properties, ConfigurationKey key, Object value) {\n if (value instanceof String) {\n value = key.convertValue((String) value);\n }\n if (key.isValidValue(value)) {\n Object previous = properties.put(key, value);\n if (previous != null && !previous.equals(value)) {\n throw ConfigurationLogger.LOG.configurationKeyHasDifferentValues(key.get(), previous, value);\n }\n } else {\n throw ConfigurationLogger.LOG.invalidConfigurationPropertyValue(value, key.get());\n }\n }", "static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {\n int patIdxStart = 0;\n int patIdxEnd = tokenizedPattern.length - 1;\n int strIdxStart = 0;\n int strIdxEnd = strDirs.length - 1;\n\n // up to first '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxStart];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {\n return false;\n }\n patIdxStart++;\n strIdxStart++;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n } else {\n if (patIdxStart > patIdxEnd) {\n // String not exhausted, but pattern is. Failure.\n return false;\n }\n }\n\n // up to last '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxEnd];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {\n return false;\n }\n patIdxEnd--;\n strIdxEnd--;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n }\n\n while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {\n int patIdxTmp = -1;\n for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {\n if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n patIdxTmp = i;\n break;\n }\n }\n if (patIdxTmp == patIdxStart + 1) {\n // '**/**' situation, so skip one\n patIdxStart++;\n continue;\n }\n // Find the pattern between padIdxStart & padIdxTmp in str between\n // strIdxStart & strIdxEnd\n int patLength = (patIdxTmp - patIdxStart - 1);\n int strLength = (strIdxEnd - strIdxStart + 1);\n int foundIdx = -1;\n strLoop:\n for (int i = 0; i <= strLength - patLength; i++) {\n for (int j = 0; j < patLength; j++) {\n String subPat = tokenizedPattern[patIdxStart + j + 1];\n String subStr = strDirs[strIdxStart + i + j];\n if (!match(subPat, subStr, isCaseSensitive)) {\n continue strLoop;\n }\n }\n\n foundIdx = strIdxStart + i;\n break;\n }\n\n if (foundIdx == -1) {\n return false;\n }\n\n patIdxStart = patIdxTmp;\n strIdxStart = foundIdx + patLength;\n }\n\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n\n return true;\n }", "String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }", "public ParallelTaskBuilder setHttpPollerProcessor(\n HttpPollerProcessor httpPollerProcessor) {\n this.httpMeta.setHttpPollerProcessor(httpPollerProcessor);\n this.httpMeta.setPollable(true);\n return this;\n }" ]
Close the ClientRequestExecutor.
[ "@Override\n public void destroy(SocketDestination dest, ClientRequestExecutor clientRequestExecutor)\n throws Exception {\n clientRequestExecutor.close();\n int numDestroyed = destroyed.incrementAndGet();\n if(stats != null) {\n stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_DESTROYED_EVENT);\n }\n\n if(logger.isDebugEnabled())\n logger.debug(\"Destroyed socket \" + numDestroyed + \" connection to \" + dest.getHost()\n + \":\" + dest.getPort());\n }" ]
[ "public void writeTo(Writer destination) {\n Element eltRuleset = new Element(\"ruleset\");\n addAttribute(eltRuleset, \"name\", name);\n addChild(eltRuleset, \"description\", description);\n for (PmdRule pmdRule : rules) {\n Element eltRule = new Element(\"rule\");\n addAttribute(eltRule, \"ref\", pmdRule.getRef());\n addAttribute(eltRule, \"class\", pmdRule.getClazz());\n addAttribute(eltRule, \"message\", pmdRule.getMessage());\n addAttribute(eltRule, \"name\", pmdRule.getName());\n addAttribute(eltRule, \"language\", pmdRule.getLanguage());\n addChild(eltRule, \"priority\", String.valueOf(pmdRule.getPriority()));\n if (pmdRule.hasProperties()) {\n Element ruleProperties = processRuleProperties(pmdRule);\n if (ruleProperties.getContentSize() > 0) {\n eltRule.addContent(ruleProperties);\n }\n }\n eltRuleset.addContent(eltRule);\n }\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n try {\n serializer.output(new Document(eltRuleset), destination);\n } catch (IOException e) {\n throw new IllegalStateException(\"An exception occurred while serializing PmdRuleSet.\", e);\n }\n }", "public void process(File file) throws Exception\n {\n openLogFile();\n\n int blockIndex = 0;\n int length = (int) file.length();\n m_buffer = new byte[length];\n FileInputStream is = new FileInputStream(file);\n try\n {\n int bytesRead = is.read(m_buffer);\n if (bytesRead != length)\n {\n throw new RuntimeException(\"Read count different\");\n }\n }\n finally\n {\n is.close();\n }\n\n List<Integer> blocks = new ArrayList<Integer>();\n for (int index = 64; index < m_buffer.length - 11; index++)\n {\n if (matchPattern(PARENT_BLOCK_PATTERNS, index))\n {\n blocks.add(Integer.valueOf(index));\n }\n }\n\n int startIndex = 0;\n for (int endIndex : blocks)\n {\n int blockLength = endIndex - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n startIndex = endIndex;\n ++blockIndex;\n }\n\n int blockLength = m_buffer.length - startIndex;\n readBlock(blockIndex, startIndex, blockLength);\n\n closeLogFile();\n }", "public String getUniformDescriptor(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate.getUniformDescriptor();\n }", "public void seekToDayOfMonth(String dayOfMonth) {\n int dayOfMonthInt = Integer.parseInt(dayOfMonth);\n assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31);\n \n markDateInvocation();\n \n dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt);\n }", "public static String insertDumpInformation(String pattern,\n\t\t\tString dateStamp, String project) {\n\t\tif (pattern == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn pattern.replace(\"{DATE}\", dateStamp).replace(\"{PROJECT}\",\n\t\t\t\t\tproject);\n\t\t}\n\t}", "private void printClassRecord(PrintStream out, ClassRecord classRecord,\n\t\t\tEntityIdValue entityIdValue) {\n\t\tprintTerms(out, classRecord.itemDocument, entityIdValue, \"\\\"\"\n\t\t\t\t+ getClassLabel(entityIdValue) + \"\\\"\");\n\t\tprintImage(out, classRecord.itemDocument);\n\n\t\tout.print(\",\" + classRecord.itemCount + \",\" + classRecord.subclassCount);\n\n\t\tprintClassList(out, classRecord.superClasses);\n\n\t\tHashSet<EntityIdValue> superClasses = new HashSet<>();\n\t\tfor (EntityIdValue superClass : classRecord.superClasses) {\n\t\t\taddSuperClasses(superClass, superClasses);\n\t\t}\n\n\t\tprintClassList(out, superClasses);\n\n\t\tprintRelatedProperties(out, classRecord);\n\n\t\tout.println(\"\");\n\t}", "private String getClassNameFromPath(String path) {\n String className = path.replace(\".class\", \"\");\n\n // for *nix\n if (className.startsWith(\"/\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"/\", \".\");\n\n // for windows\n if (className.startsWith(\"\\\\\")) {\n className = className.substring(1, className.length());\n }\n className = className.replace(\"\\\\\", \".\");\n\n return className;\n }", "protected String getFormattedDatatypeValue(ICompositeNode node, AbstractRule rule, String text) throws ValueConverterException {\n\t\tObject value = valueConverter.toValue(text, rule.getName(), node);\n\t\ttext = valueConverter.toString(value, rule.getName());\n\t\treturn text;\n\t}", "public Response getBill(int month, int year)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new Response(request.get(\"/bill/\" + year + String.format(\"-%02d\", month)));\n }" ]
Use this API to fetch dnsview resource of given name .
[ "public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public NamespacesList<Namespace> getNamespaces(String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Namespace> nsList = new NamespacesList<Namespace>();\r\n parameters.put(\"method\", METHOD_GET_NAMESPACES);\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(\"namespace\");\r\n nsList.setPage(\"1\");\r\n nsList.setPages(\"1\");\r\n nsList.setPerPage(\"\" + nsNodes.getLength());\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parseNamespace(element));\r\n }\r\n return nsList;\r\n }", "public static boolean containsAllQualifiers(Set<QualifierInstance> requiredQualifiers, Set<QualifierInstance> qualifiers) {\n return qualifiers.containsAll(requiredQualifiers);\n }", "public static final String printDuration(Duration duration)\n {\n String result = null;\n if (duration != null)\n {\n result = duration.getDuration() + \" \" + printTimeUnits(duration.getUnits());\n }\n return result;\n }", "private boolean isRelated(Task task, List<Relation> list)\n {\n boolean result = false;\n for (Relation relation : list)\n {\n if (relation.getTargetTask().getUniqueID().intValue() == task.getUniqueID().intValue())\n {\n result = true;\n break;\n }\n }\n return result;\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}", "public void clearHistory(int profileId, String clientUUID) {\n PreparedStatement query = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"DELETE FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is null or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId;\n }\n\n // see if clientUUID is null or not\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \" AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"'\";\n }\n\n sqlQuery += \";\";\n\n logger.info(\"Query: {}\", sqlQuery);\n query = sqlConnection.prepareStatement(sqlQuery);\n query.executeUpdate();\n } catch (Exception e) {\n } finally {\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\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}", "@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\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 }" ]
Read the data for all of the tables we're interested in. @param tables list of all available tables @param is input stream
[ "private void readTableData(List<SynchroTable> tables, InputStream is) throws IOException\n {\n for (SynchroTable table : tables)\n {\n if (REQUIRED_TABLES.contains(table.getName()))\n {\n readTable(is, table);\n }\n }\n }" ]
[ "public void clearResponseSettings(int pathId, String clientUUID) throws Exception {\n logger.info(\"clearing response settings\");\n this.setResponseEnabled(pathId, false, clientUUID);\n OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_RESPONSE);\n EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_RESPONSE, pathId, clientUUID);\n }", "public AT_Row setPaddingRightChar(Character paddingRightChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static boolean xpathExists(Node document, String xpathExpression, Map<String, String> namespaceMapping) throws XPathException,\n MarshallingException\n {\n Boolean result = (Boolean) executeXPath(document, xpathExpression, namespaceMapping, XPathConstants.BOOLEAN);\n return result != null && result;\n }", "private void addClasses(XMLStreamWriter writer, File jarFile, boolean mapClassMethods) throws IOException, ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();\n\n URLClassLoader loader = new URLClassLoader(new URL[]\n {\n jarFile.toURI().toURL()\n }, currentThreadClassLoader);\n\n JarFile jar = new JarFile(jarFile);\n Enumeration<JarEntry> enumeration = jar.entries();\n while (enumeration.hasMoreElements())\n {\n JarEntry jarEntry = enumeration.nextElement();\n if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(\".class\"))\n {\n addClass(loader, jarEntry, writer, mapClassMethods);\n }\n }\n jar.close();\n }", "private String extractNumericVersion(Collection<String> versionStrings) {\n if (versionStrings == null) {\n return \"\";\n }\n for (String value : versionStrings) {\n String releaseValue = calculateReleaseVersion(value);\n if (!releaseValue.equals(value)) {\n return releaseValue;\n }\n }\n return \"\";\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 Tree determineHead(Tree t, Tree parent) {\r\n if (nonTerminalInfo == null) {\r\n throw new RuntimeException(\"Classes derived from AbstractCollinsHeadFinder must\" + \" create and fill HashMap nonTerminalInfo.\");\r\n }\r\n if (t == null || t.isLeaf()) {\r\n return null;\r\n }\r\n if (DEBUG) {\r\n System.err.println(\"determineHead for \" + t.value());\r\n }\r\n \r\n Tree[] kids = t.children();\r\n\r\n Tree theHead;\r\n // first check if subclass found explicitly marked head\r\n if ((theHead = findMarkedHead(t)) != null) {\r\n if (DEBUG) {\r\n System.err.println(\"Find marked head method returned \" +\r\n theHead.label() + \" as head of \" + t.label());\r\n }\r\n return theHead;\r\n }\r\n\r\n // if the node is a unary, then that kid must be the head\r\n // it used to special case preterminal and ROOT/TOP case\r\n // but that seemed bad (especially hardcoding string \"ROOT\")\r\n if (kids.length == 1) {\r\n if (DEBUG) {\r\n System.err.println(\"Only one child determines \" +\r\n kids[0].label() + \" as head of \" + t.label());\r\n }\r\n return kids[0];\r\n }\r\n\r\n return determineNonTrivialHead(t, parent);\r\n }", "public void setSessionFactory(SessionFactory sessionFactory) throws HibernateLayerException {\n\t\ttry {\n\t\t\tthis.sessionFactory = sessionFactory;\n\t\t\tif (null != layerInfo) {\n\t\t\t\tentityMetadata = sessionFactory.getClassMetadata(layerInfo.getFeatureInfo().getDataSourceName());\n\t\t\t}\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_NO_SESSION_FACTORY);\n\t\t}\n\t}", "public Diff compare(CtElement left, CtElement right) {\n\t\tfinal SpoonGumTreeBuilder scanner = new SpoonGumTreeBuilder();\n\t\treturn new DiffImpl(scanner.getTreeContext(), scanner.getTree(left), scanner.getTree(right));\n\t}" ]
Send an error to the client with a message. @param httpServletResponse the response to send the error to. @param message the message to send @param code the error code
[ "protected static void error(\n final HttpServletResponse httpServletResponse, final String message, final HttpStatus code) {\n try {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(code.value());\n setNoCache(httpServletResponse);\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n out.println(message);\n }\n\n LOGGER.error(\"Error while processing request: {}\", message);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }" ]
[ "private void setSiteFilters(String filters) {\n\t\tthis.filterSites = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterSites, filters.split(\",\"));\n\t\t}\n\t}", "public static void dumpMaterial(AiMaterial material) {\n for (AiMaterial.Property prop : material.getProperties()) {\n dumpMaterialProperty(prop);\n }\n }", "public static base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private Long fetchServiceId(ServiceReference serviceReference) {\n return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);\n }", "public static int getChunkId(String fileName) {\n Pattern pattern = Pattern.compile(\"_[\\\\d]+\\\\.\");\n Matcher matcher = pattern.matcher(fileName);\n\n if(matcher.find()) {\n return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1));\n } else {\n throw new VoldemortException(\"Could not extract out chunk id from \" + fileName);\n }\n }", "@Override\r\n public boolean add(E o) {\r\n Integer index = indexes.get(o);\r\n if (index == null && ! locked) {\r\n index = objects.size();\r\n objects.add(o);\r\n indexes.put(o, index);\r\n return true;\r\n }\r\n return false;\r\n }", "public static String getSerializedVectorClock(VectorClock vc) {\n VectorClockWrapper vcWrapper = new VectorClockWrapper(vc);\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vcWrapper);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "protected String ensureTextColorFormat(String textColor) {\n String formatted = \"\";\n boolean mainColor = true;\n for (String style : textColor.split(\" \")) {\n if (mainColor) {\n // the main color\n if (!style.endsWith(\"-text\")) {\n style += \"-text\";\n }\n mainColor = false;\n } else {\n // the shading type\n if (!style.startsWith(\"text-\")) {\n style = \" text-\" + style;\n }\n }\n formatted += style;\n }\n return formatted;\n }", "private Collection parseCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n collection.setId(collectionElement.getAttribute(\"id\"));\n collection.setServer(collectionElement.getAttribute(\"server\"));\n collection.setSecret(collectionElement.getAttribute(\"secret\"));\n collection.setChildCount(collectionElement.getAttribute(\"child_count\"));\n collection.setIconLarge(collectionElement.getAttribute(\"iconlarge\"));\n collection.setIconSmall(collectionElement.getAttribute(\"iconsmall\"));\n collection.setDateCreated(collectionElement.getAttribute(\"datecreate\"));\n collection.setTitle(XMLUtilities.getChildValue(collectionElement, \"title\"));\n collection.setDescription(XMLUtilities.getChildValue(collectionElement, \"description\"));\n\n Element iconPhotos = XMLUtilities.getChild(collectionElement, \"iconphotos\");\n if (iconPhotos != null) {\n NodeList photoElements = iconPhotos.getElementsByTagName(\"photo\");\n for (int i = 0; i < photoElements.getLength(); i++) {\n Element photoElement = (Element) photoElements.item(i);\n collection.addPhoto(PhotoUtils.createPhoto(photoElement));\n }\n }\n\n return collection;\n }" ]
Creates an empty block style definition. @return
[ "protected NodeData createBlockStyle()\n {\n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"display\", tf.createIdent(\"block\")));\n return ret;\n }" ]
[ "public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }", "public static appflowpolicy_appflowglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_appflowglobal_binding obj = new appflowpolicy_appflowglobal_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_appflowglobal_binding response[] = (appflowpolicy_appflowglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected String calculateNextVersion(String fromVersion) {\n // first turn it to release version\n fromVersion = calculateReleaseVersion(fromVersion);\n String nextVersion;\n int lastDotIndex = fromVersion.lastIndexOf('.');\n try {\n if (lastDotIndex != -1) {\n // probably a major minor version e.g., 2.1.1\n String minorVersionToken = fromVersion.substring(lastDotIndex + 1);\n String nextMinorVersion;\n int lastDashIndex = minorVersionToken.lastIndexOf('-');\n if (lastDashIndex != -1) {\n // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5)\n String buildNumber = minorVersionToken.substring(lastDashIndex + 1);\n int nextBuildNumber = Integer.parseInt(buildNumber) + 1;\n nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber;\n } else {\n nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + \"\";\n }\n nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion;\n } else {\n // maybe it's just a major version; try to parse as an int\n int nextMajorVersion = Integer.parseInt(fromVersion) + 1;\n nextVersion = nextMajorVersion + \"\";\n }\n } catch (NumberFormatException e) {\n return fromVersion;\n }\n return nextVersion + \"-SNAPSHOT\";\n }", "public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){\n\t\tfinal Artifact artifact = new Artifact();\n\n\t\tartifact.setGroupId(groupId);\n\t\tartifact.setArtifactId(artifactId);\n\t\tartifact.setVersion(version);\n\n\t\tif(classifier != null){\n\t\t\tartifact.setClassifier(classifier);\n\t\t}\n\n\t\tif(type != null){\n\t\t\tartifact.setType(type);\n\t\t}\n\n\t\tif(extension != null){\n\t\t\tartifact.setExtension(extension);\n\t\t}\n\n\t\tartifact.setOrigin(origin == null ? \"maven\" : origin);\n\n\t\treturn artifact;\n\t}", "public static <E> Collection<E> sampleWithReplacement(Collection<E> c, int n) {\r\n return sampleWithReplacement(c, n, new Random());\r\n }", "public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }", "public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }", "public AT_CellContext setPadding(int padding){\r\n\t\tif(padding>-1){\r\n\t\t\tthis.paddingTop = padding;\r\n\t\t\tthis.paddingBottom = padding;\r\n\t\t\tthis.paddingLeft = padding;\r\n\t\t\tthis.paddingRight = padding;\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private String getDateTimeString(Date value)\n {\n String result = null;\n if (value != null)\n {\n Calendar cal = DateHelper.popCalendar(value);\n StringBuilder sb = new StringBuilder(16);\n sb.append(m_fourDigitFormat.format(cal.get(Calendar.YEAR)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.MONTH) + 1));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.DAY_OF_MONTH)));\n sb.append('T');\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.HOUR_OF_DAY)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.MINUTE)));\n sb.append(m_twoDigitFormat.format(cal.get(Calendar.SECOND)));\n sb.append('Z');\n result = sb.toString();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }" ]
Generates a full list of all parents and their children, in order. Uses Map to preserve last expanded state. @param parentList A list of the parents from the {@link ExpandableRecyclerAdapter} @param savedLastExpansionState A map of the last expanded state for a given parent key. @return A list of all parents and their children, expanded accordingly
[ "private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) {\n List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>();\n\n int parentCount = parentList.size();\n for (int i = 0; i < parentCount; i++) {\n P parent = parentList.get(i);\n Boolean lastExpandedState = savedLastExpansionState.get(parent);\n boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState;\n\n generateParentWrapper(flatItemList, parent, shouldExpand);\n }\n\n return flatItemList;\n }" ]
[ "public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE);\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)\n\t\t\tthrows IllegalArgumentException {\n\t\tMethod fieldSetMethod = findMethodFromNames(field, false, throwExceptions,\n\t\t\t\tmethodFromField(field, \"set\", databaseType, true), methodFromField(field, \"set\", databaseType, false));\n\t\tif (fieldSetMethod == null) {\n\t\t\treturn null;\n\t\t}\n\t\tif (fieldSetMethod.getReturnType() != void.class) {\n\t\t\tif (throwExceptions) {\n\t\t\t\tthrow new IllegalArgumentException(\"Return type of set method \" + fieldSetMethod.getName() + \" returns \"\n\t\t\t\t\t\t+ fieldSetMethod.getReturnType() + \" instead of void\");\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn fieldSetMethod;\n\t}", "public static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }", "public static cachecontentgroup get(nitro_service service, String name) throws Exception{\n\t\tcachecontentgroup obj = new cachecontentgroup();\n\t\tobj.set_name(name);\n\t\tcachecontentgroup response = (cachecontentgroup) obj.get_resource(service);\n\t\treturn response;\n\t}", "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 appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public static Command newSetGlobal(String identifier,\n Object object) {\n return getCommandFactoryProvider().newSetGlobal( identifier,\n object );\n }", "public boolean addSsextension(String ssExt) {\n if (this.ssextensions == null) {\n this.ssextensions = new ArrayList<String>();\n }\n return this.ssextensions.add(ssExt);\n }", "public void convertToSparse() {\n switch ( mat.getType() ) {\n case DDRM: {\n DMatrixSparseCSC m = new DMatrixSparseCSC(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrixRMaj) mat, m,0);\n setMatrix(m);\n } break;\n case FDRM: {\n FMatrixSparseCSC m = new FMatrixSparseCSC(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrixRMaj) mat, m,0);\n setMatrix(m);\n } break;\n\n case DSCC:\n case FSCC:\n break;\n default:\n throw new RuntimeException(\"Conversion not supported!\");\n }\n }" ]
Set default value with @param iso ISO2 of country
[ "public void setEmptyDefault(String iso) {\n if (iso == null || iso.isEmpty()) {\n iso = DEFAULT_COUNTRY;\n }\n int defaultIdx = mCountries.indexOfIso(iso);\n mSelectedCountry = mCountries.get(defaultIdx);\n mCountrySpinner.setSelection(defaultIdx);\n }" ]
[ "public <T> T find(Class<T> classType, String id, String rev) {\n assertNotEmpty(classType, \"Class\");\n assertNotEmpty(id, \"id\");\n assertNotEmpty(id, \"rev\");\n final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, \"rev\", rev);\n return couchDbClient.get(uri, classType);\n }", "public void stopServer() throws Exception {\n if (!externalDatabaseHost) {\n try (Connection sqlConnection = getConnection()) {\n sqlConnection.prepareStatement(\"SHUTDOWN\").execute();\n } catch (Exception e) {\n }\n\n try {\n server.stop();\n } catch (Exception e) {\n }\n }\n }", "private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException {\n\n final PrintWriter pw = res.getWriter();\n final JSONObject response = getJsonFormattedSpellcheckResult(request);\n pw.println(response.toString());\n pw.close();\n }", "public static String getContext(final PObject[] objs) {\n StringBuilder result = new StringBuilder(\"(\");\n boolean first = true;\n for (PObject obj: objs) {\n if (!first) {\n result.append('|');\n }\n first = false;\n result.append(obj.getCurrentPath());\n }\n result.append(')');\n return result.toString();\n }", "@Override\n\tpublic boolean exists() {\n\t\ttry {\n\t\t\tInputStream inputStream = this.assetManager.open(this.fileName);\n\t\t\tif (inputStream != null) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\treturn false;\n\t\t}\n\t}", "public static String getSerializedVectorClock(VectorClock vc) {\n VectorClockWrapper vcWrapper = new VectorClockWrapper(vc);\n String serializedVC = \"\";\n try {\n serializedVC = mapper.writeValueAsString(vcWrapper);\n } catch(Exception e) {\n e.printStackTrace();\n }\n return serializedVC;\n }", "void countNonZeroInV( int []parent ) {\n int []w = gwork.data;\n findMinElementIndexInRows(leftmost);\n createRowElementLinkedLists(leftmost,w);\n countNonZeroUsingLinkedList(parent,w);\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 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}" ]
Retrieves the timephased breakdown of actual cost. @return timephased actual cost
[ "public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }" ]
[ "static int lastArgMatchesVarg(Parameter[] params, ClassNode... args) {\n if (!isVargs(params)) return -1;\n // case length ==0 handled already\n // we have now two cases,\n // the argument is wrapped in the vargs array or\n // the argument is an array that can be used for the vargs part directly\n // we test only the wrapping part, since the non wrapping is done already\n ClassNode lastParamType = params[params.length - 1].getType();\n ClassNode ptype = lastParamType.getComponentType();\n ClassNode arg = args[args.length - 1];\n if (isNumberType(ptype) && isNumberType(arg) && !ptype.equals(arg)) return -1;\n return isAssignableTo(arg, ptype)?Math.min(getDistance(arg, lastParamType), getDistance(arg, ptype)):-1;\n }", "public static vrid6 get(nitro_service service, Long id) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tobj.set_id(id);\n\t\tvrid6 response = (vrid6) obj.get_resource(service);\n\t\treturn response;\n\t}", "private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) {\n\t\tint age=this.getProperties().getMaxFileAge();\n\t\tGregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH));\n\t\tresult.add(Calendar.DAY_OF_MONTH, -age);\n\t\treturn result;\n\t}", "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 }", "private void writeFileCreationRecord() throws IOException\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n\n m_buffer.setLength(0);\n m_buffer.append(\"MPX\");\n m_buffer.append(m_delimiter);\n m_buffer.append(properties.getMpxProgramName());\n m_buffer.append(m_delimiter);\n m_buffer.append(properties.getMpxFileVersion());\n m_buffer.append(m_delimiter);\n m_buffer.append(properties.getMpxCodePage());\n m_buffer.append(MPXConstants.EOL);\n m_writer.write(m_buffer.toString());\n }", "public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }", "protected final void _onConnect(WebSocketContext context) {\n if (null != connectionListener) {\n connectionListener.onConnect(context);\n }\n connectionListenerManager.notifyFreeListeners(context, false);\n Act.eventBus().emit(new WebSocketConnectEvent(context));\n }", "public BoxFolder.Info getFolderInfo(String folderID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFolder folder = new BoxFolder(this.api, jsonObject.get(\"id\").asString());\n return folder.new Info(response.getJSON());\n }", "public static String getOjbClassName(ResultSet rs)\r\n {\r\n try\r\n {\r\n return rs.getString(OJB_CLASS_COLUMN);\r\n }\r\n catch (SQLException e)\r\n {\r\n return null;\r\n }\r\n }" ]
The transform method for this DataTransformer @param cr a reference to DataPipe from which to read the current map
[ "public void transform(DataPipe cr) {\n for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) {\n String value = entry.getValue();\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n entry.setValue(String.valueOf(ran));\n }\n }\n }" ]
[ "public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\n }", "synchronized void stop(Integer timeout) {\n final InternalState required = this.requiredState;\n if(required != InternalState.STOPPED) {\n this.requiredState = InternalState.STOPPED;\n ROOT_LOGGER.stoppingServer(serverName);\n // Only send the stop operation if the server is started\n if (internalState == InternalState.SERVER_STARTED) {\n internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);\n } else {\n transition(false);\n }\n }\n }", "public ModelNode translateOperationForProxy(final ModelNode op) {\n return translateOperationForProxy(op, PathAddress.pathAddress(op.get(OP_ADDR)));\n }", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnssimpleacl clearresource = new nssimpleacl();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "private String escapeQuotes(String value)\n {\n StringBuilder sb = new StringBuilder();\n int length = value.length();\n char c;\n\n sb.append('\"');\n for (int index = 0; index < length; index++)\n {\n c = value.charAt(index);\n sb.append(c);\n\n if (c == '\"')\n {\n sb.append('\"');\n }\n }\n sb.append('\"');\n\n return (sb.toString());\n }", "public static String getDateTimeStrStandard(Date d) {\n if (d == null)\n return \"\";\n\n if (d.getTime() == 0L)\n return \"Never\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy.MM.dd.HH.mm.ss.SSSZ\");\n\n return sdf.format(d);\n }", "public Script updateName(int id, String name) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SCRIPT +\n \" SET \" + Constants.SCRIPT_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return this.getScript(id);\n }", "public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\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 }" ]
Changes the index buffer associated with this mesh. @param ibuf new index buffer to use @see #setIndices(int[]) @see #getIndexBuffer() @see #getIntIndices()
[ "public void setIndexBuffer(GVRIndexBuffer ibuf)\n {\n mIndices = ibuf;\n NativeMesh.setIndexBuffer(getNative(), (ibuf != null) ? ibuf.getNative() : 0L);\n }" ]
[ "public static base_response delete(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 deleteresource = new nsacl6();\n\t\tdeleteresource.acl6name = acl6name;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public String splitSpecialStateSwitch(String specialStateTransition){\n\t\tMatcher transformedSpecialStateMatcher =\n\t\t\t\tTRANSORMED_SPECIAL_STATE_TRANSITION_METHOD.matcher(specialStateTransition);\n\t\tif( !transformedSpecialStateMatcher.find() ){\n\t\t\treturn specialStateTransition;\n\t\t}\n\t\t\n\t\tString specialStateSwitch = transformedSpecialStateMatcher.group(3);\n\t\t\n\t\tMatcher transformedCaseMatcher = TRANSFORMED_CASE_PATTERN.matcher(specialStateSwitch);\n\t\t\n\t\tStringBuffer switchReplacementBuffer = new StringBuffer();\n\t\tStringBuffer extractedMethods = new StringBuffer();\n\t\tList<String> extractedCasesList = new ArrayList<String>();\n\n\t\tswitchReplacementBuffer.append(\"$2\\n\");\n\t\t\n\t\tboolean methodExtracted = false;\n\t\tboolean isFirst = true;\n\t\tString from = \"0\";\n\t\tString to = \"0\";\n\t\t//Process individual case statements\n\t\twhile(transformedCaseMatcher.find()){\n\t\t\tif(isFirst){\n\t\t\t\tisFirst = false;\n\t\t\t\tfrom = transformedCaseMatcher.group(2);\n\t\t\t}\n\t\t\tto = transformedCaseMatcher.group(2);\n\t\t\textractedCasesList.add(transformedCaseMatcher.group());\n\t\t\t//If the list of not processed extracted cases exceeds the maximal allowed number\n\t\t\t//generate individual method for those cases\n\t\t\tif (extractedCasesList.size() >= casesPerSpecialStateSwitch ){\n\t\t\t\tgenerateExtractedSwitch(extractedCasesList, from, to, extractedMethods, switchReplacementBuffer);\n\t\t\t\textractedCasesList.clear();\n\t\t\t\tisFirst = true;\n\t\t\t\tmethodExtracted = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//If no method was extracted return the input unchanged\n\t\t//or process rest of cases by generating method for them\n\t\tif(!methodExtracted){\n\t\t\treturn specialStateTransition;\n\t\t}else if(!extractedCasesList.isEmpty() && methodExtracted){\n\t\t\tgenerateExtractedSwitch(extractedCasesList, from, to, extractedMethods, switchReplacementBuffer);\n\t\t}\n\t\tswitchReplacementBuffer.append(\"$5\");\n\t\t\n\t\tStringBuffer result = new StringBuffer();\n\t\ttransformedSpecialStateMatcher.appendReplacement( result, switchReplacementBuffer.toString());\n\t\tresult.append(extractedMethods);\n\t\ttransformedSpecialStateMatcher.appendTail(result);\n\t\treturn result.toString();\n\t}", "public static BufferedImage createImage(ImageProducer producer) {\n\t\tPixelGrabber pg = new PixelGrabber(producer, 0, 0, -1, -1, null, 0, 0);\n\t\ttry {\n\t\t\tpg.grabPixels();\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(\"Image fetch interrupted\");\n\t\t}\n\t\tif ((pg.status() & ImageObserver.ABORT) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch aborted\");\n\t\tif ((pg.status() & ImageObserver.ERROR) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch error\");\n\t\tBufferedImage p = new BufferedImage(pg.getWidth(), pg.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\t\tp.setRGB(0, 0, pg.getWidth(), pg.getHeight(), (int[])pg.getPixels(), 0, pg.getWidth());\n\t\treturn p;\n\t}", "protected int parseZoneId() {\n int result = -1;\n String zoneIdStr = this.request.getHeader(RestMessageHeaders.X_VOLD_ZONE_ID);\n if(zoneIdStr != null) {\n try {\n int zoneId = Integer.parseInt(zoneIdStr);\n if(zoneId < 0) {\n logger.error(\"ZoneId cannot be negative. Assuming the default zone id.\");\n } else {\n result = zoneId;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect zone id parameter. Cannot parse this to int: \"\n + zoneIdStr,\n nfe);\n }\n }\n return result;\n }", "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 static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}", "public Where<T, ID> rawComparison(String columnName, String rawOperator, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value, rawOperator));\n\t\treturn this;\n\t}", "@NonNull\n public static File[] listAllFiles(File directory) {\n if (directory == null) {\n return new File[0];\n }\n File[] files = directory.listFiles();\n return files != null ? files : new File[0];\n }", "public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }" ]
Remove a bundle. @param moduleName the module name @param slot the module slot @param existingHash the existing hash @return the builder
[ "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 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 Response executeToResponse(HttpConnection connection) {\n InputStream is = null;\n try {\n is = this.executeToInputStream(connection);\n Response response = getResponse(is, Response.class, getGson());\n response.setStatusCode(connection.getConnection().getResponseCode());\n response.setReason(connection.getConnection().getResponseMessage());\n return response;\n } catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response code or message.\", e);\n } finally {\n close(is);\n }\n }", "public <T> InternalEjbDescriptor<T> get(String beanName) {\n return cast(ejbByName.get(beanName));\n }", "@Override public void setUniqueID(Integer uniqueID)\n {\n ProjectFile parent = getParentFile();\n\n if (m_uniqueID != null)\n {\n parent.getCalendars().unmapUniqueID(m_uniqueID);\n }\n\n parent.getCalendars().mapUniqueID(uniqueID, this);\n\n m_uniqueID = uniqueID;\n }", "public Date dateTime(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n String dateString;\n // From https://tools.ietf.org/html/rfc3501 :\n // date-time = DQUOTE date-day-fixed \"-\" date-month \"-\" date-year\n // SP time SP zone DQUOTE\n // zone = (\"+\" / \"-\") 4DIGIT\n if (next == '\"') {\n dateString = consumeQuoted(request);\n } else {\n throw new ProtocolException(\"DateTime values must be quoted.\");\n }\n\n try {\n // You can use Z or zzzz\n return new SimpleDateFormat(\"dd-MMM-yyyy hh:mm:ss Z\", Locale.US).parse(dateString);\n } catch (ParseException e) {\n throw new ProtocolException(\"Invalid date format <\" + dateString + \">, should comply to dd-MMM-yyyy hh:mm:ss Z\");\n }\n }", "public Criteria copy(boolean includeGroupBy, boolean includeOrderBy, boolean includePrefetchedRelationships)\r\n {\r\n Criteria copy = new Criteria();\r\n\r\n copy.m_criteria = new Vector(this.m_criteria);\r\n copy.m_negative = this.m_negative;\r\n\r\n if (includeGroupBy)\r\n {\r\n copy.groupby = this.groupby;\r\n }\r\n if (includeOrderBy)\r\n {\r\n copy.orderby = this.orderby;\r\n }\r\n if (includePrefetchedRelationships)\r\n {\r\n copy.prefetchedRelationships = this.prefetchedRelationships;\r\n }\r\n\r\n return copy;\r\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 }", "public Sequence compile( String equation , boolean assignment, boolean debug ) {\n\n functions.setManagerTemp(managerTemp);\n\n Sequence sequence = new Sequence();\n TokenList tokens = extractTokens(equation,managerTemp);\n\n if( tokens.size() < 3 )\n throw new RuntimeException(\"Too few tokens\");\n\n TokenList.Token t0 = tokens.getFirst();\n\n if( t0.word != null && t0.word.compareToIgnoreCase(\"macro\") == 0 ) {\n parseMacro(tokens,sequence);\n } else {\n insertFunctionsAndVariables(tokens);\n insertMacros(tokens);\n if (debug) {\n System.out.println(\"Parsed tokens:\\n------------\");\n tokens.print();\n System.out.println();\n }\n\n // Get the results variable\n if (t0.getType() != Type.VARIABLE && t0.getType() != Type.WORD) {\n compileTokens(sequence,tokens);\n // If there's no output then this is acceptable, otherwise it's assumed to be a bug\n // If there's no output then a configuration was changed\n Variable variable = tokens.getFirst().getVariable();\n if( variable != null ) {\n if( assignment )\n throw new IllegalArgumentException(\"No assignment to an output variable could be found. Found \" + t0);\n else {\n sequence.output = variable; // set this to be the output for print()\n }\n }\n\n } else {\n compileAssignment(sequence, tokens, t0);\n }\n\n if (debug) {\n System.out.println(\"Operations:\\n------------\");\n for (int i = 0; i < sequence.operations.size(); i++) {\n System.out.println(sequence.operations.get(i).name());\n }\n }\n }\n\n return sequence;\n }", "public static int validateGeohashMaxLevels(Integer userMaxLevels, int defaultMaxLevels) {\n int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels;\n if (maxLevels < 1 || maxLevels > GeohashPrefixTree.getMaxLevelsPossible()) {\n throw new IndexException(\"max_levels must be in range [1, {}], but found {}\",\n GeohashPrefixTree.getMaxLevelsPossible(),\n maxLevels);\n }\n return maxLevels;\n }" ]
Use this API to add route6 resources.
[ "public static base_responses add(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 addresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new route6();\n\t\t\t\taddresources[i].network = resources[i].network;\n\t\t\t\taddresources[i].gateway = resources[i].gateway;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].weight = resources[i].weight;\n\t\t\t\taddresources[i].distance = resources[i].distance;\n\t\t\t\taddresources[i].cost = resources[i].cost;\n\t\t\t\taddresources[i].advertise = resources[i].advertise;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }", "public final double getMedian()\n {\n assertNotEmpty();\n // Sort the data (take a copy to do this).\n double[] dataCopy = new double[getSize()];\n System.arraycopy(dataSet, 0, dataCopy, 0, dataCopy.length);\n Arrays.sort(dataCopy);\n int midPoint = dataCopy.length / 2;\n if (dataCopy.length % 2 != 0)\n {\n return dataCopy[midPoint];\n }\n else\n {\n return dataCopy[midPoint - 1] + (dataCopy[midPoint] - dataCopy[midPoint - 1]) / 2;\n }\n }", "public static vlan get(nitro_service service, Long id) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tobj.set_id(id);\n\t\tvlan response = (vlan) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static Span exact(Bytes row) {\n Objects.requireNonNull(row);\n return new Span(row, true, row, true);\n }", "protected List<String> parseOptionalStringValues(final String path) {\n\n final List<I_CmsXmlContentValue> values = m_xml.getValues(path, m_locale);\n if (values == null) {\n return null;\n } else {\n List<String> stringValues = new ArrayList<String>(values.size());\n for (I_CmsXmlContentValue value : values) {\n stringValues.add(value.getStringValue(null));\n }\n return stringValues;\n }\n }", "private void addTransformInterceptors(List<Interceptor<?>> inInterceptors,\n List<Interceptor<?>> outInterceptors,\n boolean newClient) {\n \n // The old service expects the Customer data be qualified with\n // the 'http://customer/v1' namespace.\n \n // The new service expects the Customer data be qualified with\n // the 'http://customer/v2' namespace.\n \n // If it is an old client talking to the new service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v1' qualified data be transformed into\n // 'http://customer/v2' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v2' qualified response data be transformed into\n // 'http://customer/v1' qualified data.\n \n // If it is a new client talking to the old service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v2' qualified data be transformed into\n // 'http://customer/v1' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v1' qualified response data be transformed into\n // 'http://customer/v2' qualified data.\n // - new Customer type also introduces a briefDescription property\n // which needs to be dropped for the old service validation to succeed\n \n \n // this configuration can be provided externally\n \n Map<String, String> newToOldTransformMap = new HashMap<String, String>();\n newToOldTransformMap.put(\"{http://customer/v2}*\", \"{http://customer/v1}*\");\n Map<String, String> oldToNewTransformMap = \n Collections.singletonMap(\"{http://customer/v1}*\", \"{http://customer/v2}*\");\n \n TransformOutInterceptor outTransform = new TransformOutInterceptor();\n outTransform.setOutTransformElements(newClient ? newToOldTransformMap \n : oldToNewTransformMap);\n \n if (newClient) {\n newToOldTransformMap.put(\"{http://customer/v2}briefDescription\", \"\");\n //outTransform.setOutDropElements(\n // Collections.singletonList(\"{http://customer/v2}briefDescription\")); \n }\n \n TransformInInterceptor inTransform = new TransformInInterceptor();\n inTransform.setInTransformElements(newClient ? oldToNewTransformMap \n : newToOldTransformMap);\n\n inInterceptors.add(inTransform);\n outInterceptors.add(outTransform);\n \n \n }", "public final void setWeekDay(WeekDay weekDay) {\n\n SortedSet<WeekDay> wds = new TreeSet<>();\n if (null != weekDay) {\n wds.add(weekDay);\n }\n setWeekDays(wds);\n\n }", "public void setSingletonVariable(String name, WindupVertexFrame frame)\n {\n setVariable(name, Collections.singletonList(frame));\n }", "@Override\n public GroupDiscussInterface getDiscussionInterface() {\n if (discussionInterface == null) {\n discussionInterface = new GroupDiscussInterface(apiKey, sharedSecret, transport);\n }\n return discussionInterface;\n }" ]
If needed declares and sets up internal data structures. @param A Matrix being decomposed.
[ "public void init( DMatrixRMaj A ) {\n if( A.numRows != A.numCols)\n throw new IllegalArgumentException(\"Must be square\");\n\n if( A.numCols != N ) {\n N = A.numCols;\n QT.reshape(N,N, false);\n\n if( w.length < N ) {\n w = new double[ N ];\n gammas = new double[N];\n b = new double[N];\n }\n }\n\n // just copy the top right triangle\n QT.set(A);\n }" ]
[ "public String getUnicodeString(Integer id, Integer type)\n {\n return (getUnicodeString(m_meta.getOffset(id, type)));\n }", "private static int findTrackIdAtOffset(SlotReference slot, Client client, int offset) throws IOException {\n Message entry = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot.slot, CdjStatus.TrackType.REKORDBOX, offset, 1).get(0);\n if (entry.getMenuItemType() == Message.MenuItemType.UNKNOWN) {\n logger.warn(\"Encountered unrecognized track list entry item type: {}\", entry);\n }\n return (int)((NumberField)entry.arguments.get(1)).getValue();\n }", "public RandomVariable[] getValues(double[] times) {\n\t\tRandomVariable[] values = new RandomVariable[times.length];\n\n\t\tfor(int i=0; i<times.length; i++) {\n\t\t\tvalues[i] = getValue(null, times[i]);\n\t\t}\n\n\t\treturn values;\n\t}", "public GVRShaderId getShaderType(Class<? extends GVRShader> shaderClass)\n {\n GVRShaderId shaderId = mShaderTemplates.get(shaderClass);\n\n if (shaderId == null)\n {\n GVRContext ctx = getGVRContext();\n shaderId = new GVRShaderId(shaderClass);\n mShaderTemplates.put(shaderClass, shaderId);\n shaderId.getTemplate(ctx);\n }\n return shaderId;\n }", "public void fire(StepEvent event) {\n Step step = stepStorage.getLast();\n event.process(step);\n\n notifier.fire(event);\n }", "public Map<String, EntityDocument> wbGetEntities(\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\treturn wbGetEntities(properties.ids, properties.sites,\n\t\t\t\tproperties.titles, properties.props, properties.languages,\n\t\t\t\tproperties.sitefilter);\n\t}", "public ThreadUsage getThreadUsage() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n\n ThreadUsage threadUsage = new ThreadUsage();\n long[] threadIds = threadMxBean.getAllThreadIds();\n threadUsage.liveThreadCount = threadIds.length;\n\n for (long tId : threadIds) {\n ThreadInfo threadInfo = threadMxBean.getThreadInfo(tId);\n threadUsage.threadData.put(Long.toString(tId), new ThreadData(\n threadInfo.getThreadName(), threadInfo.getThreadState()\n .name(), threadMxBean.getThreadCpuTime(tId)));\n\n }\n return threadUsage;\n }", "public ServerRedirect addServerMapping(String sourceHost, String destinationHost, String hostHeader) {\n JSONObject response = null;\n\n ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();\n params.add(new BasicNameValuePair(\"srcUrl\", sourceHost));\n params.add(new BasicNameValuePair(\"destUrl\", destinationHost));\n params.add(new BasicNameValuePair(\"profileIdentifier\", this._profileName));\n if (hostHeader != null) {\n params.add(new BasicNameValuePair(\"hostHeader\", hostHeader));\n }\n\n try {\n BasicNameValuePair paramArray[] = new BasicNameValuePair[params.size()];\n params.toArray(paramArray);\n response = new JSONObject(doPost(BASE_SERVER, paramArray));\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return getServerRedirectFromJSON(response);\n }", "protected void checkJobType(final String jobName, final Class<?> jobType) {\n if (jobName == null) {\n throw new IllegalArgumentException(\"jobName must not be null\");\n }\n if (jobType == null) {\n throw new IllegalArgumentException(\"jobType must not be null\");\n }\n if (!(Runnable.class.isAssignableFrom(jobType)) \n && !(Callable.class.isAssignableFrom(jobType))) {\n throw new IllegalArgumentException(\n \"jobType must implement either Runnable or Callable: \" + jobType);\n }\n }" ]
Validates that the data structure at position startEndRecord has a field in the expected position that points to the start of the first central directory file, and, if so, that the file has a complete end of central directory record comment at the end. @param file the file being checked @param channel the channel @param startEndRecord the start of the end of central directory record @param endSig the end of central dir signature @return true if it can be confirmed that the end of directory record points to a central directory file and a complete comment is present, false otherwise @throws java.io.IOException
[ "private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException {\n\n try {\n channel.position(startEndRecord);\n\n final ByteBuffer endDirHeader = getByteBuffer(ENDLEN);\n read(endDirHeader, channel);\n if (endDirHeader.limit() < ENDLEN) {\n // Couldn't read the full end of central directory record header\n return false;\n } else if (getUnsignedInt(endDirHeader, 0) != endSig) {\n return false;\n }\n\n long pos = getUnsignedInt(endDirHeader, END_CENSTART);\n // TODO deal with Zip64\n if (pos == ZIP64_MARKER) {\n return false;\n }\n\n ByteBuffer cdfhBuffer = getByteBuffer(CENLEN);\n read(cdfhBuffer, channel, pos);\n long header = getUnsignedInt(cdfhBuffer, 0);\n if (header == CENSIG) {\n long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET);\n long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ);\n if (firstLoc == 0) {\n // normal case -- first bytes are the first local file\n if (!validateLocalFileRecord(channel, 0, firstSize)) {\n return false;\n }\n } else {\n // confirm that firstLoc is indeed the first local file\n long fileFirstLoc = scanForLocSig(channel);\n if (firstLoc != fileFirstLoc) {\n if (fileFirstLoc == 0) {\n return false;\n } else {\n // scanForLocSig() found a LOCSIG, but not at position zero and not\n // at the expected position.\n // With a file like this, we can't tell if we're in a nested zip\n // or we're in an outer zip and had the bad luck to find random bytes\n // that look like LOCSIG.\n return false;\n }\n }\n }\n\n // At this point, endDirHeader points to the correct end of central dir record.\n // Just need to validate the record is complete, including any comment\n int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN);\n long commentEnd = startEndRecord + ENDLEN + commentLen;\n return commentEnd <= channel.size();\n }\n\n return false;\n } catch (EOFException eof) {\n // pos or firstLoc weren't really positions and moved us to an invalid location\n return false;\n }\n }" ]
[ "public String processProcedure(Properties attributes) throws XDocletException\r\n {\r\n String type = attributes.getProperty(ATTRIBUTE_TYPE);\r\n ProcedureDef procDef = _curClassDef.getProcedure(type);\r\n String attrName;\r\n\r\n if (procDef == null)\r\n { \r\n procDef = new ProcedureDef(type);\r\n _curClassDef.addProcedure(procDef);\r\n }\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n procDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }", "private void nodeProperties(Options opt) {\n\tOptions def = opt.getGlobalOptions();\n\tif (opt.nodeFontName != def.nodeFontName)\n\t w.print(\",fontname=\\\"\" + opt.nodeFontName + \"\\\"\");\n\tif (opt.nodeFontColor != def.nodeFontColor)\n\t w.print(\",fontcolor=\\\"\" + opt.nodeFontColor + \"\\\"\");\n\tif (opt.nodeFontSize != def.nodeFontSize)\n\t w.print(\",fontsize=\" + fmt(opt.nodeFontSize));\n\tw.print(opt.shape.style);\n\tw.println(\"];\");\n }", "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 }", "protected void modify(Transaction t) {\n try {\n this.lock.writeLock().lock();\n t.perform();\n } finally {\n this.lock.writeLock().unlock();\n }\n }", "public void addVars(Map<String, String> env) {\n if (tagUrl != null) {\n env.put(\"RELEASE_SCM_TAG\", tagUrl);\n env.put(RT_RELEASE_STAGING + \"SCM_TAG\", tagUrl);\n }\n if (releaseBranch != null) {\n env.put(\"RELEASE_SCM_BRANCH\", releaseBranch);\n env.put(RT_RELEASE_STAGING + \"SCM_BRANCH\", releaseBranch);\n }\n if (releaseVersion != null) {\n env.put(RT_RELEASE_STAGING + \"VERSION\", releaseVersion);\n }\n if (nextVersion != null) {\n env.put(RT_RELEASE_STAGING + \"NEXT_VERSION\", nextVersion);\n }\n }", "public static PredicateExpression nin(Object... rhs) {\n PredicateExpression ex = new PredicateExpression(\"$nin\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }", "public static long makeReasonable(long expectedTimeoutMillis, long bufferMillis) {\n checkArgument(expectedTimeoutMillis > 0,\n \"expectedTimeoutMillis: %s (expected: > 0)\", expectedTimeoutMillis);\n checkArgument(bufferMillis >= 0,\n \"bufferMillis: %s (expected: > 0)\", bufferMillis);\n\n final long timeout = Math.min(expectedTimeoutMillis, MAX_MILLIS);\n if (bufferMillis == 0) {\n return timeout;\n }\n\n if (timeout > MAX_MILLIS - bufferMillis) {\n return MAX_MILLIS;\n } else {\n return bufferMillis + timeout;\n }\n }", "public void animate(float timeInSec)\n {\n GVRSkeleton skel = getSkeleton();\n GVRPose pose = skel.getPose();\n computePose(timeInSec,pose);\n skel.poseToBones();\n skel.updateBonePose();\n skel.updateSkinPose();\n }", "public void awaitPodReadinessOrFail(Predicate<Pod> filter) {\n await().atMost(5, TimeUnit.MINUTES).until(() -> {\n List<Pod> list = client.pods().inNamespace(namespace).list().getItems();\n return list.stream()\n .filter(filter)\n .filter(Readiness::isPodReady)\n .collect(Collectors.toList()).size() >= 1;\n }\n );\n }" ]
Creates a code location URL from a URL @param url the URL external form @return A URL created from URL @throws InvalidCodeLocation if URL creation fails
[ "public static URL codeLocationFromURL(String url) {\n try {\n return new URL(url);\n } catch (Exception e) {\n throw new InvalidCodeLocation(url);\n }\n }" ]
[ "public static <T> DatabaseTableConfig<T> fromReader(BufferedReader reader) throws SQLException {\n\t\tDatabaseTableConfig<T> config = new DatabaseTableConfig<T>();\n\t\tboolean anything = false;\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read DatabaseTableConfig from stream\", e);\n\t\t\t}\n\t\t\tif (line == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_END_MARKER)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// we do this so we can support multiple class configs per file\n\t\t\tif (line.equals(CONFIG_FILE_FIELDS_START)) {\n\t\t\t\treadFields(reader, config);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// skip empty lines or comments\n\t\t\tif (line.length() == 0 || line.startsWith(\"#\") || line.equals(CONFIG_FILE_START_MARKER)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] parts = line.split(\"=\", -2);\n\t\t\tif (parts.length != 2) {\n\t\t\t\tthrow new SQLException(\"DatabaseTableConfig reading from stream cannot parse line: \" + line);\n\t\t\t}\n\t\t\treadTableField(config, parts[0], parts[1]);\n\t\t\tanything = true;\n\t\t}\n\t\t// if we got any config lines then we return the config\n\t\tif (anything) {\n\t\t\treturn config;\n\t\t} else {\n\t\t\t// otherwise we return null for none\n\t\t\treturn null;\n\t\t}\n\t}", "public void setDateMax(Date dateMax) {\n this.dateMax = dateMax;\n\n if (isAttached() && dateMax != null) {\n getPicker().set(\"max\", JsDate.create((double) dateMax.getTime()));\n }\n }", "private Variable createVariableInferred(TokenList.Token t0, Variable variableRight) {\n Variable result;\n\n if( t0.getType() == Type.WORD ) {\n switch( variableRight.getType()) {\n case MATRIX:\n alias(new DMatrixRMaj(1,1),t0.getWord());\n break;\n\n case SCALAR:\n if( variableRight instanceof VariableInteger) {\n alias(0,t0.getWord());\n } else {\n alias(1.0,t0.getWord());\n }\n break;\n\n case INTEGER_SEQUENCE:\n alias((IntegerSequence)null,t0.getWord());\n break;\n\n default:\n throw new RuntimeException(\"Type not supported for assignment: \"+variableRight.getType());\n }\n\n result = variables.get(t0.getWord());\n } else {\n result = t0.getVariable();\n }\n return result;\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 Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException {\n if (!locale.isPresent()) {\n return Optional.absent();\n }\n\n synchronized (msgBundles) {\n SoyMsgBundle soyMsgBundle = null;\n if (isHotReloadModeOff()) {\n soyMsgBundle = msgBundles.get(locale.get());\n }\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(locale.get());\n if (soyMsgBundle == null) {\n soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage()));\n }\n\n if (soyMsgBundle == null && fallbackToEnglish) {\n soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH);\n }\n\n if (soyMsgBundle == null) {\n return Optional.absent();\n }\n\n if (isHotReloadModeOff()) {\n msgBundles.put(locale.get(), soyMsgBundle);\n }\n }\n\n return Optional.fromNullable(soyMsgBundle);\n }\n }", "public Triple<Double, Integer, Integer> getAccuracyInfo()\r\n {\r\n int totalCorrect = tokensCorrect;\r\n int totalWrong = tokensCount - tokensCorrect;\r\n return new Triple<Double, Integer, Integer>((((double) totalCorrect) / tokensCount),\r\n totalCorrect, totalWrong);\r\n }", "public static SQLService getInstance() throws Exception {\n if (_instance == null) {\n _instance = new SQLService();\n _instance.startServer();\n\n // default pool size is 20\n // can be overriden by env variable\n int dbPool = 20;\n if (Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE) != null) {\n dbPool = Integer.valueOf(Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE));\n }\n\n // initialize connection pool\n PoolProperties p = new PoolProperties();\n String connectString = \"jdbc:h2:tcp://\" + _instance.databaseHost + \":\" + String.valueOf(_instance.port) + \"/\" +\n _instance.databaseName + \"/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON\";\n p.setUrl(connectString);\n p.setDriverClassName(\"org.h2.Driver\");\n p.setUsername(\"sa\");\n p.setJmxEnabled(true);\n p.setTestWhileIdle(false);\n p.setTestOnBorrow(true);\n p.setValidationQuery(\"SELECT 1\");\n p.setTestOnReturn(false);\n p.setValidationInterval(5000);\n p.setTimeBetweenEvictionRunsMillis(30000);\n p.setMaxActive(dbPool);\n p.setInitialSize(5);\n p.setMaxWait(30000);\n p.setRemoveAbandonedTimeout(60);\n p.setMinEvictableIdleTimeMillis(30000);\n p.setMinIdle(10);\n p.setLogAbandoned(true);\n p.setRemoveAbandoned(true);\n _instance.datasource = new DataSource();\n _instance.datasource.setPoolProperties(p);\n }\n return _instance;\n }", "public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) {\n return createEnterpriseUser(api, login, name, null);\n }", "private LocatorSelectionStrategy getLocatorSelectionStrategy(String locatorSelectionStrategy) {\n if (null == locatorSelectionStrategy) {\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Strategy \" + locatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n\n if (locatorSelectionStrategyMap.containsKey(locatorSelectionStrategy)) {\n return locatorSelectionStrategyMap.get(locatorSelectionStrategy).getInstance();\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"LocatorSelectionStrategy \" + locatorSelectionStrategy\n + \" not registered at LocatorClientEnabler.\");\n }\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n }" ]
The period of time to ban a node that gives an error on an operation. @param nodeBannagePeriod The period of time to ban the node @param unit The time unit of the given value @deprecated Use {@link #setFailureDetectorBannagePeriod(long)} instead
[ "@Deprecated\n public ClientConfig setNodeBannagePeriod(int nodeBannagePeriod, TimeUnit unit) {\n this.failureDetectorBannagePeriod = unit.toMillis(nodeBannagePeriod);\n return this;\n }" ]
[ "public static List<String> splitAndTrimAsList(String text, String sep) {\n ArrayList<String> answer = new ArrayList<>();\n if (text != null && text.length() > 0) {\n for (String v : text.split(sep)) {\n String trim = v.trim();\n if (trim.length() > 0) {\n answer.add(trim);\n }\n }\n }\n return answer;\n }", "public int count() {\n int n = 0;\n for (ConcurrentMap<?, ?> bag : registry.values()) {\n n += bag.size();\n }\n return n;\n }", "public SubReportBuilder setParameterMapPath(String path) {\r\n\t\tsubreport.setParametersExpression(path);\r\n\t\tsubreport.setParametersMapOrigin(DJConstants.SUBREPORT_PARAMETER_MAP_ORIGIN_PARAMETER);\r\n\t\treturn this;\r\n\t}", "public static VectorTile.Tile.GeomType toGeomType(Geometry geometry) {\n VectorTile.Tile.GeomType result = VectorTile.Tile.GeomType.UNKNOWN;\n\n if(geometry instanceof Point\n || geometry instanceof MultiPoint) {\n result = VectorTile.Tile.GeomType.POINT;\n\n } else if(geometry instanceof LineString\n || geometry instanceof MultiLineString) {\n result = VectorTile.Tile.GeomType.LINESTRING;\n\n } else if(geometry instanceof Polygon\n || geometry instanceof MultiPolygon) {\n result = VectorTile.Tile.GeomType.POLYGON;\n }\n\n return result;\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory,\n SerializerDefinition serializerDefinition) {\n return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition);\n }", "void addOption(final String value) {\n Assert.checkNotNullParam(\"value\", value);\n synchronized (options) {\n options.add(value);\n }\n }", "protected void processAssignmentBaseline(Row row)\n {\n Integer id = row.getInteger(\"ASSN_UID\");\n ResourceAssignment assignment = m_assignmentMap.get(id);\n if (assignment != null)\n {\n int index = row.getInt(\"AB_BASE_NUM\");\n\n assignment.setBaselineStart(index, row.getDate(\"AB_BASE_START\"));\n assignment.setBaselineFinish(index, row.getDate(\"AB_BASE_FINISH\"));\n assignment.setBaselineWork(index, row.getDuration(\"AB_BASE_WORK\"));\n assignment.setBaselineCost(index, row.getCurrency(\"AB_BASE_COST\"));\n }\n }", "public int scrollToItem(int position) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"scrollToItem position = %d\", position);\n scrollToPosition(position);\n return mCurrentItemIndex;\n }", "public static boolean reconnectContext(RedirectException re, CommandContext ctx) {\n boolean reconnected = false;\n try {\n ConnectionInfo info = ctx.getConnectionInfo();\n ControllerAddress address = null;\n if (info != null) {\n address = info.getControllerAddress();\n }\n if (address != null && isHttpsRedirect(re, address.getProtocol())) {\n LOG.debug(\"Trying to reconnect an http to http upgrade\");\n try {\n ctx.connectController();\n reconnected = true;\n } catch (Exception ex) {\n LOG.warn(\"Exception reconnecting\", ex);\n // Proper https redirect but error.\n // Ignoring it.\n }\n }\n } catch (URISyntaxException ex) {\n LOG.warn(\"Invalid URI: \", ex);\n // OK, invalid redirect.\n }\n return reconnected;\n }" ]
Read a text file resource into a single string @param context A non-null Android Context @param resourceId An Android resource id @return The contents, or null on error.
[ "public static String readTextFile(Context context, int resourceId) {\n InputStream inputStream = context.getResources().openRawResource(\n resourceId);\n return readTextFile(inputStream);\n }" ]
[ "public static dnssuffix get(nitro_service service, String Dnssuffix) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tobj.set_Dnssuffix(Dnssuffix);\n\t\tdnssuffix response = (dnssuffix) obj.get_resource(service);\n\t\treturn response;\n\t}", "private static ClassLoader getParentCl()\n {\n try\n {\n Method m = ClassLoader.class.getMethod(\"getPlatformClassLoader\");\n return (ClassLoader) m.invoke(null);\n }\n catch (NoSuchMethodException e)\n {\n // Java < 9, just use the bootstrap CL.\n return null;\n }\n catch (Exception e)\n {\n throw new JqmInitError(\"Could not fetch Platform Class Loader\", e);\n }\n }", "public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }", "private DecompilerSettings getDefaultSettings(File outputDir)\n {\n DecompilerSettings settings = new DecompilerSettings();\n procyonConf.setDecompilerSettings(settings);\n settings.setOutputDirectory(outputDir.getPath());\n settings.setShowSyntheticMembers(false);\n settings.setForceExplicitImports(true);\n\n if (settings.getTypeLoader() == null)\n settings.setTypeLoader(new ClasspathTypeLoader());\n return settings;\n }", "public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {\n Set<String> orderedChildTypes = resource.getOrderedChildTypes();\n if (orderedChildTypes.size() > 0) {\n orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());\n }\n }", "public static base_response delete(nitro_service client, String viewname) throws Exception {\n\t\tdnsview deleteresource = new dnsview();\n\t\tdeleteresource.viewname = viewname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public static base_responses flush(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup flushresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cachecontentgroup();\n\t\t\t\tflushresources[i].name = resources[i].name;\n\t\t\t\tflushresources[i].query = resources[i].query;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].selectorvalue = resources[i].selectorvalue;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}", "private FormInput formInputMatchingNode(Node element) {\n\t\tNamedNodeMap attributes = element.getAttributes();\n\t\tIdentification id;\n\n\t\tif (attributes.getNamedItem(\"id\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.id,\n\t\t\t\t\tattributes.getNamedItem(\"id\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tif (attributes.getNamedItem(\"name\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.name,\n\t\t\t\t\tattributes.getNamedItem(\"name\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tString xpathExpr = XPathHelper.getXPathExpression(element);\n\t\tif (xpathExpr != null && !xpathExpr.equals(\"\")) {\n\t\t\tid = new Identification(Identification.How.xpath, xpathExpr);\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }" ]
Set default values for annotations. Initial annotation take precedence over the default annotation when both annotation types are present @param defaultAnnotations default value for annotations
[ "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 }" ]
[ "public static Pool<Jedis> createJedisPool(final Config jesqueConfig, final GenericObjectPoolConfig poolConfig) {\n if (jesqueConfig == null) {\n throw new IllegalArgumentException(\"jesqueConfig must not be null\");\n }\n if (poolConfig == null) {\n throw new IllegalArgumentException(\"poolConfig must not be null\");\n }\n if (jesqueConfig.getMasterName() != null && !\"\".equals(jesqueConfig.getMasterName()) \n && jesqueConfig.getSentinels() != null && jesqueConfig.getSentinels().size() > 0) {\n return new JedisSentinelPool(jesqueConfig.getMasterName(), jesqueConfig.getSentinels(), poolConfig, \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n } else {\n return new JedisPool(poolConfig, jesqueConfig.getHost(), jesqueConfig.getPort(), \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n }\n }", "private Set<File> findThriftFiles() throws IOException, MojoExecutionException {\n final File thriftSourceRoot = getThriftSourceRoot();\n Set<File> thriftFiles = new HashSet<File>();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n thriftFiles.addAll(findThriftFilesInDirectory(thriftSourceRoot));\n }\n getLog().info(\"finding thrift files in dependencies\");\n extractFilesFromDependencies(findThriftDependencies(), getResourcesOutputDirectory());\n if (buildExtractedThrift && getResourcesOutputDirectory().exists()) {\n thriftFiles.addAll(findThriftFilesInDirectory(getResourcesOutputDirectory()));\n }\n getLog().info(\"finding thrift files in referenced (reactor) projects\");\n thriftFiles.addAll(getReferencedThriftFiles());\n return thriftFiles;\n }", "public Scale getNearestScale(\n final ZoomLevels zoomLevels,\n final double tolerance,\n final ZoomLevelSnapStrategy zoomLevelSnapStrategy,\n final boolean geodetic,\n final Rectangle paintArea,\n final double dpi) {\n\n final Scale scale = getScale(paintArea, dpi);\n final Scale correctedScale;\n final double scaleRatio;\n if (geodetic) {\n final double currentScaleDenominator = scale.getGeodeticDenominator(\n getProjection(), dpi, getCenter());\n scaleRatio = scale.getDenominator(dpi) / currentScaleDenominator;\n correctedScale = scale.toResolution(scale.getResolution() / scaleRatio);\n } else {\n scaleRatio = 1;\n correctedScale = scale;\n }\n\n DistanceUnit unit = DistanceUnit.fromProjection(getProjection());\n final ZoomLevelSnapStrategy.SearchResult result = zoomLevelSnapStrategy.search(\n correctedScale, tolerance, zoomLevels);\n final Scale newScale;\n\n if (geodetic) {\n newScale = new Scale(\n result.getScale(unit).getDenominator(PDF_DPI) * scaleRatio,\n getProjection(), dpi);\n } else {\n newScale = result.getScale(unit);\n }\n\n return newScale;\n }", "public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }", "private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {\n if (tries >= 5) {\n throw new BindException(\"Unable to bind to several ports, most recently \" + relay.getPort() + \". Giving up\");\n }\n try {\n if (server.isStarted()) {\n relay.start();\n } else {\n throw new RuntimeException(\"Can't start SslRelay: server is not started (perhaps it was just shut down?)\");\n }\n } catch (BindException e) {\n // doh - the port is being used up, let's pick a new port\n LOG.info(\"Unable to bind to port %d, going to try port %d now\", relay.getPort(), relay.getPort() + 1);\n relay.setPort(relay.getPort() + 1);\n startRelayWithPortTollerance(server, relay, tries + 1);\n }\n }", "public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}", "private UserAlias getUserAlias(Object attribute)\r\n\t{\r\n\t\tif (m_userAlias != null)\r\n\t\t{\r\n\t\t\treturn m_userAlias;\r\n\t\t}\r\n\t\tif (!(attribute instanceof String))\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_alias == null)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_aliasPath == null)\r\n\t\t{\r\n\t\t\tboolean allPathsAliased = true;\r\n\t\t\treturn new UserAlias(m_alias, (String)attribute, allPathsAliased);\r\n\t\t}\r\n\t\treturn new UserAlias(m_alias, (String)attribute, m_aliasPath);\r\n\t}", "public static authenticationradiuspolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_authenticationvserver_binding obj = new authenticationradiuspolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_authenticationvserver_binding response[] = (authenticationradiuspolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public RandomVariable[]\tgetParameter() {\n\t\tdouble[] parameterAsDouble = this.getParameterAsDouble();\n\t\tRandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];\n\t\tfor(int i=0; i<parameter.length; i++) {\n\t\t\tparameter[i] = new Scalar(parameterAsDouble[i]);\n\t\t}\n\t\treturn parameter;\n\t}" ]
Throws an IllegalArgumentException when the given value is null. @param value the value to assert if not null @param name the name of the argument @param <T> The generic type of the value to assert if not null @return the value
[ "public static <T> T assertNotNull(T value, String name) {\n if (value == null)\n throw new IllegalArgumentException(\"Null \" + name);\n\n return value;\n }" ]
[ "@Override\n\tpublic Object executeJavaScript(String code) throws CrawljaxException {\n\t\ttry {\n\t\t\tJavascriptExecutor js = (JavascriptExecutor) browser;\n\t\t\treturn js.executeScript(code);\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t}", "public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}", "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 }", "@Override\n public double get( int row , int col ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds: \"+row+\" \"+col);\n }\n\n return data[ row * numCols + col ];\n }", "public void setParent(ProjectCalendar calendar)\n {\n // I've seen a malformed MSPDI file which sets the parent calendar to itself.\n // Silently ignore this here.\n if (calendar != this)\n {\n if (getParent() != null)\n {\n getParent().removeDerivedCalendar(this);\n }\n\n super.setParent(calendar);\n\n if (calendar != null)\n {\n calendar.addDerivedCalendar(this);\n }\n clearWorkingDateCache();\n }\n }", "public void setCurrencyDigits(Integer currDigs)\n {\n if (currDigs == null)\n {\n currDigs = DEFAULT_CURRENCY_DIGITS;\n }\n set(ProjectField.CURRENCY_DIGITS, currDigs);\n }", "@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }", "public static Method findGetter(final Object object, final String fieldName) {\n\t\tif( object == null ) {\n\t\t\tthrow new NullPointerException(\"object should not be null\");\n\t\t} else if( fieldName == null ) {\n\t\t\tthrow new NullPointerException(\"fieldName should not be null\");\n\t\t}\n\t\t\n\t\tfinal Class<?> clazz = object.getClass();\n\t\t\n\t\t// find a standard getter\n\t\tfinal String standardGetterName = getMethodNameForField(GET_PREFIX, fieldName);\n\t\tMethod getter = findGetterWithCompatibleReturnType(standardGetterName, clazz, false);\n\t\t\n\t\t// if that fails, try for an isX() style boolean getter\n\t\tif( getter == null ) {\n\t\t\tfinal String booleanGetterName = getMethodNameForField(IS_PREFIX, fieldName);\n\t\t\tgetter = findGetterWithCompatibleReturnType(booleanGetterName, clazz, true);\n\t\t}\n\t\t\n\t\tif( getter == null ) {\n\t\t\tthrow new SuperCsvReflectionException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"unable to find getter for field %s in class %s - check that the corresponding nameMapping element matches the field name in the bean\",\n\t\t\t\t\t\tfieldName, clazz.getName()));\n\t\t}\n\t\t\n\t\treturn getter;\n\t}", "public void onDrawerOpened(View drawerView) {\n super.onDrawerOpened(drawerView);\n if (listener != null) listener.onDrawerClosed(drawerView);\n }" ]
Set the method arguments for an enabled method override @param pathName Path name @param methodName Fully qualified method name @param ordinal 1-based index of the override within the overrides of type methodName @param arguments Array of arguments to set(specify all arguments) @return true if success, false otherwise
[ "public boolean setMethodArguments(String pathName, String methodName, Integer ordinal, Object... arguments) {\n try {\n BasicNameValuePair[] params = new BasicNameValuePair[arguments.length + 2];\n int x = 0;\n for (Object argument : arguments) {\n params[x] = new BasicNameValuePair(\"arguments[]\", argument.toString());\n x++;\n }\n params[x] = new BasicNameValuePair(\"profileIdentifier\", this._profileName);\n params[x + 1] = new BasicNameValuePair(\"ordinal\", ordinal.toString());\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodName, params));\n\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }" ]
[ "protected static final float[] getSpreadInRange(float member, int count, int max, int offset) {\n // to find the spread, we first find the min that is a\n // multiple of max/count away from the member\n\n int interval = max / count;\n float min = (member + offset) % interval;\n\n if (min == 0 && member == max) {\n min += interval;\n }\n\n float[] range = new float[count];\n for (int i = 0; i < count; i++) {\n range[i] = min + interval * i + offset;\n }\n\n return range;\n }", "public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }", "private boolean hasMultipleCostRates()\n {\n boolean result = false;\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n //\n // We assume here that if there is just one entry in the cost rate\n // table, this is an open ended rate which covers any work, it won't\n // have specific dates attached to it.\n //\n if (table.size() > 1)\n {\n //\n // If we have multiple rates in the table, see if the same rate\n // is in force at the start and the end of the aaaignment.\n //\n CostRateTableEntry startEntry = table.getEntryByDate(getStart());\n CostRateTableEntry finishEntry = table.getEntryByDate(getFinish());\n result = (startEntry != finishEntry);\n }\n }\n return result;\n }", "public static DMatrixSparseCSC diag(double... values ) {\n int N = values.length;\n return diag(new DMatrixSparseCSC(N,N,N),values,0,N);\n }", "public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),\n\t\t\t\tfilterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}", "@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }", "private void writeResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx)\n {\n Project.Resources.Resource.ExtendedAttribute attrib;\n List<Project.Resources.Resource.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (ResourceField mpxFieldID : getAllResourceExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPResourceField.getID(mpxFieldID) | MPPResourceField.RESOURCE_FIELD_BASE);\n\n attrib = m_factory.createProjectResourcesResourceExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }", "public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }" ]
Returns the WDTK datatype IRI for the property datatype as represented by the given JSON datatype string. @param jsonDatatype the JSON datatype string; case-sensitive @throws IllegalArgumentException if the given datatype string is not known
[ "public static String getDatatypeIriFromJsonDatatype(String jsonDatatype) {\n\t\tswitch (jsonDatatype) {\n\t\tcase JSON_DT_ITEM:\n\t\t\treturn DT_ITEM;\n\t\tcase JSON_DT_PROPERTY:\n\t\t\treturn DT_PROPERTY;\n\t\tcase JSON_DT_GLOBE_COORDINATES:\n\t\t\treturn DT_GLOBE_COORDINATES;\n\t\tcase JSON_DT_URL:\n\t\t\treturn DT_URL;\n\t\tcase JSON_DT_COMMONS_MEDIA:\n\t\t\treturn DT_COMMONS_MEDIA;\n\t\tcase JSON_DT_TIME:\n\t\t\treturn DT_TIME;\n\t\tcase JSON_DT_QUANTITY:\n\t\t\treturn DT_QUANTITY;\n\t\tcase JSON_DT_STRING:\n\t\t\treturn DT_STRING;\n\t\tcase JSON_DT_MONOLINGUAL_TEXT:\n\t\t\treturn DT_MONOLINGUAL_TEXT;\n\t\tdefault:\n\t\t\tif(!JSON_DATATYPE_PATTERN.matcher(jsonDatatype).matches()) {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid JSON datatype \\\"\" + jsonDatatype + \"\\\"\");\n\t\t\t}\n\n\t\t\tString[] parts = jsonDatatype.split(\"-\");\n\t\t\tfor(int i = 0; i < parts.length; i++) {\n\t\t\t\tparts[i] = StringUtils.capitalize(parts[i]);\n\t\t\t}\n\t\t\treturn \"http://wikiba.se/ontology#\" + StringUtils.join(parts);\n\t\t}\n\t}" ]
[ "public void deleteIndex(String indexName, String designDocId, String type) {\n assertNotEmpty(indexName, \"indexName\");\n assertNotEmpty(designDocId, \"designDocId\");\n assertNotNull(type, \"type\");\n if (!designDocId.startsWith(\"_design\")) {\n designDocId = \"_design/\" + designDocId;\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).path(\"_index\").path(designDocId)\n .path(type).path(indexName).build();\n InputStream response = null;\n try {\n HttpConnection connection = Http.DELETE(uri);\n response = client.couchDbClient.executeToInputStream(connection);\n getResponse(response, Response.class, client.getGson());\n } finally {\n close(response);\n }\n }", "public static String fileNameClean(String s) {\r\n char[] chars = s.toCharArray();\r\n StringBuilder sb = new StringBuilder();\r\n for (char c : chars) {\r\n if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {\r\n sb.append(c);\r\n } else {\r\n if (c == ' ' || c == '-') {\r\n sb.append('_');\r\n } else {\r\n sb.append('x').append((int) c).append('x');\r\n }\r\n }\r\n }\r\n return sb.toString();\r\n }", "public Iterable<BoxMetadataCascadePolicy.Info> getMetadataCascadePolicies(String... fields) {\n Iterable<BoxMetadataCascadePolicy.Info> cascadePoliciesInfo =\n BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields);\n\n return cascadePoliciesInfo;\n }", "static void backupDirectory(final File source, final File target) throws IOException {\n if (!target.exists()) {\n if (!target.mkdirs()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(target.getAbsolutePath());\n }\n }\n final File[] files = source.listFiles(CONFIG_FILTER);\n for (final File file : files) {\n final File t = new File(target, file.getName());\n IoUtils.copyFile(file, t);\n }\n }", "@Override\n\tpublic void validate() throws HostNameException {\n\t\tif(parsedHost != null) {\n\t\t\treturn;\n\t\t}\n\t\tif(validationException != null) {\n\t\t\tthrow validationException;\n\t\t}\n\t\tsynchronized(this) {\n\t\t\tif(parsedHost != null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(validationException != null) {\n\t\t\t\tthrow validationException;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tparsedHost = getValidator().validateHost(this);\n\t\t\t} catch(HostNameException e) {\n\t\t\t\tvalidationException = e;\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}", "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 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 static void addVersionInfo(byte[] grid, int size, int version) {\n // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/\n long version_data = QR_ANNEX_D[version - 7];\n for (int i = 0; i < 6; i++) {\n grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;\n grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;\n grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;\n grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;\n }\n }", "public void rotate(String photoId, int degrees) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ROTATE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"degrees\", String.valueOf(degrees));\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 }" ]
Declaration of the variable within a block
[ "@Override\n public boolean visit(VariableDeclarationStatement node)\n {\n for (int i = 0; i < node.fragments().size(); ++i)\n {\n String nodeType = node.getType().toString();\n VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i);\n state.getNames().add(frag.getName().getIdentifier());\n state.getNameInstance().put(frag.getName().toString(), nodeType.toString());\n }\n\n processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION,\n compilationUnit.getLineNumber(node.getStartPosition()),\n compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString());\n return super.visit(node);\n }" ]
[ "static Project convert(\n String name, com.linecorp.centraldogma.server.storage.project.Project project) {\n return new Project(name);\n }", "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public void resolveLazyCrossReferences(final CancelIndicator mon) {\n\t\tfinal CancelIndicator monitor = mon == null ? CancelIndicator.NullImpl : mon;\n\t\tTreeIterator<Object> iterator = EcoreUtil.getAllContents(this, true);\n\t\twhile (iterator.hasNext()) {\n\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\tInternalEObject source = (InternalEObject) iterator.next();\n\t\t\tEStructuralFeature[] eStructuralFeatures = ((EClassImpl.FeatureSubsetSupplier) source.eClass()\n\t\t\t\t\t.getEAllStructuralFeatures()).crossReferences();\n\t\t\tif (eStructuralFeatures != null) {\n\t\t\t\tfor (EStructuralFeature crossRef : eStructuralFeatures) {\n\t\t\t\t\toperationCanceledManager.checkCanceled(monitor);\n\t\t\t\t\tresolveLazyCrossReference(source, crossRef);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public static sslvserver_sslciphersuite_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"rawtypes\")\n\tpublic void setReplicationClassLoader(Fqn regionFqn, ClassLoader classLoader) {\n\t\tif (!isLocalMode()) {\n\t\t\tfinal Region region = jBossCache.getRegion(regionFqn, true);\n\t\t\tregion.registerContextClassLoader(classLoader);\n\t\t\tif (!region.isActive() && jBossCache.getCacheStatus() == CacheStatus.STARTED) {\n\t\t\t\tregion.activate();\n\t\t\t}\t\t\t\n\t\t}\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n final Set<DeviceAnnouncement> lastDevices = getCurrentDevices();\n socket.get().close();\n socket.set(null);\n devices.clear();\n firstDeviceTime.set(0);\n // Report the loss of all our devices, on the proper thread, outside our lock\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeviceAnnouncement announcement : lastDevices) {\n deliverLostAnnouncement(announcement);\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "public static base_response update(nitro_service client, dospolicy resource) throws Exception {\n\t\tdospolicy updateresource = new dospolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.qdepth = resource.qdepth;\n\t\tupdateresource.cltdetectrate = resource.cltdetectrate;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static Trajectory addPositionNoise(Trajectory t, double sd){\n\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\tTrajectory newt = new Trajectory(t.getDimension());\n\t\t\n\t\tfor(int i = 0; i < t.size(); i++){\n\t\t\tnewt.add(t.get(i));\n\t\t\tfor(int j = 1; j <= t.getDimension(); j++){\n\t\t\t\tswitch (j) {\n\t\t\t\tcase 1:\n\t\t\t\t\tnewt.get(i).setX(newt.get(i).x + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tnewt.get(i).setY(newt.get(i).y + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tnewt.get(i).setZ(newt.get(i).z + r.nextGaussian()*sd);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn newt;\n\t\t\n\t}", "public static String constructUrl(final HttpServerExchange exchange, final String path) {\n final HeaderMap headers = exchange.getRequestHeaders();\n String host = headers.getFirst(HOST);\n String protocol = exchange.getConnection().getSslSessionInfo() != null ? \"https\" : \"http\";\n\n return protocol + \"://\" + host + path;\n }" ]
Moves everything up so that the specified shift or latch character can be inserted. @param position the position beyond which everything needs to be shifted @param c the latch or shift character to insert at the specified position, after everything has been shifted
[ "private void insert(int position, int c) {\r\n for (int i = 143; i > position; i--) {\r\n set[i] = set[i - 1];\r\n character[i] = character[i - 1];\r\n }\r\n character[position] = c;\r\n }" ]
[ "public PhotoList<Photo> photosForLocation(GeoData location, Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n parameters.put(\"method\", METHOD_PHOTOS_FOR_LOCATION);\r\n\r\n if (extras.size() > 0) {\r\n parameters.put(\"extras\", StringUtilities.join(extras, \",\"));\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n parameters.put(\"lat\", Float.toString(location.getLatitude()));\r\n parameters.put(\"lon\", Float.toString(location.getLongitude()));\r\n parameters.put(\"accuracy\", Integer.toString(location.getAccuracy()));\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 Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoElements = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "private SortedSet<Date> calculateDates() {\n\n if (null == m_allDates) {\n SortedSet<Date> result = new TreeSet<>();\n if (isAnyDatePossible()) {\n Calendar date = getFirstDate();\n int previousOccurrences = 0;\n while (showMoreEntries(date, previousOccurrences)) {\n result.add(date.getTime());\n toNextDate(date);\n previousOccurrences++;\n }\n }\n m_allDates = result;\n }\n return m_allDates;\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> void defaultHandleContextMenuForMultiselect(\n Table table,\n CmsContextMenu menu,\n ItemClickEvent event,\n List<I_CmsSimpleContextMenuEntry<Collection<T>>> entries) {\n\n if (!event.isCtrlKey() && !event.isShiftKey()) {\n if (event.getButton().equals(MouseButton.RIGHT)) {\n Collection<T> oldValue = ((Collection<T>)table.getValue());\n if (oldValue.isEmpty() || !oldValue.contains(event.getItemId())) {\n table.setValue(new HashSet<Object>(Arrays.asList(event.getItemId())));\n }\n Collection<T> selection = (Collection<T>)table.getValue();\n menu.setEntries(entries, selection);\n menu.openForTable(event, table);\n }\n }\n\n }", "public static Pool<Jedis> createJedisPool(final Config jesqueConfig, final GenericObjectPoolConfig poolConfig) {\n if (jesqueConfig == null) {\n throw new IllegalArgumentException(\"jesqueConfig must not be null\");\n }\n if (poolConfig == null) {\n throw new IllegalArgumentException(\"poolConfig must not be null\");\n }\n if (jesqueConfig.getMasterName() != null && !\"\".equals(jesqueConfig.getMasterName()) \n && jesqueConfig.getSentinels() != null && jesqueConfig.getSentinels().size() > 0) {\n return new JedisSentinelPool(jesqueConfig.getMasterName(), jesqueConfig.getSentinels(), poolConfig, \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n } else {\n return new JedisPool(poolConfig, jesqueConfig.getHost(), jesqueConfig.getPort(), \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n }\n }", "public void putInWakeUpQueue(SerialMessage serialMessage) {\r\n\t\tif (this.wakeUpQueue.contains(serialMessage)) {\r\n\t\t\tlogger.debug(\"Message already on the wake-up queue for node {}. Discarding.\", this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t\r\n\t\tlogger.debug(\"Putting message in wakeup queue for node {}.\", this.getNode().getNodeId());\r\n\t\tthis.wakeUpQueue.add(serialMessage);\r\n\t}", "public void initialize() {\n if (isClosed.get()) {\n logger.info(\"Initialing Parallel Client Resources: actor system, HttpClientStore, Task Manager ....\");\n ActorConfig.createAndGetActorSystem();\n httpClientStore.init();\n tcpSshPingResourceStore.init();\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been initialized.\");\n } else {\n logger.debug(\"NO OP. Parallel Client Resources has already been initialized.\");\n }\n }", "public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }", "public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }", "public static Object getFieldValue(Object object, String fieldName) {\n try {\n return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }" ]
Search for groups. 18+ groups will only be returned for authenticated calls where the authenticated user is over 18. This method does not require authentication. @param text The text to search for. @param perPage Number of groups to return per page. If this argument is 0, it defaults to 100. The maximum allowed value is 500. @param page The page of results to return. If this argument is 0, it defaults to 1. @return A GroupList Object. Only the fields <em>id</em>, <em>name</em> and <em>eighteenplus</em> in the Groups will be set. @throws FlickrException
[ "public Collection<Group> search(String text, int perPage, int page) throws FlickrException {\r\n GroupList<Group> groupList = new GroupList<Group>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SEARCH);\r\n\r\n parameters.put(\"text\", text);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(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 groupsElement = response.getPayload();\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n groupList.setPage(XMLUtilities.getIntAttribute(groupsElement, \"page\"));\r\n groupList.setPages(XMLUtilities.getIntAttribute(groupsElement, \"pages\"));\r\n groupList.setPerPage(XMLUtilities.getIntAttribute(groupsElement, \"perpage\"));\r\n groupList.setTotal(XMLUtilities.getIntAttribute(groupsElement, \"total\"));\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"nsid\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n groupList.add(group);\r\n }\r\n return groupList;\r\n }" ]
[ "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 }", "@JmxGetter(name = \"avgUpdateEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgUpdateEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.UPDATE_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }", "public static double J0(double x) {\r\n double ax;\r\n\r\n if ((ax = Math.abs(x)) < 8.0) {\r\n double y = x * x;\r\n double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7\r\n + y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));\r\n double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718\r\n + y * (59272.64853 + y * (267.8532712 + y * 1.0))));\r\n\r\n return ans1 / ans2;\r\n } else {\r\n double z = 8.0 / ax;\r\n double y = z * z;\r\n double xx = ax - 0.785398164;\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n - y * 0.934935152e-7)));\r\n\r\n return Math.sqrt(0.636619772 / ax) *\r\n (Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);\r\n }\r\n }", "public static String encodePath(String path, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH);\n\t}", "private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds)\r\n {\r\n Query fkQuery;\r\n QueryByCriteria fkQueryCrit;\r\n\r\n if (cds.isMtoNRelation())\r\n {\r\n fkQueryCrit = getFKQueryMtoN(obj, cld, cds);\r\n }\r\n else\r\n {\r\n fkQueryCrit = getFKQuery1toN(obj, cld, cds);\r\n }\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n fkQueryCrit.addOrderBy((FieldHelper)iter.next());\r\n }\r\n }\r\n\r\n // BRJ: customize the query\r\n if (cds.getQueryCustomizer() != null)\r\n {\r\n fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit);\r\n }\r\n else\r\n {\r\n fkQuery = fkQueryCrit;\r\n }\r\n\r\n return fkQuery;\r\n }", "public void setConnectTimeout(int millis) {\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t}", "public Object getProperty(Object object) {\n MetaMethod getter = getGetter();\n if (getter == null) {\n if (field != null) return field.getProperty(object);\n //TODO: create a WriteOnlyException class?\n throw new GroovyRuntimeException(\"Cannot read write-only property: \" + name);\n }\n return getter.invoke(object, MetaClassHelper.EMPTY_ARRAY);\n }", "public static String get(Properties props, String name, String defval) {\n String value = props.getProperty(name);\n if (value == null)\n value = defval;\n return value;\n }", "public void setOccurence(int min, int max) throws ParseException {\n if (!simplified) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n optional = true;\n }\n minimumOccurence = Math.max(1, min);\n maximumOccurence = max;\n } else {\n throw new ParseException(\"already simplified\");\n }\n }" ]
Use this API to fetch sslvserver_sslcertkey_binding resources of given name .
[ "public static sslvserver_sslcertkey_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "private void transform(File file, Source transformSource)\n throws TransformerConfigurationException, IOException, SAXException, TransformerException,\n ParserConfigurationException {\n\n Transformer transformer = m_transformerFactory.newTransformer(transformSource);\n transformer.setOutputProperty(OutputKeys.ENCODING, \"us-ascii\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\");\n String configDirPath = m_configDir.getAbsolutePath();\n configDirPath = configDirPath.replaceFirst(\"[/\\\\\\\\]$\", \"\");\n transformer.setParameter(\"configDir\", configDirPath);\n XMLReader reader = m_parserFactory.newSAXParser().getXMLReader();\n reader.setEntityResolver(NO_ENTITY_RESOLVER);\n\n Source source;\n\n if (file.exists()) {\n source = new SAXSource(reader, new InputSource(file.getCanonicalPath()));\n } else {\n source = new SAXSource(reader, new InputSource(new ByteArrayInputStream(DEFAULT_XML.getBytes(\"UTF-8\"))));\n }\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n Result target = new StreamResult(baos);\n transformer.transform(source, target);\n byte[] transformedConfig = baos.toByteArray();\n try (FileOutputStream output = new FileOutputStream(file)) {\n output.write(transformedConfig);\n }\n }", "public static DoubleMatrix expm(DoubleMatrix A) {\n // constants for pade approximation\n final double c0 = 1.0;\n final double c1 = 0.5;\n final double c2 = 0.12;\n final double c3 = 0.01833333333333333;\n final double c4 = 0.0019927536231884053;\n final double c5 = 1.630434782608695E-4;\n final double c6 = 1.0351966873706E-5;\n final double c7 = 5.175983436853E-7;\n final double c8 = 2.0431513566525E-8;\n final double c9 = 6.306022705717593E-10;\n final double c10 = 1.4837700484041396E-11;\n final double c11 = 2.5291534915979653E-13;\n final double c12 = 2.8101705462199615E-15;\n final double c13 = 1.5440497506703084E-17;\n\n int j = Math.max(0, 1 + (int) Math.floor(Math.log(A.normmax()) / Math.log(2)));\n DoubleMatrix As = A.div((double) Math.pow(2, j)); // scaled version of A\n int n = A.getRows();\n\n // calculate D and N using special Horner techniques\n DoubleMatrix As_2 = As.mmul(As);\n DoubleMatrix As_4 = As_2.mmul(As_2);\n DoubleMatrix As_6 = As_4.mmul(As_2);\n // U = c0*I + c2*A^2 + c4*A^4 + (c6*I + c8*A^2 + c10*A^4 + c12*A^6)*A^6\n DoubleMatrix U = DoubleMatrix.eye(n).muli(c0).addi(As_2.mul(c2)).addi(As_4.mul(c4)).addi(\n DoubleMatrix.eye(n).muli(c6).addi(As_2.mul(c8)).addi(As_4.mul(c10)).addi(As_6.mul(c12)).mmuli(As_6));\n // V = c1*I + c3*A^2 + c5*A^4 + (c7*I + c9*A^2 + c11*A^4 + c13*A^6)*A^6\n DoubleMatrix V = DoubleMatrix.eye(n).muli(c1).addi(As_2.mul(c3)).addi(As_4.mul(c5)).addi(\n DoubleMatrix.eye(n).muli(c7).addi(As_2.mul(c9)).addi(As_4.mul(c11)).addi(As_6.mul(c13)).mmuli(As_6));\n\n DoubleMatrix AV = As.mmuli(V);\n DoubleMatrix N = U.add(AV);\n DoubleMatrix D = U.subi(AV);\n\n // solve DF = N for F\n DoubleMatrix F = Solve.solve(D, N);\n\n // now square j times\n for (int k = 0; k < j; k++) {\n F.mmuli(F);\n }\n\n return F;\n }", "public void growMaxLength( int arrayLength , boolean preserveValue ) {\n if( arrayLength < 0 )\n throw new IllegalArgumentException(\"Negative array length. Overflow?\");\n // see if multiplying numRows*numCols will cause an overflow. If it won't then pick the smaller of the two\n if( numRows != 0 && numCols <= Integer.MAX_VALUE / numRows ) {\n // save the user from themselves\n arrayLength = Math.min(numRows*numCols, arrayLength);\n }\n if( nz_values == null || arrayLength > this.nz_values.length ) {\n double[] data = new double[ arrayLength ];\n int[] row_idx = new int[ arrayLength ];\n\n if( preserveValue ) {\n if( nz_values == null )\n throw new IllegalArgumentException(\"Can't preserve values when uninitialized\");\n System.arraycopy(this.nz_values, 0, data, 0, this.nz_length);\n System.arraycopy(this.nz_rows, 0, row_idx, 0, this.nz_length);\n }\n\n this.nz_values = data;\n this.nz_rows = row_idx;\n }\n }", "private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }", "public static boolean applyTo(ImageHolder imageHolder, ImageView imageView, String tag) {\n if (imageHolder != null && imageView != null) {\n return imageHolder.applyTo(imageView, tag);\n }\n return false;\n }", "private void storeToDb(Object obj, ClassDescriptor cld, Identity oid, boolean insert, boolean ignoreReferences)\n {\n // 1. link and store 1:1 references\n storeReferences(obj, cld, insert, ignoreReferences);\n\n Object[] pkValues = oid.getPrimaryKeyValues();\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n // BRJ: fk values may be part of pk, but the are not known during\n // creation of Identity. so we have to get them here\n pkValues = serviceBrokerHelper().getKeyValues(cld, obj);\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n String append = insert ? \" on insert\" : \" on update\" ;\n throw new PersistenceBrokerException(\"assertValidPkFields failed for Object of type: \" + cld.getClassNameOfObject() + append);\n }\n }\n\n // get super class cld then store it with the object\n /*\n now for multiple table inheritance\n 1. store super classes, topmost parent first\n 2. go down through heirarchy until current class\n 3. todo: store to full extent?\n\n// arminw: TODO: The extend-attribute feature dosn't work, should we remove this stuff?\n This if-clause will go up the inheritance heirarchy to store all the super classes.\n The id for the top most super class will be the id for all the subclasses too\n */\n if(cld.getSuperClass() != null)\n {\n\n ClassDescriptor superCld = getDescriptorRepository().getDescriptorFor(cld.getSuperClass());\n storeToDb(obj, superCld, oid, insert);\n // arminw: why this?? I comment out this section\n // storeCollections(obj, cld.getCollectionDescriptors(), insert);\n }\n\n // 2. store primitive typed attributes (Or is THIS step 3 ?)\n // if obj not present in db use INSERT\n if (insert)\n {\n dbAccess.executeInsert(cld, obj);\n if(oid.isTransient())\n {\n // Create a new Identity based on the current set of primary key values.\n oid = serviceIdentity().buildIdentity(cld, obj);\n }\n }\n // else use UPDATE\n else\n {\n try\n {\n dbAccess.executeUpdate(cld, obj);\n }\n catch(OptimisticLockException e)\n {\n // ensure that the outdated object be removed from cache\n objectCache.remove(oid);\n throw e;\n }\n }\n // cache object for symmetry with getObjectByXXX()\n // Add the object to the cache.\n objectCache.doInternalCache(oid, obj, ObjectCacheInternal.TYPE_WRITE);\n // 3. store 1:n and m:n associations\n if(!ignoreReferences) storeCollections(obj, cld, insert);\n }", "public static String readTextFile(File file) {\n try {\n return readTextFile(new FileReader(file));\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return null;\n }\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 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 }" ]
Emit information about all of suite's tests.
[ "@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 static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\n }\n }", "public static Date parseEpochTimestamp(String value)\n {\n Date result = null;\n\n if (value.length() > 0)\n {\n if (!value.equals(\"-1 -1\"))\n {\n Calendar cal = DateHelper.popCalendar(JAVA_EPOCH);\n\n int index = value.indexOf(' ');\n if (index == -1)\n {\n if (value.length() < 6)\n {\n value = \"000000\" + value;\n value = value.substring(value.length() - 6);\n }\n\n int hours = Integer.parseInt(value.substring(0, 2));\n int minutes = Integer.parseInt(value.substring(2, 4));\n int seconds = Integer.parseInt(value.substring(4));\n\n cal.set(Calendar.HOUR, hours);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, seconds);\n }\n else\n {\n long astaDays = Long.parseLong(value.substring(0, index));\n int astaSeconds = Integer.parseInt(value.substring(index + 1));\n\n cal.add(Calendar.DAY_OF_YEAR, (int) (astaDays - ASTA_EPOCH));\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.HOUR, 0);\n cal.add(Calendar.SECOND, astaSeconds);\n }\n\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n }\n\n return result;\n }", "public static void touch(final File folder , final String fileName) throws IOException {\n if(!folder.exists()){\n folder.mkdirs();\n }\n\n final File touchedFile = new File(folder, fileName);\n\n // The JVM will only 'touch' the file if you instantiate a\n // FileOutputStream instance for the file in question.\n // You don't actually write any data to the file through\n // the FileOutputStream. Just instantiate it and close it.\n\n try (\n FileOutputStream doneFOS = new FileOutputStream(touchedFile);\n ) {\n // Touching the file\n }\n catch (FileNotFoundException e) {\n throw new FileNotFoundException(\"Failed to the find file.\" + e);\n }\n }", "public synchronized void setDeviceName(String name) {\n if (name.getBytes().length > DEVICE_NAME_LENGTH) {\n throw new IllegalArgumentException(\"name cannot be more than \" + DEVICE_NAME_LENGTH + \" bytes long\");\n }\n Arrays.fill(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH, (byte)0);\n System.arraycopy(name.getBytes(), 0, announcementBytes, DEVICE_NAME_OFFSET, name.getBytes().length);\n }", "public static vrid6 get(nitro_service service, Long id) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tobj.set_id(id);\n\t\tvrid6 response = (vrid6) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static void dumpBlockData(int headerSize, int blockSize, byte[] data)\n {\n if (data != null)\n {\n System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false));\n int index = headerSize;\n while (index < data.length)\n {\n System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false));\n index += blockSize;\n }\n }\n }", "protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\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 }", "private static String formatDirName(final String prefix, final String suffix) {\n // Replace all invalid characters with '-'\n final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();\n return String.format(\"%s-%s\", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));\n }" ]
Use this API to fetch all the ipv6 resources that are configured on netscaler.
[ "public static ipv6 get(nitro_service service) throws Exception{\n\t\tipv6 obj = new ipv6();\n\t\tipv6[] response = (ipv6[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
[ "public void applyTo(Context ctx, GradientDrawable drawable) {\n if (mColorInt != 0) {\n drawable.setColor(mColorInt);\n } else if (mColorRes != -1) {\n drawable.setColor(ContextCompat.getColor(ctx, mColorRes));\n }\n }", "public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, objectOrProxy, true);\r\n }", "public static String ruleToRuleContentsString(Rule originalRule, int indentLevel)\n {\n if (originalRule instanceof Context && ((Context) originalRule).containsKey(RuleMetadataType.RULE_XML))\n {\n return (String) ((Context) originalRule).get(RuleMetadataType.RULE_XML);\n }\n\n if (!(originalRule instanceof RuleBuilder))\n {\n return wrap(originalRule.toString(), MAX_WIDTH, indentLevel);\n }\n final RuleBuilder rule = (RuleBuilder) originalRule;\n StringBuilder result = new StringBuilder();\n if (indentLevel == 0)\n result.append(\"addRule()\");\n\n for (Condition condition : rule.getConditions())\n {\n String conditionToString = conditionToString(condition, indentLevel + 1);\n if (!conditionToString.isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel + 1);\n result.append(\".when(\").append(wrap(conditionToString, MAX_WIDTH, indentLevel + 2)).append(\")\");\n }\n\n }\n for (Operation operation : rule.getOperations())\n {\n String operationToString = operationToString(operation, indentLevel + 1);\n if (!operationToString.isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel + 1);\n result.append(\".perform(\").append(wrap(operationToString, MAX_WIDTH, indentLevel + 2)).append(\")\");\n }\n }\n if (rule.getId() != null && !rule.getId().isEmpty())\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel);\n result.append(\"withId(\\\"\").append(rule.getId()).append(\"\\\")\");\n }\n\n if (rule.priority() != 0)\n {\n result.append(System.lineSeparator());\n insertPadding(result, indentLevel);\n result.append(\".withPriority(\").append(rule.priority()).append(\")\");\n }\n\n return result.toString();\n }", "private EventTypeEnum getEventType(Message message) {\n boolean isRequestor = MessageUtils.isRequestor(message);\n boolean isFault = MessageUtils.isFault(message);\n boolean isOutbound = MessageUtils.isOutbound(message);\n\n //Needed because if it is rest request and method does not exists had better to return Fault\n if(!isFault && isRestMessage(message)) {\n isFault = (message.getExchange().get(\"org.apache.cxf.resource.operation.name\") == null);\n if (!isFault) {\n Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);\n if (null != responseCode) {\n isFault = (responseCode >= 400);\n }\n }\n }\n if (isOutbound) {\n if (isFault) {\n return EventTypeEnum.FAULT_OUT;\n } else {\n return isRequestor ? EventTypeEnum.REQ_OUT : EventTypeEnum.RESP_OUT;\n }\n } else {\n if (isFault) {\n return EventTypeEnum.FAULT_IN;\n } else {\n return isRequestor ? EventTypeEnum.RESP_IN : EventTypeEnum.REQ_IN;\n }\n }\n }", "public static Map<Integer, Integer>\n getMapOfContiguousPartitionRunLengths(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = getMapOfContiguousPartitions(cluster, zoneId);\n Map<Integer, Integer> runLengthToCount = Maps.newHashMap();\n\n if(idToRunLength.isEmpty()) {\n return runLengthToCount;\n }\n\n for(int runLength: idToRunLength.values()) {\n if(!runLengthToCount.containsKey(runLength)) {\n runLengthToCount.put(runLength, 0);\n }\n runLengthToCount.put(runLength, runLengthToCount.get(runLength) + 1);\n }\n\n return runLengthToCount;\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 float smoothStep(float a, float b, float x) {\n\t\tif (x < a)\n\t\t\treturn 0;\n\t\tif (x >= b)\n\t\t\treturn 1;\n\t\tx = (x - a) / (b - a);\n\t\treturn x*x * (3 - 2*x);\n\t}", "@Pure\n\tpublic static <K, V> Pair<K, V> of(K k, V v) {\n\t\treturn new Pair<K, V>(k, v);\n\t}", "private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao)\n\t\t\tthrows SQLException {\n\t\tString foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName();\n\t\tfor (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) {\n\t\t\tif (fieldType.getType() == foreignClass\n\t\t\t\t\t&& (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) {\n\t\t\t\tif (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) {\n\t\t\t\t\t// this may never be reached\n\t\t\t\t\tthrow new SQLException(\"Foreign collection object \" + clazz + \" for field '\" + field.getName()\n\t\t\t\t\t\t\t+ \"' contains a field of class \" + foreignClass + \" but it's not foreign\");\n\t\t\t\t}\n\t\t\t\treturn fieldType;\n\t\t\t}\n\t\t}\n\t\t// build our complex error message\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"Foreign collection class \").append(clazz.getName());\n\t\tsb.append(\" for field '\").append(field.getName()).append(\"' column-name does not contain a foreign field\");\n\t\tif (foreignColumnName != null) {\n\t\t\tsb.append(\" named '\").append(foreignColumnName).append('\\'');\n\t\t}\n\t\tsb.append(\" of class \").append(foreignClass.getName());\n\t\tthrow new SQLException(sb.toString());\n\t}" ]
Set the custom projection matrix with individual matrix elements.
[ "public void setProjectionMatrix(float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4) {\n NativeCustomCamera.setProjectionMatrix(getNative(), x1, y1, z1, w1, x2,\n y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }" ]
[ "private RecurrenceType getRecurrenceType(int value)\n {\n RecurrenceType result;\n if (value < 0 || value >= RECURRENCE_TYPES.length)\n {\n result = null;\n }\n else\n {\n result = RECURRENCE_TYPES[value];\n }\n\n return result;\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 }", "public List<T> nextPermutationAsList()\n {\n List<T> permutation = new ArrayList<T>(elements.length);\n return nextPermutationAsList(permutation);\n }", "public void animate(float animationTime, Matrix4f mat)\n {\n mRotInterpolator.animate(animationTime, mRotKey);\n mPosInterpolator.animate(animationTime, mPosKey);\n mSclInterpolator.animate(animationTime, mScaleKey);\n mat.translationRotateScale(mPosKey[0], mPosKey[1], mPosKey[2], mRotKey[0], mRotKey[1], mRotKey[2], mRotKey[3], mScaleKey[0], mScaleKey[1], mScaleKey[2]);\n\n }", "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 }", "public static base_response unset(nitro_service client, onlinkipv6prefix resource, String[] args) throws Exception{\n\t\tonlinkipv6prefix unsetresource = new onlinkipv6prefix();\n\t\tunsetresource.ipv6prefix = resource.ipv6prefix;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "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 static long getTxInfoCacheWeight(FluoConfiguration conf) {\n long size = conf.getLong(TX_INFO_CACHE_WEIGHT, TX_INFO_CACHE_WEIGHT_DEFAULT);\n if (size <= 0) {\n throw new IllegalArgumentException(\"Cache size must be positive for \" + TX_INFO_CACHE_WEIGHT);\n }\n return size;\n }", "public GVRSceneObject startDrag(GVRSceneObject dragMe, float relX, float relY, float relZ) {\n synchronized (mLock) {\n if (mCursorController == null) {\n Log.w(TAG, \"Physics drag failed: Cursor controller not found!\");\n return null;\n }\n\n if (mDragMe != null) {\n Log.w(TAG, \"Physics drag failed: Previous drag wasn't finished!\");\n return null;\n }\n\n if (mPivotObject == null) {\n mPivotObject = onCreatePivotObject(mContext);\n }\n\n mDragMe = dragMe;\n\n GVRTransform t = dragMe.getTransform();\n\n /* It is not possible to drag a rigid body directly, we need a pivot object.\n We are using the pivot object's position as pivot of the dragging's physics constraint.\n */\n mPivotObject.getTransform().setPosition(t.getPositionX() + relX,\n t.getPositionY() + relY, t.getPositionZ() + relZ);\n\n mCursorController.startDrag(mPivotObject);\n }\n\n return mPivotObject;\n }" ]
Use this API to save nsconfig.
[ "public static base_response save(nitro_service client) throws Exception {\n\t\tnsconfig saveresource = new nsconfig();\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}" ]
[ "public void setResourceCalendar(ProjectCalendar calendar)\n {\n set(ResourceField.CALENDAR, calendar);\n if (calendar == null)\n {\n setResourceCalendarUniqueID(null);\n }\n else\n {\n calendar.setResource(this);\n setResourceCalendarUniqueID(calendar.getUniqueID());\n }\n }", "public void addColumn(String columnName, boolean searchable, boolean orderable,\n String searchValue) {\n this.columns.add(new Column(columnName, \"\", searchable, orderable,\n new Search(searchValue, false)));\n }", "public void setType(CheckBoxType type) {\n this.type = type;\n switch (type) {\n case FILLED:\n Element input = DOM.getChild(getElement(), 0);\n input.setAttribute(\"class\", CssName.FILLED_IN);\n break;\n case INTERMEDIATE:\n addStyleName(type.getCssName() + \"-checkbox\");\n break;\n default:\n addStyleName(type.getCssName());\n break;\n }\n }", "public MBeanOperationInfo getOperationInfo(String operationName)\n throws OperationNotFoundException, UnsupportedEncodingException {\n\n String decodedOperationName = sanitizer.urlDecode(operationName, encoding);\n Map<String, MBeanOperationInfo> operationMap = getOperationMetadata();\n if (operationMap.containsKey(decodedOperationName)) {\n return operationMap.get(decodedOperationName);\n }\n throw new OperationNotFoundException(\"Could not find operation \" + operationName + \" on MBean \" +\n objectName.getCanonicalName());\n }", "public boolean needMerge(@NotNull final BasePage left, @NotNull final BasePage right) {\n final int leftSize = left.getSize();\n final int rightSize = right.getSize();\n return leftSize == 0 || rightSize == 0 ||\n leftSize + rightSize <= (((isDupTree(left) ? getDupPageMaxSize() : getPageMaxSize()) * 7) >> 3);\n }", "public static dnspolicylabel[] get(nitro_service service) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tdnspolicylabel[] response = (dnspolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException {\n FilePath someWorkspace = project.getSomeWorkspace();\n if (someWorkspace == null) {\n throw new IllegalStateException(\"Couldn't find workspace\");\n }\n\n Map<String, String> workspaceEnv = Maps.newHashMap();\n workspaceEnv.put(\"WORKSPACE\", someWorkspace.getRemote());\n\n for (Builder builder : getBuilders()) {\n if (builder instanceof Gradle) {\n Gradle gradleBuilder = (Gradle) builder;\n String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();\n if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) {\n String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv);\n rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv);\n return new FilePath(someWorkspace, rootBuildScriptNormalized);\n } else {\n return someWorkspace;\n }\n }\n }\n\n throw new IllegalArgumentException(\"Couldn't find Gradle builder in the current builders list\");\n }", "public Headers getAllHeaders() {\n Headers requestHeaders = getHeaders();\n requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders;\n //We don't want to add headers more than once.\n return requestHeaders;\n }", "public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }" ]
Compares this value with the specified object for order. Returns a negative integer, zero, or a positive integer as this value is less than, equal to, or greater than the specified value. @param other Another Rational value. @return A negative integer, zero, or a positive integer as this value is less than, equal to, or greater than the specified value.
[ "public int compareTo(Rational other)\n {\n if (denominator == other.getDenominator())\n {\n return ((Long) numerator).compareTo(other.getNumerator());\n }\n else\n {\n Long adjustedNumerator = numerator * other.getDenominator();\n Long otherAdjustedNumerator = other.getNumerator() * denominator;\n return adjustedNumerator.compareTo(otherAdjustedNumerator);\n }\n }" ]
[ "public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }", "@Pure\n\tpublic static <T> Iterator<T> filterNull(Iterator<T> unfiltered) {\n\t\treturn Iterators.filter(unfiltered, Predicates.notNull());\n\t}", "public int addServerRedirectToProfile(String region, String srcUrl, String destUrl, String hostHeader,\n int profileId, int clientId) throws Exception {\n int serverId = -1;\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n serverId = addServerRedirect(region, srcUrl, destUrl, hostHeader, profileId, client.getActiveServerGroup());\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return serverId;\n }", "public Class<?> getType(String key) {\n Object val = this.data.get(key);\n return val == null ? null : val.getClass();\n }", "public Where<T, ID> idEq(ID id) throws SQLException {\n\t\tif (idColumnName == null) {\n\t\t\tthrow new SQLException(\"Object has no id column specified\");\n\t\t}\n\t\taddClause(new SimpleComparison(idColumnName, idFieldType, id, SimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public Location getInfo(String placeId, String woeId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\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 locationElement = response.getPayload();\r\n return parseLocation(locationElement);\r\n }", "protected void deleteAlias(MonolingualTextValue alias) {\n String lang = alias.getLanguageCode();\n AliasesWithUpdate currentAliases = newAliases.get(lang);\n if (currentAliases != null) {\n currentAliases.aliases.remove(alias);\n currentAliases.deleted.add(alias);\n currentAliases.write = true;\n }\n }", "public ProjectCalendarHours addCalendarHours(Day day)\n {\n ProjectCalendarHours bch = new ProjectCalendarHours(this);\n bch.setDay(day);\n m_hours[day.getValue() - 1] = bch;\n return (bch);\n }", "@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }" ]
Parses the field facet configurations. @param fieldFacetObject The JSON sub-node with the field facet configurations. @return The field facet configurations.
[ "protected I_CmsSearchConfigurationFacetField parseFieldFacet(JSONObject fieldFacetObject) {\n\n try {\n String field = fieldFacetObject.getString(JSON_KEY_FACET_FIELD);\n String name = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_NAME);\n String label = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_LABEL);\n Integer minCount = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_MINCOUNT);\n Integer limit = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_LIMIT);\n String prefix = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_PREFIX);\n String sorder = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (Exception e) {\n order = null;\n }\n String filterQueryModifier = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_FILTERQUERYMODIFIER);\n Boolean isAndFacet = parseOptionalBooleanValue(fieldFacetObject, JSON_KEY_FACET_ISANDFACET);\n List<String> preselection = parseOptionalStringValues(fieldFacetObject, JSON_KEY_FACET_PRESELECTION);\n Boolean ignoreFilterAllFacetFilters = parseOptionalBooleanValue(\n fieldFacetObject,\n JSON_KEY_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreFilterAllFacetFilters);\n } catch (JSONException e) {\n LOG.error(\n Messages.get().getBundle().key(Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1, JSON_KEY_FACET_FIELD),\n e);\n return null;\n }\n }" ]
[ "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 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 }", "@GET\n @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})\n @Path(\"/{name}\" + ServerAPI.GET_CORPORATE_GROUPIDS)\n public Response getCorporateGroupIdPrefix(@PathParam(\"name\") final String organizationId){\n LOG.info(\"Got a get corporate groupId prefix request for organization \" + organizationId +\".\");\n\n final ListView view = new ListView(\"Organization \" + organizationId, \"Corporate GroupId Prefix\");\n final List<String> corporateGroupIds = getOrganizationHandler().getCorporateGroupIds(organizationId);\n view.addAll(corporateGroupIds);\n\n return Response.ok(view).build();\n }", "private void waitForOutstandingRequest() throws IOException {\n if (outstandingRequest == null) {\n return;\n }\n try {\n RetryHelper.runWithRetries(new Callable<Void>() {\n @Override\n public Void call() throws IOException, InterruptedException {\n if (RetryHelper.getContext().getAttemptNumber() > 1) {\n outstandingRequest.retry();\n }\n token = outstandingRequest.waitForNextToken();\n outstandingRequest = null;\n return null;\n }\n }, retryParams, GcsServiceImpl.exceptionHandler);\n } catch (RetryInterruptedException ex) {\n token = null;\n throw new ClosedByInterruptException();\n } catch (NonRetriableException e) {\n Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);\n throw e;\n }\n }", "protected OJBIterator getIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n RsIteratorFactory factory = RsIteratorFactoryImpl.getInstance();\n OJBIterator result = getRsIteratorFromQuery(query, cld, factory);\n\n if (query.usePaging())\n {\n result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());\n }\n return result;\n }", "public CrosstabBuilder addInvisibleMeasure(String property, String className, String title) {\r\n DJCrosstabMeasure measure = new DJCrosstabMeasure(property, className, DJCalculation.NOTHING, title);\r\n measure.setVisible(false);\r\n crosstab.getMeasures().add(measure);\r\n return this;\r\n }", "public static <T> List<T> asImmutable(List<? extends T> self) {\n return Collections.unmodifiableList(self);\n }", "protected void append(Env env) {\n addAllWithFilter(this.envVars, env.envVars, filter.getPatternFilter());\n addAllWithFilter(this.sysVars, env.sysVars, filter.getPatternFilter());\n }", "public void animate(GVRHybridObject object, float animationTime)\n {\n GVRMeshMorph morph = (GVRMeshMorph) mTarget;\n\n mKeyInterpolator.animate(animationTime * mDuration, mCurrentValues);\n morph.setWeights(mCurrentValues);\n\n }" ]