query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Search for the first entry in the first database. Use this method for databases configured with no duplicates. @param txn enclosing transaction @param first first key. @return null if no entry found, otherwise the value.
[ "@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }" ]
[ "public Release rollback(String appName, String releaseUuid) {\n return connection.execute(new Rollback(appName, releaseUuid), apiKey);\n }", "public ByteBuffer payload() {\n ByteBuffer payload = buffer.duplicate();\n payload.position(headerSize(magic()));\n payload = payload.slice();\n payload.limit(payloadSize());\n payload.rewind();\n return payload;\n }", "void markReferenceElements(PersistenceBroker broker)\r\n {\r\n // these cases will be handled by ObjectEnvelopeTable#cascadingDependents()\r\n // if(getModificationState().needsInsert() || getModificationState().needsDelete()) return;\r\n\r\n Map oldImage = getBeforeImage();\r\n Map newImage = getCurrentImage();\r\n\r\n Iterator iter = newImage.entrySet().iterator();\r\n while (iter.hasNext())\r\n {\r\n Map.Entry entry = (Map.Entry) iter.next();\r\n Object key = entry.getKey();\r\n // we only interested in references\r\n if(key instanceof ObjectReferenceDescriptor)\r\n {\r\n Image oldRefImage = (Image) oldImage.get(key);\r\n Image newRefImage = (Image) entry.getValue();\r\n newRefImage.performReferenceDetection(oldRefImage);\r\n }\r\n }\r\n }", "public void setSlideDrawable(Drawable drawable) {\n mSlideDrawable = new SlideDrawable(drawable);\n mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL);\n\n if (mActionBarHelper != null) {\n mActionBarHelper.setDisplayShowHomeAsUpEnabled(true);\n\n if (mDrawerIndicatorEnabled) {\n mActionBarHelper.setActionBarUpIndicator(mSlideDrawable,\n isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc);\n }\n }\n }", "protected AbstractElement getEnclosingSingleElementGroup(AbstractElement elementToParse) {\n\t\tEObject container = elementToParse.eContainer();\n\t\tif (container instanceof Group) {\n\t\t\tif (((Group) container).getElements().size() == 1) {\n\t\t\t\treturn (AbstractElement) container;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public static void log(byte[] data)\n {\n if (LOG != null)\n {\n LOG.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n LOG.flush();\n }\n }", "private void readAvailabilityTable(Resource resource, AvailabilityPeriods periods)\n {\n if (periods != null)\n {\n AvailabilityTable table = resource.getAvailability();\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (AvailabilityPeriod period : list)\n {\n Date start = period.getAvailableFrom();\n Date end = period.getAvailableTo();\n Number units = DatatypeConverter.parseUnits(period.getAvailableUnits());\n Availability availability = new Availability(start, end, units);\n table.add(availability);\n }\n Collections.sort(table);\n }\n }", "public String generateInitScript(EnvVars env) throws IOException, InterruptedException {\n StringBuilder initScript = new StringBuilder();\n InputStream templateStream = getClass().getResourceAsStream(\"/initscripttemplate.gradle\");\n String templateAsString = IOUtils.toString(templateStream, Charsets.UTF_8.name());\n File extractorJar = PluginDependencyHelper.getExtractorJar(env);\n FilePath dependencyDir = PluginDependencyHelper.getActualDependencyDirectory(extractorJar, rootPath);\n String absoluteDependencyDirPath = dependencyDir.getRemote();\n absoluteDependencyDirPath = absoluteDependencyDirPath.replace(\"\\\\\", \"/\");\n String str = templateAsString.replace(\"${pluginLibDir}\", absoluteDependencyDirPath);\n initScript.append(str);\n return initScript.toString();\n }", "public V internalNonBlockingGet(K key) throws Exception {\n Pool<V> resourcePool = getResourcePoolForKey(key);\n return attemptNonBlockingCheckout(key, resourcePool);\n }" ]
Does a query for the object's Id and copies in each of the field values from the database to refresh the data parameter.
[ "public int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedRefresh == null) {\n\t\t\tmappedRefresh = MappedRefresh.build(dao, tableInfo);\n\t\t}\n\t\treturn mappedRefresh.executeRefresh(databaseConnection, data, objectCache);\n\t}" ]
[ "public PortComponentMetaData getPortComponentByWsdlPort(String name)\n {\n ArrayList<String> pcNames = new ArrayList<String>();\n for (PortComponentMetaData pc : portComponents)\n {\n String wsdlPortName = pc.getWsdlPort().getLocalPart();\n if (wsdlPortName.equals(name))\n return pc;\n\n pcNames.add(wsdlPortName);\n }\n\n Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames);\n return null;\n }", "private static final void writeJson(Writer os, //\n Object object, //\n SerializeConfig config, //\n SerializeFilter[] filters, //\n DateFormat dateFormat, //\n int defaultFeatures, //\n SerializerFeature... features) {\n SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);\n\n try {\n JSONSerializer serializer = new JSONSerializer(writer, config);\n\n if (dateFormat != null) {\n serializer.setDateFormat(dateFormat);\n serializer.config(SerializerFeature.WriteDateUseDateFormat, true);\n }\n\n if (filters != null) {\n for (SerializeFilter filter : filters) {\n serializer.addFilter(filter);\n }\n }\n serializer.write(object);\n } finally {\n writer.close();\n }\n }", "public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }", "protected long save() {\n // save leaf nodes\n ReclaimFlag flag = saveChildren();\n // save self. complementary to {@link load()}\n final byte type = getType();\n final BTreeBase tree = getTree();\n final int structureId = tree.structureId;\n final Log log = tree.log;\n if (flag == ReclaimFlag.PRESERVE) {\n // there is a chance to update the flag to RECLAIM\n if (log.getWrittenHighAddress() % log.getFileLengthBound() == 0) {\n // page will be exactly on file border\n flag = ReclaimFlag.RECLAIM;\n } else {\n final ByteIterable[] iterables = getByteIterables(flag);\n long result = log.tryWrite(type, structureId, new CompoundByteIterable(iterables));\n if (result < 0) {\n iterables[0] = CompressedUnsignedLongByteIterable.getIterable(\n (size << 1) + ReclaimFlag.RECLAIM.value\n );\n result = log.writeContinuously(type, structureId, new CompoundByteIterable(iterables));\n\n if (result < 0) {\n throw new TooBigLoggableException();\n }\n }\n return result;\n }\n }\n return log.write(type, structureId, new CompoundByteIterable(getByteIterables(flag)));\n }", "@SuppressWarnings(\"unchecked\")\n public static <E> TypeConverter<E> typeConverterFor(Class<E> cls) throws NoSuchTypeConverterException {\n TypeConverter<E> typeConverter = TYPE_CONVERTERS.get(cls);\n if (typeConverter == null) {\n throw new NoSuchTypeConverterException(cls);\n }\n return typeConverter;\n }", "public static Property getChildAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n return addressParts.get(addressParts.size() - 1);\n }", "public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }", "public void logAttributeWarning(PathAddress address, Set<String> attributes) {\n logAttributeWarning(address, null, null, attributes);\n }", "public UseCase selectUseCase()\r\n {\r\n displayUseCases();\r\n System.out.println(\"type in number to select a use case\");\r\n String in = readLine();\r\n int index = Integer.parseInt(in);\r\n return (UseCase) useCases.get(index);\r\n }" ]
It will look for all the deployments under the deploymentsRootAddress with a runtimeName in the specified list of runtime names and then transform the operation so that every server having those deployments will redeploy the affected deployments. @see #transformOperation @param removeOperation @param context @param deploymentsRootAddress @param runtimeNames @throws OperationFailedException
[ "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 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 }", "private List<CmsResource> getDetailContainerResources(CmsObject cms, CmsResource res) throws CmsException {\n\n CmsRelationFilter filter = CmsRelationFilter.relationsFromStructureId(res.getStructureId()).filterType(\n CmsRelationType.DETAIL_ONLY);\n List<CmsResource> result = Lists.newArrayList();\n List<CmsRelation> relations = cms.readRelations(filter);\n for (CmsRelation relation : relations) {\n try {\n result.add(relation.getTarget(cms, CmsResourceFilter.ALL));\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return result;\n }", "public EmailAlias addEmailAlias(String email, boolean isConfirmed) {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n\n JsonObject requestJSON = new JsonObject()\n .add(\"email\", email);\n\n if (isConfirmed) {\n requestJSON.add(\"is_confirmed\", isConfirmed);\n }\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n return new EmailAlias(responseJSON);\n }", "public static float distance(final float ax, final float ay,\n final float bx, final float by) {\n return (float) Math.sqrt(\n (ax - bx) * (ax - bx) +\n (ay - by) * (ay - by)\n );\n }", "private AirMapViewBuilder getWebMapViewBuilder() {\n if (context != null) {\n try {\n ApplicationInfo ai = context.getPackageManager()\n .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);\n Bundle bundle = ai.metaData;\n String accessToken = bundle.getString(\"com.mapbox.ACCESS_TOKEN\");\n String mapId = bundle.getString(\"com.mapbox.MAP_ID\");\n\n if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(mapId)) {\n return new MapboxWebMapViewBuilder(accessToken, mapId);\n }\n } catch (PackageManager.NameNotFoundException e) {\n Log.e(TAG, \"Failed to load Mapbox access token and map id\", e);\n }\n }\n return new WebAirMapViewBuilder();\n }", "public static StitchAppClient getAppClient(\n @Nonnull final String clientAppId\n ) {\n ensureInitialized();\n\n synchronized (Stitch.class) {\n if (!appClients.containsKey(clientAppId)) {\n throw new IllegalStateException(\n String.format(\"client for app '%s' has not yet been initialized\", clientAppId));\n }\n return appClients.get(clientAppId);\n }\n }", "public int getChunkForKey(byte[] key) throws IllegalStateException {\n if(numChunks == 0) {\n throw new IllegalStateException(\"The ChunkedFileSet is closed.\");\n }\n\n switch(storageFormat) {\n case READONLY_V0: {\n return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks);\n }\n case READONLY_V1: {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n routingPartitionList.retainAll(nodePartitionIds);\n\n if(routingPartitionList.size() != 1) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n return chunkIdToChunkStart.get(routingPartitionList.get(0))\n + ReadOnlyUtils.chunk(ByteUtils.md5(key),\n chunkIdToNumChunks.get(routingPartitionList.get(0)));\n }\n case READONLY_V2: {\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n\n Pair<Integer, Integer> bucket = null;\n for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) {\n if(bucket == null) {\n bucket = Pair.create(routingPartitionList.get(0), replicaType);\n } else {\n throw new IllegalStateException(\"Found more than one replica for a given partition on the current node!\");\n }\n }\n }\n\n if(bucket == null) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n Integer chunkStart = chunkIdToChunkStart.get(bucket);\n\n if (chunkStart == null) {\n throw new IllegalStateException(\"chunkStart is null.\");\n }\n\n return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket));\n }\n default: {\n throw new IllegalStateException(\"Unsupported storageFormat: \" + storageFormat);\n }\n }\n\n }", "public CmsJspDateSeriesBean getToDateSeries() {\n\n if (m_dateSeries == null) {\n m_dateSeries = new CmsJspDateSeriesBean(this, m_cms.getRequestContext().getLocale());\n }\n return m_dateSeries;\n }", "private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) {\n // TODO make async\n // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user\n // may not iterate over entire range\n Map<Bytes, Set<Column>> columnsToRead = new HashMap<>();\n\n for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) {\n Set<Column> rowColsRead = columnsRead.get(entry.getKey());\n if (rowColsRead == null) {\n columnsToRead.put(entry.getKey(), entry.getValue());\n } else {\n HashSet<Column> colsToRead = new HashSet<>(entry.getValue());\n colsToRead.removeAll(rowColsRead);\n if (!colsToRead.isEmpty()) {\n columnsToRead.put(entry.getKey(), colsToRead);\n }\n }\n }\n\n for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) {\n getImpl(entry.getKey(), entry.getValue(), locksSeen);\n }\n }" ]
Returns true if the request should continue. @return
[ "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 }" ]
[ "synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }", "List<String> getWarnings(JsonNode root) {\n\t\tArrayList<String> warnings = new ArrayList<>();\n\n\t\tif (root.has(\"warnings\")) {\n\t\t\tJsonNode warningNode = root.path(\"warnings\");\n\t\t\tIterator<Map.Entry<String, JsonNode>> moduleIterator = warningNode\n\t\t\t\t\t.fields();\n\t\t\twhile (moduleIterator.hasNext()) {\n\t\t\t\tMap.Entry<String, JsonNode> moduleNode = moduleIterator.next();\n\t\t\t\tIterator<JsonNode> moduleOutputIterator = moduleNode.getValue()\n\t\t\t\t\t\t.elements();\n\t\t\t\twhile (moduleOutputIterator.hasNext()) {\n\t\t\t\t\tJsonNode moduleOutputNode = moduleOutputIterator.next();\n\t\t\t\t\tif (moduleOutputNode.isTextual()) {\n\t\t\t\t\t\twarnings.add(\"[\" + moduleNode.getKey() + \"]: \"\n\t\t\t\t\t\t\t\t+ moduleOutputNode.textValue());\n\t\t\t\t\t} else if (moduleOutputNode.isArray()) {\n\t\t\t\t\t\tIterator<JsonNode> messageIterator = moduleOutputNode\n\t\t\t\t\t\t\t\t.elements();\n\t\t\t\t\t\twhile (messageIterator.hasNext()) {\n\t\t\t\t\t\t\tJsonNode messageNode = messageIterator.next();\n\t\t\t\t\t\t\twarnings.add(\"[\"\n\t\t\t\t\t\t\t\t\t+ moduleNode.getKey()\n\t\t\t\t\t\t\t\t\t+ \"]: \"\n\t\t\t\t\t\t\t\t\t+ messageNode.path(\"html\").path(\"*\")\n\t\t\t\t\t\t\t\t\t\t\t.asText(messageNode.toString()));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\twarnings.add(\"[\"\n\t\t\t\t\t\t\t\t+ moduleNode.getKey()\n\t\t\t\t\t\t\t\t+ \"]: \"\n\t\t\t\t\t\t\t\t+ \"Warning was not understood. Please report this to Wikidata Toolkit. JSON source: \"\n\t\t\t\t\t\t\t\t+ moduleOutputNode.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\treturn warnings;\n\t}", "public static Provider getCurrentProvider(boolean useSwingEventQueue) {\n Provider provider;\n if (Platform.isX11()) {\n provider = new X11Provider();\n } else if (Platform.isWindows()) {\n provider = new WindowsProvider();\n } else if (Platform.isMac()) {\n provider = new CarbonProvider();\n } else {\n LOGGER.warn(\"No suitable provider for \" + System.getProperty(\"os.name\"));\n return null;\n }\n provider.setUseSwingEventQueue(useSwingEventQueue);\n provider.init();\n return provider;\n\n }", "public void put(final K key, V value) {\n ManagedReference<V> ref = new ManagedReference<V>(bundle, value) {\n @Override\n public void finalizeReference() {\n super.finalizeReference();\n internalMap.remove(key, get());\n }\n };\n internalMap.put(key, ref);\n }", "public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }", "public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private Double getDouble(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue());\n }\n\n return result;\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getClientList(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier) throws Exception {\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n return Utils.getJQGridJSON(clientService.findAllClients(profileId), \"clients\");\n }", "@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n public List<HazeltaskTask<G>> shutdownNow() {\n\t return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();\n\t}" ]
Set the featureModel. @param featureModel feature model @throws LayerException problem setting the feature model @since 1.8.0
[ "@Api\n\tpublic void setFeatureModel(FeatureModel featureModel) throws LayerException {\n\t\tthis.featureModel = featureModel;\n\t\tif (null != getLayerInfo()) {\n\t\t\tfeatureModel.setLayerInfo(getLayerInfo());\n\t\t}\n\t\tfilterService.registerFeatureModel(featureModel);\n\t}" ]
[ "@SuppressWarnings({\"unchecked\", \"unused\"})\n public static <T> T[] object2Array(final Class<T> clazz, final Object obj) {\n return (T[]) obj;\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 }", "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 ParallelTaskBuilder setTargetHostsFromLineByLineText(\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath,\n sourceType);\n return this;\n }", "public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}", "@Pure\n\tpublic static <T> List<T> reverseView(List<T> list) {\n\t\treturn Lists.reverse(list);\n\t}", "public void addHeader(String key, String value) {\n if (key.equals(\"As-User\")) {\n for (int i = 0; i < this.headers.size(); i++) {\n if (this.headers.get(i).getKey().equals(\"As-User\")) {\n this.headers.remove(i);\n }\n }\n }\n if (key.equals(\"X-Box-UA\")) {\n throw new IllegalArgumentException(\"Altering the X-Box-UA header is not permitted\");\n }\n this.headers.add(new RequestHeader(key, value));\n }", "public void increasePriority(int overrideId, int ordinal, int pathId, String clientUUID) {\n logger.info(\"Increase priority\");\n\n int origPriority = -1;\n int newPriority = -1;\n int origId = 0;\n int newId = 0;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n results = null;\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n statement.setInt(1, pathId);\n statement.setString(2, clientUUID);\n results = statement.executeQuery();\n\n int ordinalCount = 0;\n while (results.next()) {\n if (results.getInt(Constants.ENABLED_OVERRIDES_OVERRIDE_ID) == overrideId) {\n ordinalCount++;\n if (ordinalCount == ordinal) {\n origPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n origId = results.getInt(Constants.GENERIC_ID);\n break;\n }\n }\n newPriority = results.getInt(Constants.ENABLED_OVERRIDES_PRIORITY);\n newId = results.getInt(Constants.GENERIC_ID);\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 try (Connection sqlConnection = sqlService.getConnection()) {\n // update priorities\n if (origPriority != -1 && newPriority != -1) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, origPriority);\n statement.setInt(2, newId);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" SET \" + Constants.ENABLED_OVERRIDES_PRIORITY + \"=?\" +\n \" WHERE \" + Constants.GENERIC_ID + \"=?\"\n );\n statement.setInt(1, newPriority);\n statement.setInt(2, origId);\n statement.executeUpdate();\n }\n } catch (Exception e) {\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static String getDefaultConversionFor(String javaType)\r\n {\r\n return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null;\r\n }" ]
Returns the project membership record. @param projectMembership Globally unique identifier for the project membership. @return Request object
[ "public ItemRequest<ProjectMembership> findById(String projectMembership) {\n \n String path = String.format(\"/project_memberships/%s\", projectMembership);\n return new ItemRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }" ]
[ "boolean attachmentsAreStructurallyDifferent( List<AttachmentModel> firstAttachments, List<AttachmentModel> otherAttachments ) {\n if( firstAttachments.size() != otherAttachments.size() ) {\n return true;\n }\n\n for( int i = 0; i < firstAttachments.size(); i++ ) {\n if( attachmentIsStructurallyDifferent( firstAttachments.get( i ), otherAttachments.get( i ) ) ) {\n return true;\n }\n }\n return false;\n }", "public static authenticationvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_stats response = (authenticationvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "public void disableAllOverrides(int pathID, String clientUUID) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ? \" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n statement.execute();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public boolean getHidden() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_HIDDEN);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element personElement = response.getPayload();\r\n return personElement.getAttribute(\"hidden\").equals(\"1\") ? true : false;\r\n }", "private static final double printDurationFractionsOfMinutes(Duration duration, int factor)\n {\n double result = 0;\n\n if (duration != null)\n {\n result = duration.getDuration();\n\n switch (duration.getUnits())\n {\n case HOURS:\n case ELAPSED_HOURS:\n {\n result *= 60;\n break;\n }\n\n case DAYS:\n {\n result *= (60 * 8);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n result *= (60 * 24);\n break;\n }\n\n case WEEKS:\n {\n result *= (60 * 8 * 5);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n result *= (60 * 24 * 7);\n break;\n }\n\n case MONTHS:\n {\n result *= (60 * 8 * 5 * 4);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n result *= (60 * 24 * 30);\n break;\n }\n\n case YEARS:\n {\n result *= (60 * 8 * 5 * 52);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n result *= (60 * 24 * 365);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n result *= factor;\n\n return (result);\n }", "public void writeOutput(DataPipe cr) {\n try {\n context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate)));\n } catch (Exception e) {\n throw new RuntimeException(\"Exception occurred while writing to Context\", e);\n }\n }", "private SortedProperties getLocalization(Locale locale) throws IOException, CmsException {\n\n if (null == m_localizations.get(locale)) {\n switch (m_bundleType) {\n case PROPERTY:\n loadLocalizationFromPropertyBundle(locale);\n break;\n case XML:\n loadLocalizationFromXmlBundle(locale);\n break;\n case DESCRIPTOR:\n return null;\n default:\n break;\n }\n }\n return m_localizations.get(locale);\n }", "private List<Entry> getChildNodes(DirectoryEntry parent)\n {\n List<Entry> result = new ArrayList<Entry>();\n Iterator<Entry> entries = parent.getEntries();\n while (entries.hasNext())\n {\n result.add(entries.next());\n }\n return result;\n }", "public static void generateOutputFile(Random rng,\n File outputFile) throws IOException\n {\n DataOutputStream dataOutput = null;\n try\n {\n dataOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));\n for (int i = 0; i < INT_COUNT; i++)\n {\n dataOutput.writeInt(rng.nextInt());\n }\n dataOutput.flush();\n }\n finally\n {\n if (dataOutput != null)\n {\n dataOutput.close();\n }\n }\n }" ]
From three tagNames, if one is under sectorTag and one under rowTag, returns the remaining one, which is supposedly the a box label. Otherwise, returns null.
[ "private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames)\n {\n TagGraphService tagService = new TagGraphService(graphContext);\n\n if (tagNames.size() < 3)\n throw new WindupException(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n if (tagNames.size() > 3)\n LOG.severe(\"There should always be exactly 3 placement labels - row, sector, column/box. It was: \" + tagNames);\n\n TechReportPlacement placement = new TechReportPlacement();\n\n final TagModel placeSectorsTag = tagService.getTagByName(\"techReport:placeSectors\");\n final TagModel placeBoxesTag = tagService.getTagByName(\"techReport:placeBoxes\");\n final TagModel placeRowsTag = tagService.getTagByName(\"techReport:placeRows\");\n\n Set<String> unknownTags = new HashSet<>();\n for (String name : tagNames)\n {\n final TagModel tag = tagService.getTagByName(name);\n if (null == tag)\n continue;\n\n if (TagGraphService.isTagUnderTagOrSame(tag, placeSectorsTag))\n {\n placement.sector = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeBoxesTag))\n {\n placement.box = tag;\n }\n else if (TagGraphService.isTagUnderTagOrSame(tag, placeRowsTag))\n {\n placement.row = tag;\n }\n else\n {\n unknownTags.add(name);\n }\n }\n placement.unknown = unknownTags;\n\n LOG.fine(String.format(\"\\t\\tLabels %s identified as: sector: %s, box: %s, row: %s\", tagNames, placement.sector, placement.box,\n placement.row));\n if (placement.box == null || placement.row == null)\n {\n LOG.severe(String.format(\n \"There should always be exactly 3 placement labels - row, sector, column/box. Found: %s, of which box: %s, row: %s\", tagNames,\n placement.box, placement.row));\n }\n return placement;\n }" ]
[ "public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}", "public static boolean respondsTo(Object object, String methodName) {\r\n MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object);\r\n if (!metaClass.respondsTo(object, methodName).isEmpty()) {\r\n return true;\r\n }\r\n Map properties = DefaultGroovyMethods.getProperties(object);\r\n return properties.containsKey(methodName);\r\n }", "protected void writeEntries(final StorageAwareResource resource, final ZipOutputStream zipOut) throws IOException {\n final BufferedOutputStream bufferedOutput = new BufferedOutputStream(zipOut);\n ZipEntry _zipEntry = new ZipEntry(\"emf-contents\");\n zipOut.putNextEntry(_zipEntry);\n try {\n this.writeContents(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n ZipEntry _zipEntry_1 = new ZipEntry(\"resource-description\");\n zipOut.putNextEntry(_zipEntry_1);\n try {\n this.writeResourceDescription(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n if (this.storeNodeModel) {\n ZipEntry _zipEntry_2 = new ZipEntry(\"node-model\");\n zipOut.putNextEntry(_zipEntry_2);\n try {\n this.writeNodeModel(resource, bufferedOutput);\n } finally {\n bufferedOutput.flush();\n zipOut.closeEntry();\n }\n }\n }", "public static void clearallLocalDBs() {\n for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) {\n for (final String dbName : entry.getKey().listDatabaseNames()) {\n entry.getKey().getDatabase(dbName).drop();\n }\n }\n }", "public static String expandLine(CharSequence self, int tabStop) {\n String s = self.toString();\n int index;\n while ((index = s.indexOf('\\t')) != -1) {\n StringBuilder builder = new StringBuilder(s);\n int count = tabStop - index % tabStop;\n builder.deleteCharAt(index);\n for (int i = 0; i < count; i++) builder.insert(index, \" \");\n s = builder.toString();\n }\n return s;\n }", "public void fireTaskReadEvent(Task task)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.taskRead(task);\n }\n }\n }", "public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }", "public NodeList getAt(String name) {\n NodeList answer = new NodeList();\n for (Object child : this) {\n if (child instanceof Node) {\n Node childNode = (Node) child;\n Object temp = childNode.get(name);\n if (temp instanceof Collection) {\n answer.addAll((Collection) temp);\n } else {\n answer.add(temp);\n }\n }\n }\n return answer;\n }", "public static base_response disable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm disableresource = new snmpalarm();\n\t\tdisableresource.trapname = trapname;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}" ]
Purges the JSP repository.<p< @param afterPurgeAction the action to execute after purging
[ "protected void doPurge(Runnable afterPurgeAction) {\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_WILL_PURGE_JSP_REPOSITORY_0));\n }\n\n File d;\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_ONLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n\n d = new File(getJspRepository() + CmsFlexCache.REPOSITORY_OFFLINE + File.separator);\n CmsFileUtil.purgeDirectory(d);\n if (afterPurgeAction != null) {\n afterPurgeAction.run();\n }\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\n org.opencms.flex.Messages.get().getBundle().key(\n org.opencms.flex.Messages.LOG_FLEXCACHE_PURGED_JSP_REPOSITORY_0));\n }\n\n }" ]
[ "public void setPickingEnabled(boolean enabled) {\n if (enabled != getPickingEnabled()) {\n if (enabled) {\n attachComponent(new GVRSphereCollider(getGVRContext()));\n } else {\n detachComponent(GVRCollider.getComponentType());\n }\n }\n }", "public void retrieveCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, false);\r\n }", "@Override\n protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) {\n return new StatisticsMatrix(numRows,numCols);\n }", "public static authenticationvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_auditnslogpolicy_binding obj = new authenticationvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_auditnslogpolicy_binding response[] = (authenticationvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public ImageSource apply(ImageSource input) {\n int w = input.getWidth();\n int h = input.getHeight();\n\n MatrixSource output = new MatrixSource(input);\n\n Vector3 n = new Vector3(0, 0, 1);\n\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n\n if (x < border || x == w - border || y < border || y == h - border) {\n output.setRGB(x, y, VectorHelper.Z_NORMAL);\n continue;\n }\n\n float s0 = input.getR(x - 1, y + 1);\n float s1 = input.getR(x, y + 1);\n float s2 = input.getR(x + 1, y + 1);\n float s3 = input.getR(x - 1, y);\n float s5 = input.getR(x + 1, y);\n float s6 = input.getR(x - 1, y - 1);\n float s7 = input.getR(x, y - 1);\n float s8 = input.getR(x + 1, y - 1);\n\n float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);\n float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);\n\n n.set(nx, ny, scale);\n n.nor();\n\n int rgb = VectorHelper.vectorToColor(n);\n output.setRGB(x, y, rgb);\n }\n }\n\n return new MatrixSource(output);\n }", "synchronized long storeUserProfile(String id, JSONObject obj) {\n\n if (id == null) return DB_UPDATE_ERROR;\n\n if (!this.belowMemThreshold()) {\n getConfigLogger().verbose(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = Table.USER_PROFILES.getName();\n\n long ret = DB_UPDATE_ERROR;\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(\"_id\", id);\n ret = db.insertWithOnConflict(tableName, null, cv, SQLiteDatabase.CONFLICT_REPLACE);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n return ret;\n }", "public Collection<Method> getAllMethods(String name, int paramCount) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n for (Method method : map.values()) {\n if (method.getParameterTypes().length == paramCount) {\n methods.add(method);\n }\n }\n }\n return methods;\n }", "public void start(GVRAccessibilitySpeechListener speechListener) {\n mTts.setSpeechListener(speechListener);\n mTts.getSpeechRecognizer().startListening(mTts.getSpeechRecognizerIntent());\n }", "public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) {\n ZkGroupDirs dirs = new ZkGroupDirs(group);\n List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir);\n //\n Map<String, List<String>> consumersPerTopicMap = new HashMap<String, List<String>>();\n for (String consumer : consumers) {\n TopicCount topicCount = getTopicCount(zkClient, group, consumer);\n for (Map.Entry<String, Set<String>> e : topicCount.getConsumerThreadIdsPerTopic().entrySet()) {\n final String topic = e.getKey();\n for (String consumerThreadId : e.getValue()) {\n List<String> list = consumersPerTopicMap.get(topic);\n if (list == null) {\n list = new ArrayList<String>();\n consumersPerTopicMap.put(topic, list);\n }\n //\n list.add(consumerThreadId);\n }\n }\n }\n //\n for (Map.Entry<String, List<String>> e : consumersPerTopicMap.entrySet()) {\n Collections.sort(e.getValue());\n }\n return consumersPerTopicMap;\n }" ]
Finds to a given point p the point on the spline with minimum distance. @param p Point where the nearest distance is searched for @param nPointsPerSegment Number of interpolation points between two support points @return Point spline which has the minimum distance to p
[ "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}" ]
[ "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 }", "protected String getExecutableJar() throws IOException {\n Manifest manifest = new Manifest();\n manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, \"1.0\");\n manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN);\n manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, getClasspath());\n\n Path jar = createTempDirectory(\"exec\").resolve(\"generate.jar\");\n try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {\n output.putNextEntry(new JarEntry(\"allure.properties\"));\n Path allureConfig = PROPERTIES.getAllureConfig();\n if (Files.exists(allureConfig)) {\n byte[] bytes = Files.readAllBytes(allureConfig);\n output.write(bytes);\n }\n output.closeEntry();\n }\n\n return jar.toAbsolutePath().toString();\n }", "public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static String read(final File file) throws IOException {\n final StringBuilder sb = new StringBuilder();\n\n try (\n final FileReader fr = new FileReader(file);\n final BufferedReader br = new BufferedReader(fr);\n ) {\n\n String sCurrentLine;\n\n while ((sCurrentLine = br.readLine()) != null) {\n sb.append(sCurrentLine);\n }\n }\n\n return sb.toString();\n }", "public void startScenario( Class<?> testClass, Method method, List<NamedArgument> arguments ) {\n listener.scenarioStarted( testClass, method, arguments );\n\n if( method.isAnnotationPresent( Pending.class ) ) {\n Pending annotation = method.getAnnotation( Pending.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n } else if( method.isAnnotationPresent( NotImplementedYet.class ) ) {\n NotImplementedYet annotation = method.getAnnotation( NotImplementedYet.class );\n\n if( annotation.failIfPass() ) {\n failIfPass();\n } else if( !annotation.executeSteps() ) {\n methodInterceptor.disableMethodExecution();\n executeLifeCycleMethods = false;\n }\n suppressExceptions = true;\n }\n\n }", "private static void computeBadByteSkipArray(byte[] pattern, int[] badByteArray) {\n for (int a = 0; a < ALPHABET_SIZE; a++) {\n badByteArray[a] = pattern.length;\n }\n\n for (int j = 0; j < pattern.length - 1; j++) {\n badByteArray[pattern[j] - Byte.MIN_VALUE] = pattern.length - j - 1;\n }\n }", "private boolean isSingleMultiDay() {\n\n long duration = getEnd().getTime() - getStart().getTime();\n if (duration > I_CmsSerialDateValue.DAY_IN_MILLIS) {\n return true;\n }\n if (isWholeDay() && (duration <= I_CmsSerialDateValue.DAY_IN_MILLIS)) {\n return false;\n }\n Calendar start = new GregorianCalendar();\n start.setTime(getStart());\n Calendar end = new GregorianCalendar();\n end.setTime(getEnd());\n if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)) {\n return false;\n }\n return true;\n\n }", "public T withAlias(String text, String languageCode) {\n\t\twithAlias(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}", "private void readProjectProperties(Settings phoenixSettings, Storepoint storepoint)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(phoenixSettings.getTitle());\n mpxjProperties.setDefaultDurationUnits(phoenixSettings.getBaseunit());\n mpxjProperties.setStatusDate(storepoint.getDataDate());\n }" ]
The ID field contains the identifier number that Microsoft Project automatically assigns to each task as you add it to the project. The ID indicates the position of a task with respect to the other tasks. @param val ID
[ "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n\n if (previous != null)\n {\n parent.getTasks().unmapID(previous);\n }\n\n parent.getTasks().mapID(val, this);\n\n set(TaskField.ID, val);\n }" ]
[ "public Photoset getInfo(String photosetId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\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 photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photosetElement.getAttribute(\"owner\"));\r\n photoset.setOwner(owner);\r\n\r\n Photo primaryPhoto = new Photo();\r\n primaryPhoto.setId(photosetElement.getAttribute(\"primary\"));\r\n primaryPhoto.setSecret(photosetElement.getAttribute(\"secret\")); // TODO verify that this is the secret for the photo\r\n primaryPhoto.setServer(photosetElement.getAttribute(\"server\")); // TODO verify that this is the server for the photo\r\n primaryPhoto.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n // TODO remove secret/server/farm from photoset?\r\n // It's rather related to the primaryPhoto, then to the photoset itself.\r\n photoset.setSecret(photosetElement.getAttribute(\"secret\"));\r\n photoset.setServer(photosetElement.getAttribute(\"server\"));\r\n photoset.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPhotoCount(photosetElement.getAttribute(\"count_photos\"));\r\n photoset.setVideoCount(Integer.parseInt(photosetElement.getAttribute(\"count_videos\")));\r\n photoset.setViewCount(Integer.parseInt(photosetElement.getAttribute(\"count_views\")));\r\n photoset.setCommentCount(Integer.parseInt(photosetElement.getAttribute(\"count_comments\")));\r\n photoset.setDateCreate(photosetElement.getAttribute(\"date_create\"));\r\n photoset.setDateUpdate(photosetElement.getAttribute(\"date_update\"));\r\n\r\n photoset.setIsCanComment(\"1\".equals(photosetElement.getAttribute(\"can_comment\")));\r\n\r\n photoset.setTitle(XMLUtilities.getChildValue(photosetElement, \"title\"));\r\n photoset.setDescription(XMLUtilities.getChildValue(photosetElement, \"description\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n return photoset;\r\n }", "private void fillWeekPanel() {\r\n\r\n addCheckBox(WeekOfMonth.FIRST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_1_0);\r\n addCheckBox(WeekOfMonth.SECOND.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_2_0);\r\n addCheckBox(WeekOfMonth.THIRD.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_3_0);\r\n addCheckBox(WeekOfMonth.FOURTH.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_4_0);\r\n addCheckBox(WeekOfMonth.LAST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_5_0);\r\n }", "public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }", "public void removeCustomOverride(int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"custom_response\", \"\", getProfileIdFromPathID(path_id), client_uuid, path_id);\n }", "public static Pair<String, String> stringIntern(Pair<String, String> p) {\r\n return new MutableInternedPair(p);\r\n }", "private void addUserDefinedField(FieldTypeClass fieldType, UserFieldDataType dataType, String name)\n {\n try\n {\n switch (fieldType)\n {\n case TASK:\n TaskField taskField;\n\n do\n {\n taskField = m_taskUdfCounters.nextField(TaskField.class, dataType);\n }\n while (m_taskFields.containsKey(taskField) || m_wbsFields.containsKey(taskField));\n\n m_project.getCustomFields().getCustomField(taskField).setAlias(name);\n\n break;\n case RESOURCE:\n ResourceField resourceField;\n\n do\n {\n resourceField = m_resourceUdfCounters.nextField(ResourceField.class, dataType);\n }\n while (m_resourceFields.containsKey(resourceField));\n\n m_project.getCustomFields().getCustomField(resourceField).setAlias(name);\n\n break;\n case ASSIGNMENT:\n AssignmentField assignmentField;\n\n do\n {\n assignmentField = m_assignmentUdfCounters.nextField(AssignmentField.class, dataType);\n }\n while (m_assignmentFields.containsKey(assignmentField));\n\n m_project.getCustomFields().getCustomField(assignmentField).setAlias(name);\n\n break;\n default:\n break;\n }\n }\n\n catch (Exception ex)\n {\n //\n // SF#227: If we get an exception thrown here... it's likely that\n // we've run out of user defined fields, for example\n // there are only 30 TEXT fields. We'll ignore this: the user\n // defined field won't be mapped to an alias, so we'll\n // ignore it when we read in the values.\n //\n }\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 Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }" ]
This can be called to adjust the size of the dialog glass. It is implemented using JSNI to bypass the "private" keyword on the glassResizer.
[ "public void adjustGlassSize() {\n if (isGlassEnabled()) {\n ResizeHandler handler = getGlassResizer();\n if (handler != null) handler.onResize(null);\n }\n }" ]
[ "private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)\n\t throws IOException {\n Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {\n public int compare(ClassDoc cd1, ClassDoc cd2) {\n return cd1.name().compareTo(cd2.name());\n }\n });\n for (ClassDoc classDoc : root.classes())\n classDocs.add(classDoc);\n\n\tContextView view = null;\n\tfor (ClassDoc classDoc : classDocs) {\n\t try {\n\t\tif(view == null)\n\t\t view = new ContextView(outputFolder, classDoc, root, opt);\n\t\telse\n\t\t view.setContextCenter(classDoc);\n\t\tUmlGraph.buildGraph(root, view, classDoc);\n\t\trunGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);\n\t\talterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),\n\t\t\tclassDoc.name() + \".html\", Pattern.compile(\".*(Class|Interface|Enum) \" + classDoc.name() + \".*\") , root);\n\t } catch (Exception e) {\n\t\tthrow new RuntimeException(\"Error generating \" + classDoc.name(), e);\n\t }\n\t}\n }", "private void processCustomValueLists() throws IOException\n {\n CustomFieldValueReader9 reader = new CustomFieldValueReader9(m_projectDir, m_file.getProjectProperties(), m_projectProps, m_file.getCustomFields());\n reader.process();\n }", "public static base_response disable(nitro_service client, String id) throws Exception {\n\t\tInterface disableresource = new Interface();\n\t\tdisableresource.id = id;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "public JsonNode wbSetClaim(String statement,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statement,\n\t\t\t\t\"Statement parameter cannot be null when adding or changing a statement\");\n\t\t\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", statement);\n\t\t\n\t\treturn performAPIAction(\"wbsetclaim\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}", "public void shutdown() {\n\n for (Entry<HttpClientType, AsyncHttpClient> entry : map.entrySet()) {\n AsyncHttpClient client = entry.getValue();\n if (client != null)\n client.close();\n }\n\n }", "public boolean setCurrentConfiguration(CmsGitConfiguration configuration) {\n\n if ((null != configuration) && configuration.isValid()) {\n m_currentConfiguration = configuration;\n return true;\n }\n return false;\n }", "public void setBREE(String bree) {\n\t\tString old = mainAttributes.get(BUNDLE_REQUIREDEXECUTIONENVIRONMENT);\n\t\tif (!bree.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_REQUIREDEXECUTIONENVIRONMENT, bree);\n\t\t\tthis.modified = true;\n\t\t\tthis.bree = bree;\n\t\t}\n\t}", "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}", "protected void prepForWrite(SelectionKey selectionKey) {\n if(logger.isTraceEnabled())\n traceInputBufferState(\"About to clear read buffer\");\n\n if(requestHandlerFactory.shareReadWriteBuffer() == false) {\n inputStream.clear();\n }\n\n if(logger.isTraceEnabled())\n traceInputBufferState(\"Cleared read buffer\");\n\n outputStream.getBuffer().flip();\n selectionKey.interestOps(SelectionKey.OP_WRITE);\n }" ]
Draws the specified image with the first rectangle's bounds, clipping with the second one. @param img image @param rect rectangle @param clipRect clipping bounds @param opacity opacity of the image (1 = opaque, 0= transparent)
[ "public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {\n\t\ttry {\n\t\t\ttemplate.saveState();\n\t\t\t// opacity\n\t\t\tPdfGState state = new PdfGState();\n\t\t\tstate.setFillOpacity(opacity);\n\t\t\tstate.setBlendMode(PdfGState.BM_NORMAL);\n\t\t\ttemplate.setGState(state);\n\t\t\t// clipping code\n\t\t\tif (clipRect != null) {\n\t\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),\n\t\t\t\t\t\tclipRect.getHeight());\n\t\t\t\ttemplate.clip();\n\t\t\t\ttemplate.newPath();\n\t\t\t}\n\t\t\ttemplate.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(), origY\n\t\t\t\t\t+ rect.getBottom());\n\t\t} catch (DocumentException e) {\n\t\t\tlog.warn(\"could not draw image\", e);\n\t\t} finally {\n\t\t\ttemplate.restoreState();\n\t\t}\n\t}" ]
[ "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 }", "protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }", "public static double J(int n, double x) {\r\n int j, m;\r\n double ax, bj, bjm, bjp, sum, tox, ans;\r\n boolean jsum;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n if (n == 0) return J0(x);\r\n if (n == 1) return J(x);\r\n\r\n ax = Math.abs(x);\r\n if (ax == 0.0) return 0.0;\r\n else if (ax > (double) n) {\r\n tox = 2.0 / ax;\r\n bjm = J0(ax);\r\n bj = J(ax);\r\n for (j = 1; j < n; j++) {\r\n bjp = j * tox * bj - bjm;\r\n bjm = bj;\r\n bj = bjp;\r\n }\r\n ans = bj;\r\n } else {\r\n tox = 2.0 / ax;\r\n m = 2 * ((n + (int) Math.sqrt(ACC * n)) / 2);\r\n jsum = false;\r\n bjp = ans = sum = 0.0;\r\n bj = 1.0;\r\n for (j = m; j > 0; j--) {\r\n bjm = j * tox * bj - bjp;\r\n bjp = bj;\r\n bj = bjm;\r\n if (Math.abs(bj) > BIGNO) {\r\n bj *= BIGNI;\r\n bjp *= BIGNI;\r\n ans *= BIGNI;\r\n sum *= BIGNI;\r\n }\r\n if (jsum) sum += bj;\r\n jsum = !jsum;\r\n if (j == n) ans = bjp;\r\n }\r\n sum = 2.0 * sum - bj;\r\n ans /= sum;\r\n }\r\n\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }", "public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }", "public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }", "void awaitStabilityUninterruptibly(long timeout, TimeUnit timeUnit) throws TimeoutException {\n boolean interrupted = false;\n try {\n long toWait = timeUnit.toMillis(timeout);\n long msTimeout = System.currentTimeMillis() + toWait;\n while (true) {\n if (interrupted) {\n toWait = msTimeout - System.currentTimeMillis();\n }\n try {\n if (toWait <= 0 || !monitor.awaitStability(toWait, TimeUnit.MILLISECONDS, failed, problems)) {\n throw new TimeoutException();\n }\n break;\n } catch (InterruptedException e) {\n interrupted = true;\n }\n }\n } finally {\n if (interrupted) {\n Thread.currentThread().interrupt();\n }\n }\n }", "private void createStringMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int position) throws IOException {\n // System.out.println(\"createStringMappings string \");\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n if (stringValues.length > 0 && !stringValues[0].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"t\", filterString(stringValues[0].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n if (stringValues.length > 1 && !stringValues[1].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"lemma\", filterString(stringValues[1].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n }", "public void put(String key, String value) {\n synchronized (this.cache) {\n this.cache.put(key, value);\n }\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 }" ]
Returns true if "file" is a subfile or subdirectory of "dir". For example with the directory /path/to/a, the following return values would occur: /path/to/a/foo.txt - true /path/to/a/bar/zoo/boo/team.txt - true /path/to/b/foo.txt - false
[ "public static boolean isInSubDirectory(File dir, File file)\n {\n if (file == null)\n return false;\n\n if (file.equals(dir))\n return true;\n\n return isInSubDirectory(dir, file.getParentFile());\n }" ]
[ "public synchronized void cleanWaitTaskQueue() {\n\n for (ParallelTask task : waitQ) {\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n\n }\n\n waitQ.clear();\n }", "public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}", "@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}", "public void print( String equation ) {\n // first assume it's just a variable\n Variable v = lookupVariable(equation);\n if( v == null ) {\n Sequence sequence = compile(equation,false,false);\n sequence.perform();\n v = sequence.output;\n }\n\n if( v instanceof VariableMatrix ) {\n ((VariableMatrix)v).matrix.print();\n } else if(v instanceof VariableScalar ) {\n System.out.println(\"Scalar = \"+((VariableScalar)v).getDouble() );\n } else {\n System.out.println(\"Add support for \"+v.getClass().getSimpleName());\n }\n }", "private long getEndTime(ISuite suite, IInvokedMethod method)\n {\n // Find the latest end time for all tests in the suite.\n for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())\n {\n ITestContext testContext = entry.getValue().getTestContext();\n for (ITestNGMethod m : testContext.getAllTestMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n // If we can't find a matching test method it must be a configuration method.\n for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods())\n {\n if (method == m)\n {\n return testContext.getEndDate().getTime();\n }\n }\n }\n throw new IllegalStateException(\"Could not find matching end time.\");\n }", "private ClassMatcher buildMatcher(String tagText) {\n\t// check there are at least @match <type> and a parameter\n\tString[] strings = StringUtil.tokenize(tagText);\n\tif (strings.length < 2) {\n\t System.err.println(\"Skipping uncomplete @match tag, type missing: \" + tagText + \" in view \" + viewDoc);\n\t return null;\n\t}\n\t\n\ttry {\n\t if (strings[0].equals(\"class\")) {\n\t\treturn new PatternMatcher(Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"context\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"outgoingContext\")) {\n\t\treturn new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), \n\t\t\tfalse);\n\t } else if (strings[0].equals(\"interface\")) {\n\t\treturn new InterfaceMatcher(root, Pattern.compile(strings[1]));\n\t } else if (strings[0].equals(\"subclass\")) {\n\t\treturn new SubclassMatcher(root, Pattern.compile(strings[1]));\n\t } else {\n\t\tSystem.err.println(\"Skipping @match tag, unknown match type, in view \" + viewDoc);\n\t }\n\t} catch (PatternSyntaxException pse) {\n\t System.err.println(\"Skipping @match tag due to invalid regular expression '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t} catch (Exception e) {\n\t System.err.println(\"Skipping @match tag due to an internal error '\" + tagText\n\t\t + \"'\" + \" in view \" + viewDoc);\n\t e.printStackTrace();\n\t}\n\treturn null;\n }", "private void writeDayTypes(Calendars calendars)\n {\n DayTypes dayTypes = m_factory.createDayTypes();\n calendars.setDayTypes(dayTypes);\n List<DayType> typeList = dayTypes.getDayType();\n\n DayType dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"0\");\n dayType.setName(\"Working\");\n dayType.setDescription(\"A default working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"1\");\n dayType.setName(\"Nonworking\");\n dayType.setDescription(\"A default non working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"2\");\n dayType.setName(\"Use base\");\n dayType.setDescription(\"Use day from base calendar\");\n }", "public static cmpparameter get(nitro_service service) throws Exception{\n\t\tcmpparameter obj = new cmpparameter();\n\t\tcmpparameter[] response = (cmpparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "@Beta\n public MSICredentials withIdentityId(String identityId) {\n this.identityId = identityId;\n this.clientId = null;\n this.objectId = null;\n return this;\n }" ]
Converts a time in milliseconds to the appropriate x coordinate for drawing something at that time. @param milliseconds the time at which something should be drawn @return the component x coordinate at which it should be drawn
[ "public int millisecondsToX(long milliseconds) {\n if (autoScroll.get()) {\n int playHead = (getWidth() / 2) + 2;\n long offset = milliseconds - getFurthestPlaybackPosition();\n return playHead + (Util.timeToHalfFrame(offset) / scale.get());\n }\n return Util.timeToHalfFrame(milliseconds) / scale.get();\n }" ]
[ "private void ensureIndexIsUnlocked(String dataDir) {\n\n Collection<File> lockFiles = new ArrayList<File>(2);\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"index\") + \"write.lock\"));\n lockFiles.add(\n new File(\n CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + \"spellcheck\")\n + \"write.lock\"));\n for (File lockFile : lockFiles) {\n if (lockFile.exists()) {\n lockFile.delete();\n LOG.warn(\n \"Forcely unlocking index with data dir \\\"\"\n + dataDir\n + \"\\\" by removing file \\\"\"\n + lockFile.getAbsolutePath()\n + \"\\\".\");\n }\n }\n }", "public static <X> ServiceTypeLoader<X> load(Class<X> serviceType) {\n return load(serviceType, Thread.currentThread().getContextClassLoader());\n }", "public OJBLock atomicGetOrCreateLock(Object resourceId, Object isolationId)\r\n {\r\n synchronized(globalLocks)\r\n {\r\n MultiLevelLock lock = getLock(resourceId);\r\n if(lock == null)\r\n {\r\n lock = createLock(resourceId, isolationId);\r\n }\r\n return (OJBLock) lock;\r\n }\r\n }", "public Duration getFinishVariance()\n {\n Duration variance = (Duration) getCachedValue(AssignmentField.FINISH_VARIANCE);\n if (variance == null)\n {\n TimeUnit format = getParentFile().getProjectProperties().getDefaultDurationUnits();\n variance = DateHelper.getVariance(getTask(), getBaselineFinish(), getFinish(), format);\n set(AssignmentField.FINISH_VARIANCE, variance);\n }\n return (variance);\n }", "public static tmglobal_tmsessionpolicy_binding[] get(nitro_service service) throws Exception{\n\t\ttmglobal_tmsessionpolicy_binding obj = new tmglobal_tmsessionpolicy_binding();\n\t\ttmglobal_tmsessionpolicy_binding response[] = (tmglobal_tmsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private boolean compareBytes(byte[] lhs, byte[] rhs, int rhsOffset)\n {\n boolean result = true;\n for (int loop = 0; loop < lhs.length; loop++)\n {\n if (lhs[loop] != rhs[rhsOffset + loop])\n {\n result = false;\n break;\n }\n }\n return (result);\n }", "public static boolean isTemplatePath(String string) {\n int sz = string.length();\n if (sz == 0) {\n return true;\n }\n for (int i = 0; i < sz; ++i) {\n char c = string.charAt(i);\n switch (c) {\n case ' ':\n case '\\t':\n case '\\b':\n case '<':\n case '>':\n case '(':\n case ')':\n case '[':\n case ']':\n case '{':\n case '}':\n case '!':\n case '@':\n case '#':\n case '*':\n case '?':\n case '%':\n case '|':\n case ',':\n case ':':\n case ';':\n case '^':\n case '&':\n return false;\n }\n }\n return true;\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 }", "private void wrongUsage() {\n\n String usage = \"Usage: java -cp $PATH_TO_OPENCMS_JAR org.opencms.rmi.CmsRemoteShellClient\\n\"\n + \" -script=[path to script] (optional) \\n\"\n + \" -registryPort=[port of RMI registry] (optional, default is \"\n + CmsRemoteShellConstants.DEFAULT_PORT\n + \")\\n\"\n + \" -additional=[additional commands class name] (optional)\";\n System.out.println(usage);\n System.exit(1);\n }" ]
Checks that given directory if readable & writable and prints a warning if the check fails. Warning is only printed once and is not repeated until the condition is fixed and broken again. @param directory deployment directory @return does given directory exist and is readable and writable?
[ "private boolean checkDeploymentDir(File directory) {\n if (!directory.exists()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNonexistent(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.isDirectory()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.isNotADirectory(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canRead()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotReadable(deploymentDir.getAbsolutePath());\n }\n }\n else if (!directory.canWrite()) {\n if (deploymentDirAccessible) {\n deploymentDirAccessible = false;\n ROOT_LOGGER.directoryIsNotWritable(deploymentDir.getAbsolutePath());\n }\n } else {\n deploymentDirAccessible = true;\n }\n\n return deploymentDirAccessible;\n }" ]
[ "public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}", "private List<Bucket> lookup(Record record) {\n List<Bucket> buckets = new ArrayList();\n for (Property p : config.getLookupProperties()) {\n String propname = p.getName();\n Collection<String> values = record.getValues(propname);\n if (values == null)\n continue;\n\n for (String value : values) {\n String[] tokens = StringUtils.split(value);\n for (int ix = 0; ix < tokens.length; ix++) {\n Bucket b = store.lookupToken(propname, tokens[ix]);\n if (b == null || b.records == null)\n continue;\n long[] ids = b.records;\n if (DEBUG)\n System.out.println(propname + \", \" + tokens[ix] + \": \" + b.nextfree + \" (\" + b.getScore() + \")\");\n buckets.add(b);\n }\n }\n }\n\n return buckets;\n }", "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}", "public static String read(final File file) throws IOException {\n final StringBuilder sb = new StringBuilder();\n\n try (\n final FileReader fr = new FileReader(file);\n final BufferedReader br = new BufferedReader(fr);\n ) {\n\n String sCurrentLine;\n\n while ((sCurrentLine = br.readLine()) != null) {\n sb.append(sCurrentLine);\n }\n }\n\n return sb.toString();\n }", "public static String formatDateRange(Context context, ReadablePartial start, ReadablePartial end, int flags) {\n return formatDateRange(context, toMillis(start), toMillis(end), flags);\n }", "@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }", "public void setTargetBytecode(String version) {\n if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) {\n this.targetBytecode = version;\n }\n }", "private void removeAllBroadcasts(Set<String> sessionIds) {\n\n if (sessionIds == null) {\n for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos()) {\n OpenCms.getSessionManager().getBroadcastQueue(info.getSessionId().getStringValue()).clear();\n }\n return;\n }\n for (String sessionId : sessionIds) {\n OpenCms.getSessionManager().getBroadcastQueue(sessionId).clear();\n }\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 }" ]
Informs this sequence model that the value of the element at position pos has changed. This allows this sequence model to update its internal model if desired.
[ "public void updateSequenceElement(int[] sequence, int pos, int oldVal) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].updateSequenceElement(sequence, pos, oldVal);\r\n return; \r\n }\r\n model1.updateSequenceElement(sequence, pos, 0);\r\n model2.updateSequenceElement(sequence, pos, 0);\r\n }" ]
[ "public static boolean uniform(Color color, Pixel[] pixels) {\n return Arrays.stream(pixels).allMatch(p -> p.toInt() == color.toRGB().toInt());\n }", "public void addRequiredBundles(Set<String> requiredBundles) {\n\t\taddRequiredBundles(requiredBundles.toArray(new String[requiredBundles.size()]));\n\t}", "public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }", "public void enableUniformSize(final boolean enable) {\n if (mUniformSize != enable) {\n mUniformSize = enable;\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }", "protected void refresh()\r\n {\r\n if (log.isDebugEnabled())\r\n log.debug(\"Refresh this transaction for reuse: \" + this);\r\n try\r\n {\r\n // we reuse ObjectEnvelopeTable instance\r\n objectEnvelopeTable.refresh();\r\n }\r\n catch (Exception e)\r\n {\r\n if (log.isDebugEnabled())\r\n {\r\n log.debug(\"error closing object envelope table : \" + e.getMessage());\r\n e.printStackTrace();\r\n }\r\n }\r\n cleanupBroker();\r\n // clear the temporary used named roots map\r\n // we should do that, because same tx instance\r\n // could be used several times\r\n broker = null;\r\n clearRegistrationList();\r\n unmaterializedLocks.clear();\r\n txStatus = Status.STATUS_NO_TRANSACTION;\r\n }", "@Override\r\n public V get(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V deltaResult = deltaMap.get(key);\r\n if (deltaResult == null) {\r\n return originalMap.get(key);\r\n }\r\n if (deltaResult == nullValue) {\r\n return null;\r\n }\r\n if (deltaResult == removedValue) {\r\n return null;\r\n }\r\n return deltaResult;\r\n }", "private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }", "public static vpnvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationradiuspolicy_binding obj = new vpnvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationradiuspolicy_binding response[] = (vpnvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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 }" ]
Adds a command class to the list of supported command classes by this node. Does nothing if command class is already added. @param commandClass the command class instance to add.
[ "public void addCommandClass(ZWaveCommandClass commandClass)\n\t{\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\n\t\t\n\t\tif (!supportedCommandClasses.containsKey(key)) {\n\t\t\tsupportedCommandClasses.put(key, commandClass);\n\t\t\t\n\t\t\tif (commandClass instanceof ZWaveEventListener)\n\t\t\t\tthis.controller.addEventListener((ZWaveEventListener)commandClass);\n\t\t\t\n\t\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t\t}\n\t}" ]
[ "private void setPropertyFilters(String filters) {\n\t\tthis.filterProperties = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tfor (String pid : filters.split(\",\")) {\n\t\t\t\tthis.filterProperties.add(Datamodel\n\t\t\t\t\t\t.makeWikidataPropertyIdValue(pid));\n\t\t\t}\n\t\t}\n\t}", "public static SortedMap<String, Object> asMap() {\n SortedMap<String, Object> metrics = Maps.newTreeMap();\n METRICS_SOURCE.applyMetrics(metrics);\n return metrics;\n }", "private double sumSquaredDiffs()\n { \n double mean = getArithmeticMean();\n double squaredDiffs = 0;\n for (int i = 0; i < getSize(); i++)\n {\n double diff = mean - dataSet[i];\n squaredDiffs += (diff * diff);\n }\n return squaredDiffs;\n }", "public static base_response enable(nitro_service client, String acl6name) throws Exception {\n\t\tnsacl6 enableresource = new nsacl6();\n\t\tenableresource.acl6name = acl6name;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}", "@SuppressWarnings({\"unchecked\", \"WeakerAccess\"})\n public static <T> List<T> readListAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n // todo: fix this when this method signature is corrected\n final List<T> value = (List<T>) reader.getListAttributeValue(0, type);\n requireNoContent(reader);\n return value;\n }", "public byte[] toBytes(T object) {\n try {\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n ObjectOutputStream out = new ObjectOutputStream(stream);\n out.writeObject(object);\n return stream.toByteArray();\n } catch(IOException e) {\n throw new SerializationException(e);\n }\n }", "public static AbstractReportGenerator generateHtml5Report() {\n AbstractReportGenerator report;\n try {\n Class<?> aClass = new ReportGenerator().getClass().getClassLoader()\n .loadClass( \"com.tngtech.jgiven.report.html5.Html5ReportGenerator\" );\n report = (AbstractReportGenerator) aClass.newInstance();\n } catch( ClassNotFoundException e ) {\n throw new JGivenInstallationException( \"The JGiven HTML5 Report Generator seems not to be on the classpath.\\n\"\n + \"Ensure that you have a dependency to jgiven-html5-report.\" );\n } catch( Exception e ) {\n throw new JGivenInternalDefectException( \"The HTML5 Report Generator could not be instantiated.\", e );\n }\n return report;\n }", "public static systemuser[] get(nitro_service service) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tsystemuser[] response = (systemuser[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private Number calculateUnitsPercentComplete(Row row)\n {\n double result = 0;\n\n double actualWorkQuantity = NumberHelper.getDouble(row.getDouble(\"act_work_qty\"));\n double actualEquipmentQuantity = NumberHelper.getDouble(row.getDouble(\"act_equip_qty\"));\n double numerator = actualWorkQuantity + actualEquipmentQuantity;\n\n if (numerator != 0)\n {\n double remainingWorkQuantity = NumberHelper.getDouble(row.getDouble(\"remain_work_qty\"));\n double remainingEquipmentQuantity = NumberHelper.getDouble(row.getDouble(\"remain_equip_qty\"));\n double denominator = remainingWorkQuantity + actualWorkQuantity + remainingEquipmentQuantity + actualEquipmentQuantity;\n result = denominator == 0 ? 0 : ((numerator * 100) / denominator);\n }\n\n return NumberHelper.getDouble(result);\n }" ]
Use this API to fetch all the configstatus resources that are configured on netscaler.
[ "public static configstatus[] get(nitro_service service) throws Exception{\n\t\tconfigstatus obj = new configstatus();\n\t\tconfigstatus[] response = (configstatus[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "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 static lbvserver_servicegroupmember_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_servicegroupmember_binding obj = new lbvserver_servicegroupmember_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_servicegroupmember_binding response[] = (lbvserver_servicegroupmember_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // now checking constraints\r\n FieldDescriptorConstraints fieldConstraints = new FieldDescriptorConstraints();\r\n ReferenceDescriptorConstraints refConstraints = new ReferenceDescriptorConstraints();\r\n CollectionDescriptorConstraints collConstraints = new CollectionDescriptorConstraints();\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldConstraints.check((FieldDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getReferences(); it.hasNext();)\r\n {\r\n refConstraints.check((ReferenceDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getCollections(); it.hasNext();)\r\n {\r\n collConstraints.check((CollectionDescriptorDef)it.next(), checkLevel);\r\n }\r\n new ClassDescriptorConstraints().check(this, checkLevel);\r\n }", "public long addAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.sadd(getKey(), members);\n }\n });\n }", "public GVRAnimator start(int animIndex)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n start(anim);\n return anim;\n }", "public Jar setListAttribute(String name, Collection<?> values) {\n return setAttribute(name, join(values));\n }", "@Override\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }", "List<CmsResource> getBundleResources() {\n\n List<CmsResource> resources = new ArrayList<>(m_bundleFiles.values());\n if (m_desc != null) {\n resources.add(m_desc);\n }\n return resources;\n\n }", "public void updateFrontFacingRotation(float rotation) {\n if (!Float.isNaN(rotation) && !equal(rotation, frontFacingRotation)) {\n final float oldRotation = frontFacingRotation;\n frontFacingRotation = rotation % 360;\n for (OnFrontRotationChangedListener listener : mOnFrontRotationChangedListeners) {\n try {\n listener.onFrontRotationChanged(this, frontFacingRotation, oldRotation);\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(TAG, e, \"updateFrontFacingRotation()\");\n }\n }\n }\n }" ]
Clear any current allowed job types and use the given set. @param jobTypes the job types to allow
[ "public void setJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n checkJobTypes(jobTypes);\n this.jobTypes.clear();\n this.jobTypes.putAll(jobTypes);\n }" ]
[ "public static void startNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).start();\n\t}", "public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }", "public static Operation createDeployOperation(final DeploymentDescription deployment) {\n Assert.checkNotNullParam(\"deployment\", deployment);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n addDeployOperationStep(builder, deployment);\n return builder.build();\n }", "public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);\n } catch (IncompatibleTestMatrixException e) {\n LOGGER.info(String.format(\"Unable to load test matrix for %s\", testName), e);\n resultBuilder.recordError(testName, e);\n }\n }\n return resultBuilder.build();\n }", "public E get(int i) {\r\n if (i < 0 || i >= objects.size())\r\n throw new ArrayIndexOutOfBoundsException(\"Index \" + i + \r\n \" outside the bounds [0,\" + \r\n size() + \")\");\r\n return objects.get(i);\r\n }", "private Query getReportQueryByCriteriaCount(ReportQueryByCriteria aQuery)\r\n {\r\n ReportQueryByCriteria countQuery = (ReportQueryByCriteria) getQueryByCriteriaCount(aQuery);\r\n\r\n // BRJ: keep the original columns to build the Join\r\n countQuery.setJoinAttributes(aQuery.getAttributes());\r\n\r\n // BRJ: we have to preserve groupby information\r\n Iterator iter = aQuery.getGroupBy().iterator();\r\n while(iter.hasNext())\r\n {\r\n countQuery.addGroupBy((FieldHelper) iter.next());\r\n }\r\n\r\n return countQuery;\r\n }", "public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public final Object copy(final Object toCopy, PersistenceBroker broker)\r\n\t{\r\n\t\treturn clone(toCopy, IdentityMapFactory.getIdentityMap(), new HashMap());\r\n\t}", "public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) {\n Set<Pattern> set = new HashSet<>();\n for (String wildcardExpr : runtimeNames) {\n Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr);\n set.add(pattern);\n }\n return listDeploymentNames(deploymentRootResource, set);\n }" ]
Use this API to fetch all the Interface resources that are configured on netscaler.
[ "public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }", "public void flush() throws IOException {\n checkMutable();\n long startTime = System.currentTimeMillis();\n channel.force(true);\n long elapsedTime = System.currentTimeMillis() - startTime;\n LogFlushStats.recordFlushRequest(elapsedTime);\n logger.debug(\"flush time \" + elapsedTime);\n setHighWaterMark.set(getSizeInBytes());\n logger.debug(\"flush high water mark:\" + highWaterMark());\n }", "@SuppressWarnings(\"unchecked\")\n\tstatic void logToFile(String filename) {\n\t\tLogger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);\n\n\t\tFileAppender<ILoggingEvent> fileappender = new FileAppender<>();\n\t\tfileappender.setContext(rootLogger.getLoggerContext());\n\t\tfileappender.setFile(filename);\n\t\tfileappender.setName(\"FILE\");\n\n\t\tConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender(\"STDOUT\");\n\t\tfileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());\n\n\t\tfileappender.start();\n\n\t\trootLogger.addAppender(fileappender);\n\n\t\tconsole.stop();\n\t}", "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 }", "public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}", "public static DMatrixSparseCSC symmetric( int N , int nz_total ,\n double min , double max , Random rand) {\n\n // compute the number of elements in the triangle, including diagonal\n int Ntriagle = (N*N+N)/2;\n // create a list of open elements\n int open[] = new int[Ntriagle];\n for (int row = 0, index = 0; row < N; row++) {\n for (int col = row; col < N; col++, index++) {\n open[index] = row*N+col;\n }\n }\n\n // perform a random draw\n UtilEjml.shuffle(open,open.length,0,nz_total,rand);\n Arrays.sort(open,0,nz_total);\n\n // construct the matrix\n DMatrixSparseTriplet A = new DMatrixSparseTriplet(N,N,nz_total*2);\n for (int i = 0; i < nz_total; i++) {\n int index = open[i];\n int row = index/N;\n int col = index%N;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n if( row == col ) {\n A.addItem(row,col,value);\n } else {\n A.addItem(row,col,value);\n A.addItem(col,row,value);\n }\n }\n\n DMatrixSparseCSC B = new DMatrixSparseCSC(N,N,A.nz_length);\n ConvertDMatrixStruct.convert(A,B);\n\n return B;\n }", "public static <ResultT> PollingState<ResultT> createFromJSONString(String serializedPollingState) {\n ObjectMapper mapper = initMapper(new ObjectMapper());\n PollingState<ResultT> pollingState;\n try {\n pollingState = mapper.readValue(serializedPollingState, PollingState.class);\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n return pollingState;\n }", "void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {\n assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;\n\n final PatchingHistory history = context.getHistory();\n for (final PatchElement element : patch.getElements()) {\n\n final PatchElementProvider provider = element.getProvider();\n final String name = provider.getName();\n final boolean addOn = provider.isAddOn();\n\n final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);\n final String cumulativePatchID = target.getCumulativePatchID();\n if (Constants.BASE.equals(cumulativePatchID)) {\n reenableRolledBackInBase(target);\n continue;\n }\n\n boolean found = false;\n final PatchingHistory.Iterator iterator = history.iterator();\n while (iterator.hasNextCP()) {\n final PatchingHistory.Entry entry = iterator.nextCP();\n final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);\n\n if (patchId != null && patchId.equals(cumulativePatchID)) {\n final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);\n for (final PatchElement originalElement : original.getElements()) {\n if (name.equals(originalElement.getProvider().getName())\n && addOn == originalElement.getProvider().isAddOn()) {\n PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);\n }\n }\n // Record a loader to have access to the current modules\n final DirectoryStructure structure = target.getDirectoryStructure();\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);\n context.recordContentLoader(patchId, loader);\n found = true;\n break;\n }\n }\n if (!found) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);\n }\n\n reenableRolledBackInBase(target);\n }\n }", "public static base_response unset(nitro_service client, responderparam resource, String[] args) throws Exception{\n\t\tresponderparam unsetresource = new responderparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Returns the configured request parameter for the current query string, or the default parameter if the core is not specified. @return The configured request parameter for the current query string, or the default parameter if the core is not specified.
[ "private String getQueryParam() {\n\n final String param = parseOptionalStringValue(XML_ELEMENT_QUERYPARAM);\n if (param == null) {\n return DEFAULT_QUERY_PARAM;\n } else {\n return param;\n }\n }" ]
[ "public void sendFaderStartCommand(Set<Integer> deviceNumbersToStart, Set<Integer> deviceNumbersToStop) throws IOException {\n ensureRunning();\n byte[] payload = new byte[FADER_START_PAYLOAD.length];\n System.arraycopy(FADER_START_PAYLOAD, 0, payload, 0, FADER_START_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n\n for (int i = 1; i <= 4; i++) {\n if (deviceNumbersToStart.contains(i)) {\n payload[i + 4] = 0;\n }\n if (deviceNumbersToStop.contains(i)) {\n payload[i + 4] = 1;\n }\n }\n\n assembleAndSendPacket(Util.PacketType.FADER_START_COMMAND, payload, getBroadcastAddress(), BeatFinder.BEAT_PORT);\n }", "public final static String process(final String input, final Configuration configuration)\n {\n try\n {\n return process(new StringReader(input), configuration);\n }\n catch (final IOException e)\n {\n // This _can never_ happen\n return null;\n }\n }", "public static void validate(final Organization organization) {\n if(organization.getName() == null ||\n organization.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Organization name cannot be null or empty!\")\n .build());\n }\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 static csvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_appflowpolicy_binding obj = new csvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_appflowpolicy_binding response[] = (csvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }", "static ChangeEvent<BsonDocument> changeEventForLocalDelete(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.DELETE,\n null,\n namespace,\n new BsonDocument(\"_id\", documentId),\n null,\n writePending);\n }", "public static Stack getStack() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n stack = new Stack(interceptionContexts);\n interceptionContexts.set(stack);\n }\n return stack;\n }", "public boolean hasPossibleMethod(String name, Expression arguments) {\n int count = 0;\n\n if (arguments instanceof TupleExpression) {\n TupleExpression tuple = (TupleExpression) arguments;\n // TODO this won't strictly be true when using list expansion in argument calls\n count = tuple.getExpressions().size();\n }\n ClassNode node = this;\n do {\n for (MethodNode method : getMethods(name)) {\n if (method.getParameters().length == count && !method.isStatic()) {\n return true;\n }\n }\n node = node.getSuperClass();\n }\n while (node != null);\n return false;\n }" ]
Executes the given supplier within the context of a read lock. @param <E> The result type. @param sup The supplier. @return The result of {@link Supplier#get()}.
[ "protected <E> E read(Supplier<E> sup) {\n try {\n this.lock.readLock().lock();\n return sup.get();\n } finally {\n this.lock.readLock().unlock();\n }\n }" ]
[ "public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) {\n ZkGroupDirs dirs = new ZkGroupDirs(group);\n List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir);\n //\n Map<String, List<String>> consumersPerTopicMap = new HashMap<String, List<String>>();\n for (String consumer : consumers) {\n TopicCount topicCount = getTopicCount(zkClient, group, consumer);\n for (Map.Entry<String, Set<String>> e : topicCount.getConsumerThreadIdsPerTopic().entrySet()) {\n final String topic = e.getKey();\n for (String consumerThreadId : e.getValue()) {\n List<String> list = consumersPerTopicMap.get(topic);\n if (list == null) {\n list = new ArrayList<String>();\n consumersPerTopicMap.put(topic, list);\n }\n //\n list.add(consumerThreadId);\n }\n }\n }\n //\n for (Map.Entry<String, List<String>> e : consumersPerTopicMap.entrySet()) {\n Collections.sort(e.getValue());\n }\n return consumersPerTopicMap;\n }", "public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){\n\t\tHazardCurve survivalProbabilities = new HazardCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tsurvivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn survivalProbabilities;\n\t}", "public void link(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds, Object referencedObject, boolean insert)\n {\n // MBAIRD: we have 'disassociated' this object from the referenced object,\n // the object represented by the reference descriptor is now null, so set\n // the fk in the target object to null.\n // arminw: if an insert was done and ref object was null, we should allow\n // to pass FK fields of main object (maybe only the FK fields are set)\n if (referencedObject == null)\n {\n /*\n arminw:\n if update we set FK fields to 'null', because reference was disassociated\n We do nothing on insert, maybe only the FK fields of main object (without\n materialization of the reference object) are set by the user\n */\n if(!insert)\n {\n unlinkFK(targetObject, cld, rds);\n }\n }\n else\n {\n setFKField(targetObject, cld, rds, referencedObject);\n }\n }", "private void processResourceAssignments(Task task, List<MapRow> assignments)\n {\n for (MapRow row : assignments)\n {\n processResourceAssignment(task, row);\n }\n }", "void fileWritten() throws ConfigurationPersistenceException {\n if (!doneBootup.get() || interactionPolicy.isReadOnly()) {\n return;\n }\n try {\n FilePersistenceUtils.copyFile(mainFile, lastFile);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }", "public <V> V detach(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.remove(key));\n }", "public void enableUniformSize(final boolean enable) {\n if (mUniformSize != enable) {\n mUniformSize = enable;\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }", "public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {\n assertNumericArgument(corePoolSize, true);\n assertNumericArgument(maximumPoolSize, true);\n assertNumericArgument(corePoolSize + maximumPoolSize, false);\n assertNumericArgument(keepAliveTime, true);\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.keepAliveTime = unit.toMillis(keepAliveTime);\n return this;\n }", "private String addIndexInputToList(String name, IndexInput in,\n String postingsFormatName) throws IOException {\n if (indexInputList.get(name) != null) {\n indexInputList.get(name).close();\n }\n if (in != null) {\n String localPostingsFormatName = postingsFormatName;\n if (localPostingsFormatName == null) {\n localPostingsFormatName = in.readString();\n } else if (!in.readString().equals(localPostingsFormatName)) {\n throw new IOException(\"delegate codec \" + name + \" doesn't equal \"\n + localPostingsFormatName);\n }\n indexInputList.put(name, in);\n indexInputOffsetList.put(name, in.getFilePointer());\n return localPostingsFormatName;\n } else {\n log.debug(\"no \" + name + \" registered\");\n return null;\n }\n }" ]
This method is called to format a percentage value. @param value numeric value @return percentage value
[ "private String formatPercentage(Number value)\n {\n return (value == null ? null : m_formats.getPercentageDecimalFormat().format(value) + \"%\");\n }" ]
[ "public static List<String> splitAsList(String text, String delimiter) {\n List<String> answer = new ArrayList<String>();\n if (text != null && text.length() > 0) {\n answer.addAll(Arrays.asList(text.split(delimiter)));\n }\n return answer;\n }", "public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }", "@Override\n public List<String> setTargetHostsFromLineByLineText(String sourcePath,\n HostsSourceType sourceType) throws TargetHostsLoadException {\n\n List<String> targetHosts = new ArrayList<String>();\n try {\n String content = getContentFromPath(sourcePath, sourceType);\n\n targetHosts = setTargetHostsFromString(content);\n\n } catch (IOException e) {\n throw new TargetHostsLoadException(\"IEException when reading \"\n + sourcePath, e);\n }\n\n return targetHosts;\n\n }", "public void fillRectangle(Rectangle rect, Color color) {\n\t\ttemplate.saveState();\n\t\tsetFill(color);\n\t\ttemplate.rectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight());\n\t\ttemplate.fill();\n\t\ttemplate.restoreState();\n\t}", "public static Map<String, String> parseProperties(String s) {\n\t\tMap<String, String> properties = new HashMap<String, String>();\n\t\tif (!StringUtils.isEmpty(s)) {\n\t\t\tMatcher matcher = PROPERTIES_PATTERN.matcher(s);\n\t\t\tint start = 0;\n\t\t\twhile (matcher.find()) {\n\t\t\t\taddKeyValuePairAsProperty(s.substring(start, matcher.start()), properties);\n\t\t\t\tstart = matcher.start() + 1;\n\t\t\t}\n\t\t\taddKeyValuePairAsProperty(s.substring(start), properties);\n\t\t}\n\t\treturn properties;\n\t}", "protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) {\n\n if (CmsXmlUtils.isDeepXpath(xmlPath)) {\n String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath);\n if (null == xmlContent.getValue(parentPath, l)) {\n createParentXmlElements(xmlContent, parentPath, l);\n xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1);\n }\n }\n\n }", "private void createNodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, Level parentLevel) {\n MtasToken nodeToken;\n if (level.node != null && level.positionStart != null\n && level.positionEnd != null) {\n nodeToken = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, \"\");\n nodeToken.setOffset(level.offsetStart, level.offsetEnd);\n nodeToken.setRealOffset(level.realOffsetStart, level.realOffsetEnd);\n nodeToken.addPositionRange(level.positionStart, level.positionEnd);\n tokenCollection.add(nodeToken);\n if (parentLevel != null) {\n parentLevel.tokens.add(nodeToken);\n }\n // only for first mapping(?)\n for (MtasToken token : level.tokens) {\n token.setParentId(nodeToken.getId());\n }\n }\n }", "private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\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 }" ]
Returns a PreparedStatementCreator that returns a page of the underlying result set. @param dialect Database dialect to use. @param limit Maximum number of rows to return. @param offset Index of the first row to return.
[ "public PreparedStatementCreator page(final Dialect dialect, final int limit, final int offset) {\n return new PreparedStatementCreator() {\n public PreparedStatement createPreparedStatement(Connection con) throws SQLException {\n return getPreparedStatementCreator()\n .setSql(dialect.createPageSelect(builder.toString(), limit, offset))\n .createPreparedStatement(con);\n }\n };\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 }", "public String convertToJavaString(String input, boolean useUnicode) {\n\t\tint length = input.length();\n\t\tStringBuilder result = new StringBuilder(length + 4);\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tescapeAndAppendTo(input.charAt(i), useUnicode, result);\n\t\t}\n\t\treturn result.toString();\n\t}", "public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n try {\n FileUtils.writeStringToFile(new File(outputDirName, \"plan.out\"), plan.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpPlanToFile: \" + e);\n }\n }\n }", "public double nextDouble(double lo, double hi) {\n if (lo < 0) {\n if (nextInt(2) == 0)\n return -nextDouble(0, -lo);\n else\n return nextDouble(0, hi);\n } else {\n return (lo + (hi - lo) * nextDouble());\n }\n }", "@Override\n\tprotected final void subAppend(final LoggingEvent event) {\n\t\tif (event instanceof ScheduledFileRollEvent) {\n\t\t\t// the scheduled append() call has been made by a different thread\n\t\t\tsynchronized (this) {\n\t\t\t\tif (this.closed) {\n\t\t\t\t\t// just consume the event\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.rollFile(event);\n\t\t\t}\n\t\t} else if (event instanceof FileRollEvent) {\n\t\t\t// definitely want to avoid rolling here whilst a file roll event is still being handled\n\t\t\tsuper.subAppend(event);\n\t\t} else {\n\n\t\t\tif(event instanceof FoundationLof4jLoggingEvent){\n\t\t\t\tFoundationLof4jLoggingEvent foundationLof4jLoggingEvent = (FoundationLof4jLoggingEvent)event;\n\t\t\t\tfoundationLof4jLoggingEvent.setAppenderName(this.getName());\n\t\t\t}\n\t\t\t\n\t\t\tthis.rollFile(event);\n\t\t\tsuper.subAppend(event);\n\t\t}\n\t}", "public Metadata updateMetadata(Metadata metadata) {\n String scope;\n if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) {\n scope = Metadata.GLOBAL_METADATA_SCOPE;\n } else {\n scope = Metadata.ENTERPRISE_METADATA_SCOPE;\n }\n\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(),\n scope, metadata.getTemplateName());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"PUT\");\n request.addHeader(\"Content-Type\", \"application/json-patch+json\");\n request.setBody(metadata.getPatch());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }", "protected DatabaseConnection getSavedConnection() {\n\t\tNestedConnection nested = specialConnection.get();\n\t\tif (nested == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn nested.connection;\n\t\t}\n\t}", "public static void Backward(double[] data) {\n\n double[] result = new double[data.length];\n double sum;\n double scale = Math.sqrt(2.0 / data.length);\n for (int t = 0; t < data.length; t++) {\n sum = 0;\n for (int j = 0; j < data.length; j++) {\n double cos = Math.cos(((2 * t + 1) * j * Math.PI) / (2 * data.length));\n sum += alpha(j) * data[j] * cos;\n }\n result[t] = scale * sum;\n }\n for (int i = 0; i < data.length; i++) {\n data[i] = result[i];\n }\n }", "private void showSettingsMenu(final Cursor cursor) {\n Log.d(TAG, \"showSettingsMenu\");\n enableSettingsCursor(cursor);\n context.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n new SettingsView(context, scene, CursorManager.this,\n settingsCursor.getIoDevice().getCursorControllerId(), cursor, new\n SettingsChangeListener() {\n @Override\n public void onBack(boolean cascading) {\n disableSettingsCursor();\n }\n\n @Override\n public int onDeviceChanged(IoDevice device) {\n // we are changing the io device on the settings cursor\n removeCursorFromScene(settingsCursor);\n IoDevice clickedDevice = getAvailableIoDevice(device);\n settingsCursor.setIoDevice(clickedDevice);\n addCursorToScene(settingsCursor);\n return device.getCursorControllerId();\n }\n });\n }\n });\n }" ]
Creates an IndexableTaskItem from provided FunctionalTaskItem. @param taskItem functional TaskItem @return IndexableTaskItem
[ "public static IndexableTaskItem create(final FunctionalTaskItem taskItem) {\n return new IndexableTaskItem() {\n @Override\n protected Observable<Indexable> invokeTaskAsync(TaskGroup.InvocationContext context) {\n FunctionalTaskItem.Context fContext = new FunctionalTaskItem.Context(this);\n fContext.setInnerContext(context);\n return taskItem.call(fContext);\n }\n };\n }" ]
[ "private void processUpdate(DeviceUpdate update) {\n updates.put(update.getAddress(), update);\n\n // Keep track of the largest sync number we see.\n if (update instanceof CdjStatus) {\n int syncNumber = ((CdjStatus)update).getSyncNumber();\n if (syncNumber > this.largestSyncCounter.get()) {\n this.largestSyncCounter.set(syncNumber);\n }\n }\n\n // Deal with the tempo master complexities, including handoff to/from us.\n if (update.isTempoMaster()) {\n final Integer packetYieldingTo = update.getDeviceMasterIsBeingYieldedTo();\n if (packetYieldingTo == null) {\n // This is a normal, non-yielding master packet. Update our notion of the current master, and,\n // if we were yielding, finish that process, updating our sync number appropriately.\n if (master.get()) {\n if (nextMaster.get() == update.deviceNumber) {\n syncCounter.set(largestSyncCounter.get() + 1);\n } else {\n if (nextMaster.get() == 0xff) {\n logger.warn(\"Saw master asserted by player \" + update.deviceNumber +\n \" when we were not yielding it.\");\n } else {\n logger.warn(\"Expected to yield master role to player \" + nextMaster.get() +\n \" but saw master asserted by player \" + update.deviceNumber);\n }\n }\n }\n master.set(false);\n nextMaster.set(0xff);\n setTempoMaster(update);\n setMasterTempo(update.getEffectiveTempo());\n } else {\n // This is a yielding master packet. If it is us that is being yielded to, take over master.\n // Log a message if it was unsolicited, and a warning if it's coming from a different player than\n // we asked.\n if (packetYieldingTo == getDeviceNumber()) {\n if (update.deviceNumber != masterYieldedFrom.get()) {\n if (masterYieldedFrom.get() == 0) {\n logger.info(\"Accepting unsolicited Master yield; we must be the only synced device playing.\");\n } else {\n logger.warn(\"Expected player \" + masterYieldedFrom.get() + \" to yield master to us, but player \" +\n update.deviceNumber + \" did.\");\n }\n }\n master.set(true);\n masterYieldedFrom.set(0);\n setTempoMaster(null);\n setMasterTempo(getTempo());\n }\n }\n } else {\n // This update was not acting as a tempo master; if we thought it should be, update our records.\n DeviceUpdate oldMaster = getTempoMaster();\n if (oldMaster != null && oldMaster.getAddress().equals(update.getAddress())) {\n // This device has resigned master status, and nobody else has claimed it so far\n setTempoMaster(null);\n }\n }\n deliverDeviceUpdate(update);\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 }", "protected String getExecutableJar() throws IOException {\n Manifest manifest = new Manifest();\n manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, \"1.0\");\n manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN);\n manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, getClasspath());\n\n Path jar = createTempDirectory(\"exec\").resolve(\"generate.jar\");\n try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {\n output.putNextEntry(new JarEntry(\"allure.properties\"));\n Path allureConfig = PROPERTIES.getAllureConfig();\n if (Files.exists(allureConfig)) {\n byte[] bytes = Files.readAllBytes(allureConfig);\n output.write(bytes);\n }\n output.closeEntry();\n }\n\n return jar.toAbsolutePath().toString();\n }", "public static base_response add(nitro_service client, sslaction resource) throws Exception {\n\t\tsslaction addresource = new sslaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.clientauth = resource.clientauth;\n\t\taddresource.clientcert = resource.clientcert;\n\t\taddresource.certheader = resource.certheader;\n\t\taddresource.clientcertserialnumber = resource.clientcertserialnumber;\n\t\taddresource.certserialheader = resource.certserialheader;\n\t\taddresource.clientcertsubject = resource.clientcertsubject;\n\t\taddresource.certsubjectheader = resource.certsubjectheader;\n\t\taddresource.clientcerthash = resource.clientcerthash;\n\t\taddresource.certhashheader = resource.certhashheader;\n\t\taddresource.clientcertissuer = resource.clientcertissuer;\n\t\taddresource.certissuerheader = resource.certissuerheader;\n\t\taddresource.sessionid = resource.sessionid;\n\t\taddresource.sessionidheader = resource.sessionidheader;\n\t\taddresource.cipher = resource.cipher;\n\t\taddresource.cipherheader = resource.cipherheader;\n\t\taddresource.clientcertnotbefore = resource.clientcertnotbefore;\n\t\taddresource.certnotbeforeheader = resource.certnotbeforeheader;\n\t\taddresource.clientcertnotafter = resource.clientcertnotafter;\n\t\taddresource.certnotafterheader = resource.certnotafterheader;\n\t\taddresource.owasupport = resource.owasupport;\n\t\treturn addresource.add_resource(client);\n\t}", "private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) {\n EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget();\n EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR);\n WSAEndpointReferenceUtils.setAddress(targetEPR, address);\n\n if (props != null) {\n addProperties(targetEPR, props);\n }\n return targetEPR;\n }", "public static snmpoption get(nitro_service service) throws Exception{\n\t\tsnmpoption obj = new snmpoption();\n\t\tsnmpoption[] response = (snmpoption[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void start() {\n instanceLock.writeLock().lock();\n try {\n for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry :\n nsStreamers.entrySet()) {\n streamerEntry.getValue().start();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "public HashSet<String> getDataById(String id) throws IOException {\n if (idToVersion.containsKey(id)) {\n return get(id);\n } else {\n return null;\n }\n }", "public static <T> Object callMethod(Object obj,\n Class<T> c,\n String name,\n Class<?>[] classes,\n Object[] args) {\n try {\n Method m = getMethod(c, name, classes);\n return m.invoke(obj, args);\n } catch(InvocationTargetException e) {\n throw getCause(e);\n } catch(IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }" ]
Skips the stream over the specified number of bytes, adding the skipped amount to the count. @param length the number of bytes to skip @return the actual number of bytes skipped @throws java.io.IOException if an I/O error occurs @see java.io.InputStream#skip(long)
[ "@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 }" ]
[ "public void close() {\n this.waitUntilInitialized();\n\n this.ongoingOperationsGroup.blockAndWait();\n\n syncLock.lock();\n try {\n if (this.networkMonitor != null) {\n this.networkMonitor.removeNetworkStateListener(this);\n }\n this.dispatcher.close();\n stop();\n this.localClient.close();\n } finally {\n syncLock.unlock();\n }\n }", "public static base_response add(nitro_service client, route6 resource) throws Exception {\n\t\troute6 addresource = new route6();\n\t\taddresource.network = resource.network;\n\t\taddresource.gateway = resource.gateway;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.weight = resource.weight;\n\t\taddresource.distance = resource.distance;\n\t\taddresource.cost = resource.cost;\n\t\taddresource.advertise = resource.advertise;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "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 SingleAssetEuropeanOptionProductDescriptor getDescriptor(LocalDate referenceDate, int index) throws ArrayIndexOutOfBoundsException{\n\t\tLocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);\n\t\tif(index >= strikes.length) {\n\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Strike index out of bounds\");\n\t\t}else {\n\t\t\treturn new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[index]);\n\t\t}\n\t}", "private void initFieldFactories() {\n\n if (m_model.hasMasterMode()) {\n TranslateTableFieldFactory masterFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER));\n masterFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.MASTER, masterFieldFactory);\n }\n TranslateTableFieldFactory defaultFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT));\n defaultFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, defaultFieldFactory);\n\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 }", "private void ensureFields(ClassDescriptorDef classDef, Collection fields) throws ConstraintException\r\n {\r\n boolean forceVirtual = !classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true);\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();\r\n\r\n // First we check whether this field is already present in the class\r\n FieldDescriptorDef foundFieldDef = classDef.getField(fieldDef.getName());\r\n\r\n if (foundFieldDef != null)\r\n {\r\n if (isEqual(fieldDef, foundFieldDef))\r\n {\r\n if (forceVirtual)\r\n {\r\n foundFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n continue;\r\n }\r\n else\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a different field of the same name\");\r\n }\r\n }\r\n\r\n // perhaps a reference or collection ?\r\n if (classDef.getCollection(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a collection of the same name\");\r\n }\r\n if (classDef.getReference(fieldDef.getName()) != null)\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required field \"+fieldDef.getName()+\r\n \" from type \"+fieldDef.getOwner().getName()+\" to basetype \"+classDef.getName()+\r\n \" because there is already a reference of the same name\");\r\n }\r\n classDef.addFieldClone(fieldDef);\r\n classDef.getField(fieldDef.getName()).setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, \"true\");\r\n }\r\n }", "protected synchronized void stealExistingAllocations(){\r\n\t\t\r\n\t\tfor (ConnectionHandle handle: this.threadFinalizableRefs.keySet()){\r\n\t\t\t// if they're not in use, pretend they are in use now and close them off.\r\n\t\t\t// this method assumes that the strategy has been flipped back to non-caching mode\r\n\t\t\t// prior to this method invocation.\r\n\t\t\tif (handle.logicallyClosed.compareAndSet(true, false)){ \r\n\t\t\t\ttry {\r\n\t\t\t\t\tthis.pool.releaseConnection(handle);\r\n\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\tlogger.error(\"Error releasing connection\", e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (this.warnApp.compareAndSet(false, true)){ // only issue warning once.\r\n\t\t\tlogger.warn(\"Cached strategy chosen, but more threads are requesting a connection than are configured. Switching permanently to default strategy.\");\r\n\t\t}\r\n\t\tthis.threadFinalizableRefs.clear();\r\n\t\t\r\n\t}", "public ViewGroup getContentContainer() {\n if (mDragMode == MENU_DRAG_CONTENT) {\n return mContentContainer;\n } else {\n return (ViewGroup) findViewById(android.R.id.content);\n }\n }" ]
Returns current selenium version from JAR set in classpath. @return Version of Selenium.
[ "public static String fromClassPath() {\n Set<String> versions = new HashSet<>();\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> manifests = classLoader.getResources(\"META-INF/MANIFEST.MF\");\n\n while (manifests.hasMoreElements()) {\n URL manifestURL = manifests.nextElement();\n try (InputStream is = manifestURL.openStream()) {\n Manifest manifest = new Manifest();\n manifest.read(is);\n\n Attributes buildInfo = manifest.getAttributes(\"Build-Info\");\n if (buildInfo != null) {\n if (buildInfo.getValue(\"Selenium-Version\") != null) {\n versions.add(buildInfo.getValue(\"Selenium-Version\"));\n } else {\n // might be in build-info part\n if (manifest.getEntries() != null) {\n if (manifest.getEntries().containsKey(\"Build-Info\")) {\n final Attributes attributes = manifest.getEntries().get(\"Build-Info\");\n\n if (attributes.getValue(\"Selenium-Version\") != null) {\n versions.add(attributes.getValue(\"Selenium-Version\"));\n }\n }\n }\n }\n }\n }\n }\n } catch (Exception e) {\n logger.log(Level.WARNING,\n \"Exception {0} occurred while resolving selenium version and latest image is going to be used.\",\n e.getMessage());\n return SELENIUM_VERSION;\n }\n\n if (versions.isEmpty()) {\n logger.log(Level.INFO, \"No version of Selenium found in classpath. Using latest image.\");\n return SELENIUM_VERSION;\n }\n\n String foundVersion = versions.iterator().next();\n if (versions.size() > 1) {\n logger.log(Level.WARNING, \"Multiple versions of Selenium found in classpath. Using the first one found {0}.\",\n foundVersion);\n }\n\n return foundVersion;\n }" ]
[ "private void writeDateField(String fieldName, Object value) throws IOException\n {\n if (value instanceof String)\n {\n m_writer.writeNameValuePair(fieldName + \"_text\", (String) value);\n }\n else\n {\n Date val = (Date) value;\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public void addFile(File file) {\n String name = \"file\";\n files.put(normalizeDuplicateName(name), file);\n }", "private long getTime(Date start, Date end)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n { \n endTime = DateHelper.addDays(endTime, 1);\n }\n\n total = (endTime.getTime() - startTime.getTime());\n }\n return (total);\n }", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "public 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 void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }", "@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }", "public BoxFolder.Info createFolder(String name) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", this.getID());\n\n JsonObject newFolder = new JsonObject();\n newFolder.add(\"name\", name);\n newFolder.add(\"parent\", parent);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()),\n \"POST\");\n request.setBody(newFolder.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get(\"id\").asString());\n return createdFolder.new Info(responseJSON);\n }", "public static boolean isAvailable() throws Exception {\n try {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n return true;\n } catch (Exception e) {\n return false;\n }\n }" ]
Transforms an input file into HTML. @param file The File to process. @param safeMode Set to <code>true</code> to escape unsafe HTML tags. @return The processed String. @throws IOException if an IO error occurs @see Configuration#DEFAULT
[ "public final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }" ]
[ "public static <T> IteratorFromReaderFactory<T> getFactory(String delim, Function<String,T> op) {\r\n return new DelimitRegExIteratorFactory<T>(delim, op);\r\n }", "private static void defineField(Map<String, FieldType> container, String name, FieldType type, String alias)\n {\n container.put(name, type);\n if (alias != null)\n {\n ALIASES.put(type, alias);\n }\n }", "private I_CmsSearchIndex getIndex() {\n\n I_CmsSearchIndex index = null;\n // get the configured index or the selected index\n if (isInitialCall()) {\n // the search form is in the initial state\n // get the configured index\n index = OpenCms.getSearchManager().getIndex(getSettings().getUserSettings().getWorkplaceSearchIndexName());\n } else {\n // the search form is not in the inital state, the submit button was used already or the\n // search index was changed already\n // get the selected index in the search dialog\n index = OpenCms.getSearchManager().getIndex(getJsp().getRequest().getParameter(\"indexName.0\"));\n }\n return index;\n }", "public static base_response add(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser addresource = new snmpuser();\n\t\taddresource.name = resource.name;\n\t\taddresource.group = resource.group;\n\t\taddresource.authtype = resource.authtype;\n\t\taddresource.authpasswd = resource.authpasswd;\n\t\taddresource.privtype = resource.privtype;\n\t\taddresource.privpasswd = resource.privpasswd;\n\t\treturn addresource.add_resource(client);\n\t}", "public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n int newFooterItemCount = getFooterItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (newFooterItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);\n }", "private Map<String, String> getContentsByContainerName(\n CmsContainerElementBean element,\n Collection<CmsContainer> containers) {\n\n CmsFormatterConfiguration configs = getFormatterConfiguration(element.getResource());\n Map<String, String> result = new HashMap<String, String>();\n for (CmsContainer container : containers) {\n String content = getContentByContainer(element, container, configs);\n if (content != null) {\n content = removeScriptTags(content);\n }\n result.put(container.getName(), content);\n }\n return result;\n }", "@TargetApi(VERSION_CODES.KITKAT)\n public static void showSystemUI(Activity activity) {\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n );\n }", "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 List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\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 (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return servers;\n }" ]
Pushes a basic event. @param eventName The name of the event
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushEvent(String eventName) {\n if (eventName == null || eventName.trim().equals(\"\"))\n return;\n\n pushEvent(eventName, null);\n }" ]
[ "public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\n }", "protected void statusInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n logger.info(tag + \" : [partition: \" + currentPartition + \", partitionFetched: \"\n + currentPartitionFetched\n + \"] for store \" + storageEngine.getName());\n }\n }", "public String getHeaderField(String fieldName) {\n // headers map is null for all regular response calls except when made as a batch request\n if (this.headers == null) {\n if (this.connection != null) {\n return this.connection.getHeaderField(fieldName);\n } else {\n return null;\n }\n } else {\n return this.headers.get(fieldName);\n }\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 }", "private void doFileRoll(final File from, final File to) {\n final FileHelper fileHelper = FileHelper.getInstance();\n if (!fileHelper.deleteExisting(to)) {\n this.getAppender().getErrorHandler()\n .error(\"Unable to delete existing \" + to + \" for rename\");\n }\n final String original = from.toString();\n if (fileHelper.rename(from, to)) {\n LogLog.debug(\"Renamed \" + original + \" to \" + to);\n } else {\n this.getAppender().getErrorHandler()\n .error(\"Unable to rename \" + original + \" to \" + to);\n }\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, \n CommandlineJava commandline, \n TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) {\n try {\n String tempDir = commandline.getSystemProperties().getVariablesVector().stream()\n .filter(v -> v.getKey().equals(\"java.io.tmpdir\"))\n .map(v -> v.getValue())\n .findAny()\n .orElse(null);\n\n final LocalSlaveStreamHandler streamHandler = \n new LocalSlaveStreamHandler(\n eventBus, testsClassLoader, System.err, eventStream, \n sysout, syserr, heartbeat, streamsBuffer);\n\n // Add certain properties to allow identification of the forked JVM from within\n // the subprocess. This can be used for policy files etc.\n final Path cwd = getWorkingDirectory(slaveInfo, tempDir);\n\n Variable v = new Variable();\n v.setKey(CHILDVM_SYSPROP_CWD);\n v.setFile(cwd.toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SYSPROP_TEMPDIR);\n v.setFile(getTempDir().toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID);\n v.setValue(Integer.toString(slaveInfo.id));\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT);\n v.setValue(Integer.toString(slaveInfo.slaves));\n commandline.addSysproperty(v);\n\n // Emit command line before -stdin to avoid confusion.\n slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline());\n log(\"Forked child JVM at '\" + cwd.toAbsolutePath().normalize() + \n \"', command (may need escape sequences for your shell):\\n\" + \n slaveInfo.slaveCommandLine, Project.MSG_VERBOSE);\n\n final Execute execute = new Execute();\n execute.setCommandline(commandline.getCommandline());\n execute.setVMLauncher(true);\n execute.setWorkingDirectory(cwd.toFile());\n execute.setStreamHandler(streamHandler);\n execute.setNewenvironment(newEnvironment);\n if (env.getVariables() != null)\n execute.setEnvironment(env.getVariables());\n log(\"Starting JVM J\" + slaveInfo.id, Project.MSG_DEBUG);\n execute.execute();\n return execute;\n } catch (IOException e) {\n throw new BuildException(\"Could not start the child process. Run ant with -verbose to get\" +\n \t\t\" the execution details.\", e);\n }\n }", "protected void eciProcess() {\n\n EciMode eci = EciMode.of(content, \"ISO8859_1\", 3)\n .or(content, \"ISO8859_2\", 4)\n .or(content, \"ISO8859_3\", 5)\n .or(content, \"ISO8859_4\", 6)\n .or(content, \"ISO8859_5\", 7)\n .or(content, \"ISO8859_6\", 8)\n .or(content, \"ISO8859_7\", 9)\n .or(content, \"ISO8859_8\", 10)\n .or(content, \"ISO8859_9\", 11)\n .or(content, \"ISO8859_10\", 12)\n .or(content, \"ISO8859_11\", 13)\n .or(content, \"ISO8859_13\", 15)\n .or(content, \"ISO8859_14\", 16)\n .or(content, \"ISO8859_15\", 17)\n .or(content, \"ISO8859_16\", 18)\n .or(content, \"Windows_1250\", 21)\n .or(content, \"Windows_1251\", 22)\n .or(content, \"Windows_1252\", 23)\n .or(content, \"Windows_1256\", 24)\n .or(content, \"SJIS\", 20)\n .or(content, \"UTF8\", 26);\n\n if (EciMode.NONE.equals(eci)) {\n throw new OkapiException(\"Unable to determine ECI mode.\");\n }\n\n eciMode = eci.mode;\n inputData = toBytes(content, eci.charset);\n\n encodeInfo += \"ECI Mode: \" + eci.mode + \"\\n\";\n encodeInfo += \"ECI Charset: \" + eci.charset.name() + \"\\n\";\n }", "public boolean isHomeKeyPresent() {\n final GVRApplication application = mApplication.get();\n if (null != application) {\n final String model = getHmtModel();\n if (null != model && model.contains(\"R323\")) {\n return true;\n }\n }\n return false;\n }", "private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }" ]
This method lists any notes attached to tasks. @param file MPX file
[ "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 hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor_binding obj = new hanode_routemonitor_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void addItem(T value, Direction dir, String text) {\n addItem(value, dir, text, true);\n }", "public static String[] addStringToArray(String[] array, String str) {\n if (isEmpty(array)) {\n return new String[]{str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }", "protected void onEditTitleTextBox(TextBox box) {\n\n if (m_titleEditHandler != null) {\n m_titleEditHandler.handleEdit(m_title, box);\n return;\n }\n\n String text = box.getText();\n box.removeFromParent();\n m_title.setText(text);\n m_title.setVisible(true);\n\n }", "public static int cudnnLRNCrossChannelForward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y));\n }", "public static appfwjsoncontenttype[] get(nitro_service service, options option) throws Exception{\n\t\tappfwjsoncontenttype obj = new appfwjsoncontenttype();\n\t\tappfwjsoncontenttype[] response = (appfwjsoncontenttype[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public static <T> int indexOf(T[] array, T element) {\n\t\tfor ( int i = 0; i < array.length; i++ ) {\n\t\t\tif ( array[i].equals( element ) ) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}", "@SuppressWarnings(\"unchecked\")\n public static <T extends Serializable> T makeClone(T from) {\n return (T) SerializationUtils.clone(from);\n }", "public void saveFile(File file, String type)\n {\n if (file != null)\n {\n m_treeController.saveFile(file, type);\n }\n }" ]
Set the enum representing the type of this column. @param tableType type of table to which this column belongs
[ "private void setFieldType(FastTrackTableType tableType)\n {\n switch (tableType)\n {\n case ACTBARS:\n {\n m_type = ActBarField.getInstance(m_header.getColumnType());\n break;\n }\n case ACTIVITIES:\n {\n m_type = ActivityField.getInstance(m_header.getColumnType());\n break;\n }\n case RESOURCES:\n {\n m_type = ResourceField.getInstance(m_header.getColumnType());\n break;\n }\n }\n }" ]
[ "private void writeExceptions(List<ProjectCalendar> records) throws IOException\n {\n for (ProjectCalendar record : records)\n {\n if (!record.getCalendarExceptions().isEmpty())\n {\n // Need to move HOLI up here and get 15 exceptions per line as per USACE spec.\n // for now, we'll write one line for each calendar exception, hope there aren't too many\n //\n // changing this would be a serious upgrade, too much coding to do today....\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n m_eventManager.fireCalendarWrittenEvent(record); // left here from MPX template, maybe not needed???\n }\n }", "public static String[] slice(String[] strings, int begin, int length) {\n\t\tString[] result = new String[length];\n\t\tSystem.arraycopy( strings, begin, result, 0, length );\n\t\treturn result;\n\t}", "public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, UTF_8 );\n }", "protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\n }", "public void delete(final String referenceId) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.equal(root.get(\"referenceId\"), referenceId));\n getSession().createQuery(delete).executeUpdate();\n }", "public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"layouts\");\n json.array();\n final Map<String, Template> accessibleTemplates = getTemplates();\n accessibleTemplates.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))\n .forEach(entry -> {\n json.object();\n json.key(\"name\").value(entry.getKey());\n entry.getValue().printClientConfig(json);\n json.endObject();\n });\n json.endArray();\n json.key(\"smtp\").object();\n json.key(\"enabled\").value(smtp != null);\n if (smtp != null) {\n json.key(\"storage\").object();\n json.key(\"enabled\").value(smtp.getStorage() != null);\n json.endObject();\n }\n json.endObject();\n }", "private List<TimephasedCost> getTimephasedCostMultipleRates(List<TimephasedWork> standardWorkList, List<TimephasedWork> overtimeWorkList)\n {\n List<TimephasedWork> standardWorkResult = new LinkedList<TimephasedWork>();\n List<TimephasedWork> overtimeWorkResult = new LinkedList<TimephasedWork>();\n CostRateTable table = getCostRateTable();\n ProjectCalendar calendar = getCalendar();\n\n Iterator<TimephasedWork> iter = overtimeWorkList.iterator();\n for (TimephasedWork standardWork : standardWorkList)\n {\n TimephasedWork overtimeWork = iter.hasNext() ? iter.next() : null;\n\n int startIndex = getCostRateTableEntryIndex(standardWork.getStart());\n int finishIndex = getCostRateTableEntryIndex(standardWork.getFinish());\n\n if (startIndex == finishIndex)\n {\n standardWorkResult.add(standardWork);\n if (overtimeWork != null)\n {\n overtimeWorkResult.add(overtimeWork);\n }\n }\n else\n {\n standardWorkResult.addAll(splitWork(table, calendar, standardWork, startIndex));\n if (overtimeWork != null)\n {\n overtimeWorkResult.addAll(splitWork(table, calendar, overtimeWork, startIndex));\n }\n }\n }\n\n return getTimephasedCostSingleRate(standardWorkResult, overtimeWorkResult);\n }", "private void sendAnnouncement(InetAddress broadcastAddress) {\n try {\n DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,\n broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);\n socket.get().send(announcement);\n Thread.sleep(getAnnounceInterval());\n } catch (Throwable t) {\n logger.warn(\"Unable to send announcement packet, shutting down\", t);\n stop();\n }\n }", "public static CssSel sel(String selector, String value) {\n\treturn j.sel(selector, value);\n }" ]
Checks to see if a subsystem resource has already been registered for the deployment. @param subsystemName the name of the subsystem @return {@code true} if the subsystem exists on the deployment otherwise {@code false}
[ "public boolean hasDeploymentSubsystemModel(final String subsystemName) {\n final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);\n final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);\n return root.hasChild(subsystem);\n }" ]
[ "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 boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }", "public static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}", "public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) {\n if (renderer == null) {\n throw new NeedsPrototypesException(\n \"RendererBuilder can't use a null Renderer<T> instance as prototype\");\n }\n this.prototypes.add(renderer);\n return this;\n }", "public T addFile(final String name, final List<String> path, final byte[] newHash, final boolean isDirectory) {\n return addFile(name, path, newHash, isDirectory, null);\n }", "public AiTextureInfo getTextureInfo(AiTextureType type, int index) {\n return new AiTextureInfo(type, index, getTextureFile(type, index), \n getTextureUVIndex(type, index), getBlendFactor(type, index), \n getTextureOp(type, index), getTextureMapModeW(type, index), \n getTextureMapModeW(type, index), \n getTextureMapModeW(type, index));\n }", "public static <T extends Number> int[] asArray(final T... array) {\n int[] b = new int[array.length];\n for (int i = 0; i < b.length; i++) {\n b[i] = array[i].intValue();\n }\n return b;\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"classes.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\t// Add direct subclass information:\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Integer superClass : classEntry.getValue().directSuperClasses) {\n\t\t\t\t\tthis.classRecords.get(superClass).nonemptyDirectSubclasses\n\t\t\t\t\t\t\t.add(classEntry.getKey().toString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tint countNoLabel = 0;\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (classEntry.getValue().label == null) {\n\t\t\t\t\tcountNoLabel++;\n\t\t\t\t}\n\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + classEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, classEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" class items.\");\n\t\t\tSystem.out.println(\" -- class items with missing label: \"\n\t\t\t\t\t+ countNoLabel);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public void readLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock readLock = lock.readLock();\n\t\tacquireLock( key, timeout, readLock );\n\t}" ]
Specifies the angle of the effect. @param angle the angle of the effect. @angle
[ "public void setAngle(float angle) {\n this.angle = angle;\n float cos = (float) Math.cos(angle);\n float sin = (float) Math.sin(angle);\n m00 = cos;\n m01 = sin;\n m10 = -sin;\n m11 = cos;\n }" ]
[ "protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) {\n Session sess = this.getSession();\n if (sess != null) {\n String json;\n try {\n json = this.mapper.writeValueAsString(objectToSend);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Failed to serialize object\", e);\n }\n sess.getRemote().sendString(json, cb);\n }\n }", "protected void parseLinks(CmsObject cms) throws CmsException {\n\n List<CmsResource> linkParseables = new ArrayList<>();\n for (CmsResourceImportData resData : m_moduleData.getResourceData()) {\n CmsResource importRes = resData.getImportResource();\n if ((importRes != null) && m_importIds.contains(importRes.getStructureId()) && isLinkParsable(importRes)) {\n linkParseables.add(importRes);\n }\n }\n m_report.println(Messages.get().container(Messages.RPT_START_PARSE_LINKS_0), I_CmsReport.FORMAT_HEADLINE);\n CmsImportVersion10.parseLinks(cms, linkParseables, m_report);\n m_report.println(Messages.get().container(Messages.RPT_END_PARSE_LINKS_0), I_CmsReport.FORMAT_HEADLINE);\n }", "public boolean absolute(int row) throws PersistenceBrokerException\r\n {\r\n boolean retval;\r\n if (supportsAdvancedJDBCCursorControl())\r\n {\r\n retval = absoluteAdvanced(row);\r\n }\r\n else\r\n {\r\n retval = absoluteBasic(row);\r\n }\r\n return retval;\r\n }", "public static int getNumberOfDependentLayers(String imageContent) throws IOException {\n JsonNode history = Utils.mapper().readTree(imageContent).get(\"history\");\n if (history == null) {\n throw new IllegalStateException(\"Could not find 'history' tag\");\n }\n\n int layersNum = history.size();\n boolean newImageLayers = true;\n for (int i = history.size() - 1; i >= 0; i--) {\n\n if (newImageLayers) {\n layersNum--;\n }\n\n JsonNode layer = history.get(i);\n JsonNode emptyLayer = layer.get(\"empty_layer\");\n if (!newImageLayers && emptyLayer != null) {\n layersNum--;\n }\n\n if (layer.get(\"created_by\") == null) {\n continue;\n }\n String createdBy = layer.get(\"created_by\").textValue();\n if (createdBy.contains(\"ENTRYPOINT\") || createdBy.contains(\"MAINTAINER\")) {\n newImageLayers = false;\n }\n }\n return layersNum;\n }", "private static void close(Closeable closeable) {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException ignored) {\n\t\t\t\tlogger.error(\"Failed to close output stream: \"\n\t\t\t\t\t\t+ ignored.getMessage());\n\t\t\t}\n\t\t}\n\t}", "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 }", "void addOption(final String value) {\n Assert.checkNotNullParam(\"value\", value);\n synchronized (options) {\n options.add(value);\n }\n }", "protected String getClasspath() throws IOException {\n List<String> classpath = new ArrayList<>();\n classpath.add(getBundleJarPath());\n classpath.addAll(getPluginsPath());\n return StringUtils.toString(classpath.toArray(new String[classpath.size()]), \" \");\n }", "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 }" ]
Get the list of store names from a list of store definitions @param list @param ignoreViews @return list of store names
[ "public static List<String> getStoreNames(List<StoreDefinition> list, boolean ignoreViews) {\n List<String> storeNameSet = new ArrayList<String>();\n for(StoreDefinition def: list)\n if(!def.isView() || !ignoreViews)\n storeNameSet.add(def.getName());\n return storeNameSet;\n }" ]
[ "public float getSize(final Axis axis) {\n float size = 0;\n if (mViewPort != null && mViewPort.isClippingEnabled(axis)) {\n size = mViewPort.get(axis);\n } else if (mContainer != null) {\n size = getSizeImpl(axis);\n }\n return size;\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 }", "@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }", "public static ClassNode getWrapper(ClassNode cn) {\n cn = cn.redirect();\n if (!isPrimitiveType(cn)) return cn;\n if (cn==boolean_TYPE) {\n return Boolean_TYPE;\n } else if (cn==byte_TYPE) {\n return Byte_TYPE;\n } else if (cn==char_TYPE) {\n return Character_TYPE;\n } else if (cn==short_TYPE) {\n return Short_TYPE;\n } else if (cn==int_TYPE) {\n return Integer_TYPE;\n } else if (cn==long_TYPE) {\n return Long_TYPE;\n } else if (cn==float_TYPE) {\n return Float_TYPE;\n } else if (cn==double_TYPE) {\n return Double_TYPE;\n } else if (cn==VOID_TYPE) {\n return void_WRAPPER_TYPE;\n }\n else {\n return cn;\n }\n }", "public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }", "public void authenticate(String authCode) {\n URL url = null;\n try {\n url = new URL(this.tokenURL);\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String urlParameters = String.format(\"grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s\",\n authCode, this.clientID, this.clientSecret);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n String json = response.getJSON();\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.accessToken = jsonObject.get(\"access_token\").asString();\n this.refreshToken = jsonObject.get(\"refresh_token\").asString();\n this.lastRefresh = System.currentTimeMillis();\n this.expires = jsonObject.get(\"expires_in\").asLong() * 1000;\n }", "private void logOriginalResponseHistory(\n PluginResponse httpServletResponse, History history) throws URIException {\n RequestInformation requestInfo = requestInformation.get();\n if (requestInfo.handle && requestInfo.client.getIsActive()) {\n logger.info(\"Storing original response history\");\n history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setOriginalResponseContentType(httpServletResponse.getContentType());\n history.setOriginalResponseData(httpServletResponse.getContentString());\n logger.info(\"Done storing\");\n }\n }", "public boolean remove(long key) {\n int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n Entry previous = null;\n Entry entry = table[index];\n while (entry != null) {\n Entry next = entry.next;\n if (entry.key == key) {\n if (previous == null) {\n table[index] = next;\n } else {\n previous.next = next;\n }\n size--;\n return true;\n }\n previous = entry;\n entry = next;\n }\n return false;\n }", "public void setFromJSON(Context context, JSONObject properties) {\n String backgroundResStr = optString(properties, Properties.background);\n if (backgroundResStr != null && !backgroundResStr.isEmpty()) {\n final int backgroundResId = getId(context, backgroundResStr, \"drawable\");\n setBackGround(context.getResources().getDrawable(backgroundResId, null));\n }\n\n setBackgroundColor(getJSONColor(properties, Properties.background_color, getBackgroundColor()));\n setGravity(optInt(properties, TextContainer.Properties.gravity, getGravity()));\n setRefreshFrequency(optEnum(properties, Properties.refresh_freq, getRefreshFrequency()));\n setTextColor(getJSONColor(properties, Properties.text_color, getTextColor()));\n setText(optString(properties, Properties.text, (String) getText()));\n setTextSize(optFloat(properties, Properties.text_size, getTextSize()));\n\n final JSONObject typefaceJson = optJSONObject(properties, Properties.typeface);\n\n if (typefaceJson != null) {\n try {\n Typeface typeface = WidgetLib.getTypefaceManager().getTypeface(typefaceJson);\n setTypeface(typeface);\n } catch (Throwable e) {\n Log.e(TAG, e, \"Couldn't set typeface from properties: %s\", typefaceJson);\n }\n }\n }" ]
Returns the name of this alias if path has been added to the aliased portions of attributePath @param path the path to test for inclusion in the alias
[ "public String getAlias(String path)\r\n {\r\n if (m_allPathsAliased && m_attributePath.lastIndexOf(path) != -1)\r\n {\r\n return m_name;\r\n }\r\n Object retObj = m_mapping.get(path);\r\n if (retObj != null)\r\n {\r\n return (String) retObj;\r\n }\r\n return null;\r\n }" ]
[ "private OAuth1RequestToken constructToken(Response response) {\r\n Element authElement = response.getPayload();\r\n String oauthToken = XMLUtilities.getChildValue(authElement, \"oauth_token\");\r\n String oauthTokenSecret = XMLUtilities.getChildValue(authElement, \"oauth_token_secret\");\r\n\r\n OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret);\r\n return token;\r\n }", "public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }", "public static String encodeQuery(String query, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(query, encoding, HierarchicalUriComponents.Type.QUERY);\n\t}", "public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }", "public final void error(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.ERROR, pObject, null);\r\n\t}", "public static <T> T get(String key, Class<T> clz) {\n return (T)m().get(key);\n }", "public static String join(Collection<String> s, String delimiter, boolean doQuote) {\r\n StringBuffer buffer = new StringBuffer();\r\n Iterator<String> iter = s.iterator();\r\n while (iter.hasNext()) {\r\n if (doQuote) {\r\n buffer.append(\"\\\"\" + iter.next() + \"\\\"\");\r\n } else {\r\n buffer.append(iter.next());\r\n }\r\n if (iter.hasNext()) {\r\n buffer.append(delimiter);\r\n }\r\n }\r\n return buffer.toString();\r\n }", "public static TimeZone getStockTimeZone(String symbol) {\n // First check if it's a known stock index\n if(INDEX_TIMEZONES.containsKey(symbol)) {\n return INDEX_TIMEZONES.get(symbol);\n }\n \n if(!symbol.contains(\".\")) {\n return ExchangeTimeZone.get(\"\");\n }\n String[] split = symbol.split(\"\\\\.\");\n return ExchangeTimeZone.get(split[split.length - 1]);\n }", "public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }" ]
Convert a Throwable into a list containing all of its causes. @param t The throwable for which the causes are to be returned. @return A (possibly empty) list of {@link Throwable}s.
[ "public List<Throwable> getCauses(Throwable t)\n {\n List<Throwable> causes = new LinkedList<Throwable>();\n Throwable next = t;\n while (next.getCause() != null)\n {\n next = next.getCause();\n causes.add(next);\n }\n return causes;\n }" ]
[ "public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException\r\n {\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n int i = 0;\r\n try\r\n {\r\n for (; i < pkValues.length; i++)\r\n {\r\n setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindDelete failed for: \" + oid.toString() + \", while set value '\" +\r\n pkValues[i] + \"' for column \" + pkFields[i].getColumnName());\r\n throw e;\r\n }\r\n }", "@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}", "public boolean isIPv4Compatible() {\n\t\treturn getSegment(0).isZero() && getSegment(1).isZero() && getSegment(2).isZero() &&\n\t\t\t\tgetSegment(3).isZero() && getSegment(4).isZero() && getSegment(5).isZero();\n\t}", "public static base_response change(nitro_service client, appfwsignatures resource) throws Exception {\n\t\tappfwsignatures updateresource = new appfwsignatures();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.mergedefault = resource.mergedefault;\n\t\treturn updateresource.perform_operation(client,\"update\");\n\t}", "public void setRegularExpression(String regularExpression) {\n\t\tif (regularExpression != null)\n\t\t\tthis.regularExpression = Pattern.compile(regularExpression);\n\t\telse\n\t\t\tthis.regularExpression = null;\n\t}", "public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }", "@Deprecated\r\n public void setViews(String views) {\r\n if (views != null) {\r\n try {\r\n setViews(Integer.parseInt(views));\r\n } catch (NumberFormatException e) {\r\n setViews(-1);\r\n }\r\n }\r\n }", "private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, boolean logDetails) {\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\tdatabaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter);\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"dropping table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"DROP TABLE \");\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(' ');\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t}", "private void createAndAddButton(PatternType pattern, String messageKey) {\n\n CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));\n btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());\n btn.setGroup(m_groupPattern);\n m_patternButtons.put(pattern, btn);\n m_patternRadioButtonsPanel.add(btn);\n\n }" ]
package for testing purpose
[ "static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }" ]
[ "public void handleEvent(Event event) {\n LOG.fine(\"ContentLengthHandler called\");\n\n //if maximum length is shorter then <cut><![CDATA[ ]]></cut> it's not possible to cut the content\n if(CUT_START_TAG.length() + CUT_END_TAG.length() > length) {\n LOG.warning(\"Trying to cut content. But length is shorter then needed for \"\n + CUT_START_TAG + CUT_END_TAG + \". So content is skipped.\");\n event.setContent(\"\");\n return;\n }\n\n int currentLength = length - CUT_START_TAG.length() - CUT_END_TAG.length();\n\n if (event.getContent() != null && event.getContent().length() > length) {\n LOG.fine(\"cutting content to \" + currentLength\n + \" characters. Original length was \"\n + event.getContent().length());\n LOG.fine(\"Content before cutting: \" + event.getContent());\n event.setContent(CUT_START_TAG\n + event.getContent().substring(0, currentLength) + CUT_END_TAG);\n LOG.fine(\"Content after cutting: \" + event.getContent());\n }\n }", "public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\n }", "public static csvserver_copolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_copolicy_binding obj = new csvserver_copolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_copolicy_binding response[] = (csvserver_copolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void injectAdditionalStyles() {\n\n try {\n Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();\n for (String stylesheet : stylesheets) {\n A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }", "public ParallelTaskBuilder prepareHttpPost(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.POST);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {\n BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);\n declarationBinders.put(declarationBinderRef, binderDescriptor);\n }", "@Deprecated\n public static TraceContextHolder wrap(TraceContext traceContext) {\n return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;\n }", "public PhotoList<Photo> getWithGeoData(Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate, int privacyFilter, String sort,\r\n Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_WITH_GEO_DATA);\r\n\r\n if (minUploadDate != null) {\r\n parameters.put(\"min_upload_date\", Long.toString(minUploadDate.getTime() / 1000L));\r\n }\r\n if (maxUploadDate != null) {\r\n parameters.put(\"max_upload_date\", Long.toString(maxUploadDate.getTime() / 1000L));\r\n }\r\n if (minTakenDate != null) {\r\n parameters.put(\"min_taken_date\", Long.toString(minTakenDate.getTime() / 1000L));\r\n }\r\n if (maxTakenDate != null) {\r\n parameters.put(\"max_taken_date\", Long.toString(maxTakenDate.getTime() / 1000L));\r\n }\r\n if (privacyFilter > 0) {\r\n parameters.put(\"privacy_filter\", Integer.toString(privacyFilter));\r\n }\r\n if (sort != null) {\r\n parameters.put(\"sort\", sort);\r\n }\r\n if (extras != null && !extras.isEmpty()) {\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\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 PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }", "public static void closeWindow(Component component) {\n\n Window window = getWindow(component);\n if (window != null) {\n window.close();\n }\n }" ]
Updates the date and time formats. @param properties project properties
[ "private void updateDateTimeFormats(ProjectProperties properties)\n {\n String[] timePatterns = getTimePatterns(properties);\n String[] datePatterns = getDatePatterns(properties);\n String[] dateTimePatterns = getDateTimePatterns(properties, timePatterns);\n\n m_dateTimeFormat.applyPatterns(dateTimePatterns);\n m_dateFormat.applyPatterns(datePatterns);\n m_timeFormat.applyPatterns(timePatterns);\n\n m_dateTimeFormat.setLocale(m_locale);\n m_dateFormat.setLocale(m_locale);\n\n m_dateTimeFormat.setNullText(m_nullText);\n m_dateFormat.setNullText(m_nullText);\n m_timeFormat.setNullText(m_nullText);\n\n m_dateTimeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\n m_timeFormat.setAmPmText(properties.getAMText(), properties.getPMText());\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 notifySubscriberCallback(ContentNotification cn) {\n String content = fetchContentFromPublisher(cn);\n\n distributeContentToSubscribers(content, cn.getUrl());\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 ThreadInfo[] getThreadDump() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n return threadMxBean.dumpAllThreads(true, 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}", "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "public MessageSet read(long offset, int length) throws IOException {\n List<LogSegment> views = segments.getView();\n LogSegment found = findRange(views, offset, views.size());\n if (found == null) {\n if (logger.isTraceEnabled()) {\n logger.trace(format(\"NOT FOUND MessageSet from Log[%s], offset=%d, length=%d\", name, offset, length));\n }\n return MessageSet.Empty;\n }\n return found.getMessageSet().read(offset - found.start(), length);\n }", "public String build() {\n if (!root.containsKey(\"mdm\")) {\n insertCustomAlert();\n root.put(\"aps\", aps);\n }\n try {\n return mapper.writeValueAsString(root);\n } catch (final Exception e) {\n throw new RuntimeException(e);\n }\n }", "private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,\n PrintStream out) throws JsonIOException {\n Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)\n .create();\n\n Map<String, String> json = new LinkedHashMap<>();\n for (RowColumnValue rcv : cellScanner) {\n json.put(FLUO_ROW, encoder.apply(rcv.getRow()));\n json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));\n json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));\n json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));\n json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));\n gson.toJson(json, out);\n out.append(\"\\n\");\n\n if (out.checkError()) {\n break;\n }\n }\n out.flush();\n }" ]
The entity instance is not in the session cache Copied from Loader#instanceNotYetLoaded
[ "private Object instanceNotYetLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\tfinal Loadable persister,\n\t\tfinal String rowIdAlias,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal LockMode lockMode,\n\t\tfinal org.hibernate.engine.spi.EntityKey optionalObjectKey,\n\t\tfinal Object optionalObject,\n\t\tfinal List hydratedObjects,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tfinal String instanceClass = getInstanceClass(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tpersister,\n\t\t\t\tkey.getIdentifier(),\n\t\t\t\tsession\n\t\t\t);\n\n\t\tfinal Object object;\n\t\tif ( optionalObjectKey != null && key.equals( optionalObjectKey ) ) {\n\t\t\t//its the given optional object\n\t\t\tobject = optionalObject;\n\t\t}\n\t\telse {\n\t\t\t// instantiate a new instance\n\t\t\tobject = session.instantiate( instanceClass, key.getIdentifier() );\n\t\t}\n\n\t\t//need to hydrate it.\n\n\t\t// grab its state from the ResultSet and keep it in the Session\n\t\t// (but don't yet initialize the object itself)\n\t\t// note that we acquire LockMode.READ even if it was not requested\n\t\tLockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;\n\t\tloadFromResultSet(\n\t\t\t\tresultset,\n\t\t\t\ti,\n\t\t\t\tobject,\n\t\t\t\tinstanceClass,\n\t\t\t\tkey,\n\t\t\t\trowIdAlias,\n\t\t\t\tacquiredLockMode,\n\t\t\t\tpersister,\n\t\t\t\tsession\n\t\t\t);\n\n\t\t//materialize associations (and initialize the object) later\n\t\thydratedObjects.add( object );\n\n\t\treturn object;\n\t}" ]
[ "public void override(HiveRunnerConfig hiveRunnerConfig) {\n config.putAll(hiveRunnerConfig.config);\n hiveConfSystemOverride.putAll(hiveRunnerConfig.hiveConfSystemOverride);\n }", "public List<String> findAssociationPath(String targetTypeName, List<String> pathWithoutAlias) {\n\t\tList<String> subPath = new ArrayList<String>( pathWithoutAlias.size() );\n\t\tfor ( String name : pathWithoutAlias ) {\n\t\t\tsubPath.add( name );\n\t\t\tif ( isAssociation( targetTypeName, subPath ) ) {\n\t\t\t\treturn subPath;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) {\n \tCollection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size());\n \t\n \tMap<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members);\n \tfor(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) {\n \t\tFuture<T> future = futureEntry.getValue();\n \t\tMember member = futureEntry.getKey();\n \t\t\n \t\ttry {\n if(maxWaitTime > 0) {\n \tresult.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit)));\n } else {\n \tresult.add(new MemberResponse<T>(member, future.get()));\n } \n //ignore exceptions... return what you can\n } catch (InterruptedException e) {\n \tThread.currentThread().interrupt(); //restore interrupted status and return what we have\n \treturn result;\n } catch (MemberLeftException e) {\n \tlog.warn(\"Member {} left while trying to get a distributed callable result\", member);\n } catch (ExecutionException e) {\n \tif(e.getCause() instanceof InterruptedException) {\n \t //restore interrupted state and return\n \t Thread.currentThread().interrupt();\n \t return result;\n \t} else {\n \t log.warn(\"Unable to execute callable on \"+member+\". There was an error.\", e);\n \t}\n } catch (TimeoutException e) {\n \tlog.error(\"Unable to execute task on \"+member+\" within 10 seconds.\");\n } catch (RuntimeException e) {\n \tlog.error(\"Unable to execute task on \"+member+\". An unexpected error occurred.\", e);\n }\n \t}\n \n return result;\n }", "private void toNextDate(Calendar date, int interval) {\n\n long previousDate = date.getTimeInMillis();\n if (!m_weekOfMonthIterator.hasNext()) {\n date.add(Calendar.MONTH, interval);\n m_weekOfMonthIterator = m_weeksOfMonth.iterator();\n }\n toCorrectDateWithDay(date, m_weekOfMonthIterator.next());\n if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.\n toNextDate(date);\n }\n\n }", "@Override\n public final Float optFloat(final String key, final Float defaultValue) {\n Float result = optFloat(key);\n return result == null ? defaultValue : result;\n }", "public int readFrom(byte[] src, int srcOffset, long destOffset, int length) {\n int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length));\n ByteBuffer b = toDirectByteBuffer(destOffset, readLen);\n b.position(0);\n b.put(src, srcOffset, readLen);\n return readLen;\n }", "private void printImage(PrintStream out, ItemDocument itemDocument) {\n\t\tString imageFile = null;\n\n\t\tif (itemDocument != null) {\n\t\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t\tboolean isImage = \"P18\".equals(sg.getProperty().getId());\n\t\t\t\tif (!isImage) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Statement s : sg) {\n\t\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\t\tValue value = s.getMainSnak().getValue();\n\t\t\t\t\t\tif (value instanceof StringValue) {\n\t\t\t\t\t\t\timageFile = ((StringValue) value).getString();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (imageFile != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (imageFile == null) {\n\t\t\tout.print(\",\\\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\\\"\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tString imageFileEncoded;\n\t\t\t\timageFileEncoded = URLEncoder.encode(\n\t\t\t\t\t\timageFile.replace(\" \", \"_\"), \"utf-8\");\n\t\t\t\t// Keep special title symbols unescaped:\n\t\t\t\timageFileEncoded = imageFileEncoded.replace(\"%3A\", \":\")\n\t\t\t\t\t\t.replace(\"%2F\", \"/\");\n\t\t\t\tout.print(\",\"\n\t\t\t\t\t\t+ csvStringEscape(\"http://commons.wikimedia.org/w/thumb.php?f=\"\n\t\t\t\t\t\t\t\t+ imageFileEncoded) + \"&w=50\");\n\t\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Your JRE does not support UTF-8 encoding. Srsly?!\", e);\n\t\t\t}\n\t\t}\n\t}", "public static String analyzeInvalidMetadataRate(final Cluster currentCluster,\n List<StoreDefinition> currentStoreDefs,\n final Cluster finalCluster,\n List<StoreDefinition> finalStoreDefs) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Dump of invalid metadata rates per zone\").append(Utils.NEWLINE);\n\n HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs);\n\n for(StoreDefinition currentStoreDef: uniqueStores.keySet()) {\n sb.append(\"Store exemplar: \" + currentStoreDef.getName())\n .append(Utils.NEWLINE)\n .append(\"\\tThere are \" + uniqueStores.get(currentStoreDef) + \" other similar stores.\")\n .append(Utils.NEWLINE);\n\n StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef);\n StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs,\n currentStoreDef.getName());\n StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef);\n\n // Only care about existing zones\n for(int zoneId: currentCluster.getZoneIds()) {\n int zonePrimariesCount = 0;\n int invalidMetadata = 0;\n\n // Examine nodes in current cluster in existing zone.\n for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) {\n // For every zone-primary in current cluster\n for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) {\n zonePrimariesCount++;\n // Determine if original zone-primary node is still some\n // form of n-ary in final cluster. If not,\n // InvalidMetadataException will fire.\n if(!finalSRP.getZoneNAryPartitionIds(nodeId)\n .contains(zonePrimaryPartitionId)) {\n invalidMetadata++;\n }\n }\n }\n float rate = invalidMetadata / (float) zonePrimariesCount;\n sb.append(\"\\tZone \" + zoneId)\n .append(\" : total zone primaries \" + zonePrimariesCount)\n .append(\", # that trigger invalid metadata \" + invalidMetadata)\n .append(\" => \" + rate)\n .append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }", "public EventBus emitSync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }" ]
This must be called with the write lock held. @param requirement the requirement
[ "private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }" ]
[ "@Nullable\n public ByteIterable get2(@NotNull final Transaction txn, @NotNull final ByteIterable second) {\n return this.second.get(txn, second);\n }", "@NonNull public Context getContext() {\n if (searchView != null) {\n return searchView.getContext();\n } else if (supportView != null) {\n return supportView.getContext();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "public void randomize() {\n\t\tnumKnots = 4 + (int)(6*Math.random());\n\t\txKnots = new int[numKnots];\n\t\tyKnots = new int[numKnots];\n\t\tknotTypes = new byte[numKnots];\n\t\tfor (int i = 0; i < numKnots; i++) {\n\t\t\txKnots[i] = (int)(255 * Math.random());\n\t\t\tyKnots[i] = 0xff000000 | ((int)(255 * Math.random()) << 16) | ((int)(255 * Math.random()) << 8) | (int)(255 * Math.random());\n\t\t\tknotTypes[i] = RGB|SPLINE;\n\t\t}\n\t\txKnots[0] = -1;\n\t\txKnots[1] = 0;\n\t\txKnots[numKnots-2] = 255;\n\t\txKnots[numKnots-1] = 256;\n\t\tsortKnots();\n\t\trebuildGradient();\n\t}", "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 }", "public String nstring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n String value = atom(request);\n if (\"NIL\".equals(value)) {\n return null;\n } else {\n throw new ProtocolException(\"Invalid nstring value: valid values are '\\\"...\\\"', '{12} CRLF *CHAR8', and 'NIL'.\");\n }\n }\n }", "@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }", "private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }", "public CodePage getCodePage(int field)\n {\n CodePage result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = CodePage.getInstance(m_fields[field]);\n }\n else\n {\n result = CodePage.getInstance(null);\n }\n\n return (result);\n }", "public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }" ]
Read a task relationship. @param link ConceptDraw PROJECT task link
[ "private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }" ]
[ "static ProcessedLayers process(final InstalledConfiguration conf, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n final ProcessedLayers layers = new ProcessedLayers(conf);\n // Process module roots\n final LayerPathSetter moduleSetter = new LayerPathSetter() {\n @Override\n public boolean setPath(final LayerPathConfig pending, final File root) {\n if (pending.modulePath == null) {\n pending.modulePath = root;\n return true;\n }\n return false;\n }\n };\n for (final File moduleRoot : moduleRoots) {\n processRoot(moduleRoot, layers, moduleSetter);\n }\n // Process bundle root\n final LayerPathSetter bundleSetter = new LayerPathSetter() {\n @Override\n public boolean setPath(LayerPathConfig pending, File root) {\n if (pending.bundlePath == null) {\n pending.bundlePath = root;\n return true;\n }\n return false;\n }\n };\n for (final File bundleRoot : bundleRoots) {\n processRoot(bundleRoot, layers, bundleSetter);\n }\n// if (conf.getInstalledLayers().size() != layers.getLayers().size()) {\n// throw processingError(\"processed layers don't match expected %s, but was %s\", conf.getInstalledLayers(), layers.getLayers().keySet());\n// }\n// if (conf.getInstalledAddOns().size() != layers.getAddOns().size()) {\n// throw processingError(\"processed add-ons don't match expected %s, but was %s\", conf.getInstalledAddOns(), layers.getAddOns().keySet());\n// }\n return layers;\n }", "public Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\n }", "public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,\n\t\t\t\t\t\t\t\t\t\t\t\tCrawlerContext context) {\n\t\tStateVertex cloneState = this.addStateToCurrentState(newState, event);\n\n\t\trunOnInvariantViolationPlugins(context);\n\n\t\tif (cloneState == null) {\n\t\t\tchangeState(newState);\n\t\t\tplugins.runOnNewStatePlugins(context, newState);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tchangeState(cloneState);\n\t\t\treturn false;\n\t\t}\n\t}", "public CurrencyQueryBuilder setNumericCodes(int... codes) {\n return set(CurrencyQuery.KEY_QUERY_NUMERIC_CODES,\n Arrays.stream(codes).boxed().collect(Collectors.toList()));\n }", "public synchronized boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"LM.checkWrite(tx-\" + tx.getGUID() + \", \" + new Identity(obj, tx.getBroker()).toString() + \")\");\r\n LockStrategy lockStrategy = LockStrategyFactory.getStrategyFor(obj);\r\n return lockStrategy.checkWrite(tx, obj);\r\n }", "public void histogramToStructure(int histogram[] ) {\n col_idx[0] = 0;\n int index = 0;\n for (int i = 1; i <= numCols; i++) {\n col_idx[i] = index += histogram[i-1];\n }\n nz_length = index;\n growMaxLength( nz_length , false);\n if( col_idx[numCols] != nz_length )\n throw new RuntimeException(\"Egads\");\n }", "protected Map<String, OperationTransformer> buildOperationTransformers(AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry) {\n final Map<String, OperationTransformer> operations = new HashMap<String, OperationTransformer>();\n for(final Map.Entry<String, OperationTransformationEntry> entry: operationTransformers.entrySet()) {\n final OperationTransformer transformer = entry.getValue().getOperationTransformer(registry);\n operations.put(entry.getKey(), transformer);\n }\n return operations;\n }", "private void addOp(String op, String path, String value) {\n if (this.operations == null) {\n this.operations = new JsonArray();\n }\n\n this.operations.add(new JsonObject()\n .add(\"op\", op)\n .add(\"path\", path)\n .add(\"value\", value));\n }", "private void processProperties() {\n state = true;\n try {\n exporterServiceFilter = getFilter(exporterServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n exportDeclarationFilter = getFilter(exportDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }" ]
Add a custom query parameter to the _changes request. Useful for specifying extra parameters to a filter function for example. @param name the name of the query parameter @param value the value of the query parameter @return this Changes instance @since 2.5.0
[ "public Changes parameter(String name, String value) {\n this.databaseHelper.query(name, value);\n return this;\n }" ]
[ "public LogStreamResponse getLogs(Log.LogRequestBuilder logRequest) {\n return connection.execute(new Log(logRequest), apiKey);\n }", "public final void notifyFooterItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount + contentItemCount, itemCount);\n }", "public static boolean classNodeImplementsType(ClassNode node, Class target) {\r\n ClassNode targetNode = ClassHelper.make(target);\r\n if (node.implementsInterface(targetNode)) {\r\n return true;\r\n }\r\n if (node.isDerivedFrom(targetNode)) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getName())) {\r\n return true;\r\n }\r\n if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getSimpleName())) {\r\n return true;\r\n }\r\n if (node.getInterfaces() != null) {\r\n for (ClassNode declaredInterface : node.getInterfaces()) {\r\n if (classNodeImplementsType(declaredInterface, target)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "public ServerRedirect getRedirect(int id) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n\n return curServer;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }", "private static void transposeBlock(DMatrixRBlock A , DMatrixRBlock A_tran,\n int indexA , int indexC ,\n int width , int height )\n {\n for( int i = 0; i < height; i++ ) {\n int rowIndexC = indexC + i;\n int rowIndexA = indexA + width*i;\n int end = rowIndexA + width;\n for( ; rowIndexA < end; rowIndexC += height, rowIndexA++ ) {\n A_tran.data[ rowIndexC ] = A.data[ rowIndexA ];\n }\n }\n }", "private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)\n throws CmsException {\n\n CmsObject cmsClone;\n if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {\n cmsClone = cms;\n } else {\n cmsClone = OpenCms.initCmsObject(cms);\n cmsClone.getRequestContext().setSiteRoot(module.getSite());\n }\n\n return cmsClone;\n }", "public static double blackScholesDigitalOptionDelta(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate delta\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);\n\n\t\t\treturn delta;\n\t\t}\n\t}", "private void initializeLogging() {\n\t\t// Since logging is static, make sure this is done only once even if\n\t\t// multiple clients are created (e.g., during tests)\n\t\tif (consoleAppender != null) {\n\t\t\treturn;\n\t\t}\n\n\t\tconsoleAppender = new ConsoleAppender();\n\t\tconsoleAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\t\tLevelRangeFilter filter = new LevelRangeFilter();\n\t\tfilter.setLevelMin(Level.TRACE);\n\t\tfilter.setLevelMax(Level.INFO);\n\t\tconsoleAppender.addFilter(filter);\n\t\tconsoleAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender);\n\n\t\terrorAppender = new ConsoleAppender();\n\t\terrorAppender.setLayout(new PatternLayout(LOG_PATTERN));\n\t\terrorAppender.setThreshold(Level.WARN);\n\t\terrorAppender.setTarget(ConsoleAppender.SYSTEM_ERR);\n\t\terrorAppender.activateOptions();\n\t\torg.apache.log4j.Logger.getRootLogger().addAppender(errorAppender);\n\t}", "public void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }" ]
Make log segment file name from offset bytes. All this does is pad out the offset number with zeros so that ls sorts the files numerically @param offset offset value (padding with zero) @return filename with offset
[ "public static String nameFromOffset(long offset) {\n NumberFormat nf = NumberFormat.getInstance();\n nf.setMinimumIntegerDigits(20);\n nf.setMaximumFractionDigits(0);\n nf.setGroupingUsed(false);\n return nf.format(offset) + Log.FileSuffix;\n }" ]
[ "public static int lengthOfCodePoint(int codePoint)\n {\n if (codePoint < 0) {\n throw new InvalidCodePointException(codePoint);\n }\n if (codePoint < 0x80) {\n // normal ASCII\n // 0xxx_xxxx\n return 1;\n }\n if (codePoint < 0x800) {\n return 2;\n }\n if (codePoint < 0x1_0000) {\n return 3;\n }\n if (codePoint < 0x11_0000) {\n return 4;\n }\n // Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal\n throw new InvalidCodePointException(codePoint);\n }", "public String getUrl(){\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tsb.append(\"http://\");\n\t\tsb.append(getHttpConfiguration().getBindHost().get());\n\t\tsb.append(\":\");\n\t\tsb.append(getHttpConfiguration().getPort());\n\t\t\n\t\treturn sb.toString();\n\t}", "public static DoubleMatrix absi(DoubleMatrix x) { \n\t\t/*# mapfct('Math.abs') #*/\n//RJPP-BEGIN------------------------------------------------------------\n\t for (int i = 0; i < x.length; i++)\n\t x.put(i, (double) Math.abs(x.get(i)));\n\t return x;\n//RJPP-END--------------------------------------------------------------\n\t}", "private void writeDoubleField(String fieldName, Object value) throws IOException\n {\n double val = ((Number) value).doubleValue();\n if (val != 0)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public String format(String value) {\n StringBuilder s = new StringBuilder();\n\n if (value != null && value.trim().length() > 0) {\n boolean continuationLine = false;\n\n s.append(getName()).append(\":\");\n if (isFirstLineEmpty()) {\n s.append(\"\\n\");\n continuationLine = true;\n }\n\n try {\n BufferedReader reader = new BufferedReader(new StringReader(value));\n String line;\n while ((line = reader.readLine()) != null) {\n if (continuationLine && line.trim().length() == 0) {\n // put a dot on the empty continuation lines\n s.append(\" .\\n\");\n } else {\n s.append(\" \").append(line).append(\"\\n\");\n }\n\n continuationLine = true;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return s.toString();\n }", "public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }", "private void handleGlobalArguments(CommandLine cmd) {\n\t\tif (cmd.hasOption(CMD_OPTION_DUMP_LOCATION)) {\n\t\t\tthis.dumpDirectoryLocation = cmd\n\t\t\t\t\t.getOptionValue(CMD_OPTION_DUMP_LOCATION);\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_OFFLINE_MODE)) {\n\t\t\tthis.offlineMode = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_QUIET)) {\n\t\t\tthis.quiet = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CREATE_REPORT)) {\n\t\t\tthis.reportFilename = cmd.getOptionValue(CMD_OPTION_CREATE_REPORT);\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_LANGUAGES)) {\n\t\t\tsetLanguageFilters(cmd.getOptionValue(OPTION_FILTER_LANGUAGES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_SITES)) {\n\t\t\tsetSiteFilters(cmd.getOptionValue(OPTION_FILTER_SITES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_PROPERTIES)) {\n\t\t\tsetPropertyFilters(cmd.getOptionValue(OPTION_FILTER_PROPERTIES));\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_LOCAL_DUMPFILE)) {\n\t\t\tthis.inputDumpLocation = cmd.getOptionValue(OPTION_LOCAL_DUMPFILE);\n\t\t}\n\t}", "@Override\n\tpublic CrawlSession call() {\n\t\tsetMaximumCrawlTimeIfNeeded();\n\t\tplugins.runPreCrawlingPlugins(config);\n\t\tCrawlTaskConsumer firstConsumer = consumerFactory.get();\n\t\tStateVertex firstState = firstConsumer.crawlIndex();\n\t\tcrawlSessionProvider.setup(firstState);\n\t\tplugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);\n\t\texecuteConsumers(firstConsumer);\n\t\treturn crawlSessionProvider.get();\n\t}", "public void drawImage(Image img, Rectangle rect, Rectangle clipRect) {\n\t\tdrawImage(img, rect, clipRect, 1);\n\t}" ]
Returns true if all pixels in the array have the same color
[ "public static boolean uniform(Color color, Pixel[] pixels) {\n return Arrays.stream(pixels).allMatch(p -> p.toInt() == color.toRGB().toInt());\n }" ]
[ "private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,\n PrintStream out) throws JsonIOException {\n Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)\n .create();\n\n Map<String, String> json = new LinkedHashMap<>();\n for (RowColumnValue rcv : cellScanner) {\n json.put(FLUO_ROW, encoder.apply(rcv.getRow()));\n json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));\n json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));\n json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));\n json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));\n gson.toJson(json, out);\n out.append(\"\\n\");\n\n if (out.checkError()) {\n break;\n }\n }\n out.flush();\n }", "public static rewriteglobal_binding get(nitro_service service) throws Exception{\n\t\trewriteglobal_binding obj = new rewriteglobal_binding();\n\t\trewriteglobal_binding response = (rewriteglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static String unexpand(CharSequence self, int tabStop) {\n String s = self.toString();\n if (s.length() == 0) return s;\n try {\n StringBuilder builder = new StringBuilder();\n for (String line : readLines((CharSequence) s)) {\n builder.append(unexpandLine(line, tabStop));\n builder.append(\"\\n\");\n }\n // remove the normalized ending line ending if it was not present\n if (!s.endsWith(\"\\n\")) {\n builder.deleteCharAt(builder.length() - 1);\n }\n return builder.toString();\n } catch (IOException e) {\n /* ignore */\n }\n return s;\n }", "public static double elementMin( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a minimum.\n // Otherwise zero needs to be considered\n double min = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val < min ) {\n min = val;\n }\n }\n\n return min;\n }", "public static base_response update(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy updateresource = new responderpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.undefaction = resource.undefaction;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.logaction = resource.logaction;\n\t\tupdateresource.appflowaction = resource.appflowaction;\n\t\treturn updateresource.update_resource(client);\n\t}", "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }", "public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }", "@Override\n public final double getDouble(final String key) {\n Double result = optDouble(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "@SuppressWarnings(\"unchecked\") public final List<MapRow> getRows(String name)\n {\n return (List<MapRow>) getObject(name);\n }" ]
This handler will be triggered when there's no search result
[ "@Override\n public HandlerRegistration addSearchNoResultHandler(final SearchNoResultEvent.SearchNoResultHandler handler) {\n return addHandler(handler, SearchNoResultEvent.TYPE);\n }" ]
[ "@Override\n public void process(TestCaseResult context) {\n context.getParameters().add(new Parameter()\n .withName(getName())\n .withValue(getValue())\n .withKind(ParameterKind.valueOf(getKind()))\n );\n }", "String getQuery(String key)\n {\n String res = this.adapter.getSqlText(key);\n if (res == null)\n {\n throw new DatabaseException(\"Query \" + key + \" does not exist\");\n }\n return res;\n }", "public void updateBitmapShader() {\n\t\tif (image == null)\n\t\t\treturn;\n\n\t\tshader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\n\t\tif(canvasSize != image.getWidth() || canvasSize != image.getHeight()) {\n\t\t\tMatrix matrix = new Matrix();\n\t\t\tfloat scale = (float) canvasSize / (float) image.getWidth();\n\t\t\tmatrix.setScale(scale, scale);\n\t\t\tshader.setLocalMatrix(matrix);\n\t\t}\n\t}", "public void writeAuxiliaryTriples() throws RDFHandlerException {\n\t\tfor (PropertyRestriction pr : this.someValuesQueue) {\n\t\t\twriteSomeValueRestriction(pr.propertyUri, pr.rangeUri, pr.subject);\n\t\t}\n\t\tthis.someValuesQueue.clear();\n\n\t\tthis.valueRdfConverter.writeAuxiliaryTriples();\n\t}", "public Slice newSlice(long address, int size)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, 0, null);\n }", "public boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n LockEntry writer = getWriter(obj);\r\n if (writer == null)\r\n return false;\r\n else if (writer.isOwnedBy(tx))\r\n return true;\r\n else\r\n return false;\r\n }", "public String getName() {\n if (name == null && securityIdentity != null) {\n name = securityIdentity.getPrincipal().getName();\n }\n\n return name;\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 }", "public static String lookupIfEmpty( final String value,\n final Map<String, String> props,\n final String key ) {\n return value != null ? value : props.get(key);\n }" ]
Use this API to fetch all the dbdbprofile resources that are configured on netscaler.
[ "public static dbdbprofile[] get(nitro_service service) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tdbdbprofile[] response = (dbdbprofile[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }", "public static base_response update(nitro_service client, inatparam resource) throws Exception {\n\t\tinatparam updateresource = new inatparam();\n\t\tupdateresource.nat46v6prefix = resource.nat46v6prefix;\n\t\tupdateresource.nat46ignoretos = resource.nat46ignoretos;\n\t\tupdateresource.nat46zerochecksum = resource.nat46zerochecksum;\n\t\tupdateresource.nat46v6mtu = resource.nat46v6mtu;\n\t\tupdateresource.nat46fragheader = resource.nat46fragheader;\n\t\treturn updateresource.update_resource(client);\n\t}", "public String interpolate( String input, RecursionInterceptor recursionInterceptor )\n\t throws InterpolationException\n\t {\n\t try\n\t {\n\t return interpolate( input, recursionInterceptor, new HashSet<String>() );\n\t }\n\t finally\n\t {\n\t if ( !cacheAnswers )\n\t {\n\t existingAnswers.clear();\n\t }\n\t }\n\t }", "public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }", "protected void addRow(int uniqueID, Map<String, Object> map)\n {\n m_rows.put(Integer.valueOf(uniqueID), new MapRow(map));\n }", "public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);\r\n // materialize object only if FK fields are declared\r\n if(fks.length > 0) obj = ProxyHelper.getRealObject(obj);\r\n Object[] result = new Object[fks.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fmd = fks[i];\r\n PersistentField f = fmd.getPersistentField();\r\n\r\n // BRJ: do NOT convert.\r\n // conversion is done when binding the sql-statement\r\n //\r\n // FieldConversion fc = fmd.getFieldConversion();\r\n // Object val = fc.javaToSql(f.get(obj));\r\n\r\n result[i] = f.get(obj);\r\n }\r\n return result;\r\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 }", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }", "String getStatusHelp(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_HELP_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_HELP_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_HELP_0);\n }\n long lastLogin = user.getLastlogin();\n return CmsVaadinUtils.getMessageText(\n Messages.GUI_USERMANAGEMENT_USER_ACTIVE_HELP_1,\n CmsDateUtil.getDateTime(new Date(lastLogin), DateFormat.SHORT, A_CmsUI.get().getLocale()));\n }" ]
Checks to see if all the provided matrices are the expected size for an SVD. If an error is encountered then an exception is thrown. This automatically handles compact and non-compact formats
[ "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 }" ]
[ "private static EndpointReferenceType createEPR(String address, SLProperties props) {\n EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address);\n if (props != null) {\n addProperties(epr, props);\n }\n return epr;\n }", "@Override\n\tpublic synchronized boolean fireEventAndWait(Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, NoSuchElementException, InterruptedException {\n\t\ttry {\n\n\t\t\tboolean handleChanged = false;\n\t\t\tboolean result = false;\n\n\t\t\tif (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals(\"\")) {\n\t\t\t\tLOGGER.debug(\"switching to frame: \" + eventable.getRelatedFrame());\n\t\t\t\ttry {\n\n\t\t\t\t\tswitchToFrame(eventable.getRelatedFrame());\n\t\t\t\t} catch (NoSuchFrameException e) {\n\t\t\t\t\tLOGGER.debug(\"Frame not found, possibly while back-tracking..\", e);\n\t\t\t\t\t// TODO Stefan, This exception is caught to prevent stopping\n\t\t\t\t\t// from working\n\t\t\t\t\t// This was the case on the Gmail case; find out if not switching\n\t\t\t\t\t// (catching)\n\t\t\t\t\t// Results in good performance...\n\t\t\t\t}\n\t\t\t\thandleChanged = true;\n\t\t\t}\n\n\t\t\tWebElement webElement =\n\t\t\t\t\tbrowser.findElement(eventable.getIdentification().getWebDriverBy());\n\n\t\t\tif (webElement != null) {\n\t\t\t\tresult = fireEventWait(webElement, eventable);\n\t\t\t}\n\n\t\t\tif (handleChanged) {\n\t\t\t\tbrowser.switchTo().defaultContent();\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tthrow e;\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\treturn false;\n\t\t}\n\t}", "@SuppressWarnings(\"unchecked\")\n public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> \n wrapperProvider) {\n \n return (V3) m_up;\n }", "public void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }", "public void search(String query) {\n final Query newQuery = searcher.getQuery().setQuery(query);\n searcher.setQuery(newQuery).search();\n }", "@SuppressWarnings(\"unused\")\n\t@XmlID\n @XmlAttribute(name = \"id\")\n private String getXmlID(){\n return String.format(\"%s-%s\", this.getClass().getSimpleName(), Long.valueOf(id));\n }", "private ServerSetup[] createServerSetup() {\n List<ServerSetup> setups = new ArrayList<>();\n if (smtpProtocol) {\n smtpServerSetup = createTestServerSetup(ServerSetup.SMTP);\n setups.add(smtpServerSetup);\n }\n if (smtpsProtocol) {\n smtpsServerSetup = createTestServerSetup(ServerSetup.SMTPS);\n setups.add(smtpsServerSetup);\n }\n if (pop3Protocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3));\n }\n if (pop3sProtocol) {\n setups.add(createTestServerSetup(ServerSetup.POP3S));\n }\n if (imapProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAP));\n }\n if (imapsProtocol) {\n setups.add(createTestServerSetup(ServerSetup.IMAPS));\n }\n return setups.toArray(new ServerSetup[setups.size()]);\n }", "private static String wordShapeDigits(final String s) {\r\n char[] outChars = null;\r\n\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (Character.isDigit(c)) {\r\n if (outChars == null) {\r\n outChars = s.toCharArray();\r\n }\r\n outChars[i] = '9';\r\n }\r\n }\r\n if (outChars == null) {\r\n // no digit found\r\n return s;\r\n } else {\r\n return new String(outChars);\r\n }\r\n }", "void resetCurrentRevisionData() {\n\t\tthis.revisionId = NO_REVISION_ID; // impossible as an id in MediaWiki\n\t\tthis.parentRevisionId = NO_REVISION_ID;\n\t\tthis.text = null;\n\t\tthis.comment = null;\n\t\tthis.format = null;\n\t\tthis.timeStamp = null;\n\t\tthis.model = null;\n\t}" ]
Attempts to detect the provided pattern as an exact match. @param pattern the pattern to find in the reader stream @return the number of times the pattern is found, or an error code @throws MalformedPatternException if the pattern is invalid @throws Exception if a generic error is encountered
[ "public int expect(String pattern) throws MalformedPatternException, Exception {\n logger.trace(\"Searching for '\" + pattern + \"' in the reader stream\");\n return expect(pattern, null);\n }" ]
[ "public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }", "public void logout() {\n String userIdentifier = session.get(config().sessionKeyUsername());\n SessionManager sessionManager = app().sessionManager();\n sessionManager.logout(session);\n if (S.notBlank(userIdentifier)) {\n app().eventBus().trigger(new LogoutEvent(userIdentifier));\n }\n }", "private FilePath copyClassWorldsFile(FilePath ws, URL resource) {\n try {\n FilePath remoteClassworlds =\n ws.createTextTempFile(\"classworlds\", \"conf\", \"\");\n remoteClassworlds.copyFrom(resource);\n return remoteClassworlds;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) {\n return find(project, type) != null;\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 logBinaryStringInfo(StringBuilder binaryString) {\n\n encodeInfo += \"Binary Length: \" + binaryString.length() + \"\\n\";\n encodeInfo += \"Binary String: \";\n\n int nibble = 0;\n for (int i = 0; i < binaryString.length(); i++) {\n switch (i % 4) {\n case 0:\n if (binaryString.charAt(i) == '1') {\n nibble += 8;\n }\n break;\n case 1:\n if (binaryString.charAt(i) == '1') {\n nibble += 4;\n }\n break;\n case 2:\n if (binaryString.charAt(i) == '1') {\n nibble += 2;\n }\n break;\n case 3:\n if (binaryString.charAt(i) == '1') {\n nibble += 1;\n }\n encodeInfo += Integer.toHexString(nibble);\n nibble = 0;\n break;\n }\n }\n\n if ((binaryString.length() % 4) != 0) {\n encodeInfo += Integer.toHexString(nibble);\n }\n\n encodeInfo += \"\\n\";\n }", "public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }", "public LayoutParams getLayoutParams() {\n if (mLayoutParams == null) {\n mLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n }\n return mLayoutParams;\n }", "public static Span exact(Bytes row) {\n Objects.requireNonNull(row);\n return new Span(row, true, row, true);\n }" ]
Retrieves the GC timestamp, set by the Oracle, from zookeeper @param zookeepers Zookeeper connection string @return Oldest active timestamp or oldest possible ts (-1) if not found
[ "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 }" ]
[ "@SuppressWarnings(\"unused\")\n private void setTextureNumber(int type, int number) {\n m_numTextures.put(AiTextureType.fromRawValue(type), number);\n }", "public History[] refreshHistory(int limit, int offset) throws Exception {\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"limit\", String.valueOf(limit)),\n new BasicNameValuePair(\"offset\", String.valueOf(offset))\n };\n return constructHistory(params);\n }", "public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }", "public void addFile(InputStream inputStream) {\n String name = \"file\";\n fileStreams.put(normalizeDuplicateName(name), inputStream);\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 }", "protected DatabaseConnection getSavedConnection() {\n\t\tNestedConnection nested = specialConnection.get();\n\t\tif (nested == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn nested.connection;\n\t\t}\n\t}", "public EventsRequest<Event> get(String resource, String sync) {\n return new EventsRequest<Event>(this, Event.class, \"/events\", \"GET\")\n .query(\"resource\", resource)\n .query(\"sync\", sync);\n }", "private void loadLibraryFromStream(String libname, InputStream is) {\r\n try {\r\n File tempfile = createTempFile(libname);\r\n OutputStream os = new FileOutputStream(tempfile);\r\n\r\n logger.debug(\"tempfile.getPath() = \" + tempfile.getPath());\r\n\r\n long savedTime = System.currentTimeMillis();\r\n\r\n // Leo says 8k block size is STANDARD ;)\r\n byte buf[] = new byte[8192];\r\n int len;\r\n while ((len = is.read(buf)) > 0) {\r\n os.write(buf, 0, len);\r\n }\r\n\r\n os.flush();\r\n InputStream lock = new FileInputStream(tempfile);\r\n os.close();\r\n\r\n double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;\r\n logger.debug(\"Copying took \" + seconds + \" seconds.\");\r\n\r\n logger.debug(\"Loading library from \" + tempfile.getPath() + \".\");\r\n System.load(tempfile.getPath());\r\n\r\n lock.close();\r\n } catch (IOException io) {\r\n logger.error(\"Could not create the temp file: \" + io.toString() + \".\\n\");\r\n } catch (UnsatisfiedLinkError ule) {\r\n logger.error(\"Couldn't load copied link file: \" + ule.toString() + \".\\n\");\r\n throw ule;\r\n }\r\n }", "public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType,\n Class<V> valueType) {\n return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(),\n valueType));\n }" ]
Read a Synchro string from an input stream. @param is input stream @return String instance
[ "public static final String getString(InputStream is) throws IOException\n {\n int type = is.read();\n if (type != 1)\n {\n throw new IllegalArgumentException(\"Unexpected string format\");\n }\n\n Charset charset = CharsetHelper.UTF8;\n \n int length = is.read();\n if (length == 0xFF)\n {\n length = getShort(is);\n if (length == 0xFFFE)\n {\n charset = CharsetHelper.UTF16LE;\n length = (is.read() * 2);\n }\n }\n\n String result;\n if (length == 0)\n {\n result = null;\n }\n else\n {\n byte[] stringData = new byte[length]; \n is.read(stringData);\n result = new String(stringData, charset);\n }\n return result;\n }" ]
[ "public final void setValue(String value) {\n\n if ((null == value) || value.isEmpty()) {\n setDefaultValue();\n } else {\n try {\n tryToSetParsedValue(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n CmsDebugLog.consoleLog(\"Could not set invalid serial date value: \" + value);\n setDefaultValue();\n }\n }\n notifyOnValueChange();\n }", "public 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}", "private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {\n long now = System.nanoTime();\n return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >\n slack.get();\n }", "private Class<?> beanType(String name) {\n\t\tClass<?> type = context.getType(name);\n\t\tif (ClassUtils.isCglibProxyClass(type)) {\n\t\t\treturn AopProxyUtils.ultimateTargetClass(context.getBean(name));\n\t\t}\n\t\treturn type;\n\t}", "protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n \r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n \r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading schemas for catalog \" \r\n + this.getAttribute(ATT_CATALOG_NAME));\r\n rs = getDbMeta().getSchemas();\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n int count = 0;\r\n while (rs.next())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Creating schema \" + getCatalogName() + \".\" + rs.getString(\"TABLE_SCHEM\"));\r\n alNew.add(new DBMetaSchemaNode(getDbMeta(),\r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, \r\n rs.getString(\"TABLE_SCHEM\")));\r\n count++;\r\n }\r\n if (count == 0) \r\n alNew.add(new DBMetaSchemaNode(getDbMeta(), \r\n getDbMetaTreeModel(),\r\n DBMetaCatalogNode.this, null));\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving schemas\", sqlEx2);\r\n } \r\n return false;\r\n }\r\n return true;\r\n }", "private byte[] getBytes(String value, boolean unicode)\n {\n byte[] result;\n if (unicode)\n {\n int start = 0;\n // Get the bytes in UTF-16\n byte[] bytes;\n\n try\n {\n bytes = value.getBytes(\"UTF-16\");\n }\n catch (UnsupportedEncodingException e)\n {\n bytes = value.getBytes();\n }\n\n if (bytes.length > 2 && bytes[0] == -2 && bytes[1] == -1)\n {\n // Skip the unicode identifier\n start = 2;\n }\n result = new byte[bytes.length - start];\n for (int loop = start; loop < bytes.length - 1; loop += 2)\n {\n // Swap the order here\n result[loop - start] = bytes[loop + 1];\n result[loop + 1 - start] = bytes[loop];\n }\n }\n else\n {\n result = new byte[value.length() + 1];\n System.arraycopy(value.getBytes(), 0, result, 0, value.length());\n }\n return (result);\n }", "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}", "public static File createTempDirectory(String prefix) {\n\tFile temp = null;\n\t\n\ttry {\n\t temp = File.createTempFile(prefix != null ? prefix : \"temp\", Long.toString(System.nanoTime()));\n\t\n\t if (!(temp.delete())) {\n\t throw new IOException(\"Could not delete temp file: \"\n\t\t + temp.getAbsolutePath());\n\t }\n\t\n\t if (!(temp.mkdir())) {\n\t throw new IOException(\"Could not create temp directory: \"\n\t + temp.getAbsolutePath());\n\t }\n\t} catch (IOException e) {\n\t throw new DukeException(\"Unable to create temporary directory with prefix \" + prefix, e);\n\t}\n\t\n\treturn temp;\n }", "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}" ]
Removes all candidates from this collection which are not associated with an initialising method. @return a {@code Collection} containing the removed unassociated candidates. This list is empty if none were removed, i. e. the result is never {@code null}.
[ "public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() {\n final List<FieldNode> result = new ArrayList<FieldNode>();\n for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) {\n final Initialisers setters = entry.getValue();\n final List<MethodNode> initialisingMethods = setters.getMethods();\n if (initialisingMethods.isEmpty()) {\n result.add(entry.getKey());\n }\n }\n for (final FieldNode unassociatedVariable : result) {\n candidatesAndInitialisers.remove(unassociatedVariable);\n }\n return result;\n }" ]
[ "private synchronized void finishTransition(final InternalState current, final InternalState next) {\n internalSetState(getTransitionTask(next), current, next);\n transition();\n }", "final void compress(final File backupFile,\n final AppenderRollingProperties properties) {\n if (this.isCompressed(backupFile)) {\n LogLog.debug(\"Backup log file \" + backupFile.getName()\n + \" is already compressed\");\n return; // try not to do unnecessary work\n }\n final long lastModified = backupFile.lastModified();\n if (0L == lastModified) {\n LogLog.debug(\"Backup log file \" + backupFile.getName()\n + \" may have been scavenged\");\n return; // backup file may have been scavenged\n }\n final File deflatedFile = this.createDeflatedFile(backupFile);\n if (deflatedFile == null) {\n LogLog.debug(\"Backup log file \" + backupFile.getName()\n + \" may have been scavenged\");\n return; // an error occurred creating the file\n }\n if (this.compress(backupFile, deflatedFile, properties)) {\n deflatedFile.setLastModified(lastModified);\n FileHelper.getInstance().deleteExisting(backupFile);\n LogLog.debug(\"Compressed backup log file to \" + deflatedFile.getName());\n } else {\n FileHelper.getInstance().deleteExisting(deflatedFile); // clean up\n LogLog\n .debug(\"Unable to compress backup log file \" + backupFile.getName());\n }\n }", "@Override\n public void detachScriptFile(IScriptable target) {\n IScriptFile scriptFile = mScriptMap.remove(target);\n if (scriptFile != null) {\n scriptFile.invokeFunction(\"onDetach\", new Object[] { target });\n }\n }", "public void put(final K key, V value) {\n ManagedReference<V> ref = new ManagedReference<V>(bundle, value) {\n @Override\n public void finalizeReference() {\n super.finalizeReference();\n internalMap.remove(key, get());\n }\n };\n internalMap.put(key, ref);\n }", "private String getResourceType(Resource resource)\n {\n String result;\n net.sf.mpxj.ResourceType type = resource.getType();\n if (type == null)\n {\n type = net.sf.mpxj.ResourceType.WORK;\n }\n\n switch (type)\n {\n case MATERIAL:\n {\n result = \"Material\";\n break;\n }\n\n case COST:\n {\n result = \"Nonlabor\";\n break;\n }\n\n default:\n {\n result = \"Labor\";\n break;\n }\n }\n\n return result;\n }", "public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }", "public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnd6ravariables updateresources[] = new nd6ravariables[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nd6ravariables();\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].ceaserouteradv = resources[i].ceaserouteradv;\n\t\t\t\tupdateresources[i].sendrouteradv = resources[i].sendrouteradv;\n\t\t\t\tupdateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption;\n\t\t\t\tupdateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse;\n\t\t\t\tupdateresources[i].managedaddrconfig = resources[i].managedaddrconfig;\n\t\t\t\tupdateresources[i].otheraddrconfig = resources[i].otheraddrconfig;\n\t\t\t\tupdateresources[i].currhoplimit = resources[i].currhoplimit;\n\t\t\t\tupdateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval;\n\t\t\t\tupdateresources[i].minrtadvinterval = resources[i].minrtadvinterval;\n\t\t\t\tupdateresources[i].linkmtu = resources[i].linkmtu;\n\t\t\t\tupdateresources[i].reachabletime = resources[i].reachabletime;\n\t\t\t\tupdateresources[i].retranstime = resources[i].retranstime;\n\t\t\t\tupdateresources[i].defaultlifetime = resources[i].defaultlifetime;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private Path getTempDir() {\n if (this.tempDir == null) {\n if (this.dir != null) {\n this.tempDir = dir;\n } else {\n this.tempDir = getProject().getBaseDir().toPath();\n }\n }\n return tempDir;\n }", "private void bumpScores(Map<Long, Score> candidates,\n List<Bucket> buckets,\n int ix) {\n for (; ix < buckets.size(); ix++) {\n Bucket b = buckets.get(ix);\n if (b.nextfree > CUTOFF_FACTOR_2 * candidates.size())\n return;\n double score = b.getScore();\n for (Score s : candidates.values())\n if (b.contains(s.id))\n s.score += score;\n }\n }" ]
This method is used to associate a child task with the current task instance. It has been designed to allow the hierarchical outline structure of tasks in an MPX file to be updated once all of the task data has been read. @param child child task
[ "public void addChildTask(Task child)\n {\n child.m_parent = this;\n m_children.add(child);\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }" ]
[ "public CurrencyQueryBuilder setCurrencyCodes(String... codes) {\n return set(CurrencyQuery.KEY_QUERY_CURRENCY_CODES, Arrays.asList(codes));\n }", "public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\ttry {\n\t\t\t// there is always and id field as an argument so just return 0 lines updated\n\t\t\tif (argFieldTypes.length <= 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tObject[] args = getFieldObjects(data);\n\t\t\tObject newVersion = null;\n\t\t\tif (versionFieldType != null) {\n\t\t\t\tnewVersion = versionFieldType.extractJavaFieldValue(data);\n\t\t\t\tnewVersion = versionFieldType.moveToNextValue(newVersion);\n\t\t\t\targs[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);\n\t\t\t}\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (newVersion != null) {\n\t\t\t\t\t// if we have updated a row then update the version field in our object to the new value\n\t\t\t\t\tversionFieldType.assignField(connectionSource, data, newVersion, false, null);\n\t\t\t\t}\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\t// if we've changed something then see if we need to update our cache\n\t\t\t\t\tObject id = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT cachedData = objectCache.get(clazz, id);\n\t\t\t\t\tif (cachedData != null && cachedData != data) {\n\t\t\t\t\t\t// copy each field from the updated data into the cached object\n\t\t\t\t\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t\t\t\t\tif (fieldType != idField) {\n\t\t\t\t\t\t\t\tfieldType.assignField(connectionSource, cachedData,\n\t\t\t\t\t\t\t\t\t\tfieldType.extractJavaFieldValue(data), false, objectCache);\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\t\t\tlogger.debug(\"update data with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"update arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}", "public void updateIteratorPosition(int length) {\n if(length > 0) {\n //make sure we dont go OB\n if((length + character) > parsedLine.line().length())\n length = parsedLine.line().length() - character;\n\n //move word counter to the correct word\n while(hasNextWord() &&\n (length + character) >= parsedLine.words().get(word).lineIndex() +\n parsedLine.words().get(word).word().length())\n word++;\n\n character = length + character;\n }\n else\n throw new IllegalArgumentException(\"The length given must be > 0 and not exceed the boundary of the line (including the current position)\");\n }", "public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }", "public void recordCheckoutQueueLength(SocketDestination dest, int queueLength) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutQueueLength(null, queueLength);\n recordCheckoutQueueLength(null, queueLength);\n } else {\n this.checkoutQueueLengthHistogram.insert(queueLength);\n checkMonitoringInterval();\n }\n }", "public static final Date parseFinishDateTime(String value)\n {\n Date result = parseDateTime(value);\n if (result != null)\n {\n result = DateHelper.addDays(result, -1);\n }\n return result;\n }", "private static void writeCharSequence(CharSequence seq, CharBuf buffer) {\n if (seq.length() > 0) {\n buffer.addJsonEscapedString(seq.toString());\n } else {\n buffer.addChars(EMPTY_STRING_CHARS);\n }\n }", "public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) {\n return create(factory, new ResourcePoolConfig());\n }", "public void printInferredRelations(ClassDoc c) {\n\t// check if the source is excluded from inference\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\n\tfor (FieldDoc field : c.fields(false)) {\n\t if(hidden(field))\n\t\tcontinue;\n\t // skip statics\n\t if(field.isStatic())\n\t\tcontinue;\n\t // skip primitives\n\t FieldRelationInfo fri = getFieldRelationInfo(field);\n\t if (fri == null)\n\t\tcontinue;\n\t // check if the destination is excluded from inference\n\t if (hidden(fri.cd))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fri.cd.toString());\n\t if (rp == null) {\n\t\tString destAdornment = fri.multiple ? \"*\" : \"\";\n\t\trelation(opt, opt.inferRelationshipType, c, fri.cd, \"\", \"\", destAdornment);\n }\n\t}\n }" ]
Creates a style definition used for pages. @return The page style definition.
[ "protected NodeData createPageStyle()\n {\n NodeData ret = createBlockStyle();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"position\", tf.createIdent(\"relative\")));\n\t\tret.push(createDeclaration(\"border-width\", tf.createLength(1f, Unit.px)));\n\t\tret.push(createDeclaration(\"border-style\", tf.createIdent(\"solid\")));\n\t\tret.push(createDeclaration(\"border-color\", tf.createColor(0, 0, 255)));\n\t\tret.push(createDeclaration(\"margin\", tf.createLength(0.5f, Unit.em)));\n\t\t\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n ret.push(createDeclaration(\"width\", tf.createLength(w, unit)));\n ret.push(createDeclaration(\"height\", tf.createLength(h, unit)));\n }\n else\n log.warn(\"No media box found\");\n \n return ret;\n }" ]
[ "public final void notifyFooterItemChanged(int position) {\n if (position < 0 || position >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount + contentItemCount);\n }", "private void parse(String header)\n {\n ArrayList<String> list = new ArrayList<String>(4);\n StringBuilder sb = new StringBuilder();\n int index = 1;\n while (index < header.length())\n {\n char c = header.charAt(index++);\n if (Character.isDigit(c))\n {\n sb.append(c);\n }\n else\n {\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n sb.setLength(0);\n }\n }\n }\n\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n }\n\n m_id = list.get(0);\n m_sequence = Integer.parseInt(list.get(1));\n m_type = Integer.valueOf(list.get(2));\n if (list.size() > 3)\n {\n m_subtype = Integer.parseInt(list.get(3));\n }\n }", "private List<TimephasedCost> getTimephasedCostFixedAmount()\n {\n List<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n ProjectCalendar cal = getCalendar();\n\n double remainingCost = getRemainingCost().doubleValue();\n\n if (remainingCost > 0)\n {\n AccrueType accrueAt = getResource().getAccrueAt();\n\n if (accrueAt == AccrueType.START)\n {\n result.add(splitCostStart(cal, remainingCost, getStart()));\n }\n else\n if (accrueAt == AccrueType.END)\n {\n result.add(splitCostEnd(cal, remainingCost, getFinish()));\n }\n else\n {\n //for prorated, we have to deal with it differently depending on whether or not\n //any actual has been entered, since we want to mimic the other timephased data\n //where planned and actual values do not overlap\n double numWorkingDays = cal.getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();\n double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;\n\n if (getActualCost().intValue() > 0)\n {\n //need to get three possible blocks of data: one for the possible partial amount\n //overlap with timephased actual cost; one with all the standard amount days\n //that happen after the actual cost stops; and one with any remaining\n //partial day cost amount\n\n int numActualDaysUsed = (int) Math.ceil(getActualCost().doubleValue() / standardAmountPerDay);\n Date actualWorkFinish = cal.getDate(getStart(), Duration.getInstance(numActualDaysUsed, TimeUnit.DAYS), false);\n\n double partialDayActualAmount = getActualCost().doubleValue() % standardAmountPerDay;\n\n if (partialDayActualAmount > 0)\n {\n double dayAmount = standardAmountPerDay < remainingCost ? standardAmountPerDay - partialDayActualAmount : remainingCost;\n\n result.add(splitCostEnd(cal, dayAmount, actualWorkFinish));\n\n remainingCost -= dayAmount;\n }\n\n //see if there's anything left to work with\n if (remainingCost > 0)\n {\n //have to split up the amount into standard prorated amount days and whatever is left\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, cal.getNextWorkStart(actualWorkFinish)));\n }\n\n }\n else\n {\n //no actual cost to worry about, so just a standard split from the beginning of the assignment\n result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, getStart()));\n }\n }\n }\n\n return result;\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 Set<Annotation> getPropertyAnnotations()\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn unmodifiableSet(((PropertyAwareAccessor) accessor).getReadMethodAnnotations());\n\t\t}\n\t\treturn unmodifiableSet(Collections.<Annotation>emptySet());\n\t}", "public void setNewCenterColor(int color) {\n\t\tmCenterNewColor = color;\n\t\tmCenterNewPaint.setColor(color);\n\t\tif (mCenterOldColor == 0) {\n\t\t\tmCenterOldColor = color;\n\t\t\tmCenterOldPaint.setColor(color);\n\t\t}\n\t\tif (onColorChangedListener != null && color != oldChangedListenerColor ) {\n\t\t\tonColorChangedListener.onColorChanged(color);\n\t\t\toldChangedListenerColor = color;\n\t\t}\n\t\tinvalidate();\n\t}", "public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }", "private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)\n {\n AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);\n if (ruleProvider == null)\n return;\n\n if (!timeTakenByProvider.containsKey(ruleProvider))\n {\n RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)\n .create();\n model.setRuleIndex(ruleIndex);\n model.setRuleProviderID(ruleProvider.getMetadata().getID());\n model.setTimeTaken(timeTaken);\n\n timeTakenByProvider.put(ruleProvider, model.getElement().id());\n }\n else\n {\n RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);\n RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);\n }", "public EventBus emitAsync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }" ]
Get a sub-list of this list @param fromIndex index of the first element in the sub-list (inclusive) @param toIndex index of the last element in the sub-list (inclusive) @return the sub-list
[ "public List<String> subList(final long fromIndex, final long toIndex) {\n return doWithJedis(new JedisCallable<List<String>>() {\n @Override\n public List<String> call(Jedis jedis) {\n return jedis.lrange(getKey(), fromIndex, toIndex);\n }\n });\n }" ]
[ "public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}", "private void removeObsoleteElements(List<String> names,\n Map<String, View> sharedElements,\n List<String> elementsToRemove) {\n if (elementsToRemove.size() > 0) {\n names.removeAll(elementsToRemove);\n for (String elementToRemove : elementsToRemove) {\n sharedElements.remove(elementToRemove);\n }\n }\n }", "public static authenticationnegotiatepolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tauthenticationnegotiatepolicy_binding obj = new authenticationnegotiatepolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationnegotiatepolicy_binding response = (authenticationnegotiatepolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void processOperandValue(int index, FieldType type, GraphicalIndicatorCriteria criteria)\n {\n boolean valueFlag = (MPPUtility.getInt(m_data, m_dataOffset) == 1);\n m_dataOffset += 4;\n\n if (valueFlag == false)\n {\n int fieldID = MPPUtility.getInt(m_data, m_dataOffset);\n criteria.setRightValue(index, FieldTypeHelper.getInstance(fieldID));\n m_dataOffset += 4;\n }\n else\n {\n //int dataTypeValue = MPPUtility.getShort(m_data, m_dataOffset);\n m_dataOffset += 2;\n\n switch (type.getDataType())\n {\n case DURATION: // 0x03\n {\n Duration value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(m_data, m_dataOffset), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(m_data, m_dataOffset + 4)));\n m_dataOffset += 6;\n criteria.setRightValue(index, value);\n break;\n }\n\n case NUMERIC: // 0x05\n {\n Double value = Double.valueOf(MPPUtility.getDouble(m_data, m_dataOffset));\n m_dataOffset += 8;\n criteria.setRightValue(index, value);\n break;\n }\n\n case CURRENCY: // 0x06\n {\n Double value = Double.valueOf(MPPUtility.getDouble(m_data, m_dataOffset) / 100);\n m_dataOffset += 8;\n criteria.setRightValue(index, value);\n break;\n }\n\n case STRING: // 0x08\n {\n String value = MPPUtility.getUnicodeString(m_data, m_dataOffset);\n m_dataOffset += ((value.length() + 1) * 2);\n criteria.setRightValue(index, value);\n break;\n }\n\n case BOOLEAN: // 0x0B\n {\n int value = MPPUtility.getShort(m_data, m_dataOffset);\n m_dataOffset += 2;\n criteria.setRightValue(index, value == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE: // 0x13\n {\n Date value = MPPUtility.getTimestamp(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setRightValue(index, value);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n }", "private void ensureCollectionClass(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF))\r\n {\r\n // an array cannot have a collection-class specified \r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS))\r\n {\r\n throw new ConstraintException(\"Collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is an array but does specify collection-class\");\r\n }\r\n else\r\n {\r\n // no further processing necessary as its an array\r\n return;\r\n }\r\n }\r\n\r\n if (CHECKLEVEL_STRICT.equals(checkLevel))\r\n { \r\n InheritanceHelper helper = new InheritanceHelper();\r\n ModelDef model = (ModelDef)collDef.getOwner().getOwner();\r\n String specifiedClass = collDef.getProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS);\r\n String variableType = collDef.getProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE);\r\n \r\n try\r\n {\r\n if (specifiedClass != null)\r\n {\r\n // if we have a specified class then it has to implement the manageable collection and be a sub type of the variable type\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, variableType))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" is not a sub type of the variable type \"+variableType);\r\n }\r\n if (!helper.isSameOrSubTypeOf(specifiedClass, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The type \"+specifiedClass+\" specified as collection-class of the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement \"+MANAGEABLE_COLLECTION_INTERFACE);\r\n }\r\n }\r\n else\r\n {\r\n // no collection class specified so the variable type has to be a collection type\r\n if (helper.isSameOrSubTypeOf(variableType, MANAGEABLE_COLLECTION_INTERFACE))\r\n {\r\n // we can specify it as a collection-class as it is an manageable collection\r\n collDef.setProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS, variableType);\r\n }\r\n else if (!helper.isSameOrSubTypeOf(variableType, JAVA_COLLECTION_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" needs the collection-class attribute as its variable type does not implement \"+JAVA_COLLECTION_INTERFACE);\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName());\r\n }\r\n }\r\n }", "private String getNotes(List<MapRow> rows)\n {\n String result = null;\n if (rows != null && !rows.isEmpty())\n {\n StringBuilder sb = new StringBuilder();\n for (MapRow row : rows)\n {\n sb.append(row.getString(\"TITLE\"));\n sb.append('\\n');\n sb.append(row.getString(\"TEXT\"));\n sb.append(\"\\n\\n\");\n }\n result = sb.toString();\n }\n return result;\n }", "@Deprecated\n public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT) {\n return findByIndex(selectorJson, classOfT, new FindByIndexOptions());\n }", "public String userAgent() {\n return String.format(\"Azure-SDK-For-Java/%s OS:%s MacAddressHash:%s Java:%s\",\n getClass().getPackage().getImplementationVersion(),\n OS,\n MAC_ADDRESS_HASH,\n JAVA_VERSION);\n }", "protected Class<?> getPropertyClass(ClassMetadata meta, String propertyName) throws HibernateLayerException {\n\t\t// try to assure the correct separator is used\n\t\tpropertyName = propertyName.replace(XPATH_SEPARATOR, SEPARATOR);\n\n\t\tif (propertyName.contains(SEPARATOR)) {\n\t\t\tString directProperty = propertyName.substring(0, propertyName.indexOf(SEPARATOR));\n\t\t\ttry {\n\t\t\t\tType prop = meta.getPropertyType(directProperty);\n\t\t\t\tif (prop.isCollectionType()) {\n\t\t\t\t\tCollectionType coll = (CollectionType) prop;\n\t\t\t\t\tprop = coll.getElementType((SessionFactoryImplementor) sessionFactory);\n\t\t\t\t}\n\t\t\t\tClassMetadata propMeta = sessionFactory.getClassMetadata(prop.getReturnedClass());\n\t\t\t\treturn getPropertyClass(propMeta, propertyName.substring(propertyName.indexOf(SEPARATOR) + 1));\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn meta.getPropertyType(propertyName).getReturnedClass();\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t}\n\t}" ]
Creates a window visually showing the matrix's state. Block means an element is zero. Red positive and blue negative. More intense the color larger the element's absolute value is. @param A A matrix. @param title Name of the window.
[ "public static void show(DMatrixD1 A , String title ) {\n JFrame frame = new JFrame(title);\n\n int width = 300;\n int height = 300;\n\n if( A.numRows > A.numCols) {\n width = width*A.numCols/A.numRows;\n } else {\n height = height*A.numRows/A.numCols;\n }\n\n DMatrixComponent panel = new DMatrixComponent(width,height);\n panel.setMatrix(A);\n\n frame.add(panel, BorderLayout.CENTER);\n\n frame.pack();\n frame.setVisible(true);\n\n }" ]
[ "private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }", "public boolean getBooleanProperty(String name, boolean defaultValue)\r\n {\r\n return PropertyHelper.toBoolean(_properties.getProperty(name), defaultValue);\r\n }", "public final Iterator<AbstractTraceRegion> leafIterator() {\n\t\tif (nestedRegions == null)\n\t\t\treturn Collections.<AbstractTraceRegion> singleton(this).iterator();\n\t\treturn new LeafIterator(this);\n\t}", "protected void writePropertiesToLog(Logger logger, Level level) {\n writeToLog(logger, level, getMapAsString(this.properties, separator), null);\n\n if (this.exception != null) {\n writeToLog(this.logger, Level.ERROR, \"Error:\", this.exception);\n }\n }", "public static int getNavigationBarHeight(Context context) {\n Resources resources = context.getResources();\n int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? \"navigation_bar_height\" : \"navigation_bar_height_landscape\", \"dimen\", \"android\");\n if (id > 0) {\n return resources.getDimensionPixelSize(id);\n }\n return 0;\n }", "public static base_responses delete(nitro_service client, String selectorname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tcacheselector deleteresources[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tdeleteresources[i] = new cacheselector();\n\t\t\t\tdeleteresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static boolean isOperationDefined(final ModelNode operation) {\n for (final AttributeDefinition def : ROOT_ATTRIBUTES) {\n if (operation.hasDefined(def.getName())) {\n return true;\n }\n }\n return false;\n }", "private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }", "public static void skip(InputStream stream, long skip) throws IOException\n {\n long count = skip;\n while (count > 0)\n {\n count -= stream.skip(count);\n }\n }" ]
Use this API to delete dnsview of given name.
[ "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}" ]
[ "private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }", "public synchronized void addListener(MaterializationListener listener)\r\n\t{\r\n\t\tif (_listeners == null)\r\n\t\t{\r\n\t\t\t_listeners = new ArrayList();\r\n\t\t}\r\n\t\t// add listener only once\r\n\t\tif (!_listeners.contains(listener))\r\n\t\t{\r\n\t\t\t_listeners.add(listener);\r\n\t\t}\r\n\t}", "@SuppressWarnings(\"unchecked\")\r\n public static <E> E[] filter(E[] elems, Filter<E> filter) {\r\n List<E> filtered = new ArrayList<E>();\r\n for (E elem: elems) {\r\n if (filter.accept(elem)) {\r\n filtered.add(elem);\r\n }\r\n }\r\n return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));\r\n }", "protected boolean isTransient(ClassDescriptor cld, Object obj, Identity oid)\r\n {\r\n // if the Identity is transient we assume a non-persistent object\r\n boolean isNew = oid != null && oid.isTransient();\r\n /*\r\n detection of new objects is costly (select of ID in DB to check if object\r\n already exists) we do:\r\n a. check if the object has nullified PK field\r\n b. check if the object is already registered\r\n c. lookup from cache and if not found, last option select on DB\r\n */\r\n if(!isNew)\r\n {\r\n final PersistenceBroker pb = getBroker();\r\n if(cld == null)\r\n {\r\n cld = pb.getClassDescriptor(obj.getClass());\r\n }\r\n isNew = pb.serviceBrokerHelper().hasNullPKField(cld, obj);\r\n if(!isNew)\r\n {\r\n if(oid == null)\r\n {\r\n oid = pb.serviceIdentity().buildIdentity(cld, obj);\r\n }\r\n final ObjectEnvelope mod = objectEnvelopeTable.getByIdentity(oid);\r\n if(mod != null)\r\n {\r\n // already registered object, use current state\r\n isNew = mod.needsInsert();\r\n }\r\n else\r\n {\r\n // if object was found cache, assume it's old\r\n // else make costly check against the DB\r\n isNew = pb.serviceObjectCache().lookup(oid) == null\r\n && !pb.serviceBrokerHelper().doesExist(cld, oid, obj);\r\n }\r\n }\r\n }\r\n return isNew;\r\n }", "public void populateContainer(Class<? extends FieldType> type, FieldContainer container, Integer id, byte[][] fixedData, Var2Data varData)\n {\n //System.out.println(container.getClass().getSimpleName()+\": \" + id);\n for (FieldItem item : m_map.values())\n {\n if (item.getType().getClass().equals(type))\n {\n //System.out.println(item.m_type);\n Object value = item.read(id, fixedData, varData);\n //System.out.println(item.m_type.getClass().getSimpleName() + \".\" + item.m_type + \": \" + value);\n container.set(item.getType(), value);\n }\n }\n }", "public void setHeader(String header, String value) {\n StringValidator.throwIfEmptyOrNull(\"header\", header);\n StringValidator.throwIfEmptyOrNull(\"value\", value);\n\n if (headers == null) {\n headers = new HashMap<String, String>();\n }\n\n headers.put(header, value);\n }", "public 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 runQueuedTask(boolean hasPermit) {\n if (!hasPermit && beginRequest(paused) == RunResult.REJECTED) {\n return false;\n }\n QueuedTask task = null;\n if (!paused) {\n task = taskQueue.poll();\n } else {\n //the container is suspended, but we still need to run any force queued tasks\n task = findForcedTask();\n }\n if (task != null) {\n if(!task.runRequest()) {\n decrementRequestCount();\n }\n return true;\n } else {\n decrementRequestCount();\n return false;\n }\n }", "public static inatparam get(nitro_service service) throws Exception{\n\t\tinatparam obj = new inatparam();\n\t\tinatparam[] response = (inatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Get a bean value from the context. @param name bean name @return bean value or null
[ "public Object getBean(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null == bean) {\n\t\t\treturn null;\n\t\t}\n\t\treturn bean.object;\n\t}" ]
[ "public static String getOffsetCodeFromSchedule(Schedule schedule) {\r\n\r\n\t\tdouble doubleLength = 0;\r\n\t\tfor(int i = 0; i < schedule.getNumberOfPeriods(); i ++) {\r\n\t\t\tdoubleLength += schedule.getPeriodLength(i);\r\n\t\t}\r\n\t\tdoubleLength /= schedule.getNumberOfPeriods();\r\n\r\n\t\tdoubleLength *= 12;\r\n\t\tint periodLength = (int) Math.round(doubleLength);\r\n\r\n\r\n\t\tString offsetCode = periodLength + \"M\";\r\n\t\treturn offsetCode;\r\n\t}", "public static float noise2(float x, float y) {\n int bx0, bx1, by0, by1, b00, b10, b01, b11;\n float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;\n int i, j;\n\n if (start) {\n start = false;\n init();\n }\n\n t = x + N;\n bx0 = ((int)t) & BM;\n bx1 = (bx0+1) & BM;\n rx0 = t - (int)t;\n rx1 = rx0 - 1.0f;\n\n t = y + N;\n by0 = ((int)t) & BM;\n by1 = (by0+1) & BM;\n ry0 = t - (int)t;\n ry1 = ry0 - 1.0f;\n\n i = p[bx0];\n j = p[bx1];\n\n b00 = p[i + by0];\n b10 = p[j + by0];\n b01 = p[i + by1];\n b11 = p[j + by1];\n\n sx = sCurve(rx0);\n sy = sCurve(ry0);\n\n q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];\n q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];\n a = lerp(sx, u, v);\n\n q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];\n q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];\n b = lerp(sx, u, v);\n\n return 1.5f*lerp(sy, a, b);\n }", "public List<Addon> listAppAddons(String appName) {\n return connection.execute(new AppAddonsList(appName), apiKey);\n }", "private void readNetscapeExt() {\n do {\n readBlock();\n if (block[0] == 1) {\n // Loop count sub-block.\n int b1 = ((int) block[1]) & 0xff;\n int b2 = ((int) block[2]) & 0xff;\n header.loopCount = (b2 << 8) | b1;\n if(header.loopCount == 0) {\n header.loopCount = GifDecoder.LOOP_FOREVER;\n }\n }\n } while ((blockSize > 0) && !err());\n }", "@Api\n\tpublic static void configureNoCaching(HttpServletResponse response) {\n\t\t// HTTP 1.0 header:\n\t\tresponse.setHeader(HTTP_EXPIRES_HEADER, HTTP_EXPIRES_HEADER_NOCACHE_VALUE);\n\t\tresponse.setHeader(HTTP_CACHE_PRAGMA, HTTP_CACHE_PRAGMA_VALUE);\n\n\t\t// HTTP 1.1 header:\n\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, HTTP_CACHE_CONTROL_HEADER_NOCACHE_VALUE);\n\t}", "public static void forceDelete(final Path path) throws IOException {\n\t\tif (!java.nio.file.Files.isDirectory(path)) {\n\t\t\tjava.nio.file.Files.delete(path);\n\t\t} else {\n\t\t\tjava.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance());\n\t\t}\n\t}", "public static Object readObject(File file) throws IOException,\n ClassNotFoundException {\n FileInputStream fileIn = new FileInputStream(file);\n ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(fileIn));\n try {\n return in.readObject();\n } finally {\n IoUtils.safeClose(in);\n }\n }", "protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}", "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 }" ]
Encodes the given URI scheme with the given encoding. @param scheme the scheme to be encoded @param encoding the character encoding to encode to @return the encoded scheme @throws UnsupportedEncodingException when the given encoding parameter is not supported
[ "public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\n\t}" ]
[ "private void readProjectProperties(Settings phoenixSettings, Storepoint storepoint)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(phoenixSettings.getTitle());\n mpxjProperties.setDefaultDurationUnits(phoenixSettings.getBaseunit());\n mpxjProperties.setStatusDate(storepoint.getDataDate());\n }", "public static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) {\n // TODO ensure primary is visible\n\n IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class);\n RollbackCheckIterator.setLocktime(is, startTs);\n\n Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol);\n\n TxInfo txInfo = new TxInfo();\n\n if (entry == null) {\n txInfo.status = TxStatus.UNKNOWN;\n return txInfo;\n }\n\n ColumnType colType = ColumnType.from(entry.getKey());\n long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;\n\n switch (colType) {\n case LOCK: {\n if (ts == startTs) {\n txInfo.status = TxStatus.LOCKED;\n txInfo.lockValue = entry.getValue().get();\n } else {\n txInfo.status = TxStatus.UNKNOWN; // locked by another tx\n }\n break;\n }\n case DEL_LOCK: {\n DelLockValue dlv = new DelLockValue(entry.getValue().get());\n\n if (ts != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(prow + \" \" + pcol + \" (\" + ts + \" != \" + startTs + \") \");\n }\n\n if (dlv.isRollback()) {\n txInfo.status = TxStatus.ROLLED_BACK;\n } else {\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = dlv.getCommitTimestamp();\n }\n break;\n }\n case WRITE: {\n long timePtr = WriteValue.getTimestamp(entry.getValue().get());\n\n if (timePtr != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(\n prow + \" \" + pcol + \" (\" + timePtr + \" != \" + startTs + \") \");\n }\n\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = ts;\n break;\n }\n default:\n throw new IllegalStateException(\"unexpected col type returned \" + colType);\n }\n\n return txInfo;\n }", "private static final double printDurationFractionsOfMinutes(Duration duration, int factor)\n {\n double result = 0;\n\n if (duration != null)\n {\n result = duration.getDuration();\n\n switch (duration.getUnits())\n {\n case HOURS:\n case ELAPSED_HOURS:\n {\n result *= 60;\n break;\n }\n\n case DAYS:\n {\n result *= (60 * 8);\n break;\n }\n\n case ELAPSED_DAYS:\n {\n result *= (60 * 24);\n break;\n }\n\n case WEEKS:\n {\n result *= (60 * 8 * 5);\n break;\n }\n\n case ELAPSED_WEEKS:\n {\n result *= (60 * 24 * 7);\n break;\n }\n\n case MONTHS:\n {\n result *= (60 * 8 * 5 * 4);\n break;\n }\n\n case ELAPSED_MONTHS:\n {\n result *= (60 * 24 * 30);\n break;\n }\n\n case YEARS:\n {\n result *= (60 * 8 * 5 * 52);\n break;\n }\n\n case ELAPSED_YEARS:\n {\n result *= (60 * 24 * 365);\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n result *= factor;\n\n return (result);\n }", "public static void main(String[] args) {\n try {\n new StartMain(args).go();\n } catch(Throwable t) {\n WeldSELogger.LOG.error(\"Application exited with an exception\", t);\n System.exit(1);\n }\n }", "protected I_CmsSearchDocument appendFieldMappingsFromElementsOnThePage(\n I_CmsSearchDocument document,\n CmsObject cms,\n CmsResource resource,\n List<String> systemFields) {\n\n try {\n CmsFile file = cms.readFile(resource);\n CmsXmlContainerPage containerPage = CmsXmlContainerPageFactory.unmarshal(cms, file);\n CmsContainerPageBean containerBean = containerPage.getContainerPage(cms);\n if (containerBean != null) {\n for (CmsContainerElementBean element : containerBean.getElements()) {\n element.initResource(cms);\n CmsResource elemResource = element.getResource();\n Set<CmsSearchField> mappedFields = getXSDMappingsForPage(cms, elemResource);\n if (mappedFields != null) {\n\n for (CmsSearchField field : mappedFields) {\n if (!systemFields.contains(field.getName())) {\n document = appendFieldMapping(\n document,\n field,\n cms,\n elemResource,\n CmsSolrDocumentXmlContent.extractXmlContent(cms, elemResource, getIndex()),\n cms.readPropertyObjects(resource, false),\n cms.readPropertyObjects(resource, true));\n } else {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.LOG_SOLR_ERR_MAPPING_TO_INTERNALLY_USED_FIELD_3,\n elemResource.getRootPath(),\n field.getName(),\n resource.getRootPath()));\n }\n }\n }\n }\n }\n } catch (CmsException e) {\n // Should be thrown if element on the page does not exist anymore - this is possible, but not necessarily an error.\n // Hence, just notice it in the debug log.\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n }\n return document;\n }", "public base_response enable_features(String[] features) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsfeature resource = new nsfeature();\n\t\tresource.set_feature(features);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}", "public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\n }\n }", "public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "private Send handle(SelectionKey key, Receive request) {\n final short requestTypeId = request.buffer().getShort();\n final RequestKeys requestType = RequestKeys.valueOf(requestTypeId);\n if (requestLogger.isTraceEnabled()) {\n if (requestType == null) {\n throw new InvalidRequestException(\"No mapping found for handler id \" + requestTypeId);\n }\n String logFormat = \"Handling %s request from %s\";\n requestLogger.trace(format(logFormat, requestType, channelFor(key).socket().getRemoteSocketAddress()));\n }\n RequestHandler handlerMapping = requesthandlerFactory.mapping(requestType, request);\n if (handlerMapping == null) {\n throw new InvalidRequestException(\"No handler found for request\");\n }\n long start = System.nanoTime();\n Send maybeSend = handlerMapping.handler(requestType, request);\n stats.recordRequest(requestType, System.nanoTime() - start);\n return maybeSend;\n }" ]
Returns an entry with the given proposal and prefix, or null if the proposal is not valid. If it is valid, the initializer function is applied to it.
[ "public ContentAssistEntry createProposal(final String proposal, final String prefix, final ContentAssistContext context, final String kind, final Procedure1<? super ContentAssistEntry> init) {\n boolean _isValidProposal = this.isValidProposal(proposal, prefix, context);\n if (_isValidProposal) {\n final ContentAssistEntry result = new ContentAssistEntry();\n result.setProposal(proposal);\n result.setPrefix(prefix);\n if ((kind != null)) {\n result.setKind(kind);\n }\n if ((init != null)) {\n init.apply(result);\n }\n return result;\n }\n return null;\n }" ]
[ "private Duration getDuration(String value)\n {\n Duration result = null;\n\n if (value != null && value.length() != 0)\n {\n double seconds = getLong(value);\n double hours = seconds / (60 * 60);\n double days = hours / 8;\n\n if (days < 1)\n {\n result = Duration.getInstance(hours, TimeUnit.HOURS);\n }\n else\n {\n double durationDays = hours / 8;\n result = Duration.getInstance(durationDays, TimeUnit.DAYS);\n }\n }\n\n return (result);\n }", "public static PasswordSpec parse(String spec) {\n char[] ca = spec.toCharArray();\n int len = ca.length;\n illegalIf(0 == len, spec);\n Builder builder = new Builder();\n StringBuilder minBuf = new StringBuilder();\n StringBuilder maxBuf = new StringBuilder();\n boolean lenSpecStart = false;\n boolean minPart = false;\n for (int i = 0; i < len; ++i) {\n char c = ca[i];\n switch (c) {\n case SPEC_LOWERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireLowercase();\n break;\n case SPEC_UPPERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireUppercase();\n break;\n case SPEC_SPECIAL_CHAR:\n illegalIf(lenSpecStart, spec);\n builder.requireSpecialChar();\n break;\n case SPEC_LENSPEC_START:\n lenSpecStart = true;\n minPart = true;\n break;\n case SPEC_LENSPEC_CLOSE:\n illegalIf(minPart, spec);\n lenSpecStart = false;\n break;\n case SPEC_LENSPEC_SEP:\n minPart = false;\n break;\n case SPEC_DIGIT:\n if (!lenSpecStart) {\n builder.requireDigit();\n } else {\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n break;\n default:\n illegalIf(!lenSpecStart || !isDigit(c), spec);\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n }\n illegalIf(lenSpecStart, spec);\n if (minBuf.length() != 0) {\n builder.minLength(Integer.parseInt(minBuf.toString()));\n }\n if (maxBuf.length() != 0) {\n builder.maxLength(Integer.parseInt(maxBuf.toString()));\n }\n return builder;\n }", "public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}", "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 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 }", "protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (PreparedStatement) Proxy.newProxyInstance(\n\t\t\t\tPreparedStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {PreparedStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}", "public void bindBundleToSceneObject(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject)\n throws IOException, GVRScriptException\n {\n bindHelper(scriptBundle, rootSceneObject, BIND_MASK_SCENE_OBJECTS);\n }", "private void processResourceAssignment(Task task, MapRow row)\n {\n Resource resource = m_resourceMap.get(row.getUUID(\"RESOURCE_UUID\"));\n task.addResourceAssignment(resource);\n }", "public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }" ]
Counts a single page of the specified gender. If this is the first page of that gender on this site, a suitable key is added to the list of the site's genders. @param gender the gender to count @param siteRecord the site record to count it for
[ "private void countGender(EntityIdValue gender, SiteRecord siteRecord) {\n\t\tInteger curValue = siteRecord.genderCounts.get(gender);\n\t\tif (curValue == null) {\n\t\t\tsiteRecord.genderCounts.put(gender, 1);\n\t\t} else {\n\t\t\tsiteRecord.genderCounts.put(gender, curValue + 1);\n\t\t}\n\t}" ]
[ "@Override\n public boolean parseAndValidateRequest() {\n if(!super.parseAndValidateRequest()) {\n return false;\n }\n isGetVersionRequest = hasGetVersionRequestHeader();\n if(isGetVersionRequest && this.parsedKeys.size() > 1) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Get version request cannot have multiple keys\");\n return false;\n }\n return true;\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 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}", "private void adjustVisibleColumns() {\n\n if (m_table.isColumnCollapsingAllowed()) {\n if ((m_model.hasDefaultValues()) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, true);\n }\n\n if (((m_model.getEditMode().equals(EditMode.MASTER) || m_model.hasDescriptionValues()))\n || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, true);\n }\n }\n }", "public boolean detectNintendo() {\r\n\r\n if ((userAgent.indexOf(deviceNintendo) != -1)\r\n || (userAgent.indexOf(deviceWii) != -1)\r\n || (userAgent.indexOf(deviceNintendoDs) != -1)) {\r\n return true;\r\n }\r\n return false;\r\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 }", "public Collection values()\r\n {\r\n if (values != null) return values;\r\n values = new AbstractCollection()\r\n {\r\n public int size()\r\n {\r\n return size;\r\n }\r\n\r\n public void clear()\r\n {\r\n ReferenceMap.this.clear();\r\n }\r\n\r\n public Iterator iterator()\r\n {\r\n return new ValueIterator();\r\n }\r\n };\r\n return values;\r\n }", "public void setMat4(String key, 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 {\n checkKeyIsUniform(key);\n NativeLight.setMat4(getNative(), key, x1, y1, z1, w1, x2, y2,\n z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }" ]
Return the List of VariableExpression objects referenced by the specified DeclarationExpression. @param declarationExpression - the DeclarationExpression @return the List of VariableExpression objects
[ "public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) {\r\n Expression leftExpression = declarationExpression.getLeftExpression();\r\n\r\n // !important: performance enhancement\r\n if (leftExpression instanceof ArrayExpression) {\r\n List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof TupleExpression) {\r\n List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions();\r\n return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions;\r\n } else if (leftExpression instanceof VariableExpression) {\r\n return Arrays.asList(leftExpression);\r\n }\r\n // todo: write warning\r\n return Collections.emptyList();\r\n }" ]
[ "private String parseMandatoryStringValue(final String path) throws Exception {\n\n final String value = parseOptionalStringValue(path);\n if (value == null) {\n throw new Exception();\n }\n return value;\n }", "private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res)\n {\n for (Assignment assignment : res.getAssignment())\n {\n readAssignment(mpxjResource, assignment);\n }\n }", "@Override\n public int read(char[] cbuf, int off, int len) throws IOException {\n int numChars = super.read(cbuf, off, len);\n replaceBadXmlCharactersBySpace(cbuf, off, len);\n return numChars;\n }", "private ImmutableList<Element> getNodeListForTagElement(Document dom,\n\t\t\tCrawlElement crawlElement,\n\t\t\tEventableConditionChecker eventableConditionChecker) {\n\n\t\tBuilder<Element> result = ImmutableList.builder();\n\n\t\tif (crawlElement.getTagName() == null) {\n\t\t\treturn result.build();\n\t\t}\n\n\t\tEventableCondition eventableCondition =\n\t\t\t\teventableConditionChecker.getEventableCondition(crawlElement.getId());\n\t\t// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent\n\t\t// performance problems.\n\t\tImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);\n\n\t\tNodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());\n\n\t\tfor (int k = 0; k < nodeList.getLength(); k++) {\n\n\t\t\tElement element = (Element) nodeList.item(k);\n\t\t\tboolean matchesXpath =\n\t\t\t\t\telementMatchesXpath(eventableConditionChecker, eventableCondition,\n\t\t\t\t\t\t\texpressions, element);\n\t\t\tLOG.debug(\"Element {} matches Xpath={}\", DomUtils.getElementString(element),\n\t\t\t\t\tmatchesXpath);\n\t\t\t/*\n\t\t\t * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return\n\t\t\t * false and when needed to add it can return true. / check if element is a candidate\n\t\t\t */\n\t\t\tString id = element.getNodeName() + \": \" + DomUtils.getAllElementAttributes(element);\n\t\t\tif (matchesXpath && !checkedElements.isChecked(id)\n\t\t\t\t\t&& !isExcluded(dom, element, eventableConditionChecker)) {\n\t\t\t\taddElement(element, result, crawlElement);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Element {} was not added\", element);\n\t\t\t}\n\t\t}\n\t\treturn result.build();\n\t}", "public boolean projectExists(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return listProjects().stream()\n .map(p -> p.getMetadata().getName())\n .anyMatch(Predicate.isEqual(name));\n }", "public synchronized GeoInterface getGeoInterface() {\r\n if (geoInterface == null) {\r\n geoInterface = new GeoInterface(apiKey, sharedSecret, transport);\r\n }\r\n return geoInterface;\r\n }", "public GetSingleConversationOptions filters(List<String> filters) {\n if(filters.size() == 1) { //Canvas API doesn't want the [] if it is only one value\n addSingleItem(\"filter\", filters.get(0));\n } else {\n optionsMap.put(\"filter[]\", filters);\n }\n return this;\n }", "public static CmsShell getTopShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.isEmpty()) {\n return null;\n }\n return shells.get(shells.size() - 1);\n\n }", "public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) {\n return (List<Map<String, Object>>) collectify(mapper, source, List.class);\n }" ]
The type descriptor for a method node is a string containing the name of the method, its return type, and its parameter types in a canonical form. For simplicity, I'm using the format of a Java declaration without parameter names. @return the type descriptor
[ "public String getTypeDescriptor() {\n if (typeDescriptor == null) {\n StringBuilder buf = new StringBuilder(name.length() + parameters.length * 10);\n buf.append(returnType.getName());\n buf.append(' ');\n buf.append(name);\n buf.append('(');\n for (int i = 0; i < parameters.length; i++) {\n if (i > 0) {\n buf.append(\", \");\n }\n Parameter param = parameters[i];\n buf.append(formatTypeName(param.getType()));\n }\n buf.append(')');\n typeDescriptor = buf.toString();\n }\n return typeDescriptor;\n }" ]
[ "public boolean addMethodToResponseOverride(String pathName, String methodName) {\n // need to find out the ID for the method\n // TODO: change api for adding methods to take the name instead of ID\n try {\n Integer overrideId = getOverrideIdForMethodName(methodName);\n\n // now post to path api to add this is a selected override\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"addOverride\", overrideId.toString()),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName), params));\n // check enabled endpoints array to see if this overrideID exists\n JSONArray enabled = response.getJSONArray(\"enabledEndpoints\");\n for (int x = 0; x < enabled.length(); x++) {\n if (enabled.getJSONObject(x).getInt(\"overrideId\") == overrideId) {\n return true;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return false;\n }", "protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}", "public String createSessionForResource(String configPath, String fileName) throws CmsUgcException {\n\n CmsUgcSession formSession = CmsUgcSessionFactory.getInstance().createSessionForFile(\n getCmsObject(),\n getRequest(),\n configPath,\n fileName);\n return \"\" + formSession.getId();\n }", "public Slice newSlice(long address, int size, Object reference)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (reference == null) {\n throw new NullPointerException(\"Object reference is null\");\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, size, reference);\n }", "private static List<String> parseModifiers(int modifiers) {\n List<String> result = new ArrayList<String>();\n if (Modifier.isPrivate(modifiers)) {\n result.add(\"private\");\n }\n if (Modifier.isProtected(modifiers)) {\n result.add(\"protected\");\n }\n if (Modifier.isPublic(modifiers)) {\n result.add(\"public\");\n }\n if (Modifier.isAbstract(modifiers)) {\n result.add(\"abstract\");\n }\n if (Modifier.isFinal(modifiers)) {\n result.add(\"final\");\n }\n if (Modifier.isNative(modifiers)) {\n result.add(\"native\");\n }\n if (Modifier.isStatic(modifiers)) {\n result.add(\"static\");\n }\n if (Modifier.isStrict(modifiers)) {\n result.add(\"strict\");\n }\n if (Modifier.isSynchronized(modifiers)) {\n result.add(\"synchronized\");\n }\n if (Modifier.isTransient(modifiers)) {\n result.add(\"transient\");\n }\n if (Modifier.isVolatile(modifiers)) {\n result.add(\"volatile\");\n }\n if (Modifier.isInterface(modifiers)) {\n result.add(\"interface\");\n }\n return result;\n }", "private void registerPackageInTypeInterestFactory(String pkg)\n {\n TypeInterestFactory.registerInterest(pkg + \"_pkg\", pkg.replace(\".\", \"\\\\.\"), pkg, TypeReferenceLocation.IMPORT);\n // TODO: Finish the implementation\n }", "public void readLock(EntityKey key, int timeout) {\n\t\tReadWriteLock lock = getLock( key );\n\t\tLock readLock = lock.readLock();\n\t\tacquireLock( key, timeout, readLock );\n\t}", "private static Collection<String> addOtherClasses(Collection<String> feats, List<? extends CoreLabel> info,\r\n int loc, Clique c) {\r\n String addend = null;\r\n String pAnswer = info.get(loc - 1).get(AnswerAnnotation.class);\r\n String p2Answer = info.get(loc - 2).get(AnswerAnnotation.class);\r\n String p3Answer = info.get(loc - 3).get(AnswerAnnotation.class);\r\n String p4Answer = info.get(loc - 4).get(AnswerAnnotation.class);\r\n String p5Answer = info.get(loc - 5).get(AnswerAnnotation.class);\r\n String nAnswer = info.get(loc + 1).get(AnswerAnnotation.class);\r\n // cdm 2009: Is this really right? Do we not need to differentiate names that would collide???\r\n if (c == FeatureFactory.cliqueCpC) {\r\n addend = '|' + pAnswer;\r\n } else if (c == FeatureFactory.cliqueCp2C) {\r\n addend = '|' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCp3C) {\r\n addend = '|' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCp4C) {\r\n addend = '|' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCp5C) {\r\n addend = '|' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2C) {\r\n addend = '|' + pAnswer + '-' + p2Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer;\r\n } else if (c == FeatureFactory.cliqueCpCp2Cp3Cp4Cp5C) {\r\n addend = '|' + pAnswer + '-' + p2Answer + '-' + p3Answer + '-' + p4Answer + '-' + p5Answer;\r\n } else if (c == FeatureFactory.cliqueCnC) {\r\n addend = '|' + nAnswer;\r\n } else if (c == FeatureFactory.cliqueCpCnC) {\r\n addend = '|' + pAnswer + '-' + nAnswer;\r\n }\r\n if (addend == null) {\r\n return feats;\r\n }\r\n Collection<String> newFeats = new HashSet<String>();\r\n for (String feat : feats) {\r\n String newFeat = feat + addend;\r\n newFeats.add(newFeat);\r\n }\r\n return newFeats;\r\n }", "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }" ]
Merges the hardcoded results of this Configuration with the given Configuration. The resultant hardcoded results will be the union of the two sets of hardcoded results. Where the AnalysisResult for a class is found in both Configurations, the result from otherConfiguration will replace the existing result in this Configuration. This replacement behaviour will occur for subsequent calls to {@link #mergeHardcodedResultsFrom(Configuration)}. @param otherConfiguration - Configuration to merge hardcoded results with.
[ "protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }" ]
[ "public void notifyHeaderItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= headerItemCount || toPosition >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \" + toPosition + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition, toPosition);\n }", "public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }", "public static base_response add(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup addresource = new cachecontentgroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\taddresource.heurexpiryparam = resource.heurexpiryparam;\n\t\taddresource.relexpiry = resource.relexpiry;\n\t\taddresource.relexpirymillisec = resource.relexpirymillisec;\n\t\taddresource.absexpiry = resource.absexpiry;\n\t\taddresource.absexpirygmt = resource.absexpirygmt;\n\t\taddresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\taddresource.hitparams = resource.hitparams;\n\t\taddresource.invalparams = resource.invalparams;\n\t\taddresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\taddresource.matchcookies = resource.matchcookies;\n\t\taddresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\taddresource.polleverytime = resource.polleverytime;\n\t\taddresource.ignorereloadreq = resource.ignorereloadreq;\n\t\taddresource.removecookies = resource.removecookies;\n\t\taddresource.prefetch = resource.prefetch;\n\t\taddresource.prefetchperiod = resource.prefetchperiod;\n\t\taddresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\taddresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\taddresource.flashcache = resource.flashcache;\n\t\taddresource.expireatlastbyte = resource.expireatlastbyte;\n\t\taddresource.insertvia = resource.insertvia;\n\t\taddresource.insertage = resource.insertage;\n\t\taddresource.insertetag = resource.insertetag;\n\t\taddresource.cachecontrol = resource.cachecontrol;\n\t\taddresource.quickabortsize = resource.quickabortsize;\n\t\taddresource.minressize = resource.minressize;\n\t\taddresource.maxressize = resource.maxressize;\n\t\taddresource.memlimit = resource.memlimit;\n\t\taddresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\taddresource.minhits = resource.minhits;\n\t\taddresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\taddresource.persist = resource.persist;\n\t\taddresource.pinned = resource.pinned;\n\t\taddresource.lazydnsresolve = resource.lazydnsresolve;\n\t\taddresource.hitselector = resource.hitselector;\n\t\taddresource.invalselector = resource.invalselector;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}", "@Override\n public void invert( ZMatrixRMaj inv ) {\n if( inv.numRows != n || inv.numCols != n ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n if( inv.data == t ) {\n throw new IllegalArgumentException(\"Passing in the same matrix that was decomposed.\");\n }\n\n if(decomposer.isLower()) {\n setToInverseL(inv.data);\n } else {\n throw new RuntimeException(\"Implement\");\n }\n }", "private void readVersion(InputStream is) throws IOException\n {\n BytesReadInputStream bytesReadStream = new BytesReadInputStream(is);\n String version = DatatypeConverter.getString(bytesReadStream);\n m_offset += bytesReadStream.getBytesRead();\n SynchroLogger.log(\"VERSION\", version);\n \n String[] versionArray = version.split(\"\\\\.\");\n m_majorVersion = Integer.parseInt(versionArray[0]);\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 }", "static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {\n AzureAsyncOperation asyncOperation = null;\n String rawString = null;\n if (response.body() != null) {\n try {\n rawString = response.body().string();\n asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);\n } catch (IOException exception) {\n // Exception will be handled below\n } finally {\n response.body().close();\n }\n }\n if (asyncOperation == null || asyncOperation.status() == null) {\n throw new CloudException(\"polling response does not contain a valid body: \" + rawString, response);\n }\n else {\n asyncOperation.rawString = rawString;\n }\n return asyncOperation;\n }", "public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushEvent(String eventName) {\n if (eventName == null || eventName.trim().equals(\"\"))\n return;\n\n pushEvent(eventName, null);\n }" ]
EXecutes command to given container returning the inspection object as well. This method does 3 calls to dockerhost. Create, Start and Inspect. @param containerId to execute command.
[ "public ExecInspection execStartVerbose(String containerId, String... commands) {\n this.readWriteLock.readLock().lock();\n try {\n String id = execCreate(containerId, commands);\n CubeOutput output = execStartOutput(id);\n\n return new ExecInspection(output, inspectExec(id));\n } finally {\n this.readWriteLock.readLock().unlock();\n }\n }" ]
[ "private void readRelation(Relationship relation)\n {\n Task predecessor = m_activityMap.get(relation.getPredecessor());\n Task successor = m_activityMap.get(relation.getSuccessor());\n if (predecessor != null && successor != null)\n {\n Duration lag = relation.getLag();\n RelationType type = relation.getType();\n successor.addPredecessor(predecessor, type, lag);\n }\n }", "public T modifyModule(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createModuleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }", "protected void splitCriteria()\r\n {\r\n Criteria whereCrit = getQuery().getCriteria();\r\n Criteria havingCrit = getQuery().getHavingCriteria();\r\n\r\n if (whereCrit == null || whereCrit.isEmpty())\r\n {\r\n getJoinTreeToCriteria().put(getRoot(), null);\r\n }\r\n else\r\n {\r\n // TODO: parameters list shold be modified when the form is reduced to DNF.\r\n getJoinTreeToCriteria().put(getRoot(), whereCrit);\r\n buildJoinTree(whereCrit);\r\n }\r\n\r\n if (havingCrit != null && !havingCrit.isEmpty())\r\n {\r\n buildJoinTree(havingCrit);\r\n }\r\n\r\n }", "public void applyPattern(String primaryPattern, String[] alternativePatterns, char decimalSeparator, char groupingSeparator)\n {\n m_symbols.setDecimalSeparator(decimalSeparator);\n m_symbols.setGroupingSeparator(groupingSeparator);\n\n setDecimalFormatSymbols(m_symbols);\n applyPattern(primaryPattern);\n\n if (alternativePatterns != null && alternativePatterns.length != 0)\n {\n int loop;\n if (m_alternativeFormats == null || m_alternativeFormats.length != alternativePatterns.length)\n {\n m_alternativeFormats = new DecimalFormat[alternativePatterns.length];\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop] = new DecimalFormat();\n }\n }\n\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop].setDecimalFormatSymbols(m_symbols);\n m_alternativeFormats[loop].applyPattern(alternativePatterns[loop]);\n }\n }\n }", "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\n }", "protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}", "private void readWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar)\n {\n WorkWeeks ww = xmlCalendar.getWorkWeeks();\n if (ww != null)\n {\n for (WorkWeek xmlWeek : ww.getWorkWeek())\n {\n ProjectCalendarWeek week = mpxjCalendar.addWorkWeek();\n week.setName(xmlWeek.getName());\n Date startTime = xmlWeek.getTimePeriod().getFromDate();\n Date endTime = xmlWeek.getTimePeriod().getToDate();\n week.setDateRange(new DateRange(startTime, endTime));\n\n WeekDays xmlWeekDays = xmlWeek.getWeekDays();\n if (xmlWeekDays != null)\n {\n for (WeekDay xmlWeekDay : xmlWeekDays.getWeekDay())\n {\n int dayNumber = xmlWeekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n week.setWorkingDay(day, BooleanHelper.getBoolean(xmlWeekDay.isDayWorking()));\n ProjectCalendarHours hours = week.addCalendarHours(day);\n\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = xmlWeekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n startTime = period.getFromTime();\n endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }\n }\n }\n }", "public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt,\n final double l1Lambda, final double l2Lambda) {\n if (l1Lambda == 0 && l2Lambda == 0) {\n return opt;\n }\n return new Optimizer<DifferentiableFunction>() {\n \n @Override\n public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) {\n DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda);\n return opt.minimize(fn, point);\n }\n \n };\n }", "private void addDefaults()\n {\n this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Mandatory\", MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), \"Optional\", OPTIONAL, 1000, true));\n this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), \"Potential Issues\", POTENTIAL, 1000, true));\n this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Cloud Mandatory\", CLOUD_MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), \"Information\", INFORMATION, 1000, true));\n }" ]
Read the work weeks associated with this calendar. @param xmlCalendar XML calendar object @param mpxjCalendar MPXJ calendar object
[ "private void readWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar)\n {\n WorkWeeks ww = xmlCalendar.getWorkWeeks();\n if (ww != null)\n {\n for (WorkWeek xmlWeek : ww.getWorkWeek())\n {\n ProjectCalendarWeek week = mpxjCalendar.addWorkWeek();\n week.setName(xmlWeek.getName());\n Date startTime = xmlWeek.getTimePeriod().getFromDate();\n Date endTime = xmlWeek.getTimePeriod().getToDate();\n week.setDateRange(new DateRange(startTime, endTime));\n\n WeekDays xmlWeekDays = xmlWeek.getWeekDays();\n if (xmlWeekDays != null)\n {\n for (WeekDay xmlWeekDay : xmlWeekDays.getWeekDay())\n {\n int dayNumber = xmlWeekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n week.setWorkingDay(day, BooleanHelper.getBoolean(xmlWeekDay.isDayWorking()));\n ProjectCalendarHours hours = week.addCalendarHours(day);\n\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = xmlWeekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n startTime = period.getFromTime();\n endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }\n }\n }\n }" ]
[ "public ArrayList<String> getCarouselImages(){\n ArrayList<String> carouselImages = new ArrayList<>();\n for(CTInboxMessageContent ctInboxMessageContent: getInboxMessageContents()){\n carouselImages.add(ctInboxMessageContent.getMedia());\n }\n return carouselImages;\n }", "public static SPIProvider getInstance()\n {\n if (me == null)\n {\n final ClassLoader cl = ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader();\n me = SPIProviderResolver.getInstance(cl).getProvider();\n }\n return me;\n }", "public HttpConnection execute(HttpConnection connection) {\n\n //set our HttpUrlFactory on the connection\n connection.connectionFactory = factory;\n\n // all CouchClient requests want to receive application/json responses\n connection.requestProperties.put(\"Accept\", \"application/json\");\n connection.responseInterceptors.addAll(this.responseInterceptors);\n connection.requestInterceptors.addAll(this.requestInterceptors);\n InputStream es = null; // error stream - response from server for a 500 etc\n\n // first try to execute our request and get the input stream with the server's response\n // we want to catch IOException because HttpUrlConnection throws these for non-success\n // responses (eg 404 throws a FileNotFoundException) but we need to map to our own\n // specific exceptions\n try {\n try {\n connection = connection.execute();\n } catch (HttpConnectionInterceptorException e) {\n CouchDbException exception = new CouchDbException(connection.getConnection()\n .getResponseMessage(), connection.getConnection().getResponseCode());\n if (e.deserialize) {\n try {\n JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject\n .class);\n exception.error = getAsString(errorResponse, \"error\");\n exception.reason = getAsString(errorResponse, \"reason\");\n } catch (JsonParseException jpe) {\n exception.error = e.error;\n }\n } else {\n exception.error = e.error;\n exception.reason = e.reason;\n }\n throw exception;\n }\n int code = connection.getConnection().getResponseCode();\n String response = connection.getConnection().getResponseMessage();\n // everything ok? return the stream\n if (code / 100 == 2) { // success [200,299]\n return connection;\n } else {\n final CouchDbException ex;\n switch (code) {\n case HttpURLConnection.HTTP_NOT_FOUND: //404\n ex = new NoDocumentException(response);\n break;\n case HttpURLConnection.HTTP_CONFLICT: //409\n ex = new DocumentConflictException(response);\n break;\n case HttpURLConnection.HTTP_PRECON_FAILED: //412\n ex = new PreconditionFailedException(response);\n break;\n case 429:\n // If a Replay429Interceptor is present it will check for 429 and retry at\n // intervals. If the retries do not succeed or no 429 replay was configured\n // we end up here and throw a TooManyRequestsException.\n ex = new TooManyRequestsException(response);\n break;\n default:\n ex = new CouchDbException(response, code);\n break;\n }\n es = connection.getConnection().getErrorStream();\n //if there is an error stream try to deserialize into the typed exception\n if (es != null) {\n try {\n //read the error stream into memory\n byte[] errorResponse = IOUtils.toByteArray(es);\n\n Class<? extends CouchDbException> exceptionClass = ex.getClass();\n //treat the error as JSON and try to deserialize\n try {\n // Register an InstanceCreator that returns the existing exception so\n // we can just populate the fields, but not ignore the constructor.\n // Uses a new Gson so we don't accidentally recycle an exception.\n Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new\n CouchDbExceptionInstanceCreator(ex)).create();\n // Now populate the exception with the error/reason other info from JSON\n g.fromJson(new InputStreamReader(new ByteArrayInputStream\n (errorResponse),\n \"UTF-8\"), exceptionClass);\n } catch (JsonParseException e) {\n // The error stream was not JSON so just set the string content as the\n // error field on ex before we throw it\n ex.error = new String(errorResponse, \"UTF-8\");\n }\n } finally {\n close(es);\n }\n }\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n } catch (IOException ioe) {\n CouchDbException ex = new CouchDbException(\"Error retrieving server response\", ioe);\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n }", "public static boolean isInteger(CharSequence self) {\n try {\n Integer.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "private void checkExtents(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap processedClasses = new HashMap();\r\n InheritanceHelper helper = new InheritanceHelper();\r\n ClassDescriptorDef curExtent;\r\n boolean canBeRemoved;\r\n\r\n for (Iterator it = classDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curExtent = (ClassDescriptorDef)it.next();\r\n canBeRemoved = false;\r\n if (classDef.getName().equals(curExtent.getName()))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies itself as an extent-class\");\r\n }\r\n else if (processedClasses.containsKey(curExtent))\r\n {\r\n canBeRemoved = true;\r\n }\r\n else\r\n {\r\n try\r\n {\r\n if (!helper.isSameOrSubTypeOf(curExtent, classDef.getName(), false))\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" specifies an extent-class \"+curExtent.getName()+\" that is not a sub-type of it\");\r\n }\r\n // now we check whether we already have an extent for a base-class of this extent-class\r\n for (Iterator processedIt = processedClasses.keySet().iterator(); processedIt.hasNext();)\r\n {\r\n if (helper.isSameOrSubTypeOf(curExtent, ((ClassDescriptorDef)processedIt.next()).getName(), false))\r\n {\r\n canBeRemoved = true;\r\n break;\r\n }\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n // won't happen because we don't use lookup of the actual classes\r\n }\r\n }\r\n if (canBeRemoved)\r\n {\r\n it.remove();\r\n }\r\n processedClasses.put(curExtent, null);\r\n }\r\n }", "public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }", "public static vpnglobal_intranetip_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding();\n\t\tvpnglobal_intranetip_binding response[] = (vpnglobal_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }", "public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}" ]
Retrieves the members of the given type. @param memberNames Will receive the names of the members (for sorting) @param members Will receive the members @param type The type to process @param tagName An optional tag for filtering the types @param paramName The feature to be added to the Members attribute @param paramValue The feature to be added to the Members attribute @throws XDocletException If an error occurs
[ "private void addMembers(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n if (!type.isInterface() && (type.getFields() != null)) {\r\n XField field;\r\n\r\n for (Iterator it = type.getFields().iterator(); it.hasNext(); ) {\r\n field = (XField)it.next();\r\n if (!field.isFinal() && !field.isStatic() && !field.isTransient()) {\r\n if (checkTagAndParam(field.getDoc(), tagName, paramName, paramValue)) {\r\n // already processed ?\r\n if (!members.containsKey(field.getName())) {\r\n memberNames.add(field.getName());\r\n members.put(field.getName(), field);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (type.getMethods() != null) {\r\n XMethod method;\r\n String propertyName;\r\n\r\n for (Iterator it = type.getMethods().iterator(); it.hasNext(); ) {\r\n method = (XMethod)it.next();\r\n if (!method.isConstructor() && !method.isNative() && !method.isStatic()) {\r\n if (checkTagAndParam(method.getDoc(), tagName, paramName, paramValue)) {\r\n if (MethodTagsHandler.isGetterMethod(method) || MethodTagsHandler.isSetterMethod(method)) {\r\n propertyName = MethodTagsHandler.getPropertyNameFor(method);\r\n if (!members.containsKey(propertyName)) {\r\n memberNames.add(propertyName);\r\n members.put(propertyName, method);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }" ]
[ "public static InterceptionContext forConstructorInterception(InterceptionModel interceptionModel, CreationalContext<?> ctx, BeanManagerImpl manager, SlimAnnotatedType<?> type) {\n return of(interceptionModel, ctx, manager, null, type);\n }", "private void requestPlayerDBServerPort(DeviceAnnouncement announcement) {\n Socket socket = null;\n try {\n InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT);\n socket = new Socket();\n socket.connect(address, socketTimeout.get());\n InputStream is = socket.getInputStream();\n OutputStream os = socket.getOutputStream();\n socket.setSoTimeout(socketTimeout.get());\n os.write(DB_SERVER_QUERY_PACKET);\n byte[] response = readResponseWithExpectedSize(is, 2, \"database server port query packet\");\n if (response.length == 2) {\n setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2));\n }\n } catch (java.net.ConnectException ce) {\n logger.info(\"Player \" + announcement.getNumber() +\n \" doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata.\");\n } catch (Exception e) {\n logger.warn(\"Problem requesting database server port number\", e);\n } finally {\n if (socket != null) {\n try {\n socket.close();\n } catch (IOException e) {\n logger.warn(\"Problem closing database server port request socket\", e);\n }\n }\n }\n }", "public <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return Observable.just(event).delay(milliseconds, TimeUnit.MILLISECONDS, Schedulers.immediate());\n }", "private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) {\n\n if ((null == request) || !request.isInitialized()) {\n return null;\n }\n\n final String[] wordsToCheck = request.m_wordsToCheck;\n\n final ModifiableSolrParams params = new ModifiableSolrParams();\n params.set(\"spellcheck\", \"true\");\n params.set(\"spellcheck.dictionary\", request.m_dictionaryToUse);\n params.set(\"spellcheck.extendedResults\", \"true\");\n\n // Build one string from array of words and use it as query.\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < wordsToCheck.length; i++) {\n builder.append(wordsToCheck[i] + \" \");\n }\n\n params.set(\"spellcheck.q\", builder.toString());\n\n final SolrQuery query = new SolrQuery();\n query.setRequestHandler(\"/spell\");\n query.add(params);\n\n try {\n QueryResponse qres = m_solrClient.query(query);\n return qres.getSpellCheckResponse();\n } catch (Exception e) {\n LOG.debug(\"Exception while performing spellcheck query...\", e);\n }\n\n return null;\n }", "private void logState(final FileRollEvent fileRollEvent) {\n\n//\t\tif (ApplicationState.isApplicationStateEnabled()) {\n\t\t\t\n\t\t\tsynchronized (this) {\n\t\t\t\t\n\t\t\t\tfinal Collection<ApplicationState.ApplicationStateMessage> entries = ApplicationState.getAppStateEntries();\n\t\t\t\tfor (ApplicationState.ApplicationStateMessage entry : entries) {\n Level level = ApplicationState.getLog4jLevel(entry.getLevel());\n\t\t\t\t if(level.isGreaterOrEqual(ApplicationState.LOGGER.getEffectiveLevel())) {\n\t\t\t\t\t\tfinal org.apache.log4j.spi.LoggingEvent loggingEvent = new org.apache.log4j.spi.LoggingEvent(ApplicationState.FQCN, ApplicationState.LOGGER, level, entry.getMessage(), null);\n\n\t\t\t\t\t\t//Save the current layout before changing it to the original (relevant for marker cases when the layout was changed)\n\t\t\t\t\t\tLayout current=fileRollEvent.getSource().getLayout();\n\t\t\t\t\t\t//fileRollEvent.getSource().activeOriginalLayout();\n\t\t\t\t\t\tString flowContext = (String) MDC.get(\"flowCtxt\");\n\t\t\t\t\t\tMDC.remove(\"flowCtxt\");\n\t\t\t\t\t\t//Write applicationState:\n\t\t\t\t\t\tif(fileRollEvent.getSource().isAddApplicationState() && fileRollEvent.getSource().getFile().endsWith(\"log\")){\n\t\t\t\t\t\t\tfileRollEvent.dispatchToAppender(loggingEvent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Set current again.\n\t\t\t\t\t\tfileRollEvent.getSource().setLayout(current);\n\t\t\t\t\t\tif (flowContext != null) {\n\t\t\t\t\t\t\tMDC.put(\"flowCtxt\", flowContext);\n\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\t\n\t\t\t}\n\t\t\t\n//\t\t}\n\t}", "public boolean isHomeKeyPresent() {\n final GVRApplication application = mApplication.get();\n if (null != application) {\n final String model = getHmtModel();\n if (null != model && model.contains(\"R323\")) {\n return true;\n }\n }\n return false;\n }", "public int addServerGroup(String groupName, int profileId) throws Exception {\n int groupId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_SERVER_GROUPS\n + \"(\" + Constants.GENERIC_NAME + \",\" +\n Constants.GENERIC_PROFILE_ID + \")\"\n + \" VALUES (?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, groupName);\n statement.setInt(2, profileId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n groupId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add group\");\n }\n } catch (SQLException 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 groupId;\n }", "public static auditsyslogpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_vpnglobal_binding obj = new auditsyslogpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_vpnglobal_binding response[] = (auditsyslogpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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 }" ]
ten less than Cube Q
[ "public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,\n ArquillianDescriptor arquillianDescriptor) {\n\n DockerCompositions cubes = configuration.getDockerContainersContent();\n\n final SeleniumContainers seleniumContainers =\n SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());\n cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());\n\n final boolean recording = cubeDroneConfigurationInstance.get().isRecording();\n if (recording) {\n cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());\n cubes.add(seleniumContainers.getVideoConverterContainerName(),\n seleniumContainers.getVideoConverterContainer());\n }\n\n seleniumContainersInstanceProducer.set(seleniumContainers);\n\n System.out.println(\"SELENIUM INSTALLED\");\n System.out.println(ConfigUtil.dump(cubes));\n }" ]
[ "public static String getHeaders(HttpServletRequest request) {\n String headerString = \"\";\n Enumeration<String> headerNames = request.getHeaderNames();\n\n while (headerNames.hasMoreElements()) {\n String name = headerNames.nextElement();\n if (name.equals(Constants.ODO_PROXY_HEADER)) {\n // skip.. don't want to log this\n continue;\n }\n\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += name + \": \" + request.getHeader(name);\n }\n\n return headerString;\n }", "private void cascadeInsertFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion, so use List for registration\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeInsertSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeInsertCollectionReferences(mod, colls, alreadyPrepared);\r\n }", "public boolean projectExists(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return listProjects().stream()\n .map(p -> p.getMetadata().getName())\n .anyMatch(Predicate.isEqual(name));\n }", "public void setLabels(Collection<LabelType> labels) {\r\n this.labels.clear();\r\n if (labels != null) {\r\n this.labels.addAll(labels);\r\n }\r\n }", "@Override\n\tpublic Iterator<? extends IPAddressSeqRange> prefixIterator(int prefixLength) {\n\t\tif(!isMultiple()) {\n\t\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\t\tIPAddressSeqRange orig = IPAddressSeqRange.this;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn orig != null;\n\t\t\t\t}\n\n\t\t\t @Override\n\t\t\t\tpublic IPAddressSeqRange next() {\n\t\t\t \tif(orig == null) {\n\t\t\t \t\tthrow new NoSuchElementException();\n\t\t\t \t}\n\t\t\t \tIPAddressSeqRange result = orig;\n\t\t\t \torig = null;\n\t\t\t \treturn result;\n\t\t\t }\n\t\t\t\n\t\t\t @Override\n\t\t\t\tpublic void remove() {\n\t\t\t \tthrow new UnsupportedOperationException();\n\t\t\t }\n\t\t\t};\n\t\t}\n\t\treturn new Iterator<IPAddressSeqRange>() {\n\t\t\tIterator<? extends IPAddress> prefixBlockIterator = prefixBlockIterator(prefixLength);\n\t\t\tprivate boolean first = true;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn prefixBlockIterator.hasNext();\n\t\t\t}\n\n\t\t @Override\n\t\t\tpublic IPAddressSeqRange next() {\n\t\t \tIPAddress next = prefixBlockIterator.next();\n\t\t \tif(first) {\n\t\t \t\tfirst = false;\n\t\t \t\t// next is a prefix block\n\t\t \t\tIPAddress lower = getLower();\n\t\t \t\tif(hasNext()) {\n\t\t\t \t\tif(!lower.includesZeroHost(prefixLength)) {\n\t\t\t \t\t\treturn create(lower, next.getUpper());\n\t\t\t \t\t}\n\t\t \t\t} else {\n\t\t \t\t\tIPAddress upper = getUpper();\n\t\t \t\t\tif(!lower.includesZeroHost(prefixLength) || !upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\t\treturn create(lower, upper);\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t} else if(!hasNext()) {\n\t\t \t\tIPAddress upper = getUpper();\n\t\t \t\tif(!upper.includesMaxHost(prefixLength)) {\n\t\t \t\t\treturn create(next.getLower(), upper);\n\t\t \t\t}\n\t\t \t}\n\t\t \treturn next.toSequentialRange();\n\t\t }\n\t\t\n\t\t @Override\n\t\t\tpublic void remove() {\n\t\t \tthrow new UnsupportedOperationException();\n\t\t }\n\t\t};\n\t}", "public static final int getInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n is.read(data);\n return getInt(data, 0);\n }", "public static void extractHouseholderRow( ZMatrixRMaj A ,\n int row ,\n int col0, int col1 , double u[], int offsetU )\n {\n int indexU = (offsetU+col0)*2;\n u[indexU] = 1;\n u[indexU+1] = 0;\n\n int indexA = (row*A.numCols + (col0+1))*2;\n System.arraycopy(A.data,indexA,u,indexU+2,(col1-col0-1)*2);\n }", "public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }", "public static base_response clear(nitro_service client) throws Exception {\n\t\tnspbr6 clearresource = new nspbr6();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}" ]
Use this API to fetch statistics of nspbr6_stats resource of given name .
[ "public static nspbr6_stats get(nitro_service service, String name) throws Exception{\n\t\tnspbr6_stats obj = new nspbr6_stats();\n\t\tobj.set_name(name);\n\t\tnspbr6_stats response = (nspbr6_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}" ]
[ "private <T> T request(ClientRequest<T> delegate, String operationName) {\n long startTimeMs = -1;\n long startTimeNs = -1;\n\n if(logger.isDebugEnabled()) {\n startTimeMs = System.currentTimeMillis();\n }\n ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);\n String debugMsgStr = \"\";\n\n startTimeNs = System.nanoTime();\n\n BlockingClientRequest<T> blockingClientRequest = null;\n try {\n blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);\n clientRequestExecutor.addClientRequest(blockingClientRequest,\n timeoutMs,\n System.nanoTime() - startTimeNs);\n\n boolean awaitResult = blockingClientRequest.await();\n\n if(awaitResult == false) {\n blockingClientRequest.timeOut();\n }\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"success\";\n\n return blockingClientRequest.getResult();\n } catch(InterruptedException e) {\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"unreachable: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e);\n } catch(UnreachableStoreException e) {\n clientRequestExecutor.close();\n\n if(logger.isDebugEnabled())\n debugMsgStr += \"failure: \" + e.getMessage();\n\n throw new UnreachableStoreException(\"Failure in \" + operationName + \" on \"\n + destination + \": \" + e.getMessage(), e.getCause());\n } finally {\n if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {\n // close the executor if we timed out\n clientRequestExecutor.close();\n }\n // Record operation time\n long opTimeNs = Utils.elapsedTimeNs(startTimeNs, System.nanoTime());\n if(stats != null) {\n stats.recordSyncOpTimeNs(destination, opTimeNs);\n }\n if(logger.isDebugEnabled()) {\n logger.debug(\"Sync request end, type: \"\n + operationName\n + \" requestRef: \"\n + System.identityHashCode(delegate)\n + \" totalTimeNs: \"\n + opTimeNs\n + \" start time: \"\n + startTimeMs\n + \" end time: \"\n + System.currentTimeMillis()\n + \" client:\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalAddress()\n + \":\"\n + clientRequestExecutor.getSocketChannel().socket().getLocalPort()\n + \" server: \"\n + clientRequestExecutor.getSocketChannel()\n .socket()\n .getRemoteSocketAddress() + \" outcome: \"\n + debugMsgStr);\n }\n\n pool.checkin(destination, clientRequestExecutor);\n }\n }", "public ParallelTaskBuilder setResponseContext(\n Map<String, Object> responseContext) {\n if (responseContext != null)\n this.responseContext = responseContext;\n else\n logger.error(\"context cannot be null. skip set.\");\n return this;\n }", "public void build(double[] coords, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (coords.length / 3 < nump) {\n throw new IllegalArgumentException(\"Coordinate array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(coords, nump);\n buildHull();\n }", "public static int getMemberDimension() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getDimension();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getDimension();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getDimension();\r\n }\r\n }\r\n return 0;\r\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static int checkLong(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInLongRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), LONG_MIN, LONG_MAX);\n\t\t}\n\n\t\treturn number.intValue();\n\t}", "@Programmatic\n public <T> List<T> fromExcel(\n final Blob excelBlob,\n final Class<T> cls,\n final String sheetName) throws ExcelService.Exception {\n return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName));\n }", "protected void process(String text, Map params, Writer writer){\n\n try{\n Template t = new Template(\"temp\", new StringReader(text), FreeMarkerTL.getEnvironment().getConfiguration());\n t.process(params, writer);\n }catch(Exception e){ \n throw new ViewException(e);\n }\n }", "private static void parseChildShapes(ArrayList<Shape> shapes,\n JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"childShapes\")) {\n ArrayList<Shape> childShapes = new ArrayList<Shape>();\n\n JSONArray childShapeObject = modelJSON.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapeObject.length(); i++) {\n childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString(\"resourceId\"),\n shapes));\n }\n if (childShapes.size() > 0) {\n for (Shape each : childShapes) {\n each.setParent(current);\n }\n current.setChildShapes(childShapes);\n }\n ;\n }\n }", "public void createPath(String pathName, String pathValue, String requestType) {\n try {\n int type = getRequestTypeFromString(requestType);\n String url = BASE_PATH;\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"pathName\", pathName),\n new BasicNameValuePair(\"path\", pathValue),\n new BasicNameValuePair(\"requestType\", String.valueOf(type)),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH, params));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }" ]
Returns the logger name that should be used in the log manager. @param name the name of the logger from the resource @return the name of the logger
[ "private static String getLogManagerLoggerName(final String name) {\n return (name.equals(RESOURCE_NAME) ? CommonAttributes.ROOT_LOGGER_NAME : name);\n }" ]
[ "protected void updateLabelActiveStyle() {\n if (this.valueBoxBase.getText() != null && !this.valueBoxBase.getText().isEmpty()) {\n label.addStyleName(CssName.ACTIVE);\n } else {\n label.removeStyleName(CssName.ACTIVE);\n }\n }", "public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {\n\t\tif (clazz1 == null) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tif (clazz2 == null) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz1.isAssignableFrom(clazz2)) {\n\t\t\treturn clazz1;\n\t\t}\n\t\tif (clazz2.isAssignableFrom(clazz1)) {\n\t\t\treturn clazz2;\n\t\t}\n\t\tClass<?> ancestor = clazz1;\n\t\tdo {\n\t\t\tancestor = ancestor.getSuperclass();\n\t\t\tif (ancestor == null || Object.class.equals(ancestor)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\twhile (!ancestor.isAssignableFrom(clazz2));\n\t\treturn ancestor;\n\t}", "public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case REQUEST_PERMISSIONS_CODE:\n if (listener != null) {\n boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;\n listener.onPermissionResult(granted);\n }\n break;\n default:\n // Ignored\n }\n }", "public void fire(StepFinishedEvent event) {\n Step step = stepStorage.adopt();\n event.process(step);\n\n notifier.fire(event);\n }", "public static void addActionsTo(\n SourceBuilder code,\n Set<MergeAction> mergeActions,\n boolean forBuilder) {\n SetMultimap<String, String> nounsByVerb = TreeMultimap.create();\n mergeActions.forEach(mergeAction -> {\n if (forBuilder || !mergeAction.builderOnly) {\n nounsByVerb.put(mergeAction.verb, mergeAction.noun);\n }\n });\n List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet());\n String lastVerb = getLast(verbs, null);\n for (String verb : nounsByVerb.keySet()) {\n code.add(\", %s%s\", (verbs.size() > 1 && verb.equals(lastVerb)) ? \"and \" : \"\", verb);\n List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb));\n for (int i = 0; i < nouns.size(); ++i) {\n String separator = (i == 0) ? \"\" : (i == nouns.size() - 1) ? \" and\" : \",\";\n code.add(\"%s %s\", separator, nouns.get(i));\n }\n }\n }", "private void appendSubQuery(Query subQuery, StringBuffer buf)\r\n {\r\n buf.append(\" (\");\r\n buf.append(getSubQuerySQL(subQuery));\r\n buf.append(\") \");\r\n }", "public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params );\n\t\treturn singleResult( result );\n\t}", "private void writeCompressedText(File file, byte[] compressedContent) throws IOException\r\n {\r\n ByteArrayInputStream bais = new ByteArrayInputStream(compressedContent);\r\n GZIPInputStream gis = new GZIPInputStream(bais);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(gis));\r\n BufferedWriter output = new BufferedWriter(new FileWriter(file));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n gis.close();\r\n bais.close();\r\n output.close();\r\n }", "public static Tuple2<Double, Double> getRandomGeographicalLocation() {\r\n return new Tuple2<>(\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100,\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100);\r\n }" ]
Add a "post-run" dependent task item for this task item. @param dependent the "post-run" dependent task item. @return key to be used as parameter to taskResult(string) method to retrieve result of root task in the given dependent task group
[ "public String addPostRunDependent(FunctionalTaskItem dependent) {\n Objects.requireNonNull(dependent);\n return this.taskGroup().addPostRunDependent(dependent);\n }" ]
[ "private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }", "public int expect(String pattern) throws MalformedPatternException, Exception {\n logger.trace(\"Searching for '\" + pattern + \"' in the reader stream\");\n return expect(pattern, null);\n }", "public void createAgent(String agent_name, String path) {\n IComponentIdentifier agent = cmsService.createComponent(agent_name,\n path, null, null).get(new ThreadSuspendable());\n createdAgents.put(agent_name, agent);\n }", "public void viewDocument(DocumentEntry entry)\n {\n InputStream is = null;\n\n try\n {\n is = new DocumentInputStream(entry);\n byte[] data = new byte[is.available()];\n is.read(data);\n m_model.setData(data);\n updateTables();\n }\n\n catch (IOException ex)\n {\n throw new RuntimeException(ex);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n\n }", "public JsonNode wbSetLabel(String id, String site, String title,\n\t\t\tString newEntity, String language, String value,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting a label\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (value != null) {\n\t\t\tparameters.put(\"value\", value);\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetlabel\", id, site, title, newEntity,\n\t\t\t\tparameters, summary, baserevid, bot);\n\t\treturn response;\n\t}", "public final void setIndividualDates(SortedSet<Date> dates) {\n\n m_individualDates.clear();\n if (null != dates) {\n m_individualDates.addAll(dates);\n }\n for (Date d : getExceptions()) {\n if (!m_individualDates.contains(d)) {\n m_exceptions.remove(d);\n }\n }\n\n }", "@SuppressWarnings(\"rawtypes\")\n\tprivate MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) {\n\t\treturn Mail.imapInboundAdapter(urlName.toString())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead());\n\t}", "protected boolean isStoreValid() {\n boolean result = false;\n String requestURI = this.request.getUri();\n this.storeName = parseStoreName(requestURI);\n if(storeName != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. Missing store name.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing store name. Critical error.\");\n }\n return result;\n }", "public void setVertexBuffer(GVRVertexBuffer vbuf)\n {\n if (vbuf == null)\n {\n throw new IllegalArgumentException(\"Vertex buffer cannot be null\");\n }\n mVertices = vbuf;\n NativeMesh.setVertexBuffer(getNative(), vbuf.getNative());\n }" ]
Use this API to export sslfipskey resources.
[ "public static base_responses export(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey exportresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new sslfipskey();\n\t\t\t\texportresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\texportresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }", "private Proctor getProctorNotNull() {\n final Proctor proctor = proctorLoader.get();\n if (proctor == null) {\n throw new IllegalStateException(\"Proctor specification and/or text matrix has not been loaded\");\n }\n return proctor;\n }", "public static double blackScholesOptionRho(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate rho\n\t\t\tdouble dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\n\t\t\tdouble rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn rho;\n\t\t}\n\t}", "private void readCalendars()\n {\n //\n // Create the calendars\n //\n for (MapRow row : getTable(\"NCALTAB\"))\n {\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setUniqueID(row.getInteger(\"UNIQUE_ID\"));\n calendar.setName(row.getString(\"NAME\"));\n calendar.setWorkingDay(Day.SUNDAY, row.getBoolean(\"SUNDAY\"));\n calendar.setWorkingDay(Day.MONDAY, row.getBoolean(\"MONDAY\"));\n calendar.setWorkingDay(Day.TUESDAY, row.getBoolean(\"TUESDAY\"));\n calendar.setWorkingDay(Day.WEDNESDAY, row.getBoolean(\"WEDNESDAY\"));\n calendar.setWorkingDay(Day.THURSDAY, row.getBoolean(\"THURSDAY\"));\n calendar.setWorkingDay(Day.FRIDAY, row.getBoolean(\"FRIDAY\"));\n calendar.setWorkingDay(Day.SATURDAY, row.getBoolean(\"SATURDAY\"));\n\n for (Day day : Day.values())\n {\n if (calendar.isWorkingDay(day))\n {\n // TODO: this is an approximation\n calendar.addDefaultCalendarHours(day);\n }\n }\n }\n\n //\n // Set up the hierarchy and add exceptions\n //\n Table exceptionsTable = getTable(\"CALXTAB\");\n for (MapRow row : getTable(\"NCALTAB\"))\n {\n ProjectCalendar child = m_projectFile.getCalendarByUniqueID(row.getInteger(\"UNIQUE_ID\"));\n ProjectCalendar parent = m_projectFile.getCalendarByUniqueID(row.getInteger(\"BASE_CALENDAR_ID\"));\n if (child != null && parent != null)\n {\n child.setParent(parent);\n }\n\n addCalendarExceptions(exceptionsTable, child, row.getInteger(\"FIRST_CALENDAR_EXCEPTION_ID\"));\n\n m_eventManager.fireCalendarReadEvent(child);\n }\n }", "protected List<BoxAPIResponse> parseResponse(BoxJSONResponse batchResponse) {\n JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON());\n List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>();\n Iterator<JsonValue> responseIterator = responseJSON.get(\"responses\").asArray().iterator();\n while (responseIterator.hasNext()) {\n JsonObject jsonResponse = responseIterator.next().asObject();\n BoxAPIResponse response = null;\n\n //Gather headers\n Map<String, String> responseHeaders = new HashMap<String, String>();\n\n if (jsonResponse.get(\"headers\") != null) {\n JsonObject batchResponseHeadersObject = jsonResponse.get(\"headers\").asObject();\n for (JsonObject.Member member : batchResponseHeadersObject) {\n String headerName = member.getName();\n String headerValue = member.getValue().asString();\n responseHeaders.put(headerName, headerValue);\n }\n }\n\n // Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response\n // (not anticipating any other response as per current APIs.\n // Ideally we should do it based on response header)\n if (jsonResponse.get(\"response\") == null || jsonResponse.get(\"response\").isNull()) {\n response =\n new BoxAPIResponse(jsonResponse.get(\"status\").asInt(), responseHeaders);\n } else {\n response =\n new BoxJSONResponse(jsonResponse.get(\"status\").asInt(), responseHeaders,\n jsonResponse.get(\"response\").asObject());\n }\n responses.add(response);\n }\n return responses;\n }", "private boolean loadCustomErrorPage(\n CmsObject cms,\n HttpServletRequest req,\n HttpServletResponse res,\n String rootPath) {\n\n try {\n\n // get the site of the error page resource\n CmsSite errorSite = OpenCms.getSiteManager().getSiteForRootPath(rootPath);\n cms.getRequestContext().setSiteRoot(errorSite.getSiteRoot());\n String relPath = cms.getRequestContext().removeSiteRoot(rootPath);\n if (cms.existsResource(relPath)) {\n cms.getRequestContext().setUri(relPath);\n OpenCms.getResourceManager().loadResource(cms, cms.readResource(relPath), req, res);\n return true;\n } else {\n return false;\n }\n } catch (Throwable e) {\n // something went wrong log the exception and return false\n LOG.error(e.getMessage(), e);\n return false;\n }\n }", "public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}", "protected Boolean getSearchForEmptyQuery() {\n\n Boolean isSearchForEmptyQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_SEARCH_FOR_EMPTY_QUERY);\n return (isSearchForEmptyQuery == null) && (null != m_baseConfig)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getSearchForEmptyQueryParam())\n : isSearchForEmptyQuery;\n }", "private static void initInstance(final TransactionLogger instance, final Logger logger, final Logger auditor) {\n instance.logger = logger;\n instance.auditor = auditor;\n instance.components = new LinkedHashMap<>();\n instance.properties = new LinkedHashMap<>();\n instance.total = new Component(TOTAL_COMPONENT);\n instance.total.startTimer();\n instance.componentsMultiThread = new ComponentsMultiThread();\n instance.flowContext = FlowContextFactory.serializeNativeFlowContext();\n }" ]
Set the pickers selection type.
[ "public void setSelectionType(MaterialDatePickerType selectionType) {\n this.selectionType = selectionType;\n switch (selectionType) {\n case MONTH_DAY:\n options.selectMonths = true;\n break;\n case YEAR_MONTH_DAY:\n options.selectYears = yearsToDisplay;\n options.selectMonths = true;\n break;\n case YEAR:\n options.selectYears = yearsToDisplay;\n options.selectMonths = false;\n break;\n }\n }" ]
[ "public synchronized Set<RegistrationPoint> getRegistrationPoints() {\n Set<RegistrationPoint> result = new HashSet<>();\n for (List<RegistrationPoint> registrationPoints : registrationPoints.values()) {\n result.addAll(registrationPoints);\n }\n return Collections.unmodifiableSet(result);\n }", "public static Object instantiate(Constructor constructor) throws InstantiationException\r\n {\r\n if(constructor == null)\r\n {\r\n throw new ClassNotPersistenceCapableException(\r\n \"A zero argument constructor was not provided!\");\r\n }\r\n\r\n Object result = null;\r\n try\r\n {\r\n result = constructor.newInstance(NO_ARGS);\r\n }\r\n catch(InstantiationException e)\r\n {\r\n throw e;\r\n }\r\n catch(Exception e)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (constructor != null ? constructor.getDeclaringClass().getName() : \"null\")\r\n + \"' with given constructor: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n }", "public Map<Integer, Row> createWorkPatternMap(List<Row> rows)\n {\n Map<Integer, Row> map = new HashMap<Integer, Row>();\n for (Row row : rows)\n {\n map.put(row.getInteger(\"WORK_PATTERNID\"), row);\n }\n return map;\n }", "protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }", "@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }", "private static void mergeBlocks(List< Block > blocks) {\r\n for (int i = 1; i < blocks.size(); i++) {\r\n Block b1 = blocks.get(i - 1);\r\n Block b2 = blocks.get(i);\r\n if ((b1.mode == b2.mode) &&\r\n (b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n b1.length += b2.length;\r\n blocks.remove(i);\r\n i--;\r\n }\r\n }\r\n }", "public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }", "public static appfwprofile_safeobject_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_safeobject_binding obj = new appfwprofile_safeobject_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_safeobject_binding response[] = (appfwprofile_safeobject_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static ThreadPoolExecutor newFixedThreadPool(int threads, String groupname, int queueSize) {\n\t\treturn new ThreadPoolExecutor( threads, threads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(\n\t\t\t\tqueueSize ), new SearchThreadFactory( groupname ), new BlockPolicy() );\n\t}" ]
Enable clipping for the Widget. Widget content including its children will be clipped by a rectangular View Port. By default clipping is disabled.
[ "public void enableClipRegion() {\n if (mClippingEnabled) {\n Log.w(TAG, \"Clipping has been enabled already for %s!\", getName());\n return;\n }\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"enableClipping for %s [%f, %f, %f]\",\n getName(), getViewPortWidth(), getViewPortHeight(), getViewPortDepth());\n\n mClippingEnabled = true;\n\n GVRTexture texture = WidgetLib.getTextureHelper().getSolidColorTexture(Color.YELLOW);\n\n GVRSceneObject clippingObj = new GVRSceneObject(mContext, getViewPortWidth(), getViewPortHeight(), texture);\n clippingObj.setName(\"clippingObj\");\n clippingObj.getRenderData()\n .setRenderingOrder(GVRRenderData.GVRRenderingOrder.STENCIL)\n .setStencilTest(true)\n .setStencilFunc(GLES30.GL_ALWAYS, 1, 0xFF)\n .setStencilOp(GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_REPLACE)\n .setStencilMask(0xFF);\n\n mSceneObject.addChildObject(clippingObj);\n\n for (Widget child : getChildren()) {\n setObjectClipped(child);\n }\n }" ]
[ "protected Path normalizePath(final Path parent, final String path) {\n return parent.resolve(path).toAbsolutePath().normalize();\n }", "public static Object setProperty( String key, String value ) {\n return prp.setProperty( key, value );\n }", "private static void unpackFace(File outputDirectory) throws IOException {\n ClassLoader loader = AllureMain.class.getClassLoader();\n for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) {\n Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName());\n if (matcher.find()) {\n String resourcePath = matcher.group(1);\n File dest = new File(outputDirectory, resourcePath);\n Files.createParentDirs(dest);\n try (FileOutputStream output = new FileOutputStream(dest);\n InputStream input = info.url().openStream()) {\n IOUtils.copy(input, output);\n LOGGER.debug(\"{} successfully copied.\", resourcePath);\n }\n }\n }\n }", "public void initialize(BinaryPackageControlFile packageControlFile) {\n set(\"Binary\", packageControlFile.get(\"Package\"));\n set(\"Source\", Utils.defaultString(packageControlFile.get(\"Source\"), packageControlFile.get(\"Package\")));\n set(\"Architecture\", packageControlFile.get(\"Architecture\"));\n set(\"Version\", packageControlFile.get(\"Version\"));\n set(\"Maintainer\", packageControlFile.get(\"Maintainer\"));\n set(\"Changed-By\", packageControlFile.get(\"Maintainer\"));\n set(\"Distribution\", packageControlFile.get(\"Distribution\"));\n\n for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {\n set(entry.getKey(), entry.getValue());\n }\n\n StringBuilder description = new StringBuilder();\n description.append(packageControlFile.get(\"Package\"));\n if (packageControlFile.get(\"Description\") != null) {\n description.append(\" - \");\n description.append(packageControlFile.getShortDescription());\n }\n set(\"Description\", description.toString());\n }", "public <FV> FV extractRawJavaFieldValue(Object object) throws SQLException {\n\t\tObject val;\n\t\tif (fieldGetMethod == null) {\n\t\t\ttry {\n\t\t\t\t// field object may not be a T yet\n\t\t\t\tval = field.get(object);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not get field value for \" + this, e);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tval = fieldGetMethod.invoke(object);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not call \" + fieldGetMethod + \" for \" + this, e);\n\t\t\t}\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tFV converted = (FV) val;\n\t\treturn converted;\n\t}", "public Enumeration getPKEnumerationByQuery(Class primaryKeyClass, Query query) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getPKEnumerationByQuery \" + query);\n\n query.setFetchSize(1);\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return new PkEnumeration(query, cld, primaryKeyClass, this);\n }", "public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n List<Versioned<V>> versionedValues;\n long startTime = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"PUT requested for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + startTime\n + \" . Nested GET and PUT VERSION requests to follow ---\");\n }\n\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent put might be faster such that all the\n // steps might finish within the allotted time\n requestWrapper.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(requestWrapper);\n Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues);\n\n long endTime = System.currentTimeMillis();\n if(versioned == null)\n versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock());\n else\n versioned.setObject(requestWrapper.getRawValue());\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime);\n if(timeLeft <= 0) {\n throw new StoreTimeoutException(\"PUT request timed out\");\n }\n CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(),\n versioned,\n timeLeft);\n putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs());\n Version result = putVersionedWithCustomTimeout(putVersionedRequestObject);\n long endTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT response received for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + endTimeInMs);\n }\n return result;\n }", "public <E extends Enum<E> & FieldType> E nextField(Class<E> clazz, UserFieldDataType type)\n {\n for (String name : m_names[type.ordinal()])\n {\n int i = NumberHelper.getInt(m_counters.get(name)) + 1;\n try\n {\n E e = Enum.valueOf(clazz, name + i);\n m_counters.put(name, Integer.valueOf(i));\n return e;\n }\n catch (IllegalArgumentException ex)\n {\n // try the next name\n }\n }\n\n // no more fields available\n throw new IllegalArgumentException(\"No fields for type \" + type + \" available\");\n }", "public static BoxConfig readFrom(Reader reader) throws IOException {\n JsonObject config = JsonObject.readFrom(reader);\n JsonObject settings = (JsonObject) config.get(\"boxAppSettings\");\n String clientId = settings.get(\"clientID\").asString();\n String clientSecret = settings.get(\"clientSecret\").asString();\n JsonObject appAuth = (JsonObject) settings.get(\"appAuth\");\n String publicKeyId = appAuth.get(\"publicKeyID\").asString();\n String privateKey = appAuth.get(\"privateKey\").asString();\n String passphrase = appAuth.get(\"passphrase\").asString();\n String enterpriseId = config.get(\"enterpriseID\").asString();\n return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase);\n }" ]
Set the meta data for the photo. This method requires authentication with 'write' permission. @param photoId The photo ID @param title The new title @param description The new description @throws FlickrException
[ "public void setMeta(String photoId, String title, String description) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_META);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
[ "protected boolean checkvalue(String colorvalue) {\n\n boolean valid = validateColorValue(colorvalue);\n if (valid) {\n if (colorvalue.length() == 4) {\n char[] chr = colorvalue.toCharArray();\n for (int i = 1; i < 4; i++) {\n String foo = String.valueOf(chr[i]);\n colorvalue = colorvalue.replaceFirst(foo, foo + foo);\n }\n }\n m_textboxColorValue.setValue(colorvalue, true);\n m_colorField.getElement().getStyle().setBackgroundColor(colorvalue);\n m_colorValue = colorvalue;\n }\n return valid;\n }", "public static dnsnsecrec[] get(nitro_service service, String hostname[]) throws Exception{\n\t\tif (hostname !=null && hostname.length>0) {\n\t\t\tdnsnsecrec response[] = new dnsnsecrec[hostname.length];\n\t\t\tdnsnsecrec obj[] = new dnsnsecrec[hostname.length];\n\t\t\tfor (int i=0;i<hostname.length;i++) {\n\t\t\t\tobj[i] = new dnsnsecrec();\n\t\t\t\tobj[i].set_hostname(hostname[i]);\n\t\t\t\tresponse[i] = (dnsnsecrec) 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 removeCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);\n }", "public synchronized List<String> propertyListOf(Class<?> c) {\n String cn = c.getName();\n List<String> ls = repo.get(cn);\n if (ls != null) {\n return ls;\n }\n Set<Class<?>> circularReferenceDetector = new HashSet<>();\n ls = propertyListOf(c, circularReferenceDetector, null);\n repo.put(c.getName(), ls);\n return ls;\n }", "public final void warn(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.WARN, pObject, null);\r\n\t}", "private Profile getProfileFromResultSet(ResultSet result) throws Exception {\n Profile profile = new Profile();\n profile.setId(result.getInt(Constants.GENERIC_ID));\n Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);\n String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());\n profile.setName(profileName);\n return profile;\n }", "public static appfwsignatures get(nitro_service service, String name) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tobj.set_name(name);\n\t\tappfwsignatures response = (appfwsignatures) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }", "protected MappedPreparedStmt<T, ID> prepareStatement(Long limit, boolean cacheStore) throws SQLException {\n\t\tList<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();\n\t\tString statement = buildStatementString(argList);\n\t\tArgumentHolder[] selectArgs = argList.toArray(new ArgumentHolder[argList.size()]);\n\t\tFieldType[] resultFieldTypes = getResultFieldTypes();\n\t\tFieldType[] argFieldTypes = new FieldType[argList.size()];\n\t\tfor (int selectC = 0; selectC < selectArgs.length; selectC++) {\n\t\t\targFieldTypes[selectC] = selectArgs[selectC].getFieldType();\n\t\t}\n\t\tif (!type.isOkForStatementBuilder()) {\n\t\t\tthrow new IllegalStateException(\"Building a statement from a \" + type + \" statement is not allowed\");\n\t\t}\n\t\treturn new MappedPreparedStmt<T, ID>(dao, tableInfo, statement, argFieldTypes, resultFieldTypes, selectArgs,\n\t\t\t\t(databaseType.isLimitSqlSupported() ? null : limit), type, cacheStore);\n\t}" ]
Convert a SSE to a Stitch SSE @param event SSE to convert @param decoder decoder for decoding data @param <T> type to decode data to @return a Stitch server-sent event
[ "static <T> StitchEvent<T> fromEvent(final Event event,\n final Decoder<T> decoder) {\n return new StitchEvent<>(event.getEventName(), event.getData(), decoder);\n }" ]
[ "public static base_response add(nitro_service client, cmppolicylabel resource) throws Exception {\n\t\tcmppolicylabel addresource = new cmppolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}", "public void checkSpecialization() {\n if (isSpecializing()) {\n boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);\n String previousSpecializedBeanName = null;\n for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {\n String name = specializedBean.getName();\n if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {\n // there may be multiple beans specialized by this bean - make sure they all share the same name\n throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);\n }\n previousSpecializedBeanName = name;\n if (isNameDefined && name != null) {\n throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());\n }\n\n // When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are\n // added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among\n // these types are NOT types of the specializing bean (that's the way java works)\n boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>\n && specializedBean.getBeanClass().getTypeParameters().length > 0\n && !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));\n for (Type specializedType : specializedBean.getTypes()) {\n if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n boolean contains = getTypes().contains(specializedType);\n if (!contains) {\n for (Type specializingType : getTypes()) {\n // In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be\n // equal in the java sense. Therefore we have to use our own equality util.\n if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {\n contains = true;\n break;\n }\n }\n }\n if (!contains) {\n throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);\n }\n }\n }\n }\n }", "@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 static byte[] getContentBytes(String stringUrl) throws IOException {\n URL url = new URL(stringUrl);\n byte[] data = MyStreamUtils.readContentBytes(url.openStream());\n return data;\n }", "public void setValue(Quaternionf rot) {\n mX = rot.x;\n mY = rot.y;\n mZ = rot.z;\n mW = rot.w;\n }", "protected void ensureColumns(List columns, List existingColumns)\r\n {\r\n if (columns == null || columns.isEmpty())\r\n {\r\n return;\r\n }\r\n \r\n Iterator iter = columns.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n FieldHelper cf = (FieldHelper) iter.next();\r\n if (!existingColumns.contains(cf.name))\r\n {\r\n getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());\r\n }\r\n }\r\n }", "private synchronized void flushData() {\n BufferedWriter writer = null;\n try {\n writer = new BufferedWriter(new FileWriter(new File(this.inputPath)));\n for(String key: this.metadataMap.keySet()) {\n writer.write(NEW_PROPERTY_SEPARATOR + key.toString() + \"]\" + NEW_LINE);\n writer.write(this.metadataMap.get(key).toString());\n writer.write(\"\" + NEW_LINE + \"\" + NEW_LINE);\n }\n writer.flush();\n } catch(IOException e) {\n logger.error(\"IO exception while flushing data to file backed storage: \"\n + e.getMessage());\n }\n\n try {\n if(writer != null)\n writer.close();\n } catch(Exception e) {\n logger.error(\"Error while flushing data to file backed storage: \" + e.getMessage());\n }\n }", "private int readOptionalInt(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return Integer.valueOf(str.stringValue()).intValue();\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return 0;\n }", "public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}" ]
Await a state. @param expected the expected state @return {@code true} if the state was reached, {@code false} otherwise
[ "boolean awaitState(final InternalState expected) {\n synchronized (this) {\n final InternalState initialRequired = this.requiredState;\n for(;;) {\n final InternalState required = this.requiredState;\n // Stop in case the server failed to reach the state\n if(required == InternalState.FAILED) {\n return false;\n // Stop in case the required state changed\n } else if (initialRequired != required) {\n return false;\n }\n final InternalState current = this.internalState;\n if(expected == current) {\n return true;\n }\n try {\n wait();\n } catch(InterruptedException e) {\n Thread.currentThread().interrupt();\n return false;\n }\n }\n }\n }" ]
[ "public static nslimitidentifier_binding get(nitro_service service, String limitidentifier) throws Exception{\n\t\tnslimitidentifier_binding obj = new nslimitidentifier_binding();\n\t\tobj.set_limitidentifier(limitidentifier);\n\t\tnslimitidentifier_binding response = (nslimitidentifier_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }", "public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken) {\n return getWriter(type, oauthToken, false);\n }", "public void validateOperation(final ModelNode operation) {\n if (operation == null) {\n return;\n }\n final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));\n final String name = operation.get(OP).asString();\n\n OperationEntry entry = root.getOperationEntry(address, name);\n if (entry == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationEntry(name, address));\n }\n //noinspection ConstantConditions\n if (entry.getType() == EntryType.PRIVATE || entry.getFlags().contains(OperationEntry.Flag.HIDDEN)) {\n return;\n }\n if (entry.getOperationHandler() == null) {\n throwOrWarnAboutDescriptorProblem(ControllerLogger.ROOT_LOGGER.noOperationHandler(name, address));\n }\n final DescriptionProvider provider = getDescriptionProvider(operation);\n final ModelNode description = provider.getModelDescription(null);\n\n final Map<String, ModelNode> describedProperties = getDescribedRequestProperties(operation, description);\n final Map<String, ModelNode> actualParams = getActualRequestProperties(operation);\n\n checkActualOperationParamsAreDescribed(operation, describedProperties, actualParams);\n checkAllRequiredPropertiesArePresent(description, operation, describedProperties, actualParams);\n checkParameterTypes(description, operation, describedProperties, actualParams);\n\n //TODO check ranges\n }", "public static void hideOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.showAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoHide(channel);\r\n }\r\n }\r\n }\r\n }", "private void writeAttributeTypes(String name, FieldType[] types) throws IOException\n {\n m_writer.writeStartObject(name);\n for (FieldType field : types)\n {\n m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue());\n }\n m_writer.writeEndObject();\n }", "private void countEntity() {\n\t\tif (!this.timer.isRunning()) {\n\t\t\tstartTimer();\n\t\t}\n\n\t\tthis.entityCount++;\n\t\tif (this.entityCount % 100 == 0) {\n\t\t\ttimer.stop();\n\t\t\tint seconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\t\tif (seconds >= this.lastSeconds + this.reportInterval) {\n\t\t\t\tthis.lastSeconds = seconds;\n\t\t\t\tprintStatus();\n\t\t\t\tif (this.timeout > 0 && seconds > this.timeout) {\n\t\t\t\t\tlogger.info(\"Timeout. Aborting processing.\");\n\t\t\t\t\tthrow new TimeoutException();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer.start();\n\t\t}\n\t}", "protected void afterMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\t// listeners may remove themselves during the afterMaterialization\r\n\t\t\t// callback.\r\n\t\t\t// thus we must iterate through the listeners vector from back to\r\n\t\t\t// front\r\n\t\t\t// to avoid index problems.\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.afterMaterialization(this, _realSubject);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private int getTaskCode(String field) throws MPXJException\n {\n Integer result = m_taskNumbers.get(field.trim());\n\n if (result == null)\n {\n throw new MPXJException(MPXJException.INVALID_TASK_FIELD_NAME + \" \" + field);\n }\n\n return (result.intValue());\n }" ]
Copy the contents of the given String to the given output Writer. Closes the writer when done. @param in the String to copy from @param out the Writer to copy to @throws IOException in case of I/O errors
[ "public static void copy(String in, Writer out) throws IOException {\n\t\tAssert.notNull(in, \"No input String specified\");\n\t\tAssert.notNull(out, \"No Writer specified\");\n\t\ttry {\n\t\t\tout.write(in);\n\t\t}\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tout.close();\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t}\n\t\t}\n\t}" ]
[ "private void stereotype(Options opt, Doc c, Align align) {\n\tfor (Tag tag : c.tags(\"stereotype\")) {\n\t String t[] = tokenize(tag.text());\n\t if (t.length != 1) {\n\t\tSystem.err.println(\"@stereotype expects one field: \" + tag.text());\n\t\tcontinue;\n\t }\n\t tableLine(align, guilWrap(opt, t[0]));\n\t}\n }", "public boolean hasProperties(Set<PropertyKey> keys) {\n for (PropertyKey key : keys) {\n if (null == getProperty(key.m_key)) {\n return false;\n }\n }\n \n return true;\n }", "public ClientLayerInfo securityClone(ClientLayerInfo original) {\n\t\t// the data is explicitly copied as this assures the security is considered when copying.\n\t\tif (null == original) {\n\t\t\treturn null;\n\t\t}\n\t\tClientLayerInfo client = null;\n\t\tString layerId = original.getServerLayerId();\n\t\tif (securityContext.isLayerVisible(layerId)) {\n\t\t\tclient = (ClientLayerInfo) SerializationUtils.clone(original);\n\t\t\tclient.setWidgetInfo(securityClone(original.getWidgetInfo()));\n\t\t\tclient.getLayerInfo().setExtraInfo(securityCloneLayerExtraInfo(original.getLayerInfo().getExtraInfo()));\n\t\t\tif (client instanceof ClientVectorLayerInfo) {\n\t\t\t\tClientVectorLayerInfo vectorLayer = (ClientVectorLayerInfo) client;\n\t\t\t\t// set statuses\n\t\t\t\tvectorLayer.setCreatable(securityContext.isLayerCreateAuthorized(layerId));\n\t\t\t\tvectorLayer.setUpdatable(securityContext.isLayerUpdateAuthorized(layerId));\n\t\t\t\tvectorLayer.setDeletable(securityContext.isLayerDeleteAuthorized(layerId));\n\t\t\t\t// filter feature info\n\t\t\t\tFeatureInfo featureInfo = vectorLayer.getFeatureInfo();\n\t\t\t\tList<AttributeInfo> originalAttr = featureInfo.getAttributes();\n\t\t\t\tList<AttributeInfo> filteredAttr = new ArrayList<AttributeInfo>();\n\t\t\t\tfeatureInfo.setAttributes(filteredAttr);\n\t\t\t\tfor (AttributeInfo ai : originalAttr) {\n\t\t\t\t\tif (securityContext.isAttributeReadable(layerId, null, ai.getName())) {\n\t\t\t\t\t\tfilteredAttr.add(ai);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn client;\n\t}", "protected void reportProgress(String taskDecription) {\n if (this.progress != null) {\n if (this.progress.isCanceled()) {\n // Only AbortCompilation can stop the compiler cleanly.\n // We check cancellation again following the call to compile.\n throw new AbortCompilation(true, null);\n }\n this.progress.setTaskName(taskDecription);\n }\n }", "public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\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 static MetadataTemplate getMetadataTemplateByID(BoxAPIConnection api, String templateID) {\n\n URL url = METADATA_TEMPLATE_BY_ID_URL_TEMPLATE.build(api.getBaseURL(), templateID);\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new MetadataTemplate(response.getJSON());\n }", "public void onDrawFrame(float frameTime)\n {\n if (!isEnabled() || (owner == null) || (getFloat(\"enabled\") <= 0.0f))\n {\n return;\n }\n float[] odir = getVec3(\"world_direction\");\n float[] opos = getVec3(\"world_position\");\n GVRSceneObject parent = owner;\n Matrix4f worldmtx = parent.getTransform().getModelMatrix4f();\n\n mOldDir.x = odir[0];\n mOldDir.y = odir[1];\n mOldDir.z = odir[2];\n mOldPos.x = opos[0];\n mOldPos.y = opos[1];\n mOldPos.z = opos[2];\n mNewDir.x = 0.0f;\n mNewDir.y = 0.0f;\n mNewDir.z = -1.0f;\n worldmtx.getTranslation(mNewPos);\n worldmtx.mul(mLightRot);\n worldmtx.transformDirection(mNewDir);\n if ((mOldDir.x != mNewDir.x) || (mOldDir.y != mNewDir.y) || (mOldDir.z != mNewDir.z))\n {\n setVec4(\"world_direction\", mNewDir.x, mNewDir.y, mNewDir.z, 0);\n }\n if ((mOldPos.x != mNewPos.x) || (mOldPos.y != mNewPos.y) || (mOldPos.z != mNewPos.z))\n {\n setPosition(mNewPos.x, mNewPos.y, mNewPos.z);\n }\n }", "boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));\n }" ]
This method is currently in use only by the SvnCoordinator
[ "public String getRemoteUrl(String defaultRemoteUrl) {\n if (StringUtils.isBlank(defaultRemoteUrl)) {\n RemoteConfig remoteConfig = getJenkinsScm().getRepositories().get(0);\n URIish uri = remoteConfig.getURIs().get(0);\n return uri.toPrivateString();\n }\n\n return defaultRemoteUrl;\n }" ]
[ "public void setAddContentInfo(final Boolean doAddInfo) {\n\n if ((null != doAddInfo) && doAddInfo.booleanValue() && (null != m_addContentInfoForEntries)) {\n m_addContentInfoForEntries = Integer.valueOf(DEFAULT_CONTENTINFO_ROWS);\n }\n }", "@Override\r\n public void onBrowserEvent(Event event) {\r\n\r\n super.onBrowserEvent(event);\r\n\r\n switch (DOM.eventGetType(event)) {\r\n case Event.ONMOUSEUP:\r\n Event.releaseCapture(m_slider.getElement());\r\n m_capturedMouse = false;\r\n break;\r\n case Event.ONMOUSEDOWN:\r\n Event.setCapture(m_slider.getElement());\r\n m_capturedMouse = true;\r\n //$FALL-THROUGH$\r\n case Event.ONMOUSEMOVE:\r\n if (m_capturedMouse) {\r\n event.preventDefault();\r\n float x = ((event.getClientX() - (m_colorUnderlay.getAbsoluteLeft())) + Window.getScrollLeft());\r\n float y = ((event.getClientY() - (m_colorUnderlay.getAbsoluteTop())) + Window.getScrollTop());\r\n\r\n if (m_parent != null) {\r\n m_parent.onMapSelected(x, y);\r\n }\r\n\r\n setSliderPosition(x, y);\r\n }\r\n //$FALL-THROUGH$\r\n default:\r\n\r\n }\r\n }", "public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }", "public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(urlPattern, true), actorClass);\n }", "public static dnsglobal_binding get(nitro_service service) throws Exception{\n\t\tdnsglobal_binding obj = new dnsglobal_binding();\n\t\tdnsglobal_binding response = (dnsglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static LinearSolverDense<DMatrixRMaj> symmPosDef(int matrixWidth ) {\n if(matrixWidth < EjmlParameters.SWITCH_BLOCK64_CHOLESKY ) {\n CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true);\n return new LinearSolverChol_DDRM(decomp);\n } else {\n if( EjmlParameters.MEMORY == EjmlParameters.MemoryUsage.FASTER )\n return new LinearSolverChol_DDRB();\n else {\n CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true);\n return new LinearSolverChol_DDRM(decomp);\n }\n }\n }", "private void fillQueue(QueueItem item, Integer minStartPosition,\n Integer maxStartPosition, Integer minEndPosition) throws IOException {\n int newStartPosition;\n int newEndPosition;\n Integer firstRetrievedPosition = null;\n // remove everything below minStartPosition\n if ((minStartPosition != null) && (item.lowestPosition != null)\n && (item.lowestPosition < minStartPosition)) {\n item.del((minStartPosition - 1));\n }\n // fill queue\n while (!item.noMorePositions) {\n boolean doNotCollectAnotherPosition;\n doNotCollectAnotherPosition = item.filledPosition\n && (minStartPosition == null) && (maxStartPosition == null);\n doNotCollectAnotherPosition |= item.filledPosition\n && (maxStartPosition != null) && (item.lastRetrievedPosition != null)\n && (maxStartPosition < item.lastRetrievedPosition);\n if (doNotCollectAnotherPosition) {\n return;\n } else {\n // collect another full position\n firstRetrievedPosition = null;\n while (!item.noMorePositions) {\n newStartPosition = item.sequenceSpans.spans.nextStartPosition();\n if (newStartPosition == NO_MORE_POSITIONS) {\n if (!item.queue.isEmpty()) {\n item.filledPosition = true;\n item.lastFilledPosition = item.lastRetrievedPosition;\n }\n item.noMorePositions = true;\n return;\n } else if ((minStartPosition != null)\n && (newStartPosition < minStartPosition)) {\n // do nothing\n } else {\n newEndPosition = item.sequenceSpans.spans.endPosition();\n if ((minEndPosition == null) || (newEndPosition >= minEndPosition\n - ignoreItem.getMinStartPosition(docId, newEndPosition))) {\n item.add(newStartPosition, newEndPosition);\n if (firstRetrievedPosition == null) {\n firstRetrievedPosition = newStartPosition;\n } else if (!firstRetrievedPosition.equals(newStartPosition)) {\n break;\n }\n }\n }\n }\n }\n }\n }", "public String toStringByValue() {\r\n\tIntArrayList theKeys = new IntArrayList();\r\n\tkeysSortedByValue(theKeys);\r\n\r\n\tStringBuffer buf = new StringBuffer();\r\n\tbuf.append(\"[\");\r\n\tint maxIndex = theKeys.size() - 1;\r\n\tfor (int i = 0; i <= maxIndex; i++) {\r\n\t\tint key = theKeys.get(i);\r\n\t buf.append(String.valueOf(key));\r\n\t\tbuf.append(\"->\");\r\n\t buf.append(String.valueOf(get(key)));\r\n\t\tif (i < maxIndex) buf.append(\", \");\r\n\t}\r\n\tbuf.append(\"]\");\r\n\treturn buf.toString();\r\n}", "public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }" ]
Create a KnowledgeBuilderConfiguration on which properties can be set. Use the given properties file and ClassLoader - either of which can be null. @return The KnowledgeBuilderConfiguration.
[ "public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration(Properties properties,\n ClassLoader... classLoaders) {\n return FactoryServiceHolder.factoryService.newKnowledgeBuilderConfiguration( properties, classLoaders );\n }" ]
[ "public static List<DockerImage> getImagesByBuildId(int buildInfoId) {\n List<DockerImage> list = new ArrayList<DockerImage>();\n Iterator<DockerImage> it = images.iterator();\n while (it.hasNext()) {\n DockerImage image = it.next();\n if (image.getBuildInfoId() == buildInfoId && image.hasManifest()) {\n list.add(image);\n }\n }\n return list;\n }", "public static List<String> createBacktrace(final Throwable t) {\n final List<String> bTrace = new LinkedList<String>();\n for (final StackTraceElement ste : t.getStackTrace()) {\n bTrace.add(BT_PREFIX + ste.toString());\n }\n if (t.getCause() != null) {\n addCauseToBacktrace(t.getCause(), bTrace);\n }\n return bTrace;\n }", "private void populateExpandedExceptions()\n {\n if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty())\n {\n for (ProjectCalendarException exception : m_exceptions)\n {\n RecurringData recurring = exception.getRecurring();\n if (recurring == null)\n {\n m_expandedExceptions.add(exception);\n }\n else\n {\n for (Date date : recurring.getDates())\n {\n Date startDate = DateHelper.getDayStartDate(date);\n Date endDate = DateHelper.getDayEndDate(date);\n ProjectCalendarException newException = new ProjectCalendarException(startDate, endDate);\n int rangeCount = exception.getRangeCount();\n for (int rangeIndex = 0; rangeIndex < rangeCount; rangeIndex++)\n {\n newException.addRange(exception.getRange(rangeIndex));\n }\n m_expandedExceptions.add(newException);\n }\n }\n }\n Collections.sort(m_expandedExceptions);\n }\n }", "public static Properties getProps(Properties props, String name, Properties defaultProperties) {\n final String propString = props.getProperty(name);\n if (propString == null) return defaultProperties;\n String[] propValues = propString.split(\",\");\n if (propValues.length < 1) {\n throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propString + \"'\");\n }\n Properties properties = new Properties();\n for (int i = 0; i < propValues.length; i++) {\n String[] prop = propValues[i].split(\"=\");\n if (prop.length != 2) throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propValues[i] + \"'\");\n properties.put(prop[0], prop[1]);\n }\n return properties;\n }", "protected String classOf(List<IN> lineInfos, int pos) {\r\n Datum<String, String> d = makeDatum(lineInfos, pos, featureFactory);\r\n return classifier.classOf(d);\r\n }", "public static final Bytes of(byte[] array) {\n Objects.requireNonNull(array);\n if (array.length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[array.length];\n System.arraycopy(array, 0, copy, 0, array.length);\n return new Bytes(copy);\n }", "public String getRealm() {\n if (UNDEFINED.equals(realm)) {\n Principal principal = securityIdentity.getPrincipal();\n String realm = null;\n if (principal instanceof RealmPrincipal) {\n realm = ((RealmPrincipal)principal).getRealm();\n }\n this.realm = realm;\n\n }\n\n return this.realm;\n }", "private int getColor(int value) {\n\t\tif (value == 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tdouble scale = Math.log10(value) / Math.log10(this.topValue);\n\t\tdouble lengthScale = Math.min(1.0, scale) * (colors.length - 1);\n\t\tint index = 1 + (int) lengthScale;\n\t\tif (index == colors.length) {\n\t\t\tindex--;\n\t\t}\n\t\tdouble partScale = lengthScale - (index - 1);\n\n\t\tint r = (int) (colors[index - 1][0] + partScale\n\t\t\t\t* (colors[index][0] - colors[index - 1][0]));\n\t\tint g = (int) (colors[index - 1][1] + partScale\n\t\t\t\t* (colors[index][1] - colors[index - 1][1]));\n\t\tint b = (int) (colors[index - 1][2] + partScale\n\t\t\t\t* (colors[index][2] - colors[index - 1][2]));\n\n\t\tr = Math.min(255, r);\n\t\tb = Math.min(255, b);\n\t\tg = Math.min(255, g);\n\t\treturn (r << 16) | (g << 8) | b;\n\t}", "public List<SquigglyNode> parse(String filter) {\n filter = StringUtils.trim(filter);\n\n if (StringUtils.isEmpty(filter)) {\n return Collections.emptyList();\n }\n\n // get it from the cache if we can\n List<SquigglyNode> cachedNodes = CACHE.getIfPresent(filter);\n\n if (cachedNodes != null) {\n return cachedNodes;\n }\n\n\n SquigglyExpressionLexer lexer = ThrowingErrorListener.overwrite(new SquigglyExpressionLexer(new ANTLRInputStream(filter)));\n SquigglyExpressionParser parser = ThrowingErrorListener.overwrite(new SquigglyExpressionParser(new CommonTokenStream(lexer)));\n\n Visitor visitor = new Visitor();\n List<SquigglyNode> nodes = Collections.unmodifiableList(visitor.visit(parser.parse()));\n\n CACHE.put(filter, nodes);\n return nodes;\n }" ]
Returns an iterable containing all the enterprise users that matches the filter and specifies which child fields to retrieve from the API. @param api the API connection to be used when retrieving the users. @param filterTerm used to filter the results to only users starting with this string in either the name or the login. Can be null to not filter the results. @param fields the fields to retrieve. Leave this out for the standard fields. @return an iterable containing all the enterprise users that matches the filter.
[ "public static Iterable<BoxUser.Info> getAllEnterpriseUsers(final BoxAPIConnection api, final String filterTerm,\n final String... fields) {\n return getUsersInfoForType(api, filterTerm, null, null, fields);\n }" ]
[ "@Override\n\tpublic T next() {\n\t\tSQLException sqlException = null;\n\t\ttry {\n\t\t\tT result = nextThrow();\n\t\t\tif (result != null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\tsqlException = e;\n\t\t}\n\t\t// we have to throw if there is no next or on a SQLException\n\t\tlast = null;\n\t\tcloseQuietly();\n\t\tthrow new IllegalStateException(\"Could not get next result for \" + dataClass, sqlException);\n\t}", "public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }", "public Step createRootStep() {\n return new Step()\n .withName(\"Root step\")\n .withTitle(\"Allure step processing error: if you see this step something went wrong.\")\n .withStart(System.currentTimeMillis())\n .withStatus(Status.BROKEN);\n }", "public static base_responses add(nitro_service client, dnssuffix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnssuffix addresources[] = new dnssuffix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnssuffix();\n\t\t\t\taddresources[i].Dnssuffix = resources[i].Dnssuffix;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public void process(AvailabilityTable table, byte[] data)\n {\n if (data != null)\n {\n Calendar cal = DateHelper.popCalendar();\n int items = MPPUtility.getShort(data, 0);\n int offset = 12;\n\n for (int loop = 0; loop < items; loop++)\n {\n double unitsValue = MPPUtility.getDouble(data, offset + 4);\n if (unitsValue != 0)\n {\n Date startDate = MPPUtility.getTimestampFromTenths(data, offset);\n Date endDate = MPPUtility.getTimestampFromTenths(data, offset + 20);\n cal.setTime(endDate);\n cal.add(Calendar.MINUTE, -1);\n endDate = cal.getTime();\n Double units = NumberHelper.getDouble(unitsValue / 100);\n Availability item = new Availability(startDate, endDate, units);\n table.add(item);\n }\n offset += 20;\n }\n DateHelper.pushCalendar(cal);\n Collections.sort(table);\n }\n }", "private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) {\n ImmutableSet.Builder<Type> types = ImmutableSet.builder();\n // session beans\n Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>();\n HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass());\n for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) {\n // first we need to resolve the local interface\n Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface()));\n SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface);\n if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) {\n // WELD-1675 Only add types also included in Annotated.getTypeClosure()\n for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) {\n if (annotated.getTypeClosure().contains(entry.getValue())) {\n typeMap.put(entry.getKey(), entry.getValue());\n }\n }\n } else {\n // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class\n typeMap.putAll(interfaceDiscovery.getTypeMap());\n }\n }\n if (annotated.isAnnotationPresent(Typed.class)) {\n types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class)));\n } else {\n typeMap.put(Object.class, Object.class);\n types.addAll(typeMap.values());\n }\n return Beans.getLegalBeanTypes(types.build(), annotated);\n }", "public static double normP1( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return CommonOps_DDRM.elementSumAbs(A);\n } else {\n return inducedP1(A);\n }\n }", "public double[] getMaturities(double moneyness) {\r\n\t\tint[] maturitiesInMonths\t= getMaturities(convertMoneyness(moneyness));\r\n\t\tdouble[] maturities\t\t\t= new double[maturitiesInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < maturities.length; index++) {\r\n\t\t\tmaturities[index] = convertMaturity(maturitiesInMonths[index]);\r\n\t\t}\r\n\t\treturn maturities;\r\n\t}", "public BoxFolder.Info createFolder(String name) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", this.getID());\n\n JsonObject newFolder = new JsonObject();\n newFolder.add(\"name\", name);\n newFolder.add(\"parent\", parent);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()),\n \"POST\");\n request.setBody(newFolder.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get(\"id\").asString());\n return createdFolder.new Info(responseJSON);\n }" ]
Checks if the given String is null or contains only whitespaces. The String is trimmed before the empty check. @param argument the String to check for null or emptiness @param argumentName the name of the argument to check. This is used in the exception message. @return the String that was given as argument @throws IllegalArgumentException in case argument is null or empty
[ "public static String notNullOrEmpty(String argument, String argumentName) {\n if (argument == null || argument.trim().isEmpty()) {\n throw new IllegalArgumentException(\"Argument \" + argumentName + \" must not be null or empty.\");\n }\n return argument;\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 }", "public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }", "public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {\n\t\tlog.debug(\"clipTile before {}\", tile);\n\t\tList<InternalFeature> orgFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tGeometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.\n\t\tfor (InternalFeature feature : orgFeatures) {\n\t\t\t// clip feature if necessary\n\t\t\tif (exceedsScreenDimensions(feature, scale)) {\n\t\t\t\tlog.debug(\"feature {} exceeds screen dimensions\", feature);\n\t\t\t\tInternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();\n\t\t\t\ttile.setClipped(true);\n\t\t\t\tvectorFeature.setClipped(true);\n\t\t\t\tif (null == maxScreenBbox) {\n\t\t\t\t\tmaxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));\n\t\t\t\t}\n\t\t\t\tGeometry clipped = maxScreenBbox.intersection(feature.getGeometry());\n\t\t\t\tvectorFeature.setClippedGeometry(clipped);\n\t\t\t\ttile.addFeature(vectorFeature);\n\t\t\t} else {\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t\tlog.debug(\"clipTile after {}\", tile);\n\t}", "public void put(@NotNull final Transaction txn, final long localId,\n final int blobId, @NotNull final ByteIterable value) {\n primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value);\n allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId));\n }", "@Override\n public void process(TestCaseResult context) {\n context.getParameters().add(new Parameter()\n .withName(getName())\n .withValue(getValue())\n .withKind(ParameterKind.valueOf(getKind()))\n );\n }", "public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case REQUEST_PERMISSIONS_CODE:\n if (listener != null) {\n boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;\n listener.onPermissionResult(granted);\n }\n break;\n default:\n // Ignored\n }\n }", "public static appfwsignatures get(nitro_service service) throws Exception{\n\t\tappfwsignatures obj = new appfwsignatures();\n\t\tappfwsignatures[] response = (appfwsignatures[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){\n\t\tTrajectory track = null;\n\t\tfor(int i = 0; i < t.size() ; i++){\n\t\t\tif(t.get(i).getID()==id){\n\t\t\t\ttrack = t.get(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn track;\n\t}", "public static int Mode( int[] values ){\n int mode = 0, curMax = 0;\n\n for ( int i = 0, length = values.length; i < length; i++ )\n {\n if ( values[i] > curMax )\n {\n curMax = values[i];\n mode = i;\n }\n }\n return mode;\n }" ]
Allows testsuites to shorten the domain timeout adder
[ "private static int resolveDomainTimeoutAdder() {\n String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);\n if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {\n // First call or the system property changed\n sysPropDomainValue = propValue;\n int number = -1;\n try {\n number = Integer.valueOf(sysPropDomainValue);\n } catch (NumberFormatException nfe) {\n // ignored\n }\n\n if (number > 0) {\n defaultDomainValue = number; // this one is in ms\n } else {\n ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);\n defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;\n }\n }\n return defaultDomainValue;\n }" ]
[ "private static List<Integer> stripNodeIds(List<Node> nodeList) {\n List<Integer> nodeidList = new ArrayList<Integer>();\n if(nodeList != null) {\n for(Node node: nodeList) {\n nodeidList.add(node.getId());\n }\n }\n return nodeidList;\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public Stream<ChangeEvent<DocumentT>> watch(final BsonValue... ids)\n throws InterruptedException, IOException {\n return operations.watch(\n new HashSet<>(Arrays.asList(ids)),\n false,\n documentClass\n ).execute(service);\n }", "private static void listCalendars(ProjectFile file)\n {\n for (ProjectCalendar cal : file.getCalendars())\n {\n System.out.println(cal.toString());\n }\n }", "protected Element createPageElement()\n {\n String pstyle = \"\";\n PDRectangle layout = getCurrentMediaBox();\n if (layout != null)\n {\n /*System.out.println(\"x1 \" + layout.getLowerLeftX());\n System.out.println(\"y1 \" + layout.getLowerLeftY());\n System.out.println(\"x2 \" + layout.getUpperRightX());\n System.out.println(\"y2 \" + layout.getUpperRightY());\n System.out.println(\"rot \" + pdpage.findRotation());*/\n \n float w = layout.getWidth();\n float h = layout.getHeight();\n final int rot = pdpage.getRotation();\n if (rot == 90 || rot == 270)\n {\n float x = w; w = h; h = x;\n }\n \n pstyle = \"width:\" + w + UNIT + \";\" + \"height:\" + h + UNIT + \";\";\n pstyle += \"overflow:hidden;\";\n }\n else\n log.warn(\"No media box found\");\n \n Element el = doc.createElement(\"div\");\n el.setAttribute(\"id\", \"page_\" + (pagecnt++));\n el.setAttribute(\"class\", \"page\");\n el.setAttribute(\"style\", pstyle);\n return el;\n }", "public static Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }", "public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}", "public static String getAt(String text, IntRange range) {\n return getAt(text, (Range) range);\n }", "public void diffUpdate(List<T> newList) {\n if (getCollection().size() == 0) {\n addAll(newList);\n notifyDataSetChanged();\n } else {\n DiffCallback diffCallback = new DiffCallback(collection, newList);\n DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);\n clear();\n addAll(newList);\n diffResult.dispatchUpdatesTo(this);\n }\n }", "private void writeProjectProperties(ProjectProperties record) throws IOException\n {\n // the ProjectProperties class from MPXJ has the details of how many days per week etc....\n // so I've assigned these variables in here, but actually use them in other methods\n // see the write task method, that's where they're used, but that method only has a Task object\n m_minutesPerDay = record.getMinutesPerDay().doubleValue();\n m_minutesPerWeek = record.getMinutesPerWeek().doubleValue();\n m_daysPerMonth = record.getDaysPerMonth().doubleValue();\n\n // reset buffer to be empty, then concatenate data as required by USACE\n m_buffer.setLength(0);\n m_buffer.append(\"PROJ \");\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // DataDate\n m_buffer.append(SDEFmethods.lset(record.getManager(), 4) + \" \"); // ProjIdent\n m_buffer.append(SDEFmethods.lset(record.getProjectTitle(), 48) + \" \"); // ProjName\n m_buffer.append(SDEFmethods.lset(record.getSubject(), 36) + \" \"); // ContrName\n m_buffer.append(\"P \"); // ArrowP\n m_buffer.append(SDEFmethods.lset(record.getKeywords(), 7)); // ContractNum\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // ProjStart\n m_buffer.append(m_formatter.format(record.getFinishDate()).toUpperCase()); // ProjEnd\n m_writer.println(m_buffer);\n }" ]
Assigns the provided square matrix to be a random Hermitian matrix with elements from min to max value. @param A The matrix that is to be modified. Must be square. Modified. @param min Minimum value an element can have. @param max Maximum value an element can have. @param rand Random number generator.
[ "public static void fillHermitian(ZMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n A.set(i,i,rand.nextDouble()*range + min,0);\n\n for( int j = i+1; j < length; j++ ) {\n double real = rand.nextDouble()*range + min;\n double imaginary = rand.nextDouble()*range + min;\n A.set(i,j,real,imaginary);\n A.set(j,i,real,-imaginary);\n }\n }\n }" ]
[ "private void processColumns()\n {\n int fieldID = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n m_dataOffset = MPPUtility.getInt(m_data, m_headerOffset);\n m_headerOffset += 4;\n\n FieldType type = FieldTypeHelper.getInstance(fieldID);\n if (type.getDataType() != null)\n {\n processKnownType(type);\n }\n }", "protected List<CmsUUID> undelete() throws CmsException {\n\n List<CmsUUID> modifiedResources = new ArrayList<CmsUUID>();\n CmsObject cms = m_context.getCms();\n for (CmsResource resource : m_context.getResources()) {\n CmsLockActionRecord actionRecord = null;\n try {\n actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource);\n cms.undeleteResource(cms.getSitePath(resource), true);\n modifiedResources.add(resource.getStructureId());\n } finally {\n if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) {\n\n try {\n cms.unlockResource(resource);\n } catch (CmsLockException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }\n }\n }\n return modifiedResources;\n }", "public InsertIntoTable addRowsFrom(File file, FileParser fileParser) {\n builder.addRowsFrom(file, fileParser);\n return this;\n }", "private JSONObject getJsonFormattedSpellcheckResult(CmsSpellcheckingRequest request) {\n\n final JSONObject response = new JSONObject();\n\n try {\n if (null != request.m_id) {\n response.put(JSON_ID, request.m_id);\n }\n\n response.put(JSON_RESULT, request.m_wordSuggestions);\n\n } catch (Exception e) {\n try {\n response.put(JSON_ERROR, true);\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", e);\n } catch (JSONException ex) {\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", ex);\n }\n }\n\n return response;\n }", "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 }", "public void sendJsonToTagged(Object data, String ... labels) {\n for (String label : labels) {\n sendJsonToTagged(data, label);\n }\n }", "private void registerInterceptor(Node source,\n String beanName,\n BeanDefinitionRegistry registry) {\n List<String> methodList = buildMethodList(source);\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(SingleServiceWrapperInterceptor.class);\n initializer.addPropertyValue(\"methods\", methodList);\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n initializer.addPropertyReference(\"serviceWrapper\", perfMonitorName);\n\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n registry.registerBeanDefinition(interceptorName, initializer.getBeanDefinition());\n }", "private static Object checkComponentType(Object array, Class<?> expectedComponentType) {\n\t\tClass<?> actualComponentType = array.getClass().getComponentType();\n\t\tif (!expectedComponentType.isAssignableFrom(actualComponentType)) {\n\t\t\tthrow new ArrayStoreException(\n\t\t\t\t\tString.format(\"The expected component type %s is not assignable from the actual type %s\",\n\t\t\t\t\t\t\texpectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));\n\t\t}\n\t\treturn array;\n\t}", "protected void putResponse(JSONObject json,\n String param,\n Object value) {\n try {\n json.put(param,\n value);\n } catch (JSONException e) {\n logger.error(\"json write error\",\n e);\n }\n }" ]
Checks String to see if the parameter is null. @param paramValue Object that will be checked if null. @return this.true if the parameter that is being checked is not null
[ "private boolean isNullOrEmpty(Object paramValue) {\n boolean isNullOrEmpty = false;\n if (paramValue == null) {\n isNullOrEmpty = true;\n }\n if (paramValue instanceof String) {\n if (((String) paramValue).trim().equalsIgnoreCase(\"\")) {\n isNullOrEmpty = true;\n }\n } else if (paramValue instanceof List) {\n return ((List) paramValue).isEmpty();\n }\n return isNullOrEmpty;\n }" ]
[ "protected float getViewPortSize(final Axis axis) {\n float size = mViewPort == null ? 0 : mViewPort.get(axis);\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"getViewPortSize for %s %f mViewPort = %s\", axis, size, mViewPort);\n return size;\n }", "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 }", "private Map<String, I_CmsSearchConfigurationFacetField> getDefaultFieldFacets(boolean categoryConjunction) {\n\n Map<String, I_CmsSearchConfigurationFacetField> fieldFacets = new HashMap<String, I_CmsSearchConfigurationFacetField>();\n fieldFacets.put(\n CmsListManager.FIELD_CATEGORIES,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_CATEGORIES,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Category\",\n SortOrder.index,\n null,\n Boolean.valueOf(categoryConjunction),\n null,\n Boolean.TRUE));\n fieldFacets.put(\n CmsListManager.FIELD_PARENT_FOLDERS,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_PARENT_FOLDERS,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Folders\",\n SortOrder.index,\n null,\n Boolean.FALSE,\n null,\n Boolean.TRUE));\n return Collections.unmodifiableMap(fieldFacets);\n\n }", "public static int mixColors(float t, int rgb1, int rgb2) {\n\t\tint a1 = (rgb1 >> 24) & 0xff;\n\t\tint r1 = (rgb1 >> 16) & 0xff;\n\t\tint g1 = (rgb1 >> 8) & 0xff;\n\t\tint b1 = rgb1 & 0xff;\n\t\tint a2 = (rgb2 >> 24) & 0xff;\n\t\tint r2 = (rgb2 >> 16) & 0xff;\n\t\tint g2 = (rgb2 >> 8) & 0xff;\n\t\tint b2 = rgb2 & 0xff;\n\t\ta1 = lerp(t, a1, a2);\n\t\tr1 = lerp(t, r1, r2);\n\t\tg1 = lerp(t, g1, g2);\n\t\tb1 = lerp(t, b1, b2);\n\t\treturn (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;\n\t}", "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 LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }", "public void sendMessageToAgents(String[] agent_name, String msgtype,\n Object message_content, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\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 }", "private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException {\n\t\t//cannot batch fetch by unique key (property-ref associations)\n\t\tif ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) {\n\t\t\tEntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() );\n\t\t\tEntityKey entityKey = session.generateEntityKey( id, persister );\n\t\t\tif ( !session.getPersistenceContext().containsEntity( entityKey ) ) {\n\t\t\t\tsession.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );\n\t\t\t}\n\t\t}\n\t}", "private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}" ]
Obtains a local date in Julian calendar system from the proleptic-year, month-of-year and day-of-month fields. @param prolepticYear the proleptic-year @param month the month-of-year @param dayOfMonth the day-of-month @return the Julian local date, not null @throws DateTimeException if unable to create the date
[ "@Override\n public JulianDate date(int prolepticYear, int month, int dayOfMonth) {\n return JulianDate.of(prolepticYear, month, dayOfMonth);\n }" ]
[ "protected void finishBox()\n {\n \tif (textLine.length() > 0)\n \t{\n String s;\n if (isReversed(Character.getDirectionality(textLine.charAt(0))))\n s = textLine.reverse().toString();\n else\n s = textLine.toString();\n\n curstyle.setLeft(textMetrics.getX());\n curstyle.setTop(textMetrics.getTop());\n curstyle.setLineHeight(textMetrics.getHeight());\n\n\t renderText(s, textMetrics);\n\t textLine = new StringBuilder();\n\t textMetrics = null;\n \t}\n }", "protected static File platformIndependentUriToFile(final URI fileURI) {\n File file;\n try {\n file = new File(fileURI);\n } catch (IllegalArgumentException e) {\n if (fileURI.toString().startsWith(\"file://\")) {\n file = new File(fileURI.toString().substring(\"file://\".length()));\n } else {\n throw e;\n }\n }\n return file;\n }", "public boolean isFunctionName( String s ) {\n if( input1.containsKey(s))\n return true;\n if( inputN.containsKey(s))\n return true;\n\n return false;\n }", "protected long save() {\n // save leaf nodes\n ReclaimFlag flag = saveChildren();\n // save self. complementary to {@link load()}\n final byte type = getType();\n final BTreeBase tree = getTree();\n final int structureId = tree.structureId;\n final Log log = tree.log;\n if (flag == ReclaimFlag.PRESERVE) {\n // there is a chance to update the flag to RECLAIM\n if (log.getWrittenHighAddress() % log.getFileLengthBound() == 0) {\n // page will be exactly on file border\n flag = ReclaimFlag.RECLAIM;\n } else {\n final ByteIterable[] iterables = getByteIterables(flag);\n long result = log.tryWrite(type, structureId, new CompoundByteIterable(iterables));\n if (result < 0) {\n iterables[0] = CompressedUnsignedLongByteIterable.getIterable(\n (size << 1) + ReclaimFlag.RECLAIM.value\n );\n result = log.writeContinuously(type, structureId, new CompoundByteIterable(iterables));\n\n if (result < 0) {\n throw new TooBigLoggableException();\n }\n }\n return result;\n }\n }\n return log.write(type, structureId, new CompoundByteIterable(getByteIterables(flag)));\n }", "public void attachHoursToDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = hours;\n }", "static void prepareTasks(final IdentityPatchContext.PatchEntry entry, final IdentityPatchContext context, final List<PreparedTask> tasks, final List<ContentItem> conflicts) throws PatchingException {\n for (final PatchingTasks.ContentTaskDefinition definition : entry.getTaskDefinitions()) {\n final PatchingTask task = createTask(definition, context, entry);\n if(!task.isRelevant(entry)) {\n continue;\n }\n try {\n // backup and validate content\n if (!task.prepare(entry) || definition.hasConflicts()) {\n // Unless it a content item was manually ignored (or excluded)\n final ContentItem item = task.getContentItem();\n if (!context.isIgnored(item)) {\n conflicts.add(item);\n }\n }\n tasks.add(new PreparedTask(task, entry));\n } catch (IOException e) {\n throw new PatchingException(e);\n }\n }\n }", "public static boolean changeHost(String hostName,\n boolean enable,\n boolean disable,\n boolean remove,\n boolean isEnabled,\n boolean exists) throws Exception {\n\n // Open the file that is the first\n // command line parameter\n File hostsFile = new File(\"/etc/hosts\");\n FileInputStream fstream = new FileInputStream(\"/etc/hosts\");\n\n File outFile = null;\n BufferedWriter bw = null;\n // only do file output for destructive operations\n if (!exists && !isEnabled) {\n outFile = File.createTempFile(\"HostsEdit\", \".tmp\");\n bw = new BufferedWriter(new FileWriter(outFile));\n System.out.println(\"File name: \" + outFile.getPath());\n }\n\n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n String strLine;\n boolean foundHost = false;\n boolean hostEnabled = false;\n\n\t\t/*\n * Group 1 - possible commented out host entry\n\t\t * Group 2 - destination address\n\t\t * Group 3 - host name\n\t\t * Group 4 - everything else\n\t\t */\n Pattern pattern = Pattern.compile(\"\\\\s*(#?)\\\\s*([^\\\\s]+)\\\\s*([^\\\\s]+)(.*)\");\n while ((strLine = br.readLine()) != null) {\n\n Matcher matcher = pattern.matcher(strLine);\n\n // if there is a match to the pattern and the host name is the same as the one we want to set\n if (matcher.find() &&\n matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {\n foundHost = true;\n if (remove) {\n // skip this line altogether\n continue;\n } else if (enable) {\n // we will disregard group 2 and just set it to 127.0.0.1\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + matcher.group(3) + matcher.group(4));\n } else if (disable) {\n if (!exists && !isEnabled)\n bw.write(\"# \" + matcher.group(2) + \" \" + matcher.group(3) + matcher.group(4));\n } else if (isEnabled && matcher.group(1).compareTo(\"\") == 0) {\n // host exists and there is no # before it\n hostEnabled = true;\n }\n } else {\n // just write the line back out\n if (!exists && !isEnabled)\n bw.write(strLine);\n }\n\n if (!exists && !isEnabled)\n bw.write('\\n');\n }\n\n // if we didn't find the host in the file but need to enable it\n if (!foundHost && enable) {\n // write a new host entry\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + hostName + '\\n');\n }\n // Close the input stream\n in.close();\n\n if (!exists && !isEnabled) {\n bw.close();\n outFile.renameTo(hostsFile);\n }\n\n // return false if the host wasn't found\n if (exists && !foundHost)\n return false;\n\n // return false if the host wasn't enabled\n if (isEnabled && !hostEnabled)\n return false;\n\n return true;\n }", "public int getInt(Integer type)\n {\n int result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getInt(item, 0);\n }\n\n return (result);\n }", "public static DMatrixRMaj identity(int numRows , int numCols )\n {\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int small = numRows < numCols ? numRows : numCols;\n\n for( int i = 0; i < small; i++ ) {\n ret.set(i,i,1.0);\n }\n\n return ret;\n }" ]
Sets the global setting for this ID @param pathId ID of path @param global True if global, False otherwise
[ "public void setGlobal(int pathId, Boolean global) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_GLOBAL + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setBoolean(1, global);\n statement.setInt(2, pathId);\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 }" ]
[ "protected String getPayload(Message message) {\n try {\n String encoding = (String) message.get(Message.ENCODING);\n if (encoding == null) {\n encoding = \"UTF-8\";\n }\n CachedOutputStream cos = message.getContent(CachedOutputStream.class);\n if (cos == null) {\n LOG.warning(\"Could not find CachedOutputStream in message.\"\n + \" Continuing without message content\");\n return \"\";\n }\n return new String(cos.getBytes(), encoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }", "private static Interval parseEndDateTime(Instant start, ZoneOffset offset, CharSequence endStr) {\n try {\n TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(endStr, OffsetDateTime::from, LocalDateTime::from);\n if (temporal instanceof OffsetDateTime) {\n OffsetDateTime odt = (OffsetDateTime) temporal;\n return Interval.of(start, odt.toInstant());\n } else {\n // infer offset from start if not specified by end\n LocalDateTime ldt = (LocalDateTime) temporal;\n return Interval.of(start, ldt.toInstant(offset));\n }\n } catch (DateTimeParseException ex) {\n Instant end = Instant.parse(endStr);\n return Interval.of(start, end);\n }\n }", "public List<Shard> getShards() {\n InputStream response = null;\n try {\n response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path(\"_shards\")\n .build());\n return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS);\n } finally {\n close(response);\n }\n }", "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}", "@Nonnull\n private ReferencedEnvelope getFeatureBounds(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final MapAttributeValues mapValues, final ExecutionContext context) {\n final MapfishMapContext mapContext = createMapContext(mapValues);\n\n String layerName = mapValues.zoomToFeatures.layer;\n ReferencedEnvelope bounds = new ReferencedEnvelope();\n for (MapLayer layer: mapValues.getLayers()) {\n context.stopIfCanceled();\n\n if ((!StringUtils.isEmpty(layerName) && layerName.equals(layer.getName())) ||\n (StringUtils.isEmpty(layerName) && layer instanceof AbstractFeatureSourceLayer)) {\n AbstractFeatureSourceLayer featureLayer = (AbstractFeatureSourceLayer) layer;\n FeatureSource<?, ?> featureSource =\n featureLayer.getFeatureSource(clientHttpRequestFactory, mapContext);\n FeatureCollection<?, ?> features;\n try {\n features = featureSource.getFeatures();\n } catch (IOException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n\n if (!features.isEmpty()) {\n final ReferencedEnvelope curBounds = features.getBounds();\n bounds.expandToInclude(curBounds);\n }\n }\n }\n\n return bounds;\n }", "public static nslimitselector[] get(nitro_service service) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tnslimitselector[] response = (nslimitselector[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private int getFixedDataFieldSize(FieldType type)\n {\n int result = 0;\n DataType dataType = type.getDataType();\n if (dataType != null)\n {\n switch (dataType)\n {\n case DATE:\n case INTEGER:\n case DURATION:\n {\n result = 4;\n break;\n }\n\n case TIME_UNITS:\n case CONSTRAINT:\n case PRIORITY:\n case PERCENTAGE:\n case TASK_TYPE:\n case ACCRUE:\n case SHORT:\n case BOOLEAN:\n case DELAY:\n case WORKGROUP:\n case RATE_UNITS:\n case EARNED_VALUE_METHOD:\n case RESOURCE_REQUEST_TYPE:\n {\n result = 2;\n break;\n }\n\n case CURRENCY:\n case UNITS:\n case RATE:\n case WORK:\n {\n result = 8;\n break;\n }\n\n case WORK_UNITS:\n {\n result = 1;\n break;\n }\n\n case GUID:\n {\n result = 16;\n break;\n }\n\n default:\n {\n result = 0;\n break;\n }\n }\n }\n\n return result;\n }", "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 }", "public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }" ]
Calculate entropy value. @param values Values. @return Returns entropy value of the specified histogram array.
[ "public static double Entropy( int[] values ){\n int n = values.length;\n int total = 0;\n double entropy = 0;\n double p;\n\n // calculate total amount of hits\n for ( int i = 0; i < n; i++ )\n {\n total += values[i];\n }\n\n if ( total != 0 )\n {\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // get item's probability\n p = (double) values[i] / total;\n // calculate entropy\n if ( p != 0 )\n entropy += ( -p * (Math.log10(p)/Math.log10(2)) );\n }\n }\n return entropy;\n }" ]
[ "public final void cancelOld(\n final long starttimeThreshold, final long checkTimeThreshold, final String message) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.and(\n builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING),\n builder.or(\n builder.lessThan(root.get(\"entry\").get(\"startTime\"), starttimeThreshold),\n builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold))\n )\n ));\n update.set(root.get(\"status\"), PrintJobStatus.Status.CANCELLED);\n update.set(root.get(\"error\"), message);\n getSession().createQuery(update).executeUpdate();\n }", "public static base_response clear(nitro_service client, Interface resource) throws Exception {\n\t\tInterface clearresource = new Interface();\n\t\tclearresource.id = resource.id;\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}", "public void setNamespace(String prefix, String namespaceURI) {\n ensureNotNull(\"Prefix\", prefix);\n ensureNotNull(\"Namespace URI\", namespaceURI);\n\n namespaces.put(prefix, namespaceURI);\n }", "public CrosstabBuilder useMainReportDatasource(boolean preSorted) {\r\n\t\tDJDataSource datasource = new DJDataSource(\"ds\",DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE,DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE);\r\n\t\tdatasource.setPreSorted(preSorted);\r\n\t\tcrosstab.setDatasource(datasource);\r\n\t\treturn this;\r\n\t}", "public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }", "public void push( Token token ) {\n size++;\n if( first == null ) {\n first = token;\n last = token;\n token.previous = null;\n token.next = null;\n } else {\n last.next = token;\n token.previous = last;\n token.next = null;\n last = token;\n }\n }", "@Deprecated\n public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT) {\n return findByIndex(selectorJson, classOfT, new FindByIndexOptions());\n }", "public FinishRequest toFinishRequest(boolean includeHeaders) {\n if (includeHeaders) {\n return new FinishRequest(body, copyHeaders(headers), statusCode);\n } else {\n String mime = null;\n if (body!=null) {\n mime = \"text/plain\";\n if (headers!=null && (headers.containsKey(\"Content-Type\") || headers.containsKey(\"content-type\"))) {\n mime = headers.get(\"Content-Type\");\n if (mime==null) {\n mime = headers.get(\"content-type\");\n }\n }\n }\n\n return new FinishRequest(body, mime, statusCode);\n }\n }", "@Override\n\tpublic void clear() {\n\t\tif (dao == null) {\n\t\t\treturn;\n\t\t}\n\t\tCloseableIterator<T> iterator = closeableIterator();\n\t\ttry {\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\titerator.next();\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeQuietly(iterator);\n\t\t}\n\t}" ]
Queries the running container and attempts to lookup the information from the running container. @param client the client used to execute the management operation @return the container description @throws IOException if an error occurs while executing the management operation @throws OperationExecutionException if the operation used to query the container fails
[ "static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }" ]
[ "public final void notifyContentItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart + headerItemCount, itemCount);\n }", "public static String taskListToString(List<RebalanceTaskInfo> infos) {\n StringBuffer sb = new StringBuffer();\n for (RebalanceTaskInfo info : infos) {\n sb.append(\"\\t\").append(info.getDonorId()).append(\" -> \").append(info.getStealerId()).append(\" : [\");\n for (String storeName : info.getPartitionStores()) {\n sb.append(\"{\").append(storeName).append(\" : \").append(info.getPartitionIds(storeName)).append(\"}\");\n }\n sb.append(\"]\").append(Utils.NEWLINE);\n }\n return sb.toString();\n }", "public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException {\r\n\r\n // Use TreeMap so keys are automatically sorted alphabetically\r\n Map<String, String> parameters = new TreeMap<String, String>();\r\n parameters.put(\"method\", METHOD_EXCHANGE_TOKEN);\r\n parameters.put(Flickr.API_KEY, apiKey);\r\n // This method call must be signed using Flickr (not OAuth) style signing\r\n parameters.put(\"api_sig\", getSignature(sharedSecret, parameters));\r\n\r\n Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n OAuth1RequestToken accessToken = constructToken(response);\r\n\r\n return accessToken;\r\n }", "public float getChildSize(final int dataIndex, final Axis axis) {\n float size = 0;\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n switch (axis) {\n case X:\n size = child.getLayoutWidth();\n break;\n case Y:\n size = child.getLayoutHeight();\n break;\n case Z:\n size = child.getLayoutDepth();\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }\n return size;\n }", "public void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}", "public static lbvserver_appflowpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_appflowpolicy_binding obj = new lbvserver_appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_appflowpolicy_binding response[] = (lbvserver_appflowpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void processFile(InputStream is) throws MPXJException\n {\n try\n {\n InputStreamReader reader = new InputStreamReader(is, CharsetHelper.UTF8);\n Tokenizer tk = new ReaderTokenizer(reader)\n {\n @Override protected boolean startQuotedIsValid(StringBuilder buffer)\n {\n return buffer.length() == 1 && buffer.charAt(0) == '<';\n }\n };\n\n tk.setDelimiter(DELIMITER);\n ArrayList<String> columns = new ArrayList<String>();\n String nextTokenPrefix = null;\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n columns.clear();\n TableDefinition table = null;\n\n while (tk.nextToken() == Tokenizer.TT_WORD)\n {\n String token = tk.getToken();\n if (columns.size() == 0)\n {\n if (token.charAt(0) == '#')\n {\n int index = token.lastIndexOf(':');\n if (index != -1)\n {\n String headerToken;\n if (token.endsWith(\"-\") || token.endsWith(\"=\"))\n {\n headerToken = token;\n token = null;\n }\n else\n {\n headerToken = token.substring(0, index);\n token = token.substring(index + 1);\n }\n\n RowHeader header = new RowHeader(headerToken);\n table = m_tableDefinitions.get(header.getType());\n columns.add(header.getID());\n }\n }\n else\n {\n if (token.charAt(0) == 0)\n {\n processFileType(token);\n }\n }\n }\n\n if (table != null && token != null)\n {\n if (token.startsWith(\"<\\\"\") && !token.endsWith(\"\\\">\"))\n {\n nextTokenPrefix = token;\n }\n else\n {\n if (nextTokenPrefix != null)\n {\n token = nextTokenPrefix + DELIMITER + token;\n nextTokenPrefix = null;\n }\n\n columns.add(token);\n }\n }\n }\n\n if (table != null && columns.size() > 1)\n {\n // System.out.println(table.getName() + \" \" + columns.size());\n // ColumnDefinition[] columnDefs = table.getColumns();\n // int unknownIndex = 1;\n // for (int xx = 0; xx < columns.size(); xx++)\n // {\n // String x = columns.get(xx);\n // String columnName = xx < columnDefs.length ? (columnDefs[xx] == null ? \"UNKNOWN\" + (unknownIndex++) : columnDefs[xx].getName()) : \"?\";\n // System.out.println(columnName + \": \" + x + \", \");\n // }\n // System.out.println();\n\n TextFileRow row = new TextFileRow(table, columns, m_epochDateFormat);\n List<Row> rows = m_tables.get(table.getName());\n if (rows == null)\n {\n rows = new LinkedList<Row>();\n m_tables.put(table.getName(), rows);\n }\n rows.add(row);\n }\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR, ex);\n }\n }", "public PhotoList<Photo> getPhotos(String groupId, String userId, String[] tags, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"group_id\", groupId);\r\n if (userId != null) {\r\n parameters.put(\"user_id\", userId);\r\n }\r\n if (tags != null) {\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \"));\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 if (extras != null) {\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = extras.iterator();\r\n for (int i = 0; it.hasNext(); i++) {\r\n if (i > 0) {\r\n sb.append(\",\");\r\n }\r\n sb.append(it.next());\r\n }\r\n parameters.put(Extras.KEY_EXTRAS, sb.toString());\r\n }\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 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 photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n\r\n return photos;\r\n }", "public static base_response export(nitro_service client, sslfipskey resource) throws Exception {\n\t\tsslfipskey exportresource = new sslfipskey();\n\t\texportresource.fipskeyname = resource.fipskeyname;\n\t\texportresource.key = resource.key;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}" ]
Use this API to fetch bridgegroup_nsip_binding resources of given name .
[ "public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public int rebalanceNode(final RebalanceTaskInfo stealInfo) {\n\n final RebalanceTaskInfo info = metadataStore.getRebalancerState()\n .find(stealInfo.getDonorId());\n\n // Do we have the plan in the state?\n if(info == null) {\n throw new VoldemortException(\"Could not find plan \" + stealInfo\n + \" in the server state on \" + metadataStore.getNodeId());\n } else if(!info.equals(stealInfo)) {\n // If we do have the plan, is it the same\n throw new VoldemortException(\"The plan in server state \" + info\n + \" is not the same as the process passed \" + stealInfo);\n } else if(!acquireRebalancingPermit(stealInfo.getDonorId())) {\n // Both are same, now try to acquire a lock for the donor node\n throw new AlreadyRebalancingException(\"Node \" + metadataStore.getNodeId()\n + \" is already rebalancing from donor \"\n + info.getDonorId() + \" with info \" + info);\n }\n\n // Acquired lock successfully, start rebalancing...\n int requestId = asyncService.getUniqueRequestId();\n\n // Why do we pass 'info' instead of 'stealInfo'? So that we can change\n // the state as the stores finish rebalance\n asyncService.submitOperation(requestId,\n new StealerBasedRebalanceAsyncOperation(this,\n voldemortConfig,\n metadataStore,\n requestId,\n info));\n\n return requestId;\n }", "public Date getDate(String path) throws ParseException {\n return BoxDateFormat.parse(this.getValue(path).asString());\n }", "public static void extract( DMatrixRMaj src,\n int rows[] , int rowsSize ,\n int cols[] , int colsSize , DMatrixRMaj dst ) {\n if( rowsSize != dst.numRows || colsSize != dst.numCols )\n throw new MatrixDimensionException(\"Unexpected number of rows and/or columns in dst matrix\");\n\n int indexDst = 0;\n for (int i = 0; i < rowsSize; i++) {\n int indexSrcRow = src.numCols*rows[i];\n for (int j = 0; j < colsSize; j++) {\n dst.data[indexDst++] = src.data[indexSrcRow + cols[j]];\n }\n }\n }", "private void processProjectID()\n {\n if (m_projectID == null)\n {\n List<Row> rows = getRows(\"project\", null, null);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_projectID = row.getInteger(\"proj_id\");\n }\n }\n }", "public static void getHistory() throws Exception{\n Client client = new Client(\"ProfileName\", false);\n\n // Obtain the 100 history entries starting from offset 0\n History[] history = client.refreshHistory(100, 0);\n\n client.clearHistory();\n }", "@Nullable\n public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) {\n return this.first.get(txn, first);\n }", "public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {\n return createAppUser(api, name, new CreateUserParams());\n }", "public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) {\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken);\r\n return String.format(\"%s&perms=%s\", authorizationUrl, permission.toString());\r\n }", "public void forAllTables(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _torqueModel.getTables(); it.hasNext(); )\r\n {\r\n _curTableDef = (TableDef)it.next();\r\n generate(template);\r\n }\r\n _curTableDef = null;\r\n }" ]
Invoked periodically.
[ "public void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}" ]
[ "public void resetQuotaAndRecoverEnforcement() {\n for(Integer nodeId: nodeIds) {\n boolean quotaEnforcement = mapNodeToQuotaEnforcingEnabled.get(nodeId);\n adminClient.metadataMgmtOps.updateRemoteMetadata(Arrays.asList(nodeId),\n MetadataStore.QUOTA_ENFORCEMENT_ENABLED_KEY,\n Boolean.toString(quotaEnforcement));\n }\n for(String storeName: storeNames) {\n adminClient.quotaMgmtOps.rebalanceQuota(storeName);\n }\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "public PasswordCheckResult check(boolean isAdminitrative, String userName, String password) {\n // TODO: allow custom restrictions?\n List<PasswordRestriction> passwordValuesRestrictions = getPasswordRestrictions();\n final PasswordStrengthCheckResult strengthResult = this.passwordStrengthChecker.check(userName, password, passwordValuesRestrictions);\n\n final int failedRestrictions = strengthResult.getRestrictionFailures().size();\n final PasswordStrength strength = strengthResult.getStrength();\n final boolean strongEnough = assertStrength(strength);\n\n PasswordCheckResult.Result resultAction;\n String resultMessage = null;\n if (isAdminitrative) {\n if (strongEnough) {\n if (failedRestrictions > 0) {\n resultAction = Result.WARN;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.ACCEPT;\n }\n } else {\n resultAction = Result.WARN;\n resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());\n }\n } else {\n if (strongEnough) {\n if (failedRestrictions > 0) {\n resultAction = Result.REJECT;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.ACCEPT;\n }\n } else {\n if (failedRestrictions > 0) {\n resultAction = Result.REJECT;\n resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();\n } else {\n resultAction = Result.REJECT;\n resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());\n }\n }\n }\n\n return new PasswordCheckResult(resultAction, resultMessage);\n\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 }", "public String addClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY,\n \"enterprise\", metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "public void removeCorporateGroupId(final String organizationId, final String corporateGroupId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n\n if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){\n dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);\n repositoryHandler.store(dbOrganization);\n }\n\n repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);\n }", "public synchronized void stop() {\n if (isRunning()) {\n socket.get().close();\n socket.set(null);\n deliverLifecycleAnnouncement(logger, false);\n }\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 }" ]
removes all data for an annotation class. This should be called after an annotation has been modified through the SPI
[ "public void clearAnnotationData(Class<? extends Annotation> annotationClass) {\n stereotypes.invalidate(annotationClass);\n scopes.invalidate(annotationClass);\n qualifiers.invalidate(annotationClass);\n interceptorBindings.invalidate(annotationClass);\n }" ]
[ "public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }", "private static void listHierarchy(ProjectFile file)\n {\n for (Task task : file.getChildTasks())\n {\n System.out.println(\"Task: \" + task.getName() + \"\\t\" + task.getStart() + \"\\t\" + task.getFinish());\n listHierarchy(task, \" \");\n }\n\n System.out.println();\n }", "public void deleteRebalancingState(RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n RebalancerState rebalancerState = getRebalancerState();\n\n if(!rebalancerState.remove(stealInfo))\n throw new IllegalArgumentException(\"Couldn't find \" + stealInfo + \" in \"\n + rebalancerState + \" while deleting\");\n\n if(rebalancerState.isEmpty()) {\n logger.debug(\"Cleaning all rebalancing state\");\n cleanAllRebalancingState();\n } else {\n put(REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n }\n } finally {\n writeLock.unlock();\n }\n }", "@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}", "public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }", "public PayloadBuilder customField(final String key, final Object value) {\n root.put(key, value);\n return this;\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 AssemblyResponse save(boolean isResumable)\n throws RequestException, LocalOperationException {\n Request request = new Request(getClient());\n options.put(\"steps\", steps.toMap());\n\n // only do tus uploads if files will be uploaded\n if (isResumable && getFilesCount() > 0) {\n Map<String, String> tusOptions = new HashMap<String, String>();\n tusOptions.put(\"tus_num_expected_upload_files\", Integer.toString(getFilesCount()));\n\n AssemblyResponse response = new AssemblyResponse(\n request.post(\"/assemblies\", options, tusOptions, null, null), true);\n\n // check if the assembly returned an error\n if (response.hasError()) {\n throw new RequestException(\"Request to Assembly failed: \" + response.json().getString(\"error\"));\n }\n\n try {\n handleTusUpload(response);\n } catch (IOException e) {\n throw new LocalOperationException(e);\n } catch (ProtocolException e) {\n throw new RequestException(e);\n }\n return response;\n } else {\n return new AssemblyResponse(request.post(\"/assemblies\", options, null, files, fileStreams));\n }\n }", "public static CredentialsConfig getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) {\n if (deployerOverrider.isOverridingDefaultDeployer()) {\n CredentialsConfig deployerCredentialsConfig = deployerOverrider.getDeployerCredentialsConfig();\n if (deployerCredentialsConfig != null) {\n return deployerCredentialsConfig;\n }\n }\n\n if (server != null) {\n CredentialsConfig deployerCredentials = server.getDeployerCredentialsConfig();\n if (deployerCredentials != null) {\n return deployerCredentials;\n }\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }" ]
Convert an Object to a Timestamp.
[ "public static java.sql.Timestamp toTimestamp(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Timestamp) {\n return (java.sql.Timestamp) value;\n }\n if (value instanceof String) {\n\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime());\n }" ]
[ "public double[][] getU() {\n double[][] X = new double[n][n];\n double[][] U = X;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (i <= j) {\n U[i][j] = LU[i][j];\n } else {\n U[i][j] = 0.0;\n }\n }\n }\n return X;\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 }", "private void animateIndicatorInvalidate() {\n if (mIndicatorScroller.computeScrollOffset()) {\n mIndicatorOffset = mIndicatorScroller.getCurr();\n invalidate();\n\n if (!mIndicatorScroller.isFinished()) {\n postOnAnimation(mIndicatorRunnable);\n return;\n }\n }\n\n completeAnimatingIndicator();\n }", "public void cmdProc(Interp interp, TclObject argv[])\n throws TclException {\n int currentObjIndex, len, i;\n int objc = argv.length - 1;\n boolean doBackslashes = true;\n boolean doCmds = true;\n boolean doVars = true;\n StringBuffer result = new StringBuffer();\n String s;\n char c;\n\n for (currentObjIndex = 1; currentObjIndex < objc; currentObjIndex++) {\n if (!argv[currentObjIndex].toString().startsWith(\"-\")) {\n break;\n }\n int opt = TclIndex.get(interp, argv[currentObjIndex],\n validCmds, \"switch\", 0);\n switch (opt) {\n case OPT_NOBACKSLASHES:\n doBackslashes = false;\n break;\n case OPT_NOCOMMANDS:\n doCmds = false;\n break;\n case OPT_NOVARS:\n doVars = false;\n break;\n default:\n throw new TclException(interp,\n \"SubstCrCmd.cmdProc: bad option \" + opt\n + \" index to cmds\");\n }\n }\n if (currentObjIndex != objc) {\n throw new TclNumArgsException(interp, currentObjIndex, argv,\n \"?-nobackslashes? ?-nocommands? ?-novariables? string\");\n }\n\n /*\n * Scan through the string one character at a time, performing\n * command, variable, and backslash substitutions.\n */\n\n s = argv[currentObjIndex].toString();\n len = s.length();\n i = 0;\n while (i < len) {\n c = s.charAt(i);\n\n if ((c == '[') && doCmds) {\n ParseResult res;\n try {\n interp.evalFlags = Parser.TCL_BRACKET_TERM;\n interp.eval(s.substring(i + 1, len));\n TclObject interp_result = interp.getResult();\n interp_result.preserve();\n res = new ParseResult(interp_result,\n i + interp.termOffset);\n } catch (TclException e) {\n i = e.errIndex + 1;\n throw e;\n }\n i = res.nextIndex + 2;\n result.append( res.value.toString() );\n res.release();\n /**\n * Removed\n (ToDo) may not be portable on Mac\n } else if (c == '\\r') {\n i++;\n */\n } else if ((c == '$') && doVars) {\n ParseResult vres = Parser.parseVar(interp,\n s.substring(i, len));\n i += vres.nextIndex;\n result.append( vres.value.toString() );\n vres.release();\n } else if ((c == '\\\\') && doBackslashes) {\n BackSlashResult bs = Interp.backslash(s, i, len);\n i = bs.nextIndex;\n if (bs.isWordSep) {\n break;\n } else {\n result.append( bs.c );\n }\n } else {\n result.append( c );\n i++;\n }\n }\n\n interp.setResult(result.toString());\n }", "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 lbvserver_scpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_scpolicy_binding obj = new lbvserver_scpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_scpolicy_binding response[] = (lbvserver_scpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException\n {\n StringBuilder pstyle = new StringBuilder(\"position:absolute;\");\n pstyle.append(\"left:\").append(x).append(UNIT).append(';');\n pstyle.append(\"top:\").append(y).append(UNIT).append(';');\n pstyle.append(\"width:\").append(width).append(UNIT).append(';');\n pstyle.append(\"height:\").append(height).append(UNIT).append(';');\n //pstyle.append(\"border:1px solid red;\");\n \n Element el = doc.createElement(\"img\");\n el.setAttribute(\"style\", pstyle.toString());\n\n String imgSrc = config.getImageHandler().handleResource(resource);\n\n if (!disableImageData && !imgSrc.isEmpty())\n el.setAttribute(\"src\", imgSrc);\n else\n el.setAttribute(\"src\", \"\");\n \n return el;\n }", "private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap();\n for(Integer nodeId: cluster.getNodeIds()) {\n nodeIdToZonePrimaryCount.put(nodeId,\n storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size());\n }\n\n return nodeIdToZonePrimaryCount;\n }", "public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {\n return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);\n }" ]
Retrieve timephased baseline work. Note that index 0 represents "Baseline", index 1 represents "Baseline1" and so on. @param index baseline index @return timephased work, or null if no baseline is present
[ "public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }" ]
[ "private static String normalizeDirName(String name)\n {\n if(name == null)\n return null;\n return name.toLowerCase().replaceAll(\"[^a-zA-Z0-9]\", \"-\");\n }", "public static String fancyStringF(double value, DecimalFormat format, int length, int significant) {\n\n String formatted = fancyString(value, format, length, significant);\n\n int n = length-formatted.length();\n if( n > 0 ) {\n StringBuilder builder = new StringBuilder(n);\n for (int i = 0; i < n; i++) {\n builder.append(' ');\n }\n return formatted + builder.toString();\n } else {\n return formatted;\n }\n }", "private void initStoreDefinitions(Version storesXmlVersion) {\n if(this.storeDefinitionsStorageEngine == null) {\n throw new VoldemortException(\"The store definitions directory is empty\");\n }\n\n String allStoreDefinitions = \"<stores>\";\n Version finalStoresXmlVersion = null;\n if(storesXmlVersion != null) {\n finalStoresXmlVersion = storesXmlVersion;\n }\n this.storeNames.clear();\n\n ClosableIterator<Pair<String, Versioned<String>>> storesIterator = this.storeDefinitionsStorageEngine.entries();\n\n // Some test setups may result in duplicate entries for 'store' element.\n // Do the de-dup here\n Map<String, Versioned<String>> storeNameToDefMap = new HashMap<String, Versioned<String>>();\n Version maxVersion = null;\n while(storesIterator.hasNext()) {\n Pair<String, Versioned<String>> storeDetail = storesIterator.next();\n String storeName = storeDetail.getFirst();\n Versioned<String> versionedStoreDef = storeDetail.getSecond();\n storeNameToDefMap.put(storeName, versionedStoreDef);\n Version curVersion = versionedStoreDef.getVersion();\n\n // Get the highest version from all the store entries\n if(maxVersion == null) {\n maxVersion = curVersion;\n } else if(maxVersion.compare(curVersion) == Occurred.BEFORE) {\n maxVersion = curVersion;\n }\n }\n\n // If the specified version is null, assign highest Version to\n // 'stores.xml' key\n if(finalStoresXmlVersion == null) {\n finalStoresXmlVersion = maxVersion;\n }\n\n // Go through all the individual stores and update metadata\n for(Entry<String, Versioned<String>> storeEntry: storeNameToDefMap.entrySet()) {\n String storeName = storeEntry.getKey();\n Versioned<String> versionedStoreDef = storeEntry.getValue();\n\n // Add all the store names to the list of storeNames\n this.storeNames.add(storeName);\n\n this.metadataCache.put(storeName, new Versioned<Object>(versionedStoreDef.getValue(),\n versionedStoreDef.getVersion()));\n }\n\n Collections.sort(this.storeNames);\n for(String storeName: this.storeNames) {\n Versioned<String> versionedStoreDef = storeNameToDefMap.get(storeName);\n // Stitch together to form the complete store definition list.\n allStoreDefinitions += versionedStoreDef.getValue();\n\n }\n\n allStoreDefinitions += \"</stores>\";\n\n // Update cache with the composite store definition list.\n metadataCache.put(STORES_KEY,\n convertStringToObject(STORES_KEY,\n new Versioned<String>(allStoreDefinitions,\n finalStoresXmlVersion)));\n }", "public static Message create( String text, Object data, ProcessingUnit owner )\n {\n return new SimpleMessage( text, data, owner);\n }", "public ArrayList<Double> segmentCost(ProjectCalendar projectCalendar, List<TimephasedCost> cost, TimescaleUnits rangeUnits, ArrayList<DateRange> dateList)\n {\n ArrayList<Double> result = new ArrayList<Double>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, cost, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(NumberHelper.DOUBLE_ZERO);\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeCost(projectCalendar, rangeUnits, range, cost, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\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 }", "protected void processLink(Row row)\n {\n Task predecessorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_PRED_UID\"));\n Task successorTask = m_project.getTaskByUniqueID(row.getInteger(\"LINK_SUCC_UID\"));\n if (predecessorTask != null && successorTask != null)\n {\n RelationType type = RelationType.getInstance(row.getInt(\"LINK_TYPE\"));\n TimeUnit durationUnits = MPDUtility.getDurationTimeUnits(row.getInt(\"LINK_LAG_FMT\"));\n Duration duration = MPDUtility.getDuration(row.getDouble(\"LINK_LAG\").doubleValue(), durationUnits);\n Relation relation = successorTask.addPredecessor(predecessorTask, type, duration);\n relation.setUniqueID(row.getInteger(\"LINK_UID\"));\n m_eventManager.fireRelationReadEvent(relation);\n }\n }", "public static void endThreads(String check){\r\n //(error check)\r\n if(currentThread != -1L){\r\n throw new IllegalStateException(\"endThreads() called, but thread \" + currentThread + \" has not finished (exception in thread?)\");\r\n }\r\n //(end threaded environment)\r\n assert !control.isHeldByCurrentThread();\r\n isThreaded = false;\r\n //(write remaining threads)\r\n boolean cleanPass = false;\r\n while(!cleanPass){\r\n cleanPass = true;\r\n for(long thread : threadedLogQueue.keySet()){\r\n assert currentThread < 0L;\r\n if(threadedLogQueue.get(thread) != null && !threadedLogQueue.get(thread).isEmpty()){\r\n //(mark queue as unclean)\r\n cleanPass = false;\r\n //(variables)\r\n Queue<Runnable> backlog = threadedLogQueue.get(thread);\r\n currentThread = thread;\r\n //(clear buffer)\r\n while(currentThread >= 0){\r\n if(currentThread != thread){ throw new IllegalStateException(\"Redwood control shifted away from flushing thread\"); }\r\n if(backlog.isEmpty()){ throw new IllegalStateException(\"Forgot to call finishThread() on thread \" + currentThread); }\r\n assert !control.isHeldByCurrentThread();\r\n backlog.poll().run();\r\n }\r\n //(unregister thread)\r\n threadsWaiting.remove(thread);\r\n }\r\n }\r\n }\r\n while(threadsWaiting.size() > 0){\r\n assert currentThread < 0L;\r\n assert control.tryLock();\r\n assert !threadsWaiting.isEmpty();\r\n control.lock();\r\n attemptThreadControlThreadsafe(-1);\r\n control.unlock();\r\n }\r\n //(clean up)\r\n for(long threadId : threadedLogQueue.keySet()){\r\n assert threadedLogQueue.get(threadId).isEmpty();\r\n }\r\n assert threadsWaiting.isEmpty();\r\n assert currentThread == -1L;\r\n endTrack(\"Threads( \"+check+\" )\");\r\n }", "@Override\n public List<String> setTargetHostsFromLineByLineText(String sourcePath,\n HostsSourceType sourceType) throws TargetHostsLoadException {\n\n List<String> targetHosts = new ArrayList<String>();\n try {\n String content = getContentFromPath(sourcePath, sourceType);\n\n targetHosts = setTargetHostsFromString(content);\n\n } catch (IOException e) {\n throw new TargetHostsLoadException(\"IEException when reading \"\n + sourcePath, e);\n }\n\n return targetHosts;\n\n }" ]
Shuffle an array. @param array Array. @param seed Random seed.
[ "public static void Shuffle(double[] array, long seed) {\n Random random = new Random();\n if (seed != 0) random.setSeed(seed);\n\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n double temp = array[index];\n array[index] = array[i];\n array[i] = temp;\n }\n }" ]
[ "public String getMethodSignature() {\n if (method != null) {\n String methodSignature = method.toString();\n return methodSignature.replaceFirst(\"public void \", \"\");\n }\n return null;\n }", "public static final BigInteger printDurationInIntegerTenthsOfMinutes(Duration duration)\n {\n BigInteger result = null;\n\n if (duration != null && duration.getDuration() != 0)\n {\n result = BigInteger.valueOf((long) printDurationFractionsOfMinutes(duration, 10));\n }\n\n return 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 }", "private AlbumArt findArtInMemoryCaches(DataReference artReference) {\n // First see if we can find the new track in the hot cache as a hot cue\n for (AlbumArt cached : hotCache.values()) {\n if (cached.artReference.equals(artReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n\n // Not in the hot cache, see if it is in our LRU cache\n return artCache.get(artReference);\n }", "@Override\r\n public void close() {\r\n // Use monitor to avoid race between external close and handler thread run()\r\n synchronized (closeMonitor) {\r\n // Close and clear streams, sockets etc.\r\n if (socket != null) {\r\n try {\r\n // Terminates thread blocking on socket read\r\n // and automatically closed depending streams\r\n socket.close();\r\n } catch (IOException e) {\r\n log.warn(\"Can not close socket\", e);\r\n } finally {\r\n socket = null;\r\n }\r\n }\r\n\r\n // Clear user data\r\n session = null;\r\n response = null;\r\n }\r\n }", "public static <T> List<T> copyOf(Collection<T> source) {\n Preconditions.checkNotNull(source);\n if (source instanceof ImmutableList<?>) {\n return (ImmutableList<T>) source;\n }\n if (source.isEmpty()) {\n return Collections.emptyList();\n }\n return ofInternal(source.toArray());\n }", "public static base_response update(nitro_service client, csparameter resource) throws Exception {\n\t\tcsparameter updateresource = new csparameter();\n\t\tupdateresource.stateupdate = resource.stateupdate;\n\t\treturn updateresource.update_resource(client);\n\t}", "public List<List<IN>> classifyRaw(String str,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, readerAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }", "private void started(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }" ]
Start listening for device announcements and keeping track of the DJ Link devices visible on the network. If already listening, has no effect. @throws SocketException if the socket to listen on port 50000 cannot be created
[ "public synchronized void start() throws SocketException {\n\n if (!isRunning()) {\n socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));\n startTime.set(System.currentTimeMillis());\n deliverLifecycleAnnouncement(logger, true);\n\n final byte[] buffer = new byte[512];\n final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);\n Thread receiver = new Thread(null, new Runnable() {\n @Override\n public void run() {\n boolean received;\n while (isRunning()) {\n try {\n if (getCurrentDevices().isEmpty()) {\n socket.get().setSoTimeout(60000); // We have no devices to check for timeout; block for a whole minute to check for shutdown\n } else {\n socket.get().setSoTimeout(1000); // Check every second to see if a device has vanished\n }\n socket.get().receive(packet);\n received = !ignoredAddresses.contains(packet.getAddress());\n } catch (SocketTimeoutException ste) {\n received = false;\n } catch (IOException e) {\n // Don't log a warning if the exception was due to the socket closing at shutdown.\n if (isRunning()) {\n // We did not expect to have a problem; log a warning and shut down.\n logger.warn(\"Problem reading from DeviceAnnouncement socket, stopping\", e);\n stop();\n }\n received = false;\n }\n try {\n if (received && (packet.getLength() == 54)) {\n final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);\n if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {\n // Looks like the kind of packet we need\n if (packet.getLength() < 54) {\n logger.warn(\"Ignoring too-short \" + kind.name + \" packet; expected 54 bytes, but only got \" +\n packet.getLength() + \".\");\n } else {\n if (packet.getLength() > 54) {\n logger.warn(\"Processing too-long \" + kind.name + \" packet; expected 54 bytes, but got \" +\n packet.getLength() + \".\");\n }\n DeviceAnnouncement announcement = new DeviceAnnouncement(packet);\n final boolean foundNewDevice = isDeviceNew(announcement);\n updateDevices(announcement);\n if (foundNewDevice) {\n deliverFoundAnnouncement(announcement);\n }\n }\n }\n }\n expireDevices();\n } catch (Throwable t) {\n logger.warn(\"Problem processing DeviceAnnouncement packet\", t);\n }\n }\n }\n }, \"beat-link DeviceFinder receiver\");\n receiver.setDaemon(true);\n receiver.start();\n }\n }" ]
[ "protected List<String> getPluginsPath() throws IOException {\n List<String> result = new ArrayList<>();\n Path pluginsDirectory = PROPERTIES.getAllureHome().resolve(\"plugins\").toAbsolutePath();\n if (Files.notExists(pluginsDirectory)) {\n return Collections.emptyList();\n }\n\n try (DirectoryStream<Path> plugins = Files.newDirectoryStream(pluginsDirectory, JAR_FILES)) {\n for (Path plugin : plugins) {\n result.add(plugin.toUri().toURL().toString());\n }\n }\n return result;\n }", "public void deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService,\n\t\t\tURL schemaOverrideResource) {\n\t\t// user defined schema\n\t\tif ( schemaOverrideService != null || schemaOverrideResource != null ) {\n\t\t\tcachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema();\n\t\t}\n\n\t\t// or generate them\n\t\tgenerateProtoschema();\n\n\t\ttry {\n\t\t\tprotobufCache.put( generatedProtobufName, cachedSchema );\n\t\t\tString errors = protobufCache.get( generatedProtobufName + \".errors\" );\n\t\t\tif ( errors != null ) {\n\t\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, errors );\n\t\t\t}\n\t\t\tLOG.successfulSchemaDeploy( generatedProtobufName );\n\t\t}\n\t\tcatch (HotRodClientException hrce) {\n\t\t\tthrow LOG.errorAtSchemaDeploy( generatedProtobufName, hrce );\n\t\t}\n\t\tif ( schemaCapture != null ) {\n\t\t\tschemaCapture.put( generatedProtobufName, cachedSchema );\n\t\t}\n\t}", "public static appfwpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tappfwpolicy_stats[] response = (appfwpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "@RequestMapping(value = \"/api/scripts\", method = RequestMethod.POST)\n public\n @ResponseBody\n Script addScript(Model model,\n @RequestParam(required = true) String name,\n @RequestParam(required = true) String script) throws Exception {\n\n return ScriptService.getInstance().addScript(name, script);\n }", "public static void setFilterBoxStyle(TextField searchBox) {\n\n searchBox.setIcon(FontOpenCms.FILTER);\n\n searchBox.setPlaceholder(\n org.opencms.ui.apps.Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n org.opencms.ui.apps.Messages.GUI_EXPLORER_FILTER_0));\n searchBox.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);\n }", "public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\n }", "public int executeRefresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tID id = (ID) idField.extractJavaFieldValue(data);\n\t\t// we don't care about the cache here\n\t\tT result = super.execute(databaseConnection, id, null);\n\t\tif (result == null) {\n\t\t\treturn 0;\n\t\t}\n\t\t// copy each field from the result into the passed in object\n\t\tfor (FieldType fieldType : resultsFieldTypes) {\n\t\t\tif (fieldType != idField) {\n\t\t\t\tfieldType.assignField(connectionSource, data, fieldType.extractJavaFieldValue(result), false,\n\t\t\t\t\t\tobjectCache);\n\t\t\t}\n\t\t}\n\t\treturn 1;\n\t}", "public void prepareForEnumeration() {\n if (isPreparer()) {\n for (NodeT node : nodeTable.values()) {\n // Prepare each node for traversal\n node.initialize();\n if (!this.isRootNode(node)) {\n // Mark other sub-DAGs as non-preparer\n node.setPreparer(false);\n }\n }\n initializeDependentKeys();\n initializeQueue();\n }\n }", "public void setClasspathRef(Reference r)\r\n {\r\n createClasspath().setRefid(r);\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }" ]
Create a random video. @return random video.
[ "private Video generateRandomVideo() {\n Video video = new Video();\n configureFavoriteStatus(video);\n configureLikeStatus(video);\n configureLiveStatus(video);\n configureTitleAndThumbnail(video);\n return video;\n }" ]
[ "public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }", "protected BufferedImage createErrorImage(final Rectangle area) {\n final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);\n final Graphics2D graphics = bufferedImage.createGraphics();\n try {\n graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));\n graphics.clearRect(0, 0, area.width, area.height);\n return bufferedImage;\n } finally {\n graphics.dispose();\n }\n }", "public ImmutableList<CandidateElement> extract(StateVertex currentState)\n\t\t\tthrows CrawljaxException {\n\t\tLinkedList<CandidateElement> results = new LinkedList<>();\n\n\t\tif (!checkedElements.checkCrawlCondition(browser)) {\n\t\t\tLOG.info(\"State {} did not satisfy the CrawlConditions.\", currentState.getName());\n\t\t\treturn ImmutableList.of();\n\t\t}\n\t\tLOG.debug(\"Looking in state: {} for candidate elements\", currentState.getName());\n\n\t\ttry {\n\t\t\tDocument dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());\n\t\t\textractElements(dom, results, \"\");\n\t\t} catch (IOException e) {\n\t\t\tLOG.error(e.getMessage(), e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t\tif (randomizeElementsOrder) {\n\t\t\tCollections.shuffle(results);\n\t\t}\n\t\tcurrentState.setElementsFound(results);\n\t\tLOG.debug(\"Found {} new candidate elements to analyze!\", results.size());\n\t\treturn ImmutableList.copyOf(results);\n\t}", "@Override\n\tpublic synchronized boolean fireEventAndWait(Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, NoSuchElementException, InterruptedException {\n\t\ttry {\n\n\t\t\tboolean handleChanged = false;\n\t\t\tboolean result = false;\n\n\t\t\tif (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals(\"\")) {\n\t\t\t\tLOGGER.debug(\"switching to frame: \" + eventable.getRelatedFrame());\n\t\t\t\ttry {\n\n\t\t\t\t\tswitchToFrame(eventable.getRelatedFrame());\n\t\t\t\t} catch (NoSuchFrameException e) {\n\t\t\t\t\tLOGGER.debug(\"Frame not found, possibly while back-tracking..\", e);\n\t\t\t\t\t// TODO Stefan, This exception is caught to prevent stopping\n\t\t\t\t\t// from working\n\t\t\t\t\t// This was the case on the Gmail case; find out if not switching\n\t\t\t\t\t// (catching)\n\t\t\t\t\t// Results in good performance...\n\t\t\t\t}\n\t\t\t\thandleChanged = true;\n\t\t\t}\n\n\t\t\tWebElement webElement =\n\t\t\t\t\tbrowser.findElement(eventable.getIdentification().getWebDriverBy());\n\n\t\t\tif (webElement != null) {\n\t\t\t\tresult = fireEventWait(webElement, eventable);\n\t\t\t}\n\n\t\t\tif (handleChanged) {\n\t\t\t\tbrowser.switchTo().defaultContent();\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tthrow e;\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\treturn false;\n\t\t}\n\t}", "public static auditmessages[] get(nitro_service service) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }", "public static base_responses update(nitro_service client, tmtrafficaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\ttmtrafficaction updateresources[] = new tmtrafficaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new tmtrafficaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].apptimeout = resources[i].apptimeout;\n\t\t\t\tupdateresources[i].sso = resources[i].sso;\n\t\t\t\tupdateresources[i].formssoaction = resources[i].formssoaction;\n\t\t\t\tupdateresources[i].persistentcookie = resources[i].persistentcookie;\n\t\t\t\tupdateresources[i].initiatelogout = resources[i].initiatelogout;\n\t\t\t\tupdateresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\tupdateresources[i].samlssoprofile = resources[i].samlssoprofile;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static List<File> listFilesByRegex(String regex, File... directories) {\n return listFiles(directories,\n new RegexFileFilter(regex),\n CanReadFileFilter.CAN_READ);\n }", "public static final Bytes of(byte[] data, int offset, int length) {\n Objects.requireNonNull(data);\n if (length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return new Bytes(copy);\n }" ]
Use this API to fetch all the appfwlearningdata resources that are configured on netscaler. This uses appfwlearningdata_args which is a way to provide additional arguments while fetching the resources.
[ "public static appfwlearningdata[] get(nitro_service service, appfwlearningdata_args args) throws Exception{\n\t\tappfwlearningdata obj = new appfwlearningdata();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tappfwlearningdata[] response = (appfwlearningdata[])obj.get_resources(service, option);\n\t\treturn response;\n\t}" ]
[ "public static base_responses delete(nitro_service client, String network[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (network != null && network.length > 0) {\n\t\t\troute6 deleteresources[] = new route6[network.length];\n\t\t\tfor (int i=0;i<network.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = network[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "protected void postProcessing()\n {\n //\n // Update the internal structure. We'll take this opportunity to\n // generate outline numbers for the tasks as they don't appear to\n // be present in the MPP file.\n //\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoWBS(m_autoWBS);\n config.setAutoOutlineNumber(true);\n m_project.updateStructure();\n config.setAutoOutlineNumber(false);\n\n //\n // Perform post-processing to set the summary flag\n //\n for (Task task : m_project.getTasks())\n {\n task.setSummary(task.hasChildTasks());\n }\n\n //\n // Ensure that the unique ID counters are correct\n //\n config.updateUniqueCounters();\n }", "private Style getRowTotalStyle(DJCrosstabRow crosstabRow) {\n\t\treturn crosstabRow.getTotalStyle() == null ? this.djcross.getRowTotalStyle(): crosstabRow.getTotalStyle();\n\t}", "private void removeTimedOutLocks(long timeout)\r\n {\r\n int count = 0;\r\n long maxAge = System.currentTimeMillis() - timeout;\r\n boolean breakFromLoop = false;\r\n ObjectLocks temp = null;\r\n \tsynchronized (locktable)\r\n \t{\r\n\t Iterator it = locktable.values().iterator();\r\n\t /**\r\n\t * run this loop while:\r\n\t * - we have more in the iterator\r\n\t * - the breakFromLoop flag hasn't been set\r\n\t * - we haven't removed more than the limit for this cleaning iteration.\r\n\t */\r\n\t while (it.hasNext() && !breakFromLoop && (count <= MAX_LOCKS_TO_CLEAN))\r\n\t {\r\n\t \ttemp = (ObjectLocks) it.next();\r\n\t \tif (temp.getWriter() != null)\r\n\t \t{\r\n\t\t \tif (temp.getWriter().getTimestamp() < maxAge)\r\n\t\t \t{\r\n\t\t \t\t// writer has timed out, set it to null\r\n\t\t \t\ttemp.setWriter(null);\r\n\t\t \t}\r\n\t \t}\r\n\t \tif (temp.getYoungestReader() < maxAge)\r\n\t \t{\r\n\t \t\t// all readers are older than timeout.\r\n\t \t\ttemp.getReaders().clear();\r\n\t \t\tif (temp.getWriter() == null)\r\n\t \t\t{\r\n\t \t\t\t// all readers and writer are older than timeout,\r\n\t \t\t\t// remove the objectLock from the iterator (which\r\n\t \t\t\t// is backed by the map, so it will be removed.\r\n\t \t\t\tit.remove();\r\n\t \t\t}\r\n\t \t}\r\n\t \telse\r\n\t \t{\r\n\t \t\t// we need to walk each reader.\r\n\t \t\tIterator readerIt = temp.getReaders().values().iterator();\r\n\t \t\tLockEntry readerLock = null;\r\n\t \t\twhile (readerIt.hasNext())\r\n\t \t\t{\r\n\t \t\t\treaderLock = (LockEntry) readerIt.next();\r\n\t \t\t\tif (readerLock.getTimestamp() < maxAge)\r\n\t \t\t\t{\r\n\t \t\t\t\t// this read lock is old, remove it.\r\n\t \t\t\t\treaderIt.remove();\r\n\t \t\t\t}\r\n\t \t\t}\r\n\t \t}\r\n\t \tcount++;\r\n\t }\r\n \t}\r\n }", "public void setConnectTimeout(int connectTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}", "public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {\n final String testName = entry.getKey();\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);\n } catch (IncompatibleTestMatrixException e) {\n LOGGER.info(String.format(\"Unable to load test matrix for %s\", testName), e);\n resultBuilder.recordError(testName, e);\n }\n }\n return resultBuilder.build();\n }", "public List<MapRow> readTableConditional(Class<? extends TableReader> readerClass) throws IOException\n {\n List<MapRow> result;\n if (DatatypeConverter.getBoolean(m_stream))\n {\n result = readTable(readerClass);\n }\n else\n {\n result = Collections.emptyList();\n }\n return result;\n }", "@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }", "public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {\r\n for (String name : names) {\r\n if (hasAnnotation(node, name)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }" ]
Inserts a new instance but references via the outIdentifier, which is returned as part of the ExecutionResults @param object @param outIdentifier @return
[ "public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }" ]
[ "public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }", "public static ServiceFuture<Void> fromBody(final Completable completable, final ServiceCallback<Void> callback) {\n final ServiceFuture<Void> serviceFuture = new ServiceFuture<>();\n completable.subscribe(new Action0() {\n Void value = null;\n @Override\n public void call() {\n if (callback != null) {\n callback.success(value);\n }\n serviceFuture.set(value);\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n if (callback != null) {\n callback.failure(throwable);\n }\n serviceFuture.setException(throwable);\n }\n });\n return serviceFuture;\n }", "public ItemDocument updateStatements(ItemIdValue itemIdValue,\n\t\t\tList<Statement> addStatements, List<Statement> deleteStatements,\n\t\t\tString summary) throws MediaWikiApiErrorException, IOException {\n\n\t\tItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(itemIdValue.getId());\n\n\t\treturn updateStatements(currentDocument, addStatements,\n\t\t\t\tdeleteStatements, summary);\n\t}", "private void validateArguments() throws BuildException {\n Path tempDir = getTempDir();\n\n if (tempDir == null) {\n throw new BuildException(\"Temporary directory cannot be null.\");\n }\n \n if (Files.exists(tempDir)) {\n if (!Files.isDirectory(tempDir)) {\n throw new BuildException(\"Temporary directory is not a folder: \" + tempDir.toAbsolutePath());\n }\n } else {\n try {\n Files.createDirectories(tempDir);\n } catch (IOException e) {\n throw new BuildException(\"Failed to create temporary folder: \" + tempDir, e);\n }\n }\n }", "public void fireAssignmentWrittenEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentWritten(resourceAssignment);\n }\n }\n }", "public DynamicReportBuilder addStyle(Style style) throws DJBuilderException {\n if (style.getName() == null) {\n throw new DJBuilderException(\"Invalid style. The style must have a name\");\n }\n\n report.addStyle(style);\n\n return this;\n }", "protected void printCenter(String format, Object... args) {\n String text = S.fmt(format, args);\n info(S.center(text, 80));\n }", "public void remove(Identity oid)\r\n {\r\n if (oid == null) return;\r\n\r\n ObjectCache cache = getCache(oid, null, METHOD_REMOVE);\r\n if (cache != null)\r\n {\r\n cache.remove(oid);\r\n }\r\n }", "public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {\n MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();\n\n Object[] values = new Object[parameterInfoArray.length];\n String[] types = new String[parameterInfoArray.length];\n\n MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);\n\n for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {\n MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];\n String type = parameterInfo.getType();\n types[parameterNum] = type;\n values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);\n }\n\n return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);\n }" ]
Joins the given parts to recover the original secret. <p><b>N.B.:</b> There is no way to determine whether or not the returned value is actually the original secret. If the parts are incorrect, or are under the threshold value used to split the secret, a random value will be returned. @param parts a map of part IDs to part values @return the original secret @throws IllegalArgumentException if {@code parts} is empty or contains values of varying lengths
[ "public byte[] join(Map<Integer, byte[]> parts) {\n checkArgument(parts.size() > 0, \"No parts provided\");\n final int[] lengths = parts.values().stream().mapToInt(v -> v.length).distinct().toArray();\n checkArgument(lengths.length == 1, \"Varying lengths of part values\");\n final byte[] secret = new byte[lengths[0]];\n for (int i = 0; i < secret.length; i++) {\n final byte[][] points = new byte[parts.size()][2];\n int j = 0;\n for (Map.Entry<Integer, byte[]> part : parts.entrySet()) {\n points[j][0] = part.getKey().byteValue();\n points[j][1] = part.getValue()[i];\n j++;\n }\n secret[i] = GF256.interpolate(points);\n }\n return secret;\n }" ]
[ "protected String getKey(final String ref, final String filename, final String extension) {\n return prefix + ref + \"/\" + filename + \".\" + extension;\n }", "public void logAttributeWarning(PathAddress address, Set<String> attributes) {\n logAttributeWarning(address, null, null, attributes);\n }", "@Api\n\tpublic void setFeatureModel(FeatureModel featureModel) throws LayerException {\n\t\tthis.featureModel = featureModel;\n\t\tif (null != getLayerInfo()) {\n\t\t\tfeatureModel.setLayerInfo(getLayerInfo());\n\t\t}\n\t\tfilterService.registerFeatureModel(featureModel);\n\t}", "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 ItemRequest<Team> removeUser(String team) {\n \n String path = String.format(\"/teams/%s/removeUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }", "public synchronized void setSendingStatus(boolean send) throws IOException {\n if (isSendingStatus() == send) {\n return;\n }\n\n if (send) { // Start sending status packets.\n ensureRunning();\n if ((getDeviceNumber() < 1) || (getDeviceNumber() > 4)) {\n throw new IllegalStateException(\"Can only send status when using a standard player number, 1 through 4.\");\n }\n\n BeatFinder.getInstance().start();\n BeatFinder.getInstance().addLifecycleListener(beatFinderLifecycleListener);\n\n final AtomicBoolean stillRunning = new AtomicBoolean(true);\n sendingStatus = stillRunning; // Allow other threads to stop us when necessary.\n\n Thread sender = new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (stillRunning.get()) {\n sendStatus();\n try {\n Thread.sleep(getStatusInterval());\n } catch (InterruptedException e) {\n logger.warn(\"beat-link VirtualCDJ status sender thread was interrupted; continuing\");\n }\n }\n }\n }, \"beat-link VirtualCdj status sender\");\n sender.setDaemon(true);\n sender.start();\n\n if (isSynced()) { // If we are supposed to be synced, we need to respond to master beats and tempo changes.\n addMasterListener(ourSyncMasterListener);\n }\n\n if (isPlaying()) { // Start the beat sender too, if we are supposed to be playing.\n beatSender.set(new BeatSender(metronome));\n }\n } else { // Stop sending status packets, and responding to master beats and tempo changes if we were synced.\n BeatFinder.getInstance().removeLifecycleListener(beatFinderLifecycleListener);\n removeMasterListener(ourSyncMasterListener);\n\n sendingStatus.set(false); // Stop the status sending thread.\n sendingStatus = null; // Indicate that we are no longer sending status.\n final BeatSender activeSender = beatSender.get(); // And stop the beat sender if we have one.\n if (activeSender != null) {\n activeSender.shutDown();\n beatSender.set(null);\n }\n }\n }", "public static boolean isRevisionDumpFile(DumpContentType dumpContentType) {\n\t\tif (WmfDumpFile.REVISION_DUMP.containsKey(dumpContentType)) {\n\t\t\treturn WmfDumpFile.REVISION_DUMP.get(dumpContentType);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\"Unsupported dump type \"\n\t\t\t\t\t+ dumpContentType);\n\t\t}\n\t}", "void countNonZeroUsingLinkedList( int parent[] , int ll[] ) {\n\n Arrays.fill(pinv,0,m,-1);\n nz_in_V = 0;\n m2 = m;\n\n for (int k = 0; k < n; k++) {\n int i = ll[head+k]; // remove row i from queue k\n nz_in_V++; // count V(k,k) as nonzero\n if( i < 0) // add a fictitious row since there are no nz elements\n i = m2++;\n pinv[i] = k; // associate row i with V(:,k)\n if( --ll[nque+k] <= 0 )\n continue;\n nz_in_V += ll[nque+k];\n int pa;\n if( (pa = parent[k]) != -1 ) { // move all rows to parent of k\n if( ll[nque+pa] == 0)\n ll[tail+pa] = ll[tail+k];\n ll[next+ll[tail+k]] = ll[head+pa];\n ll[head+pa] = ll[next+i];\n ll[nque+pa] += ll[nque+k];\n }\n }\n for (int i = 0, k = n; i < m; i++) {\n if( pinv[i] < 0 )\n pinv[i] = k++;\n }\n\n if( nz_in_V < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in V counts\");\n }", "@SuppressWarnings(\"WeakerAccess\")\n public String formatCueCountdown() {\n int count = getCueCountdown();\n\n if (count == 511) {\n return \"--.-\";\n }\n\n if ((count >= 1) && (count <= 256)) {\n int bars = (count - 1) / 4;\n int beats = ((count - 1) % 4) + 1;\n return String.format(\"%02d.%d\", bars, beats);\n }\n\n if (count == 0) {\n return \"00.0\";\n }\n\n return \"??.?\";\n }" ]
Return overall per token accuracy
[ "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 AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }", "private void disableCertificateVerification()\n throws KeyManagementException, NoSuchAlgorithmException {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] { new CustomTrustManager() };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new SecureRandom());\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);\n final HostnameVerifier verifier = new HostnameVerifier() {\n @Override\n public boolean verify(final String hostname,\n final SSLSession session) {\n return true;\n }\n };\n\n HttpsURLConnection.setDefaultHostnameVerifier(verifier);\n }", "private void writeResource(Resource mpxj)\n {\n ResourceType xml = m_factory.createResourceType();\n m_apibo.getResource().add(xml);\n\n xml.setAutoComputeActuals(Boolean.TRUE);\n xml.setCalculateCostFromUnits(Boolean.TRUE);\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getResourceCalendar()));\n xml.setCurrencyObjectId(DEFAULT_CURRENCY_ID);\n xml.setDefaultUnitsPerTime(Double.valueOf(1.0));\n xml.setEmailAddress(mpxj.getEmailAddress());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(RESOURCE_ID_PREFIX + mpxj.getUniqueID());\n xml.setIsActive(Boolean.TRUE);\n xml.setMaxUnitsPerTime(getPercentage(mpxj.getMaxUnits()));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(mpxj.getParentID());\n xml.setResourceNotes(mpxj.getNotes());\n xml.setResourceType(getResourceType(mpxj));\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.RESOURCE, mpxj));\n }", "public void extractFieldTypes(DatabaseType databaseType) throws SQLException {\n\t\tif (fieldTypes == null) {\n\t\t\tif (fieldConfigs == null) {\n\t\t\t\tfieldTypes = extractFieldTypes(databaseType, dataClass, tableName);\n\t\t\t} else {\n\t\t\t\tfieldTypes = convertFieldConfigs(databaseType, tableName, fieldConfigs);\n\t\t\t}\n\t\t}\n\t}", "public static ServerSetup[] verbose(ServerSetup[] serverSetups) {\r\n ServerSetup[] copies = new ServerSetup[serverSetups.length];\r\n for (int i = 0; i < serverSetups.length; i++) {\r\n copies[i] = serverSetups[i].createCopy().setVerbose(true);\r\n }\r\n return copies;\r\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean timeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }", "public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) {\n if(timeout < 0)\n throw new IllegalArgumentException(\"The timeout must be a non-negative number.\");\n this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit);\n return this;\n }", "public void setBit(int index, boolean set)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n if (set)\n {\n data[word] |= (1 << offset);\n }\n else // Unset the bit.\n {\n data[word] &= ~(1 << offset);\n }\n }", "public static ActorSystem createAndGetActorSystem() {\n if (actorSystem == null || actorSystem.isTerminated()) {\n actorSystem = ActorSystem.create(PcConstants.ACTOR_SYSTEM, conf);\n }\n return actorSystem;\n }" ]