query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Evict cached object @param key the key indexed the cached object to be evicted
[ "public void evictCache(String key) {\n H.Session sess = session();\n if (null != sess) {\n sess.evict(key);\n } else {\n app().cache().evict(key);\n }\n }" ]
[ "private boolean pathMatches(Path path, SquigglyContext context) {\n List<SquigglyNode> nodes = context.getNodes();\n Set<String> viewStack = null;\n SquigglyNode viewNode = null;\n\n int pathSize = path.getElements().size();\n int lastIdx = pathSize - 1;\n\n for (int i = 0; i < pathSize; i++) {\n PathElement element = path.getElements().get(i);\n\n if (viewNode != null && !viewNode.isSquiggly()) {\n Class beanClass = element.getBeanClass();\n\n if (beanClass != null && !Map.class.isAssignableFrom(beanClass)) {\n Set<String> propertyNames = getPropertyNamesFromViewStack(element, viewStack);\n\n if (!propertyNames.contains(element.getName())) {\n return false;\n }\n }\n\n } else if (nodes.isEmpty()) {\n return false;\n } else {\n\n SquigglyNode match = findBestSimpleNode(element, nodes);\n\n if (match == null) {\n match = findBestViewNode(element, nodes);\n\n if (match != null) {\n viewNode = match;\n viewStack = addToViewStack(viewStack, viewNode);\n }\n } else if (match.isAnyShallow()) {\n viewNode = match;\n } else if (match.isAnyDeep()) {\n return true;\n }\n\n if (match == null) {\n if (isJsonUnwrapped(element)) {\n continue;\n }\n\n return false;\n }\n\n if (match.isNegated()) {\n return false;\n }\n\n nodes = match.getChildren();\n\n if (i < lastIdx && nodes.isEmpty() && !match.isEmptyNested() && SquigglyConfig.isFilterImplicitlyIncludeBaseFields()) {\n nodes = BASE_VIEW_NODES;\n }\n }\n }\n\n return true;\n }", "private String getSlashyPath(final String path) {\n String changedPath = path;\n if (File.separatorChar != '/')\n changedPath = changedPath.replace(File.separatorChar, '/');\n\n return changedPath;\n }", "public T[] toArray(T[] tArray) {\n List<T> array = new ArrayList<T>(100);\n for (Iterator<T> it = iterator(); it.hasNext();) {\n T val = it.next();\n if (val != null) array.add(val);\n }\n return array.toArray(tArray);\n }", "public void setHtml(String html) {\n this.html = html;\n\n if (widget != null) {\n if (widget.isAttached()) {\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\");\n } else {\n widget.addAttachHandler(event ->\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\"));\n }\n } else {\n GWT.log(\"Please initialize the Target widget.\", new IllegalStateException());\n }\n }", "private ChildTaskContainer getParentTask(Activity activity)\n {\n //\n // Make a map of activity codes and their values for this activity\n //\n Map<UUID, UUID> map = getActivityCodes(activity);\n\n //\n // Work through the activity codes in sequence\n //\n ChildTaskContainer parent = m_projectFile;\n StringBuilder uniqueIdentifier = new StringBuilder();\n for (UUID activityCode : m_codeSequence)\n {\n UUID activityCodeValue = map.get(activityCode);\n String activityCodeText = m_activityCodeValues.get(activityCodeValue);\n if (activityCodeText != null)\n {\n if (uniqueIdentifier.length() != 0)\n {\n uniqueIdentifier.append('>');\n }\n uniqueIdentifier.append(activityCodeValue.toString());\n UUID uuid = UUID.nameUUIDFromBytes(uniqueIdentifier.toString().getBytes());\n Task newParent = findChildTaskByUUID(parent, uuid);\n if (newParent == null)\n {\n newParent = parent.addTask();\n newParent.setGUID(uuid);\n newParent.setName(activityCodeText);\n }\n parent = newParent;\n }\n }\n return parent;\n }", "public void createTag(final String tagUrl, final String commitMessage)\n throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new SVNCreateTagCallable(tagUrl, commitMessage, getLocation(), getSvnAuthenticationProvider(build),\n buildListener));\n }", "public void addCell(TableLayoutCell cell) {\n GridBagConstraints constraints = cell.getConstraints();\n constraints.insets = new Insets(cellpadding, cellpadding, cellpadding, cellpadding);\n add(cell.getComponent(), constraints);\n }", "public Flags flagList(ImapRequestLineReader request) throws ProtocolException {\n Flags flags = new Flags();\n request.nextWordChar();\n consumeChar(request, '(');\n CharacterValidator validator = new NoopCharValidator();\n String nextWord = consumeWord(request, validator);\n while (!nextWord.endsWith(\")\")) {\n setFlag(nextWord, flags);\n nextWord = consumeWord(request, validator);\n }\n // Got the closing \")\", may be attached to a word.\n if (nextWord.length() > 1) {\n setFlag(nextWord.substring(0, nextWord.length() - 1), flags);\n }\n\n return flags;\n }", "Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }" ]
Adds a file to your assembly but automatically genarates the name of the file. @param inputStream {@link InputStream} the file to be uploaded.
[ "public void addFile(InputStream inputStream) {\n String name = \"file\";\n fileStreams.put(normalizeDuplicateName(name), inputStream);\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 }", "public static void scaleCol( double alpha , DMatrixRMaj A , int col ) {\n int idx = col;\n for (int row = 0; row < A.numRows; row++, idx += A.numCols) {\n A.data[idx] *= alpha;\n }\n }", "public UniqueEntityLoader buildLoader(\n\t\t\tOuterJoinLoadable persister,\n\t\t\tint batchSize,\n\t\t\tLockOptions lockOptions,\n\t\t\tSessionFactoryImplementor factory,\n\t\t\tLoadQueryInfluencers influencers,\n\t\t\tBatchableEntityLoaderBuilder innerEntityLoaderBuilder) {\n\t\tif ( batchSize <= 1 ) {\n\t\t\t// no batching\n\t\t\treturn buildNonBatchingLoader( persister, lockOptions, factory, influencers, innerEntityLoaderBuilder );\n\t\t}\n\t\treturn buildBatchingLoader( persister, batchSize, lockOptions, factory, influencers, innerEntityLoaderBuilder );\n\t}", "public Date getBaselineFinish()\n {\n Object result = getCachedValue(TaskField.BASELINE_FINISH);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_FINISH);\n }\n\n if (!(result instanceof Date))\n {\n result = null;\n }\n return (Date) result;\n }", "public T reverse() {\n String id = getId();\n String REVERSE = \"_REVERSE\";\n if (id.endsWith(REVERSE)) {\n setId(id.substring(0, id.length() - REVERSE.length()));\n }\n\n float start = mStart;\n float end = mEnd;\n mStart = end;\n mEnd = start;\n mReverse = !mReverse;\n return self();\n }", "public void reverse() {\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).reverse();\n }\n }", "public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) {\n int size = nodeValues.size();\n if(size <= 1)\n return Collections.emptyList();\n\n Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap();\n for(NodeValue<K, V> nodeValue: nodeValues) {\n List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey());\n if(keyNodeValues == null) {\n keyNodeValues = Lists.newArrayListWithCapacity(5);\n keyToNodeValues.put(nodeValue.getKey(), keyNodeValues);\n }\n keyNodeValues.add(nodeValue);\n }\n\n List<NodeValue<K, V>> result = Lists.newArrayList();\n for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values())\n result.addAll(singleKeyGetRepairs(keyNodeValues));\n return result;\n }", "public static base_response update(nitro_service client, vlan resource) throws Exception {\n\t\tvlan updateresource = new vlan();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.aliasname = resource.aliasname;\n\t\tupdateresource.ipv6dynamicrouting = resource.ipv6dynamicrouting;\n\t\treturn updateresource.update_resource(client);\n\t}", "protected void cacheCollection() {\n this.clear();\n for (FluentModelTImpl childResource : this.listChildResources()) {\n this.childCollection.put(childResource.childResourceKey(), childResource);\n }\n }" ]
Sets the bootstrap URLs used by the different Fat clients inside the Coordinator @param bootstrapUrls list of bootstrap URLs defining which cluster to connect to @return modified CoordinatorConfig
[ "public CoordinatorConfig setBootstrapURLs(List<String> bootstrapUrls) {\n this.bootstrapURLs = Utils.notNull(bootstrapUrls);\n if(this.bootstrapURLs.size() <= 0)\n throw new IllegalArgumentException(\"Must provide at least one bootstrap URL.\");\n return this;\n }" ]
[ "public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }", "@Override\n public Set<String> paramKeys() {\n Set<String> set = new HashSet<String>();\n set.addAll(C.<String>list(request.paramNames()));\n set.addAll(extraParams.keySet());\n set.addAll(bodyParams().keySet());\n set.remove(\"_method\");\n set.remove(\"_body\");\n return set;\n }", "private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef)\r\n {\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName());\r\n\r\n if ((curCollDef != null) &&\r\n !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public void inverse(GVRPose src)\n {\n if (getSkeleton() != src.getSkeleton())\n throw new IllegalArgumentException(\"GVRPose.copy: input pose is incompatible with this pose\");\n src.sync();\n int numbones = getNumBones();\n Bone srcBone = src.mBones[0];\n Bone dstBone = mBones[0];\n\n mNeedSync = true;\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n srcBone.LocalMatrix.set(dstBone.WorldMatrix);\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(0), dstBone.toString());\n\n }\n for (int i = 1; i < numbones; ++i)\n {\n srcBone = src.mBones[i];\n dstBone = mBones[i];\n srcBone.WorldMatrix.invertAffine(dstBone.WorldMatrix);\n dstBone.Changed = WORLD_ROT | WORLD_POS;\n if (sDebug)\n {\n Log.d(\"BONE\", \"invert: %s %s\", mSkeleton.getBoneName(i), dstBone.toString());\n }\n }\n sync();\n }", "public static double findMax( double[] u, int startU , int length ) {\n double max = -1;\n\n int index = startU*2;\n int stopIndex = (startU + length)*2;\n for( ; index < stopIndex;) {\n double real = u[index++];\n double img = u[index++];\n\n double val = real*real + img*img;\n\n if( val > max ) {\n max = val;\n }\n }\n\n return Math.sqrt(max);\n }", "private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) {\n MenuDrawer drawer;\n\n if (type == Type.STATIC) {\n drawer = new StaticDrawer(activity);\n\n } else if (type == Type.OVERLAY) {\n drawer = new OverlayDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n\n } else {\n drawer = new SlidingDrawer(activity, dragMode);\n if (position == Position.LEFT || position == Position.START) {\n drawer.setupUpIndicator(activity);\n }\n }\n\n drawer.mDragMode = dragMode;\n drawer.setPosition(position);\n\n return drawer;\n }", "public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {\n try {\n return c.getMethod(name, argTypes);\n } catch(NoSuchMethodException e) {\n throw new IllegalArgumentException(e);\n }\n }", "@Deprecated\n public static OptionMap create(final ExpressionResolver resolver, final ModelNode model, final OptionMap defaults) throws OperationFailedException {\n final OptionMap map = OptionMap.builder()\n .addAll(defaults)\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_CORE_THREADS, RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_KEEPALIVE, RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_LIMIT, RemotingSubsystemRootResource.WORKER_TASK_LIMIT.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_MAX_THREADS, RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_WRITE_THREADS, RemotingSubsystemRootResource.WORKER_WRITE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .getMap();\n return map;\n }", "public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }" ]
Adds the headers. @param builder the builder @param headerMap the header map
[ "public static void addHeaders(BoundRequestBuilder builder,\n Map<String, String> headerMap) {\n for (Entry<String, String> entry : headerMap.entrySet()) {\n String name = entry.getKey();\n String value = entry.getValue();\n builder.addHeader(name, value);\n }\n\n }" ]
[ "private void processFields(Map<FieldType, String> map, Row row, FieldContainer container)\n {\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n FieldType field = entry.getKey();\n String name = entry.getValue();\n\n Object value;\n switch (field.getDataType())\n {\n case INTEGER:\n {\n value = row.getInteger(name);\n break;\n }\n\n case BOOLEAN:\n {\n value = Boolean.valueOf(row.getBoolean(name));\n break;\n }\n\n case DATE:\n {\n value = row.getDate(name);\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n case PERCENTAGE:\n {\n value = row.getDouble(name);\n break;\n }\n\n case DELAY:\n case WORK:\n case DURATION:\n {\n value = row.getDuration(name);\n break;\n }\n\n case RESOURCE_TYPE:\n {\n value = RESOURCE_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case TASK_TYPE:\n {\n value = TASK_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case CONSTRAINT:\n {\n value = CONSTRAINT_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case PRIORITY:\n {\n value = PRIORITY_MAP.get(row.getString(name));\n break;\n }\n\n case GUID:\n {\n value = row.getUUID(name);\n break;\n }\n\n default:\n {\n value = row.getString(name);\n break;\n }\n }\n\n container.set(field, value);\n }\n }", "public boolean updateSelectedItemsList(int dataIndex, boolean select) {\n boolean done = false;\n boolean contains = isSelected(dataIndex);\n if (select) {\n if (!contains) {\n if (!mMultiSelectionSupported) {\n clearSelection(false);\n }\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList add index = %d\", dataIndex);\n mSelectedItemsList.add(dataIndex);\n done = true;\n }\n } else {\n if (contains) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"updateSelectedItemsList remove index = %d\", dataIndex);\n mSelectedItemsList.remove(dataIndex);\n done = true;\n }\n }\n return done;\n }", "public static void scale(GVRMesh mesh, float x, float y, float z) {\n final float [] vertices = mesh.getVertices();\n final int vsize = vertices.length;\n\n for (int i = 0; i < vsize; i += 3) {\n vertices[i] *= x;\n vertices[i + 1] *= y;\n vertices[i + 2] *= z;\n }\n\n mesh.setVertices(vertices);\n }", "public ListExternalToolsOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }", "public static void keyPresent(final String key, final Map<String, ?> map) {\n if (!map.containsKey(key)) {\n throw new IllegalStateException(\n String.format(\"expected %s to be present\", key));\n }\n }", "public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid);\n return resp.getData();\n }", "public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }", "public CompositeGeneratorNode appendTemplate(final CompositeGeneratorNode parent, final StringConcatenationClient templateString) {\n final TemplateNode proc = new TemplateNode(templateString, this);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(proc);\n return parent;\n }", "private void fillConnections(int connectionsToCreate) throws InterruptedException {\r\n\t\ttry {\r\n\t\t\tfor (int i=0; i < connectionsToCreate; i++){\r\n\t\t\t//\tboolean dbDown = this.pool.getDbIsDown().get();\r\n\t\t\t\tif (this.pool.poolShuttingDown){\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tthis.partition.addFreeConnection(new ConnectionHandle(null, this.partition, this.pool, false));\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlogger.error(\"Error in trying to obtain a connection. Retrying in \"+this.acquireRetryDelayInMs+\"ms\", e);\r\n\t\t\tThread.sleep(this.acquireRetryDelayInMs);\r\n\t\t}\r\n\r\n\t}" ]
Move the SQL value to the next one for version processing.
[ "public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}" ]
[ "public void cleanup() {\n List<String> keys = new ArrayList<>(created.keySet());\n keys.sort(String::compareTo);\n for (String key : keys) {\n created.remove(key)\n .stream()\n .sorted(Comparator.comparing(HasMetadata::getKind))\n .forEach(metadata -> {\n log.info(String.format(\"Deleting %s : %s\", key, metadata.getKind()));\n deleteWithRetries(metadata);\n });\n }\n }", "public DiscreteInterval plus(DiscreteInterval other) {\n return new DiscreteInterval(this.min + other.min, this.max + other.max);\n }", "private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception\n {\n long start = System.currentTimeMillis();\n reader.setProjectID(projectID);\n ProjectFile projectFile = reader.read();\n long elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Reading database completed in \" + elapsed + \"ms.\");\n\n System.out.println(\"Writing output file started.\");\n start = System.currentTimeMillis();\n ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);\n writer.write(projectFile, outputFile);\n elapsed = System.currentTimeMillis() - start;\n System.out.println(\"Writing output completed in \" + elapsed + \"ms.\");\n }", "public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,\n Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {\n for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {\n initializer.invoke(instance, null, manager, creationalContext, CreationException.class);\n }\n }", "public static CentralDogma forConfig(File configFile) throws IOException {\n requireNonNull(configFile, \"configFile\");\n return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));\n }", "public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }", "public ThumborUrlBuilder buildImage(String image) {\n if (image == null || image.length() == 0) {\n throw new IllegalArgumentException(\"Image must not be blank.\");\n }\n return new ThumborUrlBuilder(host, key, image);\n }", "public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tAssert.notNull(methodName, \"Method name must not be null\");\n\t\ttry {\n\t\t\tMethod method = clazz.getMethod(methodName, args);\n\t\t\treturn Modifier.isStatic(method.getModifiers()) ? method : null;\n\t\t}\n\t\tcatch (NoSuchMethodException ex) {\n\t\t\treturn null;\n\t\t}\n\t}", "private CmsVfsEntryBean buildVfsEntryBeanForQuickSearch(\n CmsResource resource,\n Multimap<CmsResource, CmsResource> childMap,\n Set<CmsResource> filterMatches,\n Set<String> parentPaths,\n boolean isRoot)\n throws CmsException {\n\n CmsObject cms = getCmsObject();\n String title = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();\n boolean isMatch = filterMatches.contains(resource);\n List<CmsVfsEntryBean> childBeans = Lists.newArrayList();\n\n Collection<CmsResource> children = childMap.get(resource);\n if (!children.isEmpty()) {\n for (CmsResource child : children) {\n CmsVfsEntryBean childBean = buildVfsEntryBeanForQuickSearch(\n child,\n childMap,\n filterMatches,\n parentPaths,\n false);\n childBeans.add(childBean);\n }\n } else if (filterMatches.contains(resource)) {\n if (parentPaths.contains(resource.getRootPath())) {\n childBeans = null;\n }\n // otherwise childBeans remains an empty list\n }\n\n String rootPath = resource.getRootPath();\n CmsVfsEntryBean result = new CmsVfsEntryBean(\n rootPath,\n resource.getStructureId(),\n title,\n CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), true),\n isRoot,\n isEditable(cms, resource),\n childBeans,\n isMatch);\n String siteRoot = null;\n if (OpenCms.getSiteManager().startsWithShared(rootPath)) {\n siteRoot = OpenCms.getSiteManager().getSharedFolder();\n } else {\n String tempSiteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);\n if (tempSiteRoot != null) {\n siteRoot = tempSiteRoot;\n } else {\n siteRoot = \"\";\n }\n }\n result.setSiteRoot(siteRoot);\n return result;\n }" ]
Opens the jar, wraps any IOException.
[ "private JarFile loadJar(File archive) throws DecompilationException\n {\n try\n {\n return new JarFile(archive);\n }\n catch (IOException ex)\n {\n throw new DecompilationException(\"Can't load .jar: \" + archive.getPath(), ex);\n }\n }" ]
[ "public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "public String getGroupNameFromId(int groupId) {\n return (String) sqlService.getFromTable(Constants.GROUPS_GROUP_NAME, Constants.GENERIC_ID, groupId,\n Constants.DB_TABLE_GROUPS);\n }", "public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\n }", "public synchronized T get(Scope scope) {\n if (instance != null) {\n return instance;\n }\n\n if (providerInstance != null) {\n if (isProvidingSingletonInScope) {\n instance = providerInstance.get();\n //gc\n providerInstance = null;\n return instance;\n }\n\n return providerInstance.get();\n }\n\n if (factoryClass != null && factory == null) {\n factory = FactoryLocator.getFactory(factoryClass);\n //gc\n factoryClass = null;\n }\n\n if (factory != null) {\n if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) {\n return factory.createInstance(scope);\n }\n instance = factory.createInstance(scope);\n //gc\n factory = null;\n return instance;\n }\n\n if (providerFactoryClass != null && providerFactory == null) {\n providerFactory = FactoryLocator.getFactory(providerFactoryClass);\n //gc\n providerFactoryClass = null;\n }\n\n if (providerFactory != null) {\n if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) {\n instance = providerFactory.createInstance(scope).get();\n //gc\n providerFactory = null;\n return instance;\n }\n if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) {\n providerInstance = providerFactory.createInstance(scope);\n //gc\n providerFactory = null;\n return providerInstance.get();\n }\n\n return providerFactory.createInstance(scope).get();\n }\n\n throw new IllegalStateException(\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\");\n }", "public static vpnclientlessaccesspolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public static base_response update(nitro_service client, rsskeytype resource) throws Exception {\n\t\trsskeytype updateresource = new rsskeytype();\n\t\tupdateresource.rsstype = resource.rsstype;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static long hash(final BsonDocument doc) {\n if (doc == null) {\n return 0L;\n }\n\n final byte[] docBytes = toBytes(doc);\n long hashValue = FNV_64BIT_OFFSET_BASIS;\n\n for (int offset = 0; offset < docBytes.length; offset++) {\n hashValue ^= (0xFF & docBytes[offset]);\n hashValue *= FNV_64BIT_PRIME;\n }\n\n return hashValue;\n }", "public static base_response update(nitro_service client, nstimeout resource) throws Exception {\n\t\tnstimeout updateresource = new nstimeout();\n\t\tupdateresource.zombie = resource.zombie;\n\t\tupdateresource.client = resource.client;\n\t\tupdateresource.server = resource.server;\n\t\tupdateresource.httpclient = resource.httpclient;\n\t\tupdateresource.httpserver = resource.httpserver;\n\t\tupdateresource.tcpclient = resource.tcpclient;\n\t\tupdateresource.tcpserver = resource.tcpserver;\n\t\tupdateresource.anyclient = resource.anyclient;\n\t\tupdateresource.anyserver = resource.anyserver;\n\t\tupdateresource.halfclose = resource.halfclose;\n\t\tupdateresource.nontcpzombie = resource.nontcpzombie;\n\t\tupdateresource.reducedfintimeout = resource.reducedfintimeout;\n\t\tupdateresource.newconnidletimeout = resource.newconnidletimeout;\n\t\treturn updateresource.update_resource(client);\n\t}", "private Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows) throws ParseException\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"ID\");\n String shifts = row.getString(\"SHIFTS\");\n map.put(workPatternID, createTimeEntryRowList(shifts));\n }\n return map;\n }" ]
Boot the controller. Called during service start. @param context the boot context @throws ConfigurationPersistenceException if the configuration failed to be loaded
[ "protected void boot(final BootContext context) throws ConfigurationPersistenceException {\n List<ModelNode> bootOps = configurationPersister.load();\n ModelNode op = registerModelControllerServiceInitializationBootStep(context);\n if (op != null) {\n bootOps.add(op);\n }\n boot(bootOps, false);\n finishBoot();\n }" ]
[ "private static List<CmsCategory> getCategories(CmsObject cms, CmsResource resource) {\n\n if ((null != resource) && (null != cms)) {\n try {\n return CmsCategoryService.getInstance().readResourceCategories(cms, resource);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return new ArrayList<CmsCategory>(0);\n }", "protected static String ConvertBinaryOperator(int oper)\r\n {\r\n // Convert the operator into the proper string\r\n String oper_string;\r\n switch (oper)\r\n {\r\n default:\r\n case EQUAL:\r\n oper_string = \"=\";\r\n break;\r\n case LIKE:\r\n oper_string = \"LIKE\";\r\n break;\r\n case NOT_EQUAL:\r\n oper_string = \"!=\";\r\n break;\r\n case LESS_THAN:\r\n oper_string = \"<\";\r\n break;\r\n case GREATER_THAN:\r\n oper_string = \">\";\r\n break;\r\n case GREATER_EQUAL:\r\n oper_string = \">=\";\r\n break;\r\n case LESS_EQUAL:\r\n oper_string = \"<=\";\r\n break;\r\n }\r\n return oper_string;\r\n }", "public static String copyToString(InputStream in, Charset charset) throws IOException {\n\t\tAssert.notNull(in, \"No InputStream specified\");\n\t\tStringBuilder out = new StringBuilder();\n\t\tInputStreamReader reader = new InputStreamReader(in, charset);\n\t\tchar[] buffer = new char[BUFFER_SIZE];\n\t\tint bytesRead = -1;\n\t\twhile ((bytesRead = reader.read(buffer)) != -1) {\n\t\t\tout.append(buffer, 0, bytesRead);\n\t\t}\n\t\treturn out.toString();\n\t}", "private void clearDeck(CdjStatus update) {\n if (hotCache.remove(DeckReference.getDeckReference(update.getDeviceNumber(), 0)) != null) {\n deliverTrackMetadataUpdate(update.getDeviceNumber(), null);\n }\n }", "public String getString(Integer offset)\n {\n String result = null;\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n if (value != null)\n {\n result = MPPUtility.getString(value, 0);\n }\n }\n\n return (result);\n }", "public synchronized int get(byte[] dst, int off, int len) {\n if (available == 0) {\n return 0;\n }\n\n // limit is last index to read + 1\n int limit = idxGet < idxPut ? idxPut : capacity;\n int count = Math.min(limit - idxGet, len);\n System.arraycopy(buffer, idxGet, dst, off, count);\n idxGet += count;\n\n if (idxGet == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxPut);\n if (count2 > 0) {\n System.arraycopy(buffer, 0, dst, off + count, count2);\n idxGet = count2;\n count += count2;\n } else {\n idxGet = 0;\n }\n }\n available -= count;\n return count;\n }", "private void readProjectProperties(Project ganttProject)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(ganttProject.getName());\n mpxjProperties.setCompany(ganttProject.getCompany());\n mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS);\n\n String locale = ganttProject.getLocale();\n if (locale == null)\n {\n locale = \"en_US\";\n }\n m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale));\n }", "private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }", "private void readLeafTasks(Task parent, Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"A1TAB\");\n while (currentID.intValue() != 0)\n {\n if (m_projectFile.getTaskByUniqueID(currentID) == null)\n {\n readTask(parent, currentID);\n }\n currentID = table.find(currentID).getInteger(\"NEXT_TASK_ID\");\n }\n }" ]
Map event type enum. @param eventType the event type @return the event type enum
[ "private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }" ]
[ "private void init(final List<DbLicense> licenses) {\n licensesRegexp.clear();\n\n for (final DbLicense license : licenses) {\n if (license.getRegexp() == null ||\n license.getRegexp().isEmpty()) {\n licensesRegexp.put(license.getName(), license);\n } else {\n licensesRegexp.put(license.getRegexp(), license);\n }\n }\n }", "public static String nextWord(String string) {\n int index = 0;\n while (index < string.length() && !Character.isWhitespace(string.charAt(index))) {\n index++;\n }\n return string.substring(0, index);\n }", "public CollectionRequest<Story> findByTask(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Story>(this, Story.class, path, \"GET\");\n }", "public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, \"photo_id\", photoId, date, perPage, page);\n }", "@Override\n public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deploymentConfig = entities.stream()\n .filter(hm -> hm instanceof DeploymentConfig)\n .map(hm -> (DeploymentConfig) hm)\n .map(dc -> dc.getMetadata().getName()).findFirst();\n\n deploymentConfig.ifPresent(name -> this.applicationName = name);\n }\n }", "public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }", "private InputStream prepareInputStream(InputStream stream) throws IOException\n {\n InputStream result;\n BufferedInputStream bis = new BufferedInputStream(stream);\n readHeaderProperties(bis);\n if (isCompressed())\n {\n result = new InflaterInputStream(bis);\n }\n else\n {\n result = bis;\n }\n return result;\n }", "private void ensureReferencedFKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException\r\n {\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);\r\n ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);\r\n String fkFieldNames = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);\r\n ArrayList missingFields = new ArrayList();\r\n SequencedHashMap fkFields = new SequencedHashMap();\r\n\r\n // first we gather all field names\r\n for (CommaListIterator it = new CommaListIterator(fkFieldNames); it.hasNext();)\r\n {\r\n String fieldName = (String)it.next();\r\n FieldDescriptorDef fieldDef = elementClassDef.getField(fieldName);\r\n\r\n if (fieldDef == null)\r\n {\r\n missingFields.add(fieldName);\r\n }\r\n fkFields.put(fieldName, fieldDef);\r\n }\r\n\r\n // next we traverse all sub types and gather fields as we go\r\n for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext() && !missingFields.isEmpty();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n for (int idx = 0; idx < missingFields.size();)\r\n {\r\n FieldDescriptorDef fieldDef = subTypeDef.getField((String)missingFields.get(idx));\r\n\r\n if (fieldDef != null)\r\n {\r\n fkFields.put(fieldDef.getName(), fieldDef);\r\n missingFields.remove(idx);\r\n }\r\n else\r\n {\r\n idx++;\r\n }\r\n }\r\n }\r\n if (!missingFields.isEmpty())\r\n {\r\n throw new ConstraintException(\"Cannot find field \"+missingFields.get(0).toString()+\" in the hierarchy with root type \"+\r\n elementClassDef.getName()+\" which is used as foreignkey in collection \"+\r\n collDef.getName()+\" in \"+collDef.getOwner().getName());\r\n }\r\n\r\n // copy the found fields into the element class\r\n ensureFields(elementClassDef, fkFields.values());\r\n }", "public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new ClusterMapper().writeCluster(cluster));\n } catch(IOException e) {\n logger.error(\"IOException during dumpClusterToFile: \" + e);\n }\n }\n }" ]
Checks the given class descriptor for correct object cache setting. @param classDef The class descriptor @param checkLevel The current check level (this constraint is only checked in strict) @exception ConstraintException If the constraint has been violated
[ "private void checkObjectCache(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n ObjectCacheDef objCacheDef = classDef.getObjectCache();\r\n\r\n if (objCacheDef == null)\r\n {\r\n return;\r\n }\r\n\r\n String objectCacheName = objCacheDef.getName();\r\n\r\n if ((objectCacheName == null) || (objectCacheName.length() == 0))\r\n {\r\n throw new ConstraintException(\"No class specified for the object-cache of class \"+classDef.getName());\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(objectCacheName, OBJECT_CACHE_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+objectCacheName+\" specified as object-cache of class \"+classDef.getName()+\" does not implement the interface \"+OBJECT_CACHE_INTERFACE);\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 object-cache class \"+objectCacheName+\" of class \"+classDef.getName());\r\n }\r\n }" ]
[ "public static base_responses delete(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 deleteresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new nsip6();\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "public static ComplexNumber Multiply(ComplexNumber z1, ComplexNumber z2) {\r\n double z1R = z1.real, z1I = z1.imaginary;\r\n double z2R = z2.real, z2I = z2.imaginary;\r\n\r\n return new ComplexNumber(z1R * z2R - z1I * z2I, z1R * z2I + z1I * z2R);\r\n }", "public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n\n for (int groupId : groupIds) {\n methods.addAll(getMethodsFromGroupId(groupId, filters));\n }\n\n return methods;\n }", "public double Function1D(double x) {\n return Math.exp(x * x / (-2 * sqrSigma)) / (Math.sqrt(2 * Math.PI) * sigma);\n }", "synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\n }", "public static dnsaaaarec[] get(nitro_service service, dnsaaaarec_args args) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}", "private void deleteByQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n logger.debug(\"deleteByQuery \" + cld.getClassNameOfObject() + \", \" + query);\n }\n\n if (query instanceof QueryBySQL)\n {\n String sql = ((QueryBySQL) query).getSql();\n this.dbAccess.executeUpdateSQL(sql, cld);\n }\n else\n {\n // if query is Identity based transform it to a criteria based query first\n if (query instanceof QueryByIdentity)\n {\n QueryByIdentity qbi = (QueryByIdentity) query;\n Object oid = qbi.getExampleObject();\n // make sure it's an Identity\n if (!(oid instanceof Identity))\n {\n oid = serviceIdentity().buildIdentity(oid);\n }\n query = referencesBroker.getPKQuery((Identity) oid);\n }\n\n if (!cld.isInterface())\n {\n this.dbAccess.executeDelete(query, cld);\n }\n\n // if class is an extent, we have to delete all extent classes too\n String lastUsedTable = cld.getFullTableName();\n if (cld.isExtent())\n {\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (!extCld.getFullTableName().equals(lastUsedTable))\n {\n lastUsedTable = extCld.getFullTableName();\n this.dbAccess.executeDelete(query, extCld);\n }\n }\n }\n\n }\n }", "public static double Taneja(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double pq = p[i] + q[i];\n r += (pq / 2) * Math.log(pq / (2 * Math.sqrt(p[i] * q[i])));\n }\n }\n return r;\n }", "public boolean isEUI64(boolean partial) {\n\t\tint segmentCount = getSegmentCount();\n\t\tint endIndex = addressSegmentIndex + segmentCount;\n\t\tif(addressSegmentIndex <= 5) {\n\t\t\tif(endIndex > 6) {\n\t\t\t\tint index3 = 5 - addressSegmentIndex;\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(index3);\n\t\t\t\tIPv6AddressSegment seg4 = getSegment(index3 + 1);\n\t\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00) && seg3.matchesWithMask(0xff, 0xff);\n\t\t\t} else if(partial && endIndex == 6) {\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(5 - addressSegmentIndex);\n\t\t\t\treturn seg3.matchesWithMask(0xff, 0xff);\n\t\t\t}\n\t\t} else if(partial && addressSegmentIndex == 6 && endIndex > 6) {\n\t\t\tIPv6AddressSegment seg4 = getSegment(6 - addressSegmentIndex);\n\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00);\n\t\t}\n\t\treturn partial;\n\t}" ]
Retrieve a timestamp field. @param dateName field containing the date component @param timeName field containing the time component @return Date instance
[ "public Date getTimestamp(FastTrackField dateName, FastTrackField timeName)\n {\n Date result = null;\n Date date = getDate(dateName);\n if (date != null)\n {\n Calendar dateCal = DateHelper.popCalendar(date);\n Date time = getDate(timeName);\n if (time != null)\n {\n Calendar timeCal = DateHelper.popCalendar(time);\n dateCal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY));\n dateCal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE));\n dateCal.set(Calendar.SECOND, timeCal.get(Calendar.SECOND));\n dateCal.set(Calendar.MILLISECOND, timeCal.get(Calendar.MILLISECOND));\n DateHelper.pushCalendar(timeCal);\n }\n\n result = dateCal.getTime();\n DateHelper.pushCalendar(dateCal);\n }\n\n return result;\n }" ]
[ "public Set<Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n for (ProcessorGraphNode<?, ?> root: this.roots) {\n for (Processor p: root.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }", "public void addFkToThisClass(String column)\r\n {\r\n if (fksToThisClass == null)\r\n {\r\n fksToThisClass = new Vector();\r\n }\r\n fksToThisClass.add(column);\r\n fksToThisClassAry = null;\r\n }", "private void afterBatch(BatchBackend backend) {\n\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\tif ( this.optimizeAtEnd ) {\n\t\t\tbackend.optimize( targetedTypes );\n\t\t}\n\t\tbackend.flush( targetedTypes );\n\t}", "private static Constraint loadConstraint(Annotation context) {\n Constraint constraint = null;\n final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);\n\n for (Constraint aConstraint : constraints) {\n try {\n aConstraint.getClass().getDeclaredMethod(\"check\", context.annotationType());\n constraint = aConstraint;\n break;\n } catch (NoSuchMethodException e) {\n // Look for next implementation if method not found with required signature.\n }\n }\n\n if (constraint == null) {\n throw new IllegalStateException(\"Couldn't found any implementation of \" + Constraint.class.getName());\n }\n return constraint;\n }", "public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(Object parent, FID id) throws SQLException {\n\t\t// this can happen if we have a foreign-auto-refresh scenario\n\t\tif (foreignFieldType == null) {\n\t\t\treturn null;\n\t\t}\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tif (!fieldConfig.isForeignCollectionEager()) {\n\t\t\t// we know this won't go recursive so no need for the counters\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\n\t\t// try not to create level counter objects unless we have to\n\t\tLevelCounters levelCounters = threadLevelCounters.get();\n\t\tif (levelCounters == null) {\n\t\t\tif (fieldConfig.getForeignCollectionMaxEagerLevel() == 0) {\n\t\t\t\t// then return a lazy collection instead\n\t\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(),\n\t\t\t\t\t\tfieldConfig.isForeignCollectionOrderAscending());\n\t\t\t}\n\t\t\tlevelCounters = new LevelCounters();\n\t\t\tthreadLevelCounters.set(levelCounters);\n\t\t}\n\n\t\tif (levelCounters.foreignCollectionLevel == 0) {\n\t\t\tlevelCounters.foreignCollectionLevelMax = fieldConfig.getForeignCollectionMaxEagerLevel();\n\t\t}\n\t\t// are we over our level limit?\n\t\tif (levelCounters.foreignCollectionLevel >= levelCounters.foreignCollectionLevelMax) {\n\t\t\t// then return a lazy collection instead\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\t\tlevelCounters.foreignCollectionLevel++;\n\t\ttry {\n\t\t\treturn new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t} finally {\n\t\t\tlevelCounters.foreignCollectionLevel--;\n\t\t}\n\t}", "public void foreach(PixelFunction fn) {\n Arrays.stream(points()).forEach(p -> fn.apply(p.x, p.y, pixel(p)));\n }", "public void hide() {\n div.removeFromParent();\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.AUTO);\n }\n if (type == LoaderType.CIRCULAR) {\n preLoader.removeFromParent();\n } else if (type == LoaderType.PROGRESS) {\n progress.removeFromParent();\n }\n }", "static void endInitialization(WeldContainer container, boolean isShutdownHookEnabled) {\n container.complete();\n // If needed, register one shutdown hook for all containers\n if (shutdownHook == null && isShutdownHookEnabled) {\n synchronized (LOCK) {\n if (shutdownHook == null) {\n shutdownHook = new ShutdownHook();\n SecurityActions.addShutdownHook(shutdownHook);\n }\n }\n }\n container.fireContainerInitializedEvent();\n }", "public Collection<Exif> getExif(String photoId, String secret) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_EXIF);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n if (secret != null) {\r\n parameters.put(\"secret\", secret);\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 List<Exif> exifs = new ArrayList<Exif>();\r\n Element photoElement = response.getPayload();\r\n NodeList exifElements = photoElement.getElementsByTagName(\"exif\");\r\n for (int i = 0; i < exifElements.getLength(); i++) {\r\n Element exifElement = (Element) exifElements.item(i);\r\n Exif exif = new Exif();\r\n exif.setTagspace(exifElement.getAttribute(\"tagspace\"));\r\n exif.setTagspaceId(exifElement.getAttribute(\"tagspaceid\"));\r\n exif.setTag(exifElement.getAttribute(\"tag\"));\r\n exif.setLabel(exifElement.getAttribute(\"label\"));\r\n exif.setRaw(XMLUtilities.getChildValue(exifElement, \"raw\"));\r\n exif.setClean(XMLUtilities.getChildValue(exifElement, \"clean\"));\r\n exifs.add(exif);\r\n }\r\n return exifs;\r\n }" ]
This method is used to push install referrer via Intent @param intent An Intent with the install referrer parameters
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }" ]
[ "private String visibility(Options opt, ProgramElementDoc e) {\n\treturn opt.showVisibility ? Visibility.get(e).symbol : \" \";\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 }", "public static base_responses update(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey updateresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslcertkey();\n\t\t\t\tupdateresources[i].certkey = resources[i].certkey;\n\t\t\t\tupdateresources[i].expirymonitor = resources[i].expirymonitor;\n\t\t\t\tupdateresources[i].notificationperiod = resources[i].notificationperiod;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}", "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}", "private ProjectFile readProjectFile(ProjectReader reader, File file) throws MPXJException\n {\n addListeners(reader);\n return reader.read(file);\n }", "private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef)\r\n {\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName());\r\n\r\n if ((curCollDef != null) &&\r\n !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public static base_responses add(nitro_service client, dbdbprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdbdbprofile addresources[] = new dbdbprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dbdbprofile();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].interpretquery = resources[i].interpretquery;\n\t\t\t\taddresources[i].stickiness = resources[i].stickiness;\n\t\t\t\taddresources[i].kcdaccount = resources[i].kcdaccount;\n\t\t\t\taddresources[i].conmultiplex = resources[i].conmultiplex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public ChannelInfo getChannel(String name) {\n final URI uri = uriWithPath(\"./channels/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ChannelInfo.class);\n }" ]
Obtains a Symmetry010 local date-time from another date-time object. @param temporal the date-time object to convert, not null @return the Symmetry010 local date-time, not null @throws DateTimeException if unable to create the date-time
[ "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<Symmetry010Date> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<Symmetry010Date>) super.localDateTime(temporal);\n }" ]
[ "public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }", "public DomainList getPhotosetDomains(Date date, String photosetId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTOSET_DOMAINS, \"photoset_id\", photosetId, date, perPage, page);\n }", "private static long getVersionId(String versionDir) {\n try {\n return Long.parseLong(versionDir.replace(\"version-\", \"\"));\n } catch(NumberFormatException e) {\n logger.trace(\"Cannot parse version directory to obtain id \" + versionDir);\n return -1;\n }\n }", "public RedwoodConfiguration loggingClass(final String classToIgnoreInTraces){\r\n tasks.add(new Runnable() { public void run() { Redwood.addLoggingClass(classToIgnoreInTraces); } });\r\n return this;\r\n }", "public void setIntVec(IntBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input buffer for indices cannot be null\");\n }\n if (getIndexSize() != 4)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with short array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setIntVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setIntArray(getNative(), data.array()))\n {\n throw new IllegalArgumentException(\"Data array incompatible with index buffer\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\"IntBuffer type not supported. Must be direct or have backing array\");\n }\n }", "public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }", "public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }", "protected boolean equivalentClaims(Claim claim1, Claim claim2) {\n\t\treturn claim1.getMainSnak().equals(claim2.getMainSnak())\n\t\t\t\t&& isSameSnakSet(claim1.getAllQualifiers(),\n\t\t\t\t\t\tclaim2.getAllQualifiers());\n\t}", "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 }" ]
Browse groups for the given category ID. If a null value is passed for the category then the root category is used. @param catId The optional category id. Null value will be ignored. @return The Collection of Photo objects @throws FlickrException @deprecated Flickr returns just empty results
[ "@Deprecated\r\n public Category browse(String catId) throws FlickrException {\r\n List<Subcategory> subcategories = new ArrayList<Subcategory>();\r\n List<Group> groups = new ArrayList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_BROWSE);\r\n\r\n if (catId != null) {\r\n parameters.put(\"cat_id\", catId);\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 categoryElement = response.getPayload();\r\n\r\n Category category = new Category();\r\n category.setName(categoryElement.getAttribute(\"name\"));\r\n category.setPath(categoryElement.getAttribute(\"path\"));\r\n category.setPathIds(categoryElement.getAttribute(\"pathids\"));\r\n\r\n NodeList subcatNodes = categoryElement.getElementsByTagName(\"subcat\");\r\n for (int i = 0; i < subcatNodes.getLength(); i++) {\r\n Element node = (Element) subcatNodes.item(i);\r\n Subcategory subcategory = new Subcategory();\r\n subcategory.setId(Integer.parseInt(node.getAttribute(\"id\")));\r\n subcategory.setName(node.getAttribute(\"name\"));\r\n subcategory.setCount(Integer.parseInt(node.getAttribute(\"count\")));\r\n\r\n subcategories.add(subcategory);\r\n }\r\n\r\n NodeList groupNodes = categoryElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element node = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(node.getAttribute(\"nsid\"));\r\n group.setName(node.getAttribute(\"name\"));\r\n group.setMembers(node.getAttribute(\"members\"));\r\n\r\n groups.add(group);\r\n }\r\n\r\n category.setGroups(groups);\r\n category.setSubcategories(subcategories);\r\n\r\n return category;\r\n }" ]
[ "private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }", "public void abort()\r\n {\r\n /*\r\n do nothing if already rolledback\r\n */\r\n if (txStatus == Status.STATUS_NO_TRANSACTION\r\n || txStatus == Status.STATUS_UNKNOWN\r\n || txStatus == Status.STATUS_ROLLEDBACK)\r\n {\r\n log.info(\"Nothing to abort, tx is not active - status is \" + TxUtil.getStatusString(txStatus));\r\n return;\r\n }\r\n // check status of tx\r\n if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED &&\r\n txStatus != Status.STATUS_MARKED_ROLLBACK)\r\n {\r\n throw new IllegalStateException(\"Illegal state for abort call, state was '\" + TxUtil.getStatusString(txStatus) + \"'\");\r\n }\r\n if(log.isEnabledFor(Logger.INFO))\r\n {\r\n log.info(\"Abort transaction was called on tx \" + this);\r\n }\r\n try\r\n {\r\n try\r\n {\r\n doAbort();\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while abort transaction, will be skipped\", e);\r\n }\r\n\r\n // used in managed environments, ignored in non-managed\r\n this.implementation.getTxManager().abortExternalTx(this);\r\n\r\n try\r\n {\r\n if(hasBroker() && getBroker().isInTransaction())\r\n {\r\n getBroker().abortTransaction();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while do abort used broker instance, will be skipped\", e);\r\n }\r\n }\r\n finally\r\n {\r\n txStatus = Status.STATUS_ROLLEDBACK;\r\n // cleanup things, e.g. release all locks\r\n doClose();\r\n }\r\n }", "WaveformPreview getWaveformPreview(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n\n final NumberField idField = new NumberField(rekordboxId);\n\n // First try to get the NXS2-style color waveform if we are supposed to.\n if (preferColor.get()) {\n try {\n Message response = client.simpleRequest(Message.KnownType.ANLZ_TAG_REQ, Message.KnownType.ANLZ_TAG,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField,\n new NumberField(Message.ANLZ_FILE_TAG_COLOR_WAVEFORM_PREVIEW), new NumberField(Message.ALNZ_FILE_TYPE_EXT));\n return new WaveformPreview(new DataReference(slot, rekordboxId), response);\n } catch (Exception e) {\n logger.info(\"No color waveform preview available for slot \" + slot + \", id \" + rekordboxId + \"; requesting blue version.\", e);\n }\n\n }\n\n Message response = client.simpleRequest(Message.KnownType.WAVE_PREVIEW_REQ, Message.KnownType.WAVE_PREVIEW,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot), NumberField.WORD_1,\n idField, NumberField.WORD_0);\n return new WaveformPreview(new DataReference(slot, rekordboxId), response);\n }", "public static int compare(double a, double b, double delta) {\n if (equals(a, b, delta)) {\n return 0;\n }\n return Double.compare(a, b);\n }", "public Script getScript(int id) {\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE id = ?\"\n );\n statement.setInt(1, id);\n results = statement.executeQuery();\n if (results.next()) {\n return 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 null;\n }", "public File getTargetFile(final MiscContentItem item) {\n final State state = this.state;\n if (state == State.NEW || state == State.ROLLBACK_ONLY) {\n return getTargetFile(miscTargetRoot, item);\n } else {\n throw new IllegalStateException(); // internal wrong usage, no i18n\n }\n }", "public WebSocketContext reTag(String label) {\n WebSocketConnectionRegistry registry = manager.tagRegistry();\n registry.signOff(connection);\n registry.signIn(label, connection);\n return this;\n }", "private void pushRight( int row ) {\n if( isOffZero(row))\n return;\n\n// B = createB();\n// B.print();\n rotatorPushRight(row);\n int end = N-2-row;\n for( int i = 0; i < end && bulge != 0; i++ ) {\n rotatorPushRight2(row,i+2);\n }\n// }\n }", "String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }" ]
Create and get actor system. @return the actor system
[ "public static ActorSystem createAndGetActorSystem() {\n if (actorSystem == null || actorSystem.isTerminated()) {\n actorSystem = ActorSystem.create(PcConstants.ACTOR_SYSTEM, conf);\n }\n return actorSystem;\n }" ]
[ "public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) {\n try {\n final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent);\n final JMXConnector connector = JMXConnectorFactory.connect(serviceURL);\n final MBeanServerConnection mbsc = connector.getMBeanServerConnection();\n return mbsc;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public static String getImageIdFromAgent(Launcher launcher, final String imageTag, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getImageIdFromTag(imageTag, host);\n }\n });\n }", "public CentralDogmaBuilder port(InetSocketAddress localAddress, SessionProtocol protocol) {\n return port(new ServerPort(localAddress, protocol));\n }", "public static base_response update(nitro_service client, systemcollectionparam resource) throws Exception {\n\t\tsystemcollectionparam updateresource = new systemcollectionparam();\n\t\tupdateresource.communityname = resource.communityname;\n\t\tupdateresource.loglevel = resource.loglevel;\n\t\tupdateresource.datapath = resource.datapath;\n\t\treturn updateresource.update_resource(client);\n\t}", "public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction updateresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleaction();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].profilename = resources[i].profilename;\n\t\t\t\tupdateresources[i].parameters = resources[i].parameters;\n\t\t\t\tupdateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\tupdateresources[i].quiettime = resources[i].quiettime;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static Cluster createUpdatedCluster(Cluster currentCluster,\n int stealerNodeId,\n List<Integer> donatedPartitions) {\n Cluster updatedCluster = Cluster.cloneCluster(currentCluster);\n // Go over every donated partition one by one\n for(int donatedPartition: donatedPartitions) {\n\n // Gets the donor Node that owns this donated partition\n Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition);\n Node stealerNode = updatedCluster.getNodeById(stealerNodeId);\n\n if(donorNode == stealerNode) {\n // Moving to the same location = No-op\n continue;\n }\n\n // Update the list of partitions for this node\n donorNode = removePartitionFromNode(donorNode, donatedPartition);\n stealerNode = addPartitionToNode(stealerNode, donatedPartition);\n\n // Sort the nodes\n updatedCluster = updateCluster(updatedCluster,\n Lists.newArrayList(donorNode, stealerNode));\n\n }\n\n return updatedCluster;\n }", "public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\n }", "public boolean detectTierRichCss() {\r\n\r\n boolean result = false;\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n if (detectMobileQuick()) {\r\n\r\n //Exclude iPhone Tier and e-Ink Kindle devices.\r\n if (!detectTierIphone() && !detectKindle()) {\r\n\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n //Older Windows 'Mobile' isn't good enough for iPhone Tier.\r\n if (detectWebkit()\r\n || detectS60OssBrowser()\r\n || detectBlackBerryHigh()\r\n || detectWindowsMobile()\r\n || (userAgent.indexOf(engineTelecaQ) != -1)) {\r\n result = true;\r\n } // if detectWebkit()\r\n } //if !detectTierIphone()\r\n } //if detectMobileQuick()\r\n return result;\r\n }" ]
Get distance between geographical coordinates @param point1 Point1 @param point2 Point2 @return Distance (double)
[ "public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n // sqrt( (x2-x1)^2 + (y2-y2)^2 )\r\n Double xDiff = point1._1() - point2._1();\r\n Double yDiff = point1._2() - point2._2();\r\n return Math.sqrt(xDiff * xDiff + yDiff * yDiff);\r\n }" ]
[ "private JSONArray datesToJson(Collection<Date> individualDates) {\n\n if (null != individualDates) {\n JSONArray result = new JSONArray();\n for (Date d : individualDates) {\n result.put(dateToJson(d));\n }\n return result;\n }\n return null;\n }", "public void configure(Properties props) throws HibernateException {\r\n\t\ttry{\r\n\t\t\tthis.config = new BoneCPConfig(props);\r\n\r\n\t\t\t// old hibernate config\r\n\t\t\tString url = props.getProperty(CONFIG_CONNECTION_URL);\r\n\t\t\tString username = props.getProperty(CONFIG_CONNECTION_USERNAME);\r\n\t\t\tString password = props.getProperty(CONFIG_CONNECTION_PASSWORD);\r\n\t\t\tString driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS);\r\n\t\t\tif (url == null){\r\n\t\t\t\turl = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (username == null){\r\n\t\t\t\tusername = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (password == null){\r\n\t\t\t\tpassword = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE);\r\n\t\t\t}\r\n\t\t\tif (driver == null){\r\n\t\t\t\tdriver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE);\r\n\t\t\t}\r\n\r\n\t\t\tif (url != null){\r\n\t\t\t\tthis.config.setJdbcUrl(url);\r\n\t\t\t}\r\n\t\t\tif (username != null){\r\n\t\t\t\tthis.config.setUsername(username);\r\n\t\t\t}\r\n\t\t\tif (password != null){\r\n\t\t\t\tthis.config.setPassword(password);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t// Remember Isolation level\r\n\t\t\tthis.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props);\r\n\t\t\tthis.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props);\r\n\r\n\t\t\tlogger.debug(this.config.toString());\r\n\r\n\t\t\tif (driver != null && !driver.trim().equals(\"\")){\r\n\t\t\t\tloadClass(driver);\r\n\t\t\t}\r\n\t\t\tif (this.config.getConnectionHookClassName() != null){\r\n\t\t\t\tObject hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance();\r\n\t\t\t\tthis.config.setConnectionHook((ConnectionHook) hookClass);\r\n\t\t\t}\r\n\t\t\t// create the connection pool\r\n\t\t\tthis.pool = createPool(this.config);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new HibernateException(e);\r\n\t\t}\r\n\t}", "public void logAttributeWarning(PathAddress address, String attribute) {\n logAttributeWarning(address, null, null, attribute);\n }", "public void actionPerformed(java.awt.event.ActionEvent e)\r\n {\r\n System.out.println(\"Action Command: \" + e.getActionCommand());\r\n System.out.println(\"Action Params : \" + e.paramString());\r\n System.out.println(\"Action Source : \" + e.getSource());\r\n System.out.println(\"Action SrcCls : \" + e.getSource().getClass().getName());\r\n org.apache.ojb.broker.metadata.ClassDescriptor cld =\r\n new org.apache.ojb.broker.metadata.ClassDescriptor(rootNode.getRepository());\r\n // cld.setClassNameOfObject(\"New Class\");\r\n cld.setTableName(\"New Table\");\r\n rootNode.addClassDescriptor(cld);\r\n }", "public void awaitStartupCompletion() {\n try {\n Object obj = startedStatusQueue.take();\n if(obj instanceof Throwable)\n throw new VoldemortException((Throwable) obj);\n } catch(InterruptedException e) {\n // this is okay, if we are interrupted we can stop waiting\n }\n }", "public static base_response delete(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = resource.ipv6address;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void load(String soundFile)\n {\n if (mSoundFile != null)\n {\n unload();\n }\n mSoundFile = soundFile;\n if (mAudioListener != null)\n {\n mAudioListener.getAudioEngine().preloadSoundFile(soundFile);\n Log.d(\"SOUND\", \"loaded audio file %s\", getSoundFile());\n }\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}", "public static nsconfig get(nitro_service service) throws Exception{\n\t\tnsconfig obj = new nsconfig();\n\t\tnsconfig[] response = (nsconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Retrieve a single field value. @param id parent entity ID @param type field type @param fixedData fixed data block @param varData var data block @return field value
[ "protected Object getFieldData(Integer id, FieldType type, byte[][] fixedData, Var2Data varData)\n {\n Object result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.read(id, fixedData, varData);\n }\n\n return result;\n }" ]
[ "private void updatePreview(TrackMetadataUpdate update, WaveformPreview preview) {\n previewHotCache.put(DeckReference.getDeckReference(update.player, 0), preview); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n previewHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), preview);\n }\n }\n }\n deliverWaveformPreviewUpdate(update.player, preview);\n }", "public ItemRequest<Project> removeMembers(String project) {\n \n String path = String.format(\"/projects/%s/removeMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "private String toRfsName(String name, IconSize size) {\n\n return CmsStringUtil.joinPaths(m_cache.getRepositoryPath(), \"\" + name.hashCode()) + size.getSuffix();\n }", "private boolean isSplit(ProjectCalendar calendar, List<TimephasedWork> list)\n {\n boolean result = false;\n for (TimephasedWork assignment : list)\n {\n if (calendar != null && assignment.getTotalAmount().getDuration() == 0)\n {\n Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);\n if (calendarWork.getDuration() != 0)\n {\n result = true;\n break;\n }\n }\n }\n return result;\n }", "public PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }", "public void identifyClasses(final String pluginDirectory) throws Exception {\n methodInformation.clear();\n jarInformation.clear();\n try {\n new FileTraversal() {\n public void onDirectory(final File d) {\n }\n\n public void onFile(final File f) {\n try {\n // loads class files\n if (f.getName().endsWith(\".class\")) {\n // get the class name for this path\n String className = f.getAbsolutePath();\n className = className.replace(pluginDirectory, \"\");\n className = getClassNameFromPath(className);\n\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getName());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = pluginDirectory;\n classInformation.put(className, classInfo);\n } else if (f.getName().endsWith(\".jar\")) {\n // loads JAR packages\n // open up jar and discover files\n // look for anything with /proxy/ in it\n // this may discover things we don't need but that is OK\n try {\n jarInformation.add(f.getAbsolutePath());\n JarFile jarFile = new JarFile(f);\n Enumeration<?> enumer = jarFile.entries();\n\n // Use the Plugin-Name manifest entry to match with the provided pluginName\n String pluginPackageName = jarFile.getManifest().getMainAttributes().getValue(\"plugin-package\");\n if (pluginPackageName == null) {\n return;\n }\n\n while (enumer.hasMoreElements()) {\n Object element = enumer.nextElement();\n String elementName = element.toString();\n\n if (!elementName.endsWith(\".class\")) {\n continue;\n }\n\n String className = getClassNameFromPath(elementName);\n if (className.contains(pluginPackageName)) {\n logger.info(\"Storing plugin information: {}, {}\", className,\n f.getAbsolutePath());\n\n ClassInformation classInfo = new ClassInformation();\n classInfo.pluginPath = f.getAbsolutePath();\n classInformation.put(className, classInfo);\n }\n }\n } catch (Exception e) {\n\n }\n }\n } catch (Exception e) {\n logger.warn(\"Exception caught: {}, {}\", e.getMessage(), e.getCause());\n }\n }\n }.traverse(new File(pluginDirectory));\n } catch (IOException e) {\n throw new Exception(\"Could not identify all plugins: \" + e.getMessage());\n }\n }", "public static <T> T assertNotNull(T value, String message) {\n if (value == null)\n throw new IllegalStateException(message);\n return value;\n }", "private void processChildTasks(Task task, MapRow row) throws IOException\n {\n List<MapRow> tasks = row.getRows(\"TASKS\");\n if (tasks != null)\n {\n for (MapRow childTask : tasks)\n {\n processTask(task, childTask);\n }\n }\n }", "public ModelSource resolveModel( Parent parent )\r\n throws UnresolvableModelException {\r\n\r\n Dependency parentDependency = new Dependency();\r\n parentDependency.setGroupId(parent.getGroupId());\r\n parentDependency.setArtifactId(parent.getArtifactId());\r\n parentDependency.setVersion(parent.getVersion());\r\n parentDependency.setClassifier(\"\");\r\n parentDependency.setType(\"pom\");\r\n\r\n Artifact parentArtifact = null;\r\n try\r\n {\r\n Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies(\r\n projectBuildingRequest, singleton(parentDependency), null, null );\r\n Iterator<ArtifactResult> iterator = artifactResults.iterator();\r\n if (iterator.hasNext()) {\r\n parentArtifact = iterator.next().getArtifact();\r\n }\r\n } catch (DependencyResolverException e) {\r\n throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(),\r\n parent.getVersion(), e );\r\n }\r\n\r\n return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() );\r\n }" ]
Generate the init script from the Artifactory URL. @return The generated script.
[ "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 }" ]
[ "private void writeAssignmentTimephasedData(BigInteger assignmentID, List<TimephasedDataType> list, List<TimephasedWork> data, int type)\n {\n for (TimephasedWork mpx : data)\n {\n TimephasedDataType xml = m_factory.createTimephasedDataType();\n list.add(xml);\n\n xml.setStart(mpx.getStart());\n xml.setFinish(mpx.getFinish());\n xml.setType(BigInteger.valueOf(type));\n xml.setUID(assignmentID);\n xml.setUnit(DatatypeConverter.printDurationTimeUnits(mpx.getTotalAmount(), false));\n xml.setValue(DatatypeConverter.printDuration(this, mpx.getTotalAmount()));\n }\n }", "public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}", "static Locale getLocale(PageContext pageContext, String name) {\r\n\r\n Locale loc = null;\r\n\r\n Object obj = javax.servlet.jsp.jstl.core.Config.find(pageContext, name);\r\n if (obj != null) {\r\n if (obj instanceof Locale) {\r\n loc = (Locale)obj;\r\n } else {\r\n loc = SetLocaleSupport.parseLocale((String)obj);\r\n }\r\n }\r\n\r\n return loc;\r\n }", "public static int minutesDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / MINUTE_MILLIS) - (earlierDate.getTime() / MINUTE_MILLIS));\n }", "public <T> T find(Class<T> classType, String id) {\n return db.find(classType, id);\n }", "public static boolean requiresReload(final Set<Flag> flags) {\n return flags.contains(Flag.RESTART_ALL_SERVICES) || flags.contains(Flag.RESTART_RESOURCE_SERVICES);\n }", "private Cluster expandCluster(final Cluster cluster,\n final Point2D point,\n final List<Point2D> neighbors,\n final KDTree<Point2D> points,\n final Map<Point2D, PointStatus> visited) {\n cluster.addPoint(point);\n visited.put(point, PointStatus.PART_OF_CLUSTER);\n\n List<Point2D> seeds = new ArrayList<Point2D>(neighbors);\n int index = 0;\n while (index < seeds.size()) {\n Point2D current = seeds.get(index);\n PointStatus pStatus = visited.get(current);\n // only check non-visited points\n if (pStatus == null) {\n final List<Point2D> currentNeighbors = getNeighbors(current, points);\n if (currentNeighbors.size() >= minPoints) {\n seeds = merge(seeds, currentNeighbors);\n }\n }\n\n if (pStatus != PointStatus.PART_OF_CLUSTER) {\n visited.put(current, PointStatus.PART_OF_CLUSTER);\n cluster.addPoint(current);\n }\n\n index++;\n }\n return cluster;\n }", "public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }", "public boolean contains(Vector3 p) {\n\t\tboolean ans = false;\n\t\tif(this.halfplane || p== null) return false;\n\n\t\tif (isCorner(p)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tPointLinePosition a12 = PointLineTest.pointLineTest(a,b,p);\n\t\tPointLinePosition a23 = PointLineTest.pointLineTest(b,c,p);\n\t\tPointLinePosition a31 = PointLineTest.pointLineTest(c,a,p);\n\n\t\tif ((a12 == PointLinePosition.LEFT && a23 == PointLinePosition.LEFT && a31 == PointLinePosition.LEFT ) ||\n\t\t\t\t(a12 == PointLinePosition.RIGHT && a23 == PointLinePosition.RIGHT && a31 == PointLinePosition.RIGHT ) ||\n\t\t\t\t(a12 == PointLinePosition.ON_SEGMENT ||a23 == PointLinePosition.ON_SEGMENT || a31 == PointLinePosition.ON_SEGMENT)) {\n\t\t\tans = true;\n\t\t}\n\n\t\treturn ans;\n\t}" ]
Creates the default editor state for editing a bundle with descriptor. @return the default editor state for editing a bundle with descriptor.
[ "private EditorState getDefaultState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.TRANSLATION);\n\n return new EditorState(cols, false);\n }" ]
[ "private void afterBatch(BatchBackend backend) {\n\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\tif ( this.optimizeAtEnd ) {\n\t\t\tbackend.optimize( targetedTypes );\n\t\t}\n\t\tbackend.flush( targetedTypes );\n\t}", "public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public static ComplexNumber Tan(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.tan(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n double real2 = 2 * z1.real;\r\n double imag2 = 2 * z1.imaginary;\r\n double denom = Math.cos(real2) + Math.cosh(real2);\r\n\r\n result.real = Math.sin(real2) / denom;\r\n result.imaginary = Math.sinh(imag2) / denom;\r\n }\r\n\r\n return result;\r\n }", "public byte[] getPacketBytes() {\n byte[] result = new byte[packetBytes.length];\n System.arraycopy(packetBytes, 0, result, 0, packetBytes.length);\n return result;\n }", "public static void shutdownStandalone(final ModelControllerClient client, final int timeout) throws IOException {\n final ModelNode op = Operations.createOperation(\"shutdown\");\n op.get(\"timeout\").set(timeout);\n final ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n while (true) {\n if (isStandaloneRunning(client)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(op, response);\n }\n }", "public static Artifact withArtifactId(String artifactId)\n {\n Artifact artifact = new Artifact();\n artifact.artifactId = new RegexParameterizedPatternParser(artifactId);\n return artifact;\n }", "public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {\n // We can't detect if their codecRegistry has any duplicate providers. There's also a chance\n // that putting ours first may prevent decoding of some of their classes if for example they\n // have their own way of decoding an Integer.\n final CodecRegistry newReg =\n CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);\n return new StitchObjectMapper(this, newReg);\n }", "public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }", "@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}" ]
Read a duration. @param units duration units @param duration duration value @return Duration instance
[ "private Duration getDuration(TimeUnit units, Double duration)\n {\n Duration result = null;\n if (duration != null)\n {\n double durationValue = duration.doubleValue() * 100.0;\n\n switch (units)\n {\n case MINUTES:\n {\n durationValue *= MINUTES_PER_DAY;\n break;\n }\n\n case HOURS:\n {\n durationValue *= HOURS_PER_DAY;\n break;\n }\n\n case DAYS:\n {\n durationValue *= 3.0;\n break;\n }\n\n case WEEKS:\n {\n durationValue *= 0.6;\n break;\n }\n\n case MONTHS:\n {\n durationValue *= 0.15;\n break;\n }\n\n default:\n {\n throw new IllegalArgumentException(\"Unsupported time units \" + units);\n }\n }\n\n durationValue = Math.round(durationValue) / 100.0;\n\n result = Duration.getInstance(durationValue, units);\n }\n\n return result;\n }" ]
[ "public Jar addClass(Class<?> clazz) throws IOException {\n final String resource = clazz.getName().replace('.', '/') + \".class\";\n return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource));\n }", "public void value2x2_fast( double a11 , double a12, double a21 , double a22 )\n {\n double left = (a11+a22)/2.0;\n double inside = 4.0*a12*a21 + (a11-a22)*(a11-a22);\n\n if( inside < 0 ) {\n value0.real = value1.real = left;\n value0.imaginary = Math.sqrt(-inside)/2.0;\n value1.imaginary = -value0.imaginary;\n } else {\n double right = Math.sqrt(inside)/2.0;\n value0.real = (left+right);\n value1.real = (left-right);\n value0.imaginary = value1.imaginary = 0.0;\n }\n }", "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 IndexedContainer createContainerForBundleWithDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.DESCRIPTION, String.class, \"\");\n container.addContainerProperty(TableProperty.DEFAULT, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(Descriptor.N_MESSAGE, Descriptor.LOCALE);\n String descValue;\n boolean hasDescription = false;\n String defaultValue;\n boolean hasDefault = false;\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n String translation = localization.getProperty(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n descValue = m_descContent.getValue(prefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DESCRIPTION).setValue(descValue);\n hasDescription = hasDescription || !descValue.isEmpty();\n defaultValue = m_descContent.getValue(prefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).getStringValue(\n m_cms);\n item.getItemProperty(TableProperty.DEFAULT).setValue(defaultValue);\n hasDefault = hasDefault || !defaultValue.isEmpty();\n }\n\n m_hasDefault = hasDefault;\n m_hasDescription = hasDescription;\n return container;\n\n }", "protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {\n final String parameterString = servletContext.getInitParameter(parameterName);\n if(parameterString != null && parameterString.trim().length() > 0) {\n try {\n return Integer.parseInt(parameterString);\n }\n catch (NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return defaultValue;\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 static String base64Encode(byte[] bytes) {\n if (bytes == null) {\n throw new IllegalArgumentException(\"Input bytes must not be null.\");\n }\n if (bytes.length >= BASE64_UPPER_BOUND) {\n throw new IllegalArgumentException(\n \"Input bytes length must not exceed \" + BASE64_UPPER_BOUND);\n }\n\n // Every three bytes is encoded into four characters.\n //\n // Example:\n // input |0 1 0 1 0 0 1 0|0 1 1 0 1 1 1 1|0 1 1 0 0 0 1 0|\n // encode grouping |0 1 0 1 0 0|1 0 0 1 1 0|1 1 1 1 0 1|1 0 0 0 1 0|\n // encoded ascii | U | m | 9 | i |\n\n int triples = bytes.length / 3;\n\n // If the number of input bytes is not a multiple of three, padding characters will be added.\n if (bytes.length % 3 != 0) {\n triples += 1;\n }\n\n // The encoded string will have four characters for every three bytes.\n char[] encoding = new char[triples << 2];\n\n for (int in = 0, out = 0; in < bytes.length; in += 3, out += 4) {\n int triple = (bytes[in] & 0xff) << 16;\n if (in + 1 < bytes.length) {\n triple |= ((bytes[in + 1] & 0xff) << 8);\n }\n if (in + 2 < bytes.length) {\n triple |= (bytes[in + 2] & 0xff);\n }\n encoding[out] = BASE64_CHARS.charAt((triple >> 18) & 0x3f);\n encoding[out + 1] = BASE64_CHARS.charAt((triple >> 12) & 0x3f);\n encoding[out + 2] = BASE64_CHARS.charAt((triple >> 6) & 0x3f);\n encoding[out + 3] = BASE64_CHARS.charAt(triple & 0x3f);\n }\n\n // Add padding characters if needed.\n for (int i = encoding.length - (triples * 3 - bytes.length); i < encoding.length; i++) {\n encoding[i] = '=';\n }\n\n return String.valueOf(encoding);\n }", "protected BlockBox createBlock(BlockBox parent, Element n, boolean replaced)\n {\n BlockBox root;\n if (replaced)\n {\n BlockReplacedBox rbox = new BlockReplacedBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n rbox.setViewport(viewport);\n rbox.setContentObj(new ReplacedImage(rbox, rbox.getVisualContext(), baseurl, n.getAttribute(\"src\")));\n root = rbox;\n }\n else\n {\n root = new BlockBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());\n root.setViewport(viewport);\n }\n root.setBase(baseurl);\n root.setParent(parent);\n root.setContainingBlockBox(parent);\n root.setClipBlock(viewport);\n root.setOrder(next_order++);\n return root;\n }", "public void setDefaultCalendarName(String calendarName)\n {\n if (calendarName == null || calendarName.length() == 0)\n {\n calendarName = DEFAULT_CALENDAR_NAME;\n }\n\n set(ProjectField.DEFAULT_CALENDAR_NAME, calendarName);\n }" ]
Access the customInfo of a message using this accessor. The CustomInfo map will be automatically created and stored in the event if it is not yet present @param message @return
[ "public static CustomInfo getOrCreateCustomInfo(Message message) {\n CustomInfo customInfo = message.get(CustomInfo.class);\n if (customInfo == null) {\n customInfo = new CustomInfo();\n message.put(CustomInfo.class, customInfo);\n }\n return customInfo;\n }" ]
[ "protected String consumeQuoted(ImapRequestLineReader request)\n throws ProtocolException {\n // The 1st character must be '\"'\n consumeChar(request, '\"');\n\n StringBuilder quoted = new StringBuilder();\n char next = request.nextChar();\n while (next != '\"') {\n if (next == '\\\\') {\n request.consume();\n next = request.nextChar();\n if (!isQuotedSpecial(next)) {\n throw new ProtocolException(\"Invalid escaped character in quote: '\" +\n next + '\\'');\n }\n }\n quoted.append(next);\n request.consume();\n next = request.nextChar();\n }\n\n consumeChar(request, '\"');\n\n return quoted.toString();\n }", "private void writeTimeUnitsField(String fieldName, Object value) throws IOException\n {\n TimeUnit val = (TimeUnit) value;\n if (val != m_projectFile.getProjectProperties().getDefaultDurationUnits())\n {\n m_writer.writeNameValuePair(fieldName, val.toString());\n }\n }", "public <U> CoreRemoteMongoIterable<U> map(final Function<ResultT, U> mapper) {\n return new CoreRemoteMappingIterable<>(this, mapper);\n }", "public String name(Properties attributes) throws XDocletException\r\n {\r\n return getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n }", "static boolean killProcess(final String processName, int id) {\n int pid;\n try {\n pid = processUtils.resolveProcessId(processName, id);\n if(pid > 0) {\n try {\n Runtime.getRuntime().exec(processUtils.getKillCommand(pid));\n return true;\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to kill process '%s' with pid '%s'\", processName, pid);\n }\n }\n } catch (Throwable t) {\n ProcessLogger.ROOT_LOGGER.debugf(t, \"failed to resolve pid of process '%s'\", processName);\n }\n return false;\n }", "public static sslvserver_sslciphersuite_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslciphersuite_binding response[] = (sslvserver_sslciphersuite_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void addProgressInterceptor() {\n httpClient.networkInterceptors().add(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n final Request request = chain.request();\n final Response originalResponse = chain.proceed(request);\n if (request.tag() instanceof ApiCallback) {\n final ApiCallback callback = (ApiCallback) request.tag();\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), callback)).build();\n }\n return originalResponse;\n }\n });\n }", "private static Data loadLeapSeconds(URL url) throws ClassNotFoundException, IOException {\n List<String> lines;\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {\n lines = reader.lines().collect(Collectors.toList());\n }\n List<Long> dates = new ArrayList<>();\n List<Integer> offsets = new ArrayList<>();\n for (String line : lines) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\")) {\n continue;\n }\n Matcher matcher = LEAP_FILE_FORMAT.matcher(line);\n if (matcher.matches() == false) {\n throw new StreamCorruptedException(\"Invalid leap second file\");\n }\n dates.add(LocalDate.parse(matcher.group(1)).getLong(JulianFields.MODIFIED_JULIAN_DAY));\n offsets.add(Integer.valueOf(matcher.group(2)));\n }\n long[] datesData = new long[dates.size()];\n int[] offsetsData = new int[dates.size()];\n long[] taiData = new long[dates.size()];\n for (int i = 0; i < datesData.length; i++) {\n datesData[i] = dates.get(i);\n offsetsData[i] = offsets.get(i);\n taiData[i] = tai(datesData[i], offsetsData[i]);\n }\n return new Data(datesData, offsetsData, taiData);\n }", "private List<TransformEntry> readTransformEntries(File file) throws Exception {\n\n List<TransformEntry> result = new ArrayList<>();\n try (FileInputStream fis = new FileInputStream(file)) {\n byte[] data = CmsFileUtil.readFully(fis, false);\n Document doc = CmsXmlUtils.unmarshalHelper(data, null, false);\n for (Node node : doc.selectNodes(\"//transform\")) {\n Element elem = ((Element)node);\n String xslt = elem.attributeValue(\"xslt\");\n String conf = elem.attributeValue(\"config\");\n TransformEntry entry = new TransformEntry(conf, xslt);\n result.add(entry);\n }\n }\n return result;\n }" ]
Creates Accumulo connector given FluoConfiguration
[ "public static AccumuloClient getClient(FluoConfiguration config) {\n return Accumulo.newClient().to(config.getAccumuloInstance(), config.getAccumuloZookeepers())\n .as(config.getAccumuloUser(), config.getAccumuloPassword()).build();\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 void setAssociation(String collectionRole, Association association) {\n\t\tif ( associations == null ) {\n\t\t\tassociations = new HashMap<>();\n\t\t}\n\t\tassociations.put( collectionRole, association );\n\t}", "@Subscribe\n @SuppressForbidden(\"legitimate printStackTrace().\")\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n try {\n if (jsonWriter == null)\n return;\n\n slaves.put(e.getSlave().id, e.getSlave());\n e.serialize(jsonWriter, outputStreams);\n } catch (Exception ex) {\n ex.printStackTrace();\n junit4.log(\"Error serializing to JSON file: \"\n + Throwables.getStackTraceAsString(ex), Project.MSG_WARN);\n if (jsonWriter != null) {\n try {\n jsonWriter.close();\n } catch (Throwable ignored) {\n // Ignore.\n } finally {\n jsonWriter = null;\n }\n }\n }\n }", "public void fatal(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.FATAL, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public static String getPrefixFromValue(String value) {\n if (value == null) {\n return null;\n } else if (value.contains(DELIMITER)) {\n String[] list = value.split(DELIMITER);\n if (list != null && list.length > 0) {\n return list[0].replaceAll(\"\\u0000\", \"\");\n } else {\n return null;\n }\n } else {\n return value.replaceAll(\"\\u0000\", \"\");\n }\n }", "public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\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 }", "private void swapROStores(List<String> swappedStoreNames, boolean useSwappedStoreNames) {\n\n try {\n for(StoreDefinition storeDef: metadataStore.getStoreDefList()) {\n\n // Only pick up the RO stores\n if(storeDef.getType().compareTo(ReadOnlyStorageConfiguration.TYPE_NAME) == 0) {\n\n if(useSwappedStoreNames && !swappedStoreNames.contains(storeDef.getName())) {\n continue;\n }\n\n ReadOnlyStorageEngine engine = (ReadOnlyStorageEngine) storeRepository.getStorageEngine(storeDef.getName());\n\n if(engine == null) {\n throw new VoldemortException(\"Could not find storage engine for \"\n + storeDef.getName() + \" to swap \");\n }\n\n logger.info(\"Swapping RO store \" + storeDef.getName());\n\n // Time to swap this store - Could have used admin client,\n // but why incur the overhead?\n engine.swapFiles(engine.getCurrentDirPath());\n\n // Add to list of stores already swapped\n if(!useSwappedStoreNames)\n swappedStoreNames.add(storeDef.getName());\n }\n }\n } catch(Exception e) {\n logger.error(\"Error while swapping RO store\");\n throw new VoldemortException(e);\n }\n }", "public Collection<EmailAlias> getEmailAliases() {\n URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n Collection<EmailAlias> emailAliases = new ArrayList<EmailAlias>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject emailAliasJSON = value.asObject();\n emailAliases.add(new EmailAlias(emailAliasJSON));\n }\n\n return emailAliases;\n }" ]
Executes a HTTP request and parses the JSON response into a Response instance. @param connection The HTTP request to execute. @return Response object of the deserialized JSON response
[ "public Response executeToResponse(HttpConnection connection) {\n InputStream is = null;\n try {\n is = this.executeToInputStream(connection);\n Response response = getResponse(is, Response.class, getGson());\n response.setStatusCode(connection.getConnection().getResponseCode());\n response.setReason(connection.getConnection().getResponseMessage());\n return response;\n } catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response code or message.\", e);\n } finally {\n close(is);\n }\n }" ]
[ "private void processPredecessor(Task task, MapRow row)\n {\n Task predecessor = m_taskMap.get(row.getUUID(\"PREDECESSOR_UUID\"));\n if (predecessor != null)\n {\n task.addPredecessor(predecessor, row.getRelationType(\"RELATION_TYPE\"), row.getDuration(\"LAG\"));\n }\n }", "public void setAngularLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularLowerLimits(getNative(), limitX, limitY, limitZ);\n }", "public static rewritepolicylabel_rewritepolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\trewritepolicylabel_rewritepolicy_binding obj = new rewritepolicylabel_rewritepolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\trewritepolicylabel_rewritepolicy_binding response[] = (rewritepolicylabel_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Integer getDurationUnits(RecurringTask recurrence)\n {\n Duration duration = recurrence.getDuration();\n Integer result = null;\n\n if (duration != null)\n {\n result = UNITS_MAP.get(duration.getUnits());\n }\n\n return (result);\n }", "public static byte[] removeContentFromExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItemNode = getContentItem(deploymentResource);\n final byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();\n final List<String> paths = REMOVED_PATHS.unwrap(context, operation);\n final byte[] hash = contentRepository.removeContentFromExploded(oldHash, paths);\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);\n slave.get(CONTENT).add().get(ARCHIVE).set(false);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }", "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }", "private void toCorrectDateWithDay(Calendar date, WeekOfMonth week) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int daysToFirstWeekDayMatch = ((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS)\n - (date.get(Calendar.DAY_OF_WEEK))) % I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n date.add(Calendar.DAY_OF_MONTH, daysToFirstWeekDayMatch);\n int wouldBeDayOfMonth = date.get(Calendar.DAY_OF_MONTH)\n + ((week.ordinal()) * I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n if (wouldBeDayOfMonth > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth - I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n } else {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth);\n }\n\n }", "private void gobble(Iterator iter)\n {\n if (eatTheRest)\n {\n while (iter.hasNext())\n {\n tokens.add(iter.next());\n }\n }\n }", "@Override\n public void registerChildren(ManagementResourceRegistration resourceRegistration) {\n // Register wildcard children last to prevent duplicate registration errors when override definitions exist\n for (ResourceDefinition rd : singletonChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n for (ResourceDefinition rd : wildcardChildren) {\n resourceRegistration.registerSubModel(rd);\n }\n }" ]
Returns the Field for a given parent class and a dot-separated path of field names. @param clazz Parent class. @param path Path to the desired field.
[ "public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }" ]
[ "void rollback() {\n if (publishedFullRegistry == null) {\n return;\n }\n writeLock.lock();\n try {\n publishedFullRegistry.readLock.lock();\n try {\n clear(true);\n copy(publishedFullRegistry, this);\n modified = false;\n } finally {\n publishedFullRegistry.readLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }", "public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }", "public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }", "public List<LogSegment> trunc(int newStart) {\n if (newStart < 0) {\n throw new IllegalArgumentException(\"Starting index must be positive.\");\n }\n while (true) {\n List<LogSegment> curr = contents.get();\n int newLength = Math.max(curr.size() - newStart, 0);\n List<LogSegment> updatedList = new ArrayList<LogSegment>(curr.subList(Math.min(newStart, curr.size() - 1),\n curr.size()));\n if (contents.compareAndSet(curr, updatedList)) {\n return curr.subList(0, curr.size() - newLength);\n }\n }\n }", "private void populateConstraints(Row row, Task task)\n {\n Date endDateMax = row.getTimestamp(\"ZGIVENENDDATEMAX_\");\n Date endDateMin = row.getTimestamp(\"ZGIVENENDDATEMIN_\");\n Date startDateMax = row.getTimestamp(\"ZGIVENSTARTDATEMAX_\");\n Date startDateMin = row.getTimestamp(\"ZGIVENSTARTDATEMIN_\");\n\n ConstraintType constraintType = null;\n Date constraintDate = null;\n\n if (endDateMax != null)\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = endDateMax;\n }\n\n if (endDateMin != null)\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = endDateMin;\n }\n\n if (endDateMin != null && endDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = endDateMin;\n }\n\n if (startDateMax != null)\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = startDateMax;\n }\n\n if (startDateMin != null)\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = startDateMin;\n }\n\n if (startDateMin != null && startDateMin == endDateMax)\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = endDateMin;\n }\n\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }", "public static int brightnessNTSC(int rgb) {\n\t\tint r = (rgb >> 16) & 0xff;\n\t\tint g = (rgb >> 8) & 0xff;\n\t\tint b = rgb & 0xff;\n\t\treturn (int)(r*0.299f + g*0.587f + b*0.114f);\n\t}", "public static<A, B, C, D, Z> Function4<A, B, C, D, Z> lift(Func4<A, B, C, D, Z> f) {\n\treturn bridge.lift(f);\n }", "@Pure\n\tpublic static <T> Iterator<T> filterNull(Iterator<T> unfiltered) {\n\t\treturn Iterators.filter(unfiltered, Predicates.notNull());\n\t}", "private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }" ]
Generate heroku-like random names @return String
[ "public String haikunate() {\n if (tokenHex) {\n tokenChars = \"0123456789abcdef\";\n }\n\n String adjective = randomString(adjectives);\n String noun = randomString(nouns);\n\n StringBuilder token = new StringBuilder();\n if (tokenChars != null && tokenChars.length() > 0) {\n for (int i = 0; i < tokenLength; i++) {\n token.append(tokenChars.charAt(random.nextInt(tokenChars.length())));\n }\n }\n\n return Stream.of(adjective, noun, token.toString())\n .filter(s -> s != null && !s.isEmpty())\n .collect(joining(delimiter));\n }" ]
[ "public boolean exists() {\n\t\t// Try file existence: can we find the file in the file system?\n\t\ttry {\n\t\t\treturn getFile().exists();\n\t\t}\n\t\tcatch (IOException ex) {\n\t\t\t// Fall back to stream existence: can we open the stream?\n\t\t\ttry {\n\t\t\t\tInputStream is = getInputStream();\n\t\t\t\tis.close();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcatch (Throwable isEx) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}", "public final void setExceptions(SortedSet<Date> dates) {\n\n m_exceptions.clear();\n if (null != dates) {\n m_exceptions.addAll(dates);\n }\n\n }", "public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }", "private void checkGAs(List l)\r\n\t{\r\n\t\tfor (final Iterator i = l.iterator(); i.hasNext();)\r\n\t\t\tif (!(i.next() instanceof GroupAddress))\r\n\t\t\t\tthrow new KNXIllegalArgumentException(\"not a group address list\");\r\n\t}", "public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }", "public List<CmsFavoriteEntry> loadFavorites() throws CmsException {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n try {\n CmsUser user = readUser();\n String data = (String)user.getAdditionalInfo(ADDINFO_KEY);\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(data)) {\n return new ArrayList<>();\n }\n JSONObject json = new JSONObject(data);\n JSONArray array = json.getJSONArray(BASE_KEY);\n for (int i = 0; i < array.length(); i++) {\n JSONObject fav = array.getJSONObject(i);\n try {\n CmsFavoriteEntry entry = new CmsFavoriteEntry(fav);\n if (validate(entry)) {\n result.add(entry);\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n\n }\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n return result;\n }", "public static base_response add(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction addresource = new tmtrafficaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.apptimeout = resource.apptimeout;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.formssoaction = resource.formssoaction;\n\t\taddresource.persistentcookie = resource.persistentcookie;\n\t\taddresource.initiatelogout = resource.initiatelogout;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn addresource.add_resource(client);\n\t}", "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}", "public void load(List<E> result) {\n ++pageCount;\n if (this.result == null || this.result.isEmpty()) {\n this.result = result;\n } else {\n this.result.addAll(result);\n }\n }" ]
Returns package name of a class @param clazz the class @return the package name of the class
[ "public static String packageNameOf(Class<?> clazz) {\n String name = clazz.getName();\n int pos = name.lastIndexOf('.');\n E.unexpectedIf(pos < 0, \"Class does not have package: \" + name);\n return name.substring(0, pos);\n }" ]
[ "public void init(Map<String, String> testConfig, Map<String, String> hiveVars) {\n\n context.init();\n\n HiveConf hiveConf = context.getHiveConf();\n\n // merge test case properties with hive conf before HiveServer is started.\n for (Map.Entry<String, String> property : testConfig.entrySet()) {\n hiveConf.set(property.getKey(), property.getValue());\n }\n\n try {\n hiveServer2 = new HiveServer2();\n hiveServer2.init(hiveConf);\n\n // Locate the ClIService in the HiveServer2\n for (Service service : hiveServer2.getServices()) {\n if (service instanceof CLIService) {\n client = (CLIService) service;\n }\n }\n\n Preconditions.checkNotNull(client, \"ClIService was not initialized by HiveServer2\");\n\n sessionHandle = client.openSession(\"noUser\", \"noPassword\", null);\n\n SessionState sessionState = client.getSessionManager().getSession(sessionHandle).getSessionState();\n currentSessionState = sessionState;\n currentSessionState.setHiveVariables(hiveVars);\n } catch (Exception e) {\n throw new IllegalStateException(\"Failed to create HiveServer :\" + e.getMessage(), e);\n }\n\n // Ping hive server before we do anything more with it! If validation\n // is switched on, this will fail if metastorage is not set up properly\n pingHiveServer();\n }", "public static float calcDet(Vector3 a ,Vector3 b, Vector3 c) {\n\t\treturn (a.x*(b.y-c.y)) - (a.y*(b.x-c.x)) + (b.x*c.y-b.y*c.x);\n\t}", "private int getItemViewType(Class prototypeClass) {\n int itemViewType = -1;\n for (Renderer renderer : prototypes) {\n if (renderer.getClass().equals(prototypeClass)) {\n itemViewType = getPrototypeIndex(renderer);\n break;\n }\n }\n if (itemViewType == -1) {\n throw new PrototypeNotFoundException(\n \"Review your RendererBuilder implementation, you are returning one\"\n + \" prototype class not found in prototypes collection\");\n }\n return itemViewType;\n }", "public static boolean queryHasResult(Statement stmt, String sql) {\n try {\n ResultSet rs = stmt.executeQuery(sql);\n try {\n return rs.next();\n } finally {\n rs.close();\n }\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }", "protected void failedToCleanupDir(final File file) {\n checkForGarbageOnRestart = true;\n PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath());\n }", "private String formatRate(Rate value)\n {\n String result = null;\n if (value != null)\n {\n StringBuilder buffer = new StringBuilder(m_formats.getCurrencyFormat().format(value.getAmount()));\n buffer.append(\"/\");\n buffer.append(formatTimeUnit(value.getUnits()));\n result = buffer.toString();\n }\n return (result);\n }", "public Object convertStringToJavaField(String value, int columnPos) throws SQLException {\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.resultStringToJava(this, value, columnPos);\n\t\t}\n\t}", "public static java.sql.Timestamp getTimestamp(Object value) {\n try {\n return toTimestamp(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "static 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 }" ]
Get random stub matching this user type @param userType User type @return Random stub
[ "public static UserStub getStubWithRandomParams(UserTypeVal userType) {\r\n // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles!\r\n // Oh the joys of type erasure.\r\n Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation();\r\n return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()),\r\n SocialNetworkUtilities.getRandomIsSecret());\r\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public void updateStoreDefinitions(Versioned<byte[]> valueBytes) {\n // acquire write lock\n writeLock.lock();\n\n try {\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n Versioned<Object> valueObject = convertStringToObject(STORES_KEY, value);\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) valueObject.getValue();\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n StoreDefinitionUtils.validateNewStoreDefsAreNonBreaking(getStoreDefList(), storeDefinitions);\n\n // Go through each store definition and do a corresponding put\n for(StoreDefinition storeDef: storeDefinitions) {\n if(!this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Cannot update a store which does not exist !\");\n }\n\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n // TODO: Make this more fine grained.. i.e only update listeners for\n // a specific store.\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }", "AlbumArt getArtwork(int artworkId, SlotReference slot, CdjStatus.TrackType trackType, Client client)\n throws IOException {\n\n // Send the artwork request\n Message response = client.simpleRequest(Message.KnownType.ALBUM_ART_REQ, Message.KnownType.ALBUM_ART,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot, trackType), new NumberField((long)artworkId));\n\n // Create an image from the response bytes\n return new AlbumArt(new DataReference(slot, artworkId), ((BinaryField)response.arguments.get(3)).getValue());\n }", "public static Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }", "private void checkExistingTracks() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n checkIfSignatureReady(entry.getKey().player);\n }\n }\n }\n });\n }", "public static void printDocumentation() {\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t\tSystem.out.println(\"*** Wikidata Toolkit: GenderRatioProcessor\");\n\t\tSystem.out.println(\"*** \");\n\t\tSystem.out\n\t\t\t\t.println(\"*** This program will download and process dumps from Wikidata.\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** It will compute the numbers of articles about humans across\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** Wikimedia projects, and in particular it will count the articles\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** for each sex/gender. Results will be stored in a CSV file.\");\n\t\tSystem.out.println(\"*** See source code for further details.\");\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t}", "public static base_response update(nitro_service client, filterhtmlinjectionparameter resource) throws Exception {\n\t\tfilterhtmlinjectionparameter updateresource = new filterhtmlinjectionparameter();\n\t\tupdateresource.rate = resource.rate;\n\t\tupdateresource.frequency = resource.frequency;\n\t\tupdateresource.strict = resource.strict;\n\t\tupdateresource.htmlsearchlen = resource.htmlsearchlen;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static base_responses unset(nitro_service client, String selectorname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tnslimitselector unsetresources[] = new nslimitselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tunsetresources[i] = new nslimitselector();\n\t\t\t\tunsetresources[i].selectorname = selectorname[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 addHours(ProjectCalendarDateRanges ranges, Record hoursRecord)\n {\n if (hoursRecord.getValue() != null)\n {\n String[] wh = hoursRecord.getValue().split(\"\\\\|\");\n try\n {\n String startText;\n String endText;\n\n if (wh[0].equals(\"s\"))\n {\n startText = wh[1];\n endText = wh[3];\n }\n else\n {\n startText = wh[3];\n endText = wh[1];\n }\n\n // for end time treat midnight as midnight next day\n if (endText.equals(\"00:00\"))\n {\n endText = \"24:00\";\n }\n Date start = m_calendarTimeFormat.parse(startText);\n Date end = m_calendarTimeFormat.parse(endText);\n\n ranges.addRange(new DateRange(start, end));\n }\n catch (ParseException e)\n {\n // silently ignore date parse exceptions\n }\n }\n }", "public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {\n if (searchView != null) {\n searchView.setOnCloseListener(new SearchView.OnCloseListener() {\n @Override public boolean onClose() {\n return listener.onClose();\n }\n });\n } else if (supportView != null) {\n supportView.setOnCloseListener(listener);\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }" ]
Removing surrounding space in image. Get trim color from specified pixel. @param value orientation from where to get the pixel color. @param colorTolerance 0 - 442. This is the euclidian distance between the colors of the reference pixel and the surrounding pixels is used. If the distance is within the tolerance they'll get trimmed.
[ "public ThumborUrlBuilder trim(TrimPixelColor value, int colorTolerance) {\n if (colorTolerance < 0 || colorTolerance > 442) {\n throw new IllegalArgumentException(\"Color tolerance must be between 0 and 442.\");\n }\n if (colorTolerance > 0 && value == null) {\n throw new IllegalArgumentException(\"Trim pixel color value must not be null.\");\n }\n isTrim = true;\n trimPixelColor = value;\n trimColorTolerance = colorTolerance;\n return this;\n }" ]
[ "public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) {\n Pipeline pipelined = jedis.pipelined();\n pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n for (String jobJson : jobJsons) {\n pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }\n pipelined.sync();\n }", "Item newStringishItem(final int type, final String value) {\n key2.set(type, value, null, null);\n Item result = get(key2);\n if (result == null) {\n pool.put12(type, newUTF8(value));\n result = new Item(index++, key2);\n put(result);\n }\n return result;\n }", "public PathElement getLastElement() {\n final List<PathElement> list = pathAddressList;\n return list.size() == 0 ? null : list.get(list.size() - 1);\n }", "public static String read(final File file) throws IOException {\n final StringBuilder sb = new StringBuilder();\n\n try (\n final FileReader fr = new FileReader(file);\n final BufferedReader br = new BufferedReader(fr);\n ) {\n\n String sCurrentLine;\n\n while ((sCurrentLine = br.readLine()) != null) {\n sb.append(sCurrentLine);\n }\n }\n\n return sb.toString();\n }", "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 }", "@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }", "public static int cudnnSoftmaxBackward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnSoftmaxBackwardNative(handle, algo, mode, alpha, yDesc, y, dyDesc, dy, beta, dxDesc, dx));\n }", "protected void prepareRequest(List<BoxAPIRequest> requests) {\n JsonObject body = new JsonObject();\n JsonArray requestsJSONArray = new JsonArray();\n for (BoxAPIRequest request: requests) {\n JsonObject batchRequest = new JsonObject();\n batchRequest.add(\"method\", request.getMethod());\n batchRequest.add(\"relative_url\", request.getUrl().toString().substring(this.api.getBaseURL().length() - 1));\n //If the actual request has a JSON body then add it to vatch request\n if (request instanceof BoxJSONRequest) {\n BoxJSONRequest jsonRequest = (BoxJSONRequest) request;\n batchRequest.add(\"body\", jsonRequest.getBodyAsJsonValue());\n }\n //Add any headers that are in the request, except Authorization\n if (request.getHeaders() != null) {\n JsonObject batchRequestHeaders = new JsonObject();\n for (RequestHeader header: request.getHeaders()) {\n if (header.getKey() != null && !header.getKey().isEmpty()\n && !HttpHeaders.AUTHORIZATION.equals(header.getKey())) {\n batchRequestHeaders.add(header.getKey(), header.getValue());\n }\n }\n batchRequest.add(\"headers\", batchRequestHeaders);\n }\n\n //Add the request to array\n requestsJSONArray.add(batchRequest);\n }\n //Add the requests array to body\n body.add(\"requests\", requestsJSONArray);\n super.setBody(body);\n }", "private void readExceptions(Project.Calendars.Calendar calendar, ProjectCalendar bc)\n {\n Project.Calendars.Calendar.Exceptions exceptions = calendar.getExceptions();\n if (exceptions != null)\n {\n for (Project.Calendars.Calendar.Exceptions.Exception exception : exceptions.getException())\n {\n readException(bc, exception);\n }\n }\n }" ]
Removes the observation that fits the model the worst and recomputes the coefficients. This is done efficiently by using an adjustable solver. Often times the elements with the largest errors are outliers and not part of the system being modeled. By removing them a more accurate set of coefficients can be computed.
[ "public void removeWorstFit() {\n // find the observation with the most error\n int worstIndex=-1;\n double worstError = -1;\n\n for( int i = 0; i < y.numRows; i++ ) {\n double predictedObs = 0;\n\n for( int j = 0; j < coef.numRows; j++ ) {\n predictedObs += A.get(i,j)*coef.get(j,0);\n }\n\n double error = Math.abs(predictedObs- y.get(i,0));\n\n if( error > worstError ) {\n worstError = error;\n worstIndex = i;\n }\n }\n\n // nothing left to remove, so just return\n if( worstIndex == -1 )\n return;\n\n // remove that observation\n removeObservation(worstIndex);\n\n // update A\n solver.removeRowFromA(worstIndex);\n\n // solve for the parameters again\n solver.solve(y,coef);\n }" ]
[ "public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}", "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 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 }", "@NotThreadsafe\n private void initFileStreams(int chunkId) {\n /**\n * {@link Set#add(Object)} returns false if the element already existed in the set.\n * This ensures we initialize the resources for each chunk only once.\n */\n if (chunksHandled.add(chunkId)) {\n try {\n this.indexFileSizeInBytes[chunkId] = 0L;\n this.valueFileSizeInBytes[chunkId] = 0L;\n this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType);\n this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType);\n this.position[chunkId] = 0;\n this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + INDEX_FILE_EXTENSION\n + fileExtension);\n this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf),\n getStoreName() + \".\"\n + Integer.toString(chunkId) + \"_\"\n + this.taskId + DATA_FILE_EXTENSION\n + fileExtension);\n if(this.fs == null)\n this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf);\n if(isValidCompressionEnabled) {\n this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]),\n DEFAULT_BUFFER_SIZE)));\n\n } else {\n this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]);\n this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]);\n\n }\n fs.setPermission(this.taskIndexFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskIndexFileName[chunkId]);\n fs.setPermission(this.taskValueFileName[chunkId],\n new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION));\n logger.info(\"Setting permission to 755 for \" + this.taskValueFileName[chunkId]);\n\n logger.info(\"Opening \" + this.taskIndexFileName[chunkId] + \" and \"\n + this.taskValueFileName[chunkId] + \" for writing.\");\n } catch(IOException e) {\n throw new RuntimeException(\"Failed to open Input/OutputStream\", e);\n }\n }\n }", "public AT_Row setPaddingRight(int paddingRight) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public int addServerRedirect(String region, String srcUrl, String destUrl, String hostHeader, int profileId, int groupId) throws Exception {\n int serverId = -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_SERVERS\n + \"(\" + Constants.SERVER_REDIRECT_REGION + \",\" +\n Constants.SERVER_REDIRECT_SRC_URL + \",\" +\n Constants.SERVER_REDIRECT_DEST_URL + \",\" +\n Constants.SERVER_REDIRECT_HOST_HEADER + \",\" +\n Constants.SERVER_REDIRECT_PROFILE_ID + \",\" +\n Constants.SERVER_REDIRECT_GROUP_ID + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?);\", PreparedStatement.RETURN_GENERATED_KEYS);\n statement.setString(1, region);\n statement.setString(2, srcUrl);\n statement.setString(3, destUrl);\n statement.setString(4, hostHeader);\n statement.setInt(5, profileId);\n statement.setInt(6, groupId);\n statement.executeUpdate();\n\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n serverId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\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 serverId;\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 }", "private static Query buildQuery(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n Criteria crit = new Criteria();\r\n\r\n for(int i = 0; i < pkFields.length; i++)\r\n {\r\n crit.addEqualTo(pkFields[i].getAttributeName(), null);\r\n }\r\n return new QueryByCriteria(cld.getClassOfObject(), crit);\r\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 }" ]
Delete a module @param moduleId String
[ "public void deleteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n repositoryHandler.deleteModule(module.getId());\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n repositoryHandler.deleteArtifact(gavc);\n }\n }" ]
[ "public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }", "protected CmsProject createAndSetModuleImportProject(CmsObject cms, CmsModule module) throws CmsException {\n\n CmsProject importProject = cms.createProject(\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_NAME_1,\n new Object[] {module.getName()}),\n org.opencms.module.Messages.get().getBundle(cms.getRequestContext().getLocale()).key(\n org.opencms.module.Messages.GUI_IMPORT_MODULE_PROJECT_DESC_1,\n new Object[] {module.getName()}),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n cms.getRequestContext().setCurrentProject(importProject);\n cms.copyResourceToProject(\"/\");\n return importProject;\n }", "public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }", "void successfulBoot() throws ConfigurationPersistenceException {\n synchronized (this) {\n if (doneBootup.get()) {\n return;\n }\n final File copySource;\n if (!interactionPolicy.isReadOnly()) {\n copySource = mainFile;\n } else {\n\n if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) {\n copySource = new File(mainFile.getParentFile(), mainFile.getName() + \".boot\");\n } else{\n copySource = new File(configurationDir, mainFile.getName() + \".boot\");\n }\n\n FilePersistenceUtils.deleteFile(copySource);\n }\n\n try {\n if (!bootFile.equals(copySource)) {\n FilePersistenceUtils.copyFile(bootFile, copySource);\n }\n\n createHistoryDirectory();\n\n final File historyBase = new File(historyRoot, mainFile.getName());\n lastFile = addSuffixToFile(historyBase, LAST);\n final File boot = addSuffixToFile(historyBase, BOOT);\n final File initial = addSuffixToFile(historyBase, INITIAL);\n\n if (!initial.exists()) {\n FilePersistenceUtils.copyFile(copySource, initial);\n }\n\n FilePersistenceUtils.copyFile(copySource, lastFile);\n FilePersistenceUtils.copyFile(copySource, boot);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile);\n } finally {\n if (interactionPolicy.isReadOnly()) {\n //Delete the temporary file\n try {\n FilePersistenceUtils.deleteFile(copySource);\n } catch (Exception ignore) {\n }\n }\n }\n doneBootup.set(true);\n }\n }", "public Object newInstance(String className) {\n try {\n return classLoader.loadClass(className).newInstance();\n } catch (Exception e) {\n throw new ScalaInstanceNotFound(className);\n }\n }", "@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }", "String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }", "public void retrieveProxyCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, true);\r\n }", "public static void symmetric(DMatrixRMaj 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 for( int j = i; j < length; j++ ) {\n double val = rand.nextDouble()*range + min;\n A.set(i,j,val);\n A.set(j,i,val);\n }\n }\n }" ]
Construct a new instance. @return the new instance
[ "public static DeploymentReflectionIndex create() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(ServerPermission.CREATE_DEPLOYMENT_REFLECTION_INDEX);\n }\n return new DeploymentReflectionIndex();\n }" ]
[ "public static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\n }", "@Override\n public ConditionBuilder as(String variable)\n {\n Assert.notNull(variable, \"Variable name must not be null.\");\n this.setOutputVariablesName(variable);\n return this;\n }", "public Backup getBackupData() throws Exception {\n Backup backupData = new Backup();\n\n backupData.setGroups(getGroups());\n backupData.setProfiles(getProfiles());\n ArrayList<Script> scripts = new ArrayList<Script>();\n Collections.addAll(scripts, ScriptService.getInstance().getScripts());\n backupData.setScripts(scripts);\n\n return backupData;\n }", "public void setBackgroundColor(int color) {\n setBackgroundColorR(Colors.byteToGl(Color.red(color)));\n setBackgroundColorG(Colors.byteToGl(Color.green(color)));\n setBackgroundColorB(Colors.byteToGl(Color.blue(color)));\n setBackgroundColorA(Colors.byteToGl(Color.alpha(color)));\n }", "public static PackageType resolve(final MavenProject project) {\n final String packaging = project.getPackaging().toLowerCase(Locale.ROOT);\n if (DEFAULT_TYPES.containsKey(packaging)) {\n return DEFAULT_TYPES.get(packaging);\n }\n return new PackageType(packaging);\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 List<Key> getScatterKeys(\n int numSplits, Query query, PartitionId partition, Datastore datastore)\n throws DatastoreException {\n Query.Builder scatterPointQuery = createScatterQuery(query, numSplits);\n\n List<Key> keySplits = new ArrayList<Key>();\n\n QueryResultBatch batch;\n do {\n RunQueryRequest scatterRequest =\n RunQueryRequest.newBuilder()\n .setPartitionId(partition)\n .setQuery(scatterPointQuery)\n .build();\n batch = datastore.runQuery(scatterRequest).getBatch();\n for (EntityResult result : batch.getEntityResultsList()) {\n keySplits.add(result.getEntity().getKey());\n }\n scatterPointQuery.setStartCursor(batch.getEndCursor());\n scatterPointQuery.getLimitBuilder().setValue(\n scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount());\n } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED);\n Collections.sort(keySplits, DatastoreHelper.getKeyComparator());\n return keySplits;\n }", "@Override\n public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public static gslbrunningconfig get(nitro_service service) throws Exception{\n\t\tgslbrunningconfig obj = new gslbrunningconfig();\n\t\tgslbrunningconfig[] response = (gslbrunningconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Clone layer information considering what may be copied to the client. @param original layer info @return cloned copy including only allowed information
[ "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}" ]
[ "@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }", "public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }", "public static String getExtensionByMimeType(String type) {\n MimeTypes types = getDefaultMimeTypes();\n try {\n return types.forName(type).getExtension();\n } catch (Exception e) {\n LOGGER.warn(\"Can't detect extension for MIME-type \" + type, e);\n return \"\";\n }\n }", "protected void postLayoutChild(final int dataIndex) {\n if (!mContainer.isDynamic()) {\n boolean visibleInLayout = !mViewPort.isClippingEnabled() || inViewPort(dataIndex);\n ViewPortVisibility visibility = visibleInLayout ?\n ViewPortVisibility.FULLY_VISIBLE : ViewPortVisibility.INVISIBLE;\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onLayout: child with dataId [%d] viewportVisibility = %s\",\n dataIndex, visibility);\n\n Widget childWidget = mContainer.get(dataIndex);\n if (childWidget != null) {\n childWidget.setViewPortVisibility(visibility);\n }\n }\n }", "public void setInitialSequence(int[] sequence) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].setInitialSequence(sequence);\r\n return;\r\n }\r\n model1.setInitialSequence(sequence);\r\n model2.setInitialSequence(sequence);\r\n }", "@Nonnull\n public final Style getDefaultStyle(@Nonnull final String geometryType) {\n String normalizedGeomName = GEOMETRY_NAME_ALIASES.get(geometryType.toLowerCase());\n if (normalizedGeomName == null) {\n normalizedGeomName = geometryType.toLowerCase();\n }\n Style style = this.defaultStyle.get(normalizedGeomName.toLowerCase());\n if (style == null) {\n style = this.namedStyles.get(normalizedGeomName.toLowerCase());\n }\n\n if (style == null) {\n StyleBuilder builder = new StyleBuilder();\n final Symbolizer symbolizer;\n if (isPointType(normalizedGeomName)) {\n symbolizer = builder.createPointSymbolizer();\n } else if (isLineType(normalizedGeomName)) {\n symbolizer = builder.createLineSymbolizer(Color.black, 2);\n } else if (isPolygonType(normalizedGeomName)) {\n symbolizer = builder.createPolygonSymbolizer(Color.lightGray, Color.black, 2);\n } else if (normalizedGeomName.equalsIgnoreCase(Constants.Style.Raster.NAME)) {\n symbolizer = builder.createRasterSymbolizer();\n } else if (normalizedGeomName.startsWith(Constants.Style.OverviewMap.NAME)) {\n symbolizer = createMapOverviewStyle(normalizedGeomName, builder);\n } else {\n final Style geomStyle = this.defaultStyle.get(Geometry.class.getSimpleName().toLowerCase());\n if (geomStyle != null) {\n return geomStyle;\n } else {\n symbolizer = builder.createPointSymbolizer();\n }\n }\n style = builder.createStyle(symbolizer);\n }\n return style;\n }", "protected static boolean isTargetOp( TokenList.Token token , Symbol[] ops ) {\n Symbol c = token.symbol;\n for (int i = 0; i < ops.length; i++) {\n if( c == ops[i])\n return true;\n }\n return false;\n }", "public static boolean matches(Map<String, Object> nodeProperties, String[] keyColumnNames, Object[] keyColumnValues) {\n\t\tfor ( int i = 0; i < keyColumnNames.length; i++ ) {\n\t\t\tString property = keyColumnNames[i];\n\t\t\tObject expectedValue = keyColumnValues[i];\n\t\t\tboolean containsProperty = nodeProperties.containsKey( property );\n\t\t\tif ( containsProperty ) {\n\t\t\t\tObject actualValue = nodeProperties.get( property );\n\t\t\t\tif ( !sameValue( expectedValue, actualValue ) ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( expectedValue != null ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "public FieldType getFieldByAlias(FieldTypeClass typeClass, String alias)\n {\n return m_aliasMap.get(new Pair<FieldTypeClass, String>(typeClass, alias));\n }" ]
Determine if the start of the buffer matches a fingerprint byte array. @param buffer bytes from file @param fingerprint fingerprint bytes @return true if the file matches the fingerprint
[ "private boolean matchesFingerprint(byte[] buffer, byte[] fingerprint)\n {\n return Arrays.equals(fingerprint, Arrays.copyOf(buffer, fingerprint.length));\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 boolean shouldCompress(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkSuffixes(uri, zipSuffixes);\n\t}", "protected final boolean isDurationValid() {\n\n if (isValidEndTypeForPattern()) {\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS));\n case TIMES:\n return getOccurrences() > 0;\n case SINGLE:\n return true;\n default:\n return false;\n }\n } else {\n return false;\n }\n }", "public static base_response add(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction addresource = new tmtrafficaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.apptimeout = resource.apptimeout;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.formssoaction = resource.formssoaction;\n\t\taddresource.persistentcookie = resource.persistentcookie;\n\t\taddresource.initiatelogout = resource.initiatelogout;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn addresource.add_resource(client);\n\t}", "public static base_response add(nitro_service client, dnstxtrec resource) throws Exception {\n\t\tdnstxtrec addresource = new dnstxtrec();\n\t\taddresource.domain = resource.domain;\n\t\taddresource.String = resource.String;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}", "public void postConstruct() throws URISyntaxException {\n WmsVersion.lookup(this.version);\n Assert.isTrue(validateBaseUrl(), \"invalid baseURL\");\n\n Assert.isTrue(this.layers.length > 0, \"There must be at least one layer defined for a WMS request\" +\n \" to make sense\");\n\n // OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are\n\n if (this.styles != null && this.styles.length != this.layers.length && this.styles.length == 1 &&\n this.styles[0].trim().isEmpty()) {\n this.styles = null;\n } else {\n Assert.isTrue(this.styles == null || this.layers.length == this.styles.length,\n String.format(\n \"If styles are defined then there must be one for each layer. Number of\" +\n \" layers: %s\\nStyles: %s\", this.layers.length,\n Arrays.toString(this.styles)));\n }\n\n if (this.imageFormat.indexOf('/') < 0) {\n LOGGER.warn(\"The format {} should be a mime type\", this.imageFormat);\n this.imageFormat = \"image/\" + this.imageFormat;\n }\n\n Assert.isTrue(this.method == HttpMethod.GET || this.method == HttpMethod.POST,\n String.format(\"Unsupported method %s for WMS layer\", this.method.toString()));\n }", "public static tmsessionparameter get(nitro_service service) throws Exception{\n\t\ttmsessionparameter obj = new tmsessionparameter();\n\t\ttmsessionparameter[] response = (tmsessionparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }", "public Task<Void> confirmUser(@NonNull final String token, @NonNull final String tokenId) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n confirmUserInternal(token, tokenId);\n return null;\n }\n });\n }" ]
Start the host controller services. @throws Exception
[ "public void bootstrap() throws Exception {\n final HostRunningModeControl runningModeControl = environment.getRunningModeControl();\n final ControlledProcessState processState = new ControlledProcessState(true);\n shutdownHook.setControlledProcessState(processState);\n ServiceTarget target = serviceContainer.subTarget();\n ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService.addService(target, processState).getValue();\n RunningStateJmx.registerMBean(controlledProcessStateService, null, runningModeControl, false);\n final HostControllerService hcs = new HostControllerService(environment, runningModeControl, authCode, processState);\n target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install();\n }" ]
[ "public void authenticate() {\n URL url;\n try {\n url = new URL(this.getTokenURL());\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 jwtAssertion = this.constructJWTAssertion();\n\n String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException ex) {\n // Use the Date advertised by the Box server as the current time to synchronize clocks\n List<String> responseDates = ex.getHeaders().get(\"Date\");\n NumericDate currentTime;\n if (responseDates != null) {\n String responseDate = responseDates.get(0);\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, d MMM yyyy HH:mm:ss zzz\");\n try {\n Date date = dateFormat.parse(responseDate);\n currentTime = NumericDate.fromMilliseconds(date.getTime());\n } catch (ParseException e) {\n currentTime = NumericDate.now();\n }\n } else {\n currentTime = NumericDate.now();\n }\n\n // Reconstruct the JWT assertion, which regenerates the jti claim, with the new \"current\" time\n jwtAssertion = this.constructJWTAssertion(currentTime);\n urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n // Re-send the updated request\n request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.setAccessToken(jsonObject.get(\"access_token\").asString());\n this.setLastRefresh(System.currentTimeMillis());\n this.setExpires(jsonObject.get(\"expires_in\").asLong() * 1000);\n\n //if token cache is specified, save to cache\n if (this.accessTokenCache != null) {\n String key = this.getAccessTokenCacheKey();\n JsonObject accessTokenCacheInfo = new JsonObject()\n .add(\"accessToken\", this.getAccessToken())\n .add(\"lastRefresh\", this.getLastRefresh())\n .add(\"expires\", this.getExpires());\n\n this.accessTokenCache.put(key, accessTokenCacheInfo.toString());\n }\n }", "private void createCodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int realOffsetStart, int realOffsetEnd, List<Integer> codePositions)\n throws IOException {\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, filterString(stringValues[0].trim()));\n token.setOffset(offsetStart, offsetEnd);\n token.setRealOffset(realOffsetStart, realOffsetEnd);\n token.addPositions(codePositions.stream().mapToInt(i -> i).toArray());\n tokenCollection.add(token);\n level.tokens.add(token);\n }", "private String getPropertyLabel(PropertyIdValue propertyIdValue) {\n\t\tPropertyRecord propertyRecord = this.propertyRecords\n\t\t\t\t.get(propertyIdValue);\n\t\tif (propertyRecord == null || propertyRecord.propertyDocument == null) {\n\t\t\treturn propertyIdValue.getId();\n\t\t} else {\n\t\t\treturn getLabel(propertyIdValue, propertyRecord.propertyDocument);\n\t\t}\n\t}", "private String getHostHeaderForHost(String hostName) {\n List<ServerRedirect> servers = serverRedirectService.tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n String hostHeader = server.getHostHeader();\n if (hostHeader == null || hostHeader.length() == 0) {\n return null;\n }\n return hostHeader;\n }\n }\n return null;\n }", "public Record getChild(String key)\n {\n Record result = null;\n if (key != null)\n {\n for (Record record : m_records)\n {\n if (key.equals(record.getField()))\n {\n result = record;\n break;\n }\n }\n }\n return result;\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 static base_responses unlink(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey unlinkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunlinkresources[i] = new sslcertkey();\n\t\t\t\tunlinkresources[i].certkey = resources[i].certkey;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, unlinkresources,\"unlink\");\n\t\t}\n\t\treturn result;\n\t}", "public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }", "public static void convertTranSrc(DMatrixRMaj src , DMatrixRBlock dst )\n {\n if( src.numRows != dst.numCols || src.numCols != dst.numRows )\n throw new IllegalArgumentException(\"Incompatible matrix shapes.\");\n\n for( int i = 0; i < dst.numRows; i += dst.blockLength ) {\n int blockHeight = Math.min( dst.blockLength , dst.numRows - i);\n\n for( int j = 0; j < dst.numCols; j += dst.blockLength ) {\n int blockWidth = Math.min( dst.blockLength , dst.numCols - j);\n\n int indexDst = i*dst.numCols + blockHeight*j;\n int indexSrc = j*src.numCols + i;\n\n for( int l = 0; l < blockWidth; l++ ) {\n int rowSrc = indexSrc + l*src.numCols;\n int rowDst = indexDst + l;\n for( int k = 0; k < blockHeight; k++ , rowDst += blockWidth ) {\n dst.data[ rowDst ] = src.data[rowSrc++];\n }\n }\n }\n }\n }" ]
Do synchronization of the given J2EE ODMG Transaction
[ "private void registerSynchronization(TransactionImpl odmgTrans, Transaction transaction)\r\n {\r\n // todo only need for development\r\n if (odmgTrans == null || transaction == null)\r\n {\r\n log.error(\"One of the given parameters was null --> cannot do synchronization!\" +\r\n \" omdg transaction was null: \" + (odmgTrans == null) +\r\n \", external transaction was null: \" + (transaction == null));\r\n return;\r\n }\r\n\r\n int status = -1; // default status.\r\n try\r\n {\r\n status = transaction.getStatus();\r\n if (status != Status.STATUS_ACTIVE)\r\n {\r\n throw new OJBRuntimeException(\r\n \"Transaction synchronization failed - wrong status of external container tx: \" +\r\n getStatusString(status));\r\n }\r\n }\r\n catch (SystemException e)\r\n {\r\n throw new OJBRuntimeException(\"Can't read status of external tx\", e);\r\n }\r\n\r\n try\r\n {\r\n //Sequence of the following method calls is significant\r\n // 1. register the synchronization with the ODMG notion of a transaction.\r\n transaction.registerSynchronization((J2EETransactionImpl) odmgTrans);\r\n // 2. mark the ODMG transaction as being in a JTA Transaction\r\n // Associate external transaction with the odmg transaction.\r\n txRepository.set(new TxBuffer(odmgTrans, transaction));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Cannot associate PersistenceBroker with running Transaction\", e);\r\n throw new OJBRuntimeException(\r\n \"Transaction synchronization failed - wrong status of external container tx\", e);\r\n }\r\n }" ]
[ "public void setOuterConeAngle(float angle)\n {\n setFloat(\"outer_cone_angle\", (float) Math.cos(Math.toRadians(angle)));\n mChanged.set(true);\n }", "public static <T_Result, T_Source> List<T_Result> map(Collection<T_Source> source,\n Mapper<T_Result, T_Source> mapper) {\n List<T_Result> result = new LinkedList<T_Result>();\n for (T_Source element : source) {\n result.add(mapper.map(element));\n }\n return result;\n }", "public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) {\n\n\t\t/*\n\t\t * The internal data structure is not optimal here (a map would make more sense here),\n\t\t * if the user does not require access to the products, we would allow non-unique symbols.\n\t\t * Hence we store both in two side by side vectors.\n\t\t */\n\t\tfor(int i=0; i<calibrationProductsSymbols.size(); i++) {\n\t\t\tString calibrationProductSymbol = calibrationProductsSymbols.get(i);\n\t\t\tif(calibrationProductSymbol.equals(symbol)) {\n\t\t\t\treturn calibrationProducts.get(i);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public static void readAndCheckVersion(ObjectInput input, int supportedVersion, Class<?> externalizedType) throws IOException {\n\t\tint version = input.readInt();\n\n\t\tif ( version != supportedVersion ) {\n\t\t\tthrow LOG.unexpectedKeyVersion( externalizedType, version, supportedVersion );\n\t\t}\n\t}", "public <T extends CoreLabel> Datum<String, String> makeDatum(List<IN> info, int loc, FeatureFactory featureFactory) {\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n Collection<String> features = new ArrayList<String>();\r\n List<Clique> cliques = featureFactory.getCliques();\r\n for (Clique c : cliques) {\r\n Collection<String> feats = featureFactory.getCliqueFeatures(pInfo, loc, c);\r\n feats = addOtherClasses(feats, pInfo, loc, c);\r\n features.addAll(feats);\r\n }\r\n\r\n printFeatures(pInfo.get(loc), features);\r\n CoreLabel c = info.get(loc);\r\n return new BasicDatum<String, String>(features, c.get(AnswerAnnotation.class));\r\n }", "private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) {\n\t\tif (logger.isTraceEnabled()) {\n\t\t\tlogger.trace(String.format(\"%s received %s\", ctx.channel(), frame.text()));\n\t\t}\n\n\t\taddTraceForFrame(frame, \"text\");\n\t\tctx.channel().write(new TextWebSocketFrame(\"Echo: \" + frame.text()));\n\t}", "public static NodeCache startAppIdWatcher(Environment env) {\n try {\n CuratorFramework curator = env.getSharedResources().getCurator();\n\n byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n if (uuidBytes == null) {\n Halt.halt(\"Fluo Application UUID not found\");\n throw new RuntimeException(); // make findbugs happy\n }\n\n final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);\n\n final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);\n nodeCache.getListenable().addListener(() -> {\n ChildData node = nodeCache.getCurrentData();\n if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {\n Halt.halt(\"Fluo Application UUID has changed or disappeared\");\n }\n });\n nodeCache.start();\n return nodeCache;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }", "public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }", "private static void writeToLog(Logger logger, Level level, String pattern, Exception exception) {\n if (level == Level.ERROR) {\n logger.error(pattern, exception);\n } else if (level == Level.INFO) {\n logger.info(pattern);\n } else if (level == Level.DEBUG) {\n logger.debug(pattern);\n }\n }" ]
return a generic Statement for the given ClassDescriptor
[ "public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,\r\n boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)\r\n throws PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }" ]
[ "public void stop() {\n instanceLock.writeLock().lock();\n try {\n for (final NamespaceChangeStreamListener streamer : nsStreamers.values()) {\n streamer.stop();\n }\n } finally {\n instanceLock.writeLock().unlock();\n }\n }", "public static SimpleMatrix diag( Class type, double ...vals ) {\n SimpleMatrix M = new SimpleMatrix(vals.length,vals.length,type);\n for (int i = 0; i < vals.length; i++) {\n M.set(i,i,vals[i]);\n }\n return M;\n }", "public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) {\n int shift = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n bytes[i] = (byte) (0xFF & (value >> shift));\n shift += 8;\n }\n }", "public List<EndpointOverride> getSelectedPaths(int overrideType, Client client, Profile profile, String uri,\n Integer requestType, boolean pathTest) throws Exception {\n List<EndpointOverride> selectPaths = new ArrayList<EndpointOverride>();\n\n // get the paths for the current active client profile\n // this returns paths in priority order\n List<EndpointOverride> paths = new ArrayList<EndpointOverride>();\n\n if (client.getIsActive()) {\n paths = getPaths(\n profile.getId(),\n client.getUUID(), null);\n }\n\n boolean foundRealPath = false;\n logger.info(\"Checking uri: {}\", uri);\n\n // it should now be ordered by priority, i updated tableOverrides to\n // return the paths in priority order\n for (EndpointOverride path : paths) {\n // first see if the request types match..\n // and if the path request type is not ALL\n // if they do not then skip this path\n // If requestType is -1 we evaluate all(probably called by the path tester)\n if (requestType != -1 && path.getRequestType() != requestType && path.getRequestType() != Constants.REQUEST_TYPE_ALL) {\n continue;\n }\n\n // first see if we get a match\n try {\n Pattern pattern = Pattern.compile(path.getPath());\n Matcher matcher = pattern.matcher(uri);\n\n // we won't select the path if there aren't any enabled endpoints in it\n // this works since the paths are returned in priority order\n if (matcher.find()) {\n // now see if this path has anything enabled in it\n // Only go into the if:\n // 1. There are enabled items in this path\n // 2. Caller was looking for ResponseOverride and Response is enabled OR looking for RequestOverride\n // 3. If pathTest is true then the rest of the conditions are not evaluated. The path tester ignores enabled states so everything is returned.\n // and request is enabled\n if (pathTest ||\n (path.getEnabledEndpoints().size() > 0 &&\n ((overrideType == Constants.OVERRIDE_TYPE_RESPONSE && path.getResponseEnabled()) ||\n (overrideType == Constants.OVERRIDE_TYPE_REQUEST && path.getRequestEnabled())))) {\n // if we haven't already seen a non global path\n // or if this is a global path\n // then add it to the list\n if (!foundRealPath || path.getGlobal()) {\n selectPaths.add(path);\n }\n }\n\n // we set this no matter what if a path matched and it was not the global path\n // this stops us from adding further non global matches to the list\n if (!path.getGlobal()) {\n foundRealPath = true;\n }\n }\n } catch (PatternSyntaxException pse) {\n // nothing to do but keep iterating over the list\n // this indicates an invalid regex\n }\n }\n\n return selectPaths;\n }", "private void recoverNamespace(final NamespaceSynchronizationConfig nsConfig) {\n final MongoCollection<BsonDocument> undoCollection =\n getUndoCollection(nsConfig.getNamespace());\n final MongoCollection<BsonDocument> localCollection =\n getLocalCollection(nsConfig.getNamespace());\n final List<BsonDocument> undoDocs = undoCollection.find().into(new ArrayList<>());\n final Set<BsonValue> recoveredIds = new HashSet<>();\n\n\n // Replace local docs with undo docs. Presence of an undo doc implies we had a system failure\n // during a write. This covers updates and deletes.\n for (final BsonDocument undoDoc : undoDocs) {\n final BsonValue documentId = BsonUtils.getDocumentId(undoDoc);\n final BsonDocument filter = getDocumentIdFilter(documentId);\n localCollection.findOneAndReplace(\n filter, undoDoc, new FindOneAndReplaceOptions().upsert(true));\n recoveredIds.add(documentId);\n }\n\n // If we recovered a document, but its pending writes are set to do something else, then the\n // failure occurred after the pending writes were set, but before the undo document was\n // deleted. In this case, we should restore the document to the state that the pending\n // write indicates. There is a possibility that the pending write is from before the failed\n // operation, but in that case, the findOneAndReplace or delete is a no-op since restoring\n // the document to the state of the change event would be the same as recovering the undo\n // document.\n for (final CoreDocumentSynchronizationConfig docConfig : nsConfig.getSynchronizedDocuments()) {\n final BsonValue documentId = docConfig.getDocumentId();\n final BsonDocument filter = getDocumentIdFilter(documentId);\n\n if (recoveredIds.contains(docConfig.getDocumentId())) {\n final ChangeEvent<BsonDocument> pendingWrite = docConfig.getLastUncommittedChangeEvent();\n if (pendingWrite != null) {\n switch (pendingWrite.getOperationType()) {\n case INSERT:\n case UPDATE:\n case REPLACE:\n localCollection.findOneAndReplace(\n filter,\n pendingWrite.getFullDocument(),\n new FindOneAndReplaceOptions().upsert(true)\n );\n break;\n case DELETE:\n localCollection.deleteOne(filter);\n break;\n default:\n // There should never be pending writes with an unknown event type, but if someone\n // is messing with the config collection we want to stop the synchronizer to prevent\n // further data corruption.\n throw new IllegalStateException(\n \"there should not be a pending write with an unknown event type\"\n );\n }\n }\n }\n }\n\n // Delete all of our undo documents. If we've reached this point, we've recovered the local\n // collection to the state we want with respect to all of our undo documents. If we fail before\n // these deletes or while carrying out the deletes, but after recovering the documents to\n // their desired state, that's okay because the next recovery pass will be effectively a no-op\n // up to this point.\n for (final BsonValue recoveredId : recoveredIds) {\n undoCollection.deleteOne(getDocumentIdFilter(recoveredId));\n }\n\n // Find local documents for which there are no document configs and delete them. This covers\n // inserts, upserts, and desync deletes. This will occur on any recovery pass regardless of\n // the documents in the undo collection, so it's fine that we do this after deleting the undo\n // documents.\n localCollection.deleteMany(new BsonDocument(\n \"_id\",\n new BsonDocument(\n \"$nin\",\n new BsonArray(new ArrayList<>(\n this.syncConfig.getSynchronizedDocumentIds(nsConfig.getNamespace()))))));\n }", "private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }", "public int getCurrentPage() {\n int currentPage = 1;\n int count = mScrollable.getScrollingItemsCount();\n if (mSupportScrollByPage && mCurrentItemIndex >= 0 &&\n mCurrentItemIndex < count) {\n currentPage = (Math.min(mCurrentItemIndex + mPageSize - 1, count - 1)/mPageSize);\n }\n return currentPage;\n }", "ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) {\n if (domain.getCodeSource() == null) {\n // no codesource to cache on\n return create(domain);\n }\n ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource());\n if (proxyProtectionDomain == null) {\n // as this is not atomic create() may be called multiple times for the same domain\n // we ignore that\n proxyProtectionDomain = create(domain);\n ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain);\n if (existing != null) {\n proxyProtectionDomain = existing;\n }\n }\n return proxyProtectionDomain;\n }", "private static ResourceBundle tryBundle(String baseName, Locale locale, boolean wantBase) {\n\n I_CmsResourceBundle first = null; // The most specialized bundle.\n I_CmsResourceBundle last = null; // The least specialized bundle.\n\n List<String> bundleNames = CmsLocaleManager.getLocaleVariants(baseName, locale, true, true);\n for (String bundleName : bundleNames) {\n // break if we would try the base bundle, but we do not want it directly\n if (bundleName.equals(baseName) && !wantBase && (first == null)) {\n break;\n }\n I_CmsResourceBundle foundBundle = tryBundle(bundleName);\n if (foundBundle != null) {\n if (first == null) {\n first = foundBundle;\n }\n\n if (last != null) {\n last.setParent((ResourceBundle)foundBundle);\n }\n foundBundle.setLocale(locale);\n\n last = foundBundle;\n }\n }\n return (ResourceBundle)first;\n }" ]
Restores a trashed file back to its original location. @param fileID the ID of the trashed file. @return info about the restored file.
[ "public BoxFile.Info restoreFile(String fileID) {\n URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFile restoredFile = new BoxFile(this.api, responseJSON.get(\"id\").asString());\n return restoredFile.new Info(responseJSON);\n }" ]
[ "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}", "protected static final float[] getSpreadInRange(float member, int count, int max, int offset) {\n // to find the spread, we first find the min that is a\n // multiple of max/count away from the member\n\n int interval = max / count;\n float min = (member + offset) % interval;\n\n if (min == 0 && member == max) {\n min += interval;\n }\n\n float[] range = new float[count];\n for (int i = 0; i < count; i++) {\n range[i] = min + interval * i + offset;\n }\n\n return range;\n }", "protected void endPersistence(final BufferedWriter writer) throws IOException {\n // Append any additional users to the end of the file.\n for (Object currentKey : toSave.keySet()) {\n String key = (String) currentKey;\n if (!key.contains(DISABLE_SUFFIX_KEY)) {\n writeProperty(writer, key, null);\n }\n }\n\n toSave = null;\n }", "public 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 }", "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 }", "protected final StyleSupplier<FeatureSource> createStyleFunction(\n final Template template,\n final String styleString) {\n return new StyleSupplier<FeatureSource>() {\n @Override\n public Style load(\n final MfClientHttpRequestFactory requestFactory,\n final FeatureSource featureSource) {\n if (featureSource == null) {\n throw new IllegalArgumentException(\"Feature source cannot be null\");\n }\n\n final String geomType = featureSource.getSchema() == null ?\n Geometry.class.getSimpleName().toLowerCase() :\n featureSource.getSchema().getGeometryDescriptor().getType().getBinding()\n .getSimpleName();\n final String styleRef = styleString != null ? styleString : geomType;\n\n final StyleParser styleParser = AbstractFeatureSourceLayerPlugin.this.parser;\n return OptionalUtils.or(\n () -> template.getStyle(styleRef),\n () -> styleParser.loadStyle(template.getConfiguration(), requestFactory, styleRef))\n .orElseGet(() -> template.getConfiguration().getDefaultStyle(geomType));\n }\n };\n }", "public static DiscountCurve createDiscountCurveFromDiscountFactors(String name, double[] times, double[] givenDiscountFactors) {\n\t\tDiscountCurve discountFactors = new DiscountCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tdiscountFactors.addDiscountFactor(times[timeIndex], givenDiscountFactors[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn discountFactors;\n\t}", "private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }", "public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }" ]
Computes FPS average
[ "public static void count() {\n long duration = SystemClock.uptimeMillis() - startTime;\n float avgFPS = sumFrames / (duration / 1000f);\n\n Log.v(\"FPSCounter\",\n \"total frames = %d, total elapsed time = %d ms, average fps = %f\",\n sumFrames, duration, avgFPS);\n }" ]
[ "public EventBus emit(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "public Collection<User> getFavorites(String photoId, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n\r\n parameters.put(\"method\", METHOD_GET_FAVORITES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\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 List<User> users = new ArrayList<User>();\r\n\r\n Element userRoot = response.getPayload();\r\n NodeList userNodes = userRoot.getElementsByTagName(\"person\");\r\n for (int i = 0; i < userNodes.getLength(); i++) {\r\n Element userElement = (Element) userNodes.item(i);\r\n User user = new User();\r\n user.setId(userElement.getAttribute(\"nsid\"));\r\n user.setUsername(userElement.getAttribute(\"username\"));\r\n user.setFaveDate(userElement.getAttribute(\"favedate\"));\r\n users.add(user);\r\n }\r\n return users;\r\n }", "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n BeatFinder.getInstance().removeBeatListener(beatListener);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n running.set(false);\n positions.clear();\n updates.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "private void generateCopyingPart(WrappingHint.Builder builder) {\n ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder()\n .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS)\n .putAll(userDefinedCopyMethods)\n .build()\n .get(typeAssignedToField);\n \n if (copyMethods.isEmpty()) {\n throw new WrappingHintGenerationException();\n }\n \n CopyMethod firstSuitable = copyMethods.iterator().next();\n builder.setCopyMethodOwnerName(firstSuitable.owner.toString())\n .setCopyMethodName(firstSuitable.name);\n \n if (firstSuitable.isGeneric && typeSignature != null) {\n CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature)\n .transformGenericTree(GenericType::withoutWildcard);\n builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString()));\n }\n }", "private final void handleHttpWorkerResponse(\n ResponseOnSingeRequest respOnSingleReq) throws Exception {\n // Successful response from GenericAsyncHttpWorker\n\n // Jeff 20310411: use generic response\n\n String responseContent = respOnSingleReq.getResponseBody();\n response.setResponseContent(respOnSingleReq.getResponseBody());\n\n /**\n * Poller logic if pollable: check if need to poll/ or already complete\n * 1. init poller data and HttpPollerProcessor 2. check if task\n * complete, if not, send the request again.\n */\n if (request.isPollable()) {\n boolean scheduleNextPoll = false;\n boolean errorFindingUuid = false;\n\n // set JobId of the poller\n if (!pollerData.isUuidHasBeenSet()) {\n String jobId = httpPollerProcessor\n .getUuidFromResponse(respOnSingleReq);\n\n if (jobId.equalsIgnoreCase(PcConstants.NA)) {\n errorFindingUuid = true;\n pollingErrorCount++;\n logger.error(\"!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. \"\n\n + \"DEBUG: REGEX_JOBID: \"\n + httpPollerProcessor.getJobIdRegex()\n\n + \"RESPONSE: \"\n + respOnSingleReq.getResponseBody()\n + \" polling Error count\"\n + pollingErrorCount\n + \" at \" + PcDateUtils.getNowDateTimeStrStandard());\n // fail fast\n pollerData.setError(true);\n pollerData.setComplete(true);\n\n } else {\n pollerData.setJobIdAndMarkHasBeenSet(jobId);\n // if myResponse has other errors, mark poll data as error.\n pollerData.setError(httpPollerProcessor\n .ifThereIsErrorInResponse(respOnSingleReq));\n }\n\n }\n if (!pollerData.isError()) {\n\n pollerData\n .setComplete(httpPollerProcessor\n .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));\n pollerData.setCurrentProgress(httpPollerProcessor\n .getProgressFromResponse(respOnSingleReq));\n }\n\n // poll again only if not complete AND no error; 2015: change to\n // over limit\n scheduleNextPoll = !pollerData.isComplete()\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError());\n\n // Schedule next poll and return. (not to answer back to manager yet\n // )\n if (scheduleNextPoll\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError())) {\n\n pollMessageCancellable = getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(httpPollerProcessor\n .getPollIntervalMillis(),\n TimeUnit.MILLISECONDS), getSelf(),\n OperationWorkerMsgType.POLL_PROGRESS,\n getContext().system().dispatcher(), getSelf());\n\n logger.info(\"\\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND\"\n + String.format(\"PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent,\n PcDateUtils.getNowDateTimeStrStandard()));\n\n String responseContentNew = errorFindingUuid ? responseContent\n + \"_PollingErrorCount:\" + pollingErrorCount\n : responseContent;\n logger.info(responseContentNew);\n // log\n pollerData.getPollingHistoryMap().put(\n \"RECV_\" + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\"PROGRESS:%.3f, BODY:%s\",\n pollerData.getCurrentProgress(),\n responseContent));\n return;\n } else {\n pollerData\n .getPollingHistoryMap()\n .put(\"RECV_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\n \"POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent));\n }\n\n }// end if (request.isPollable())\n\n reply(respOnSingleReq.isFailObtainResponse(),\n respOnSingleReq.getErrorMessage(),\n respOnSingleReq.getStackTrace(),\n respOnSingleReq.getStatusCode(),\n respOnSingleReq.getStatusCodeInt(),\n respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());\n\n }", "protected void processResourceBaseline(Row row)\n {\n Integer id = row.getInteger(\"RES_UID\");\n Resource resource = m_project.getResourceByUniqueID(id);\n if (resource != null)\n {\n int index = row.getInt(\"RB_BASE_NUM\");\n\n resource.setBaselineWork(index, row.getDuration(\"RB_BASE_WORK\"));\n resource.setBaselineCost(index, row.getCurrency(\"RB_BASE_COST\"));\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 float getTexCoordU(int vertex, int coords) {\n if (!hasTexCoords(coords)) {\n throw new IllegalStateException(\n \"mesh has no texture coordinate set \" + coords);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for coords are done by java for us */\n \n return m_texcoords[coords].getFloat(\n vertex * m_numUVComponents[coords] * SIZEOF_FLOAT);\n }", "@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }" ]
Adjusts all links in the target folder that point to the source folder so that they are kept "relative" in the target folder where possible. If a link is found from the target folder to the source folder, then the target folder is checked if a target of the same name is found also "relative" inside the target Folder, and if so, the link is changed to that "relative" target. This is mainly used to keep relative links inside a copied folder structure intact. Example: Image we have folder /folderA/ that contains files /folderA/x1 and /folderA/y1. x1 has a link to y1 and y1 to x1. Now someone copies /folderA/ to /folderB/. So we end up with /folderB/x2 and /folderB/y2. Because of the link mechanism in OpenCms, x2 will have a link to y1 and y2 to x1. By using this method, the links from x2 to y1 will be replaced by a link x2 to y2, and y2 to x1 with y2 to x2. Link replacement works for links in XML files as well as relation only type links. @param sourceFolder the source folder @param targetFolder the target folder @throws CmsException if something goes wrong
[ "public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\n }" ]
[ "public static CharSequence getAt(CharSequence text, int index) {\n index = normaliseIndex(index, text.length());\n return text.subSequence(index, index + 1);\n }", "private String applyFilters(String methodName) {\n if (filters.isEmpty()) {\n return methodName;\n }\n\n Reader in = new StringReader(methodName);\n for (TokenFilter tf : filters) {\n in = tf.chain(in);\n }\n\n try {\n return CharStreams.toString(in);\n } catch (IOException e) {\n junit4.log(\"Could not apply filters to \" + methodName + \n \": \" + Throwables.getStackTraceAsString(e), Project.MSG_WARN);\n return methodName;\n }\n }", "public static vpnvserver_appcontroller_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_appcontroller_binding obj = new vpnvserver_appcontroller_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_appcontroller_binding response[] = (vpnvserver_appcontroller_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "List<W3CEndpointReference> lookupEndpoints(QName serviceName,\n MatcherDataType matcherData) throws ServiceLocatorFault,\n InterruptedExceptionFault {\n SLPropertiesMatcher matcher = createMatcher(matcherData);\n List<String> names = null;\n List<W3CEndpointReference> result = new ArrayList<W3CEndpointReference>();\n String adress;\n try {\n initLocator();\n if (matcher == null) {\n names = locatorClient.lookup(serviceName);\n } else {\n names = locatorClient.lookup(serviceName, matcher);\n }\n } catch (ServiceLocatorException e) {\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(serviceName.toString()\n + \"throws ServiceLocatorFault\");\n throw new ServiceLocatorFault(e.getMessage(), serviceFaultDetail);\n } catch (InterruptedException e) {\n InterruptionFaultDetail interruptionFaultDetail = new InterruptionFaultDetail();\n interruptionFaultDetail.setInterruptionDetail(serviceName\n .toString() + \"throws InterruptionFault\");\n throw new InterruptedExceptionFault(e.getMessage(),\n interruptionFaultDetail);\n }\n if (names != null && !names.isEmpty()) {\n for (int i = 0; i < names.size(); i++) {\n adress = names.get(i);\n result.add(buildEndpoint(serviceName, adress));\n }\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"lookup Endpoints for \" + serviceName\n + \" failed, service is not known.\");\n }\n ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail();\n serviceFaultDetail.setLocatorFaultDetail(\"lookup Endpoint for \"\n + serviceName + \" failed, service is not known.\");\n throw new ServiceLocatorFault(\"Can not find Endpoint\",\n serviceFaultDetail);\n }\n return result;\n }", "private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }", "public static base_response update(nitro_service client, responderparam resource) throws Exception {\n\t\tresponderparam updateresource = new responderparam();\n\t\tupdateresource.undefaction = resource.undefaction;\n\t\treturn updateresource.update_resource(client);\n\t}", "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 int[] Argsort(final float[] array, final boolean ascending) {\n Integer[] indexes = new Integer[array.length];\n for (int i = 0; i < indexes.length; i++) {\n indexes[i] = i;\n }\n Arrays.sort(indexes, new Comparator<Integer>() {\n @Override\n public int compare(final Integer i1, final Integer i2) {\n return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]);\n }\n });\n return asArray(indexes);\n }", "private void processTask(ChildTaskContainer parent, MapRow row) throws IOException\n {\n Task task = parent.addTask();\n task.setName(row.getString(\"NAME\"));\n task.setGUID(row.getUUID(\"UUID\"));\n task.setText(1, row.getString(\"ID\"));\n task.setDuration(row.getDuration(\"PLANNED_DURATION\"));\n task.setRemainingDuration(row.getDuration(\"REMAINING_DURATION\"));\n task.setHyperlink(row.getString(\"URL\"));\n task.setPercentageComplete(row.getDouble(\"PERCENT_COMPLETE\"));\n task.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n task.setMilestone(task.getDuration().getDuration() == 0);\n\n ProjectCalendar calendar = m_calendarMap.get(row.getUUID(\"CALENDAR_UUID\"));\n if (calendar != m_project.getDefaultCalendar())\n {\n task.setCalendar(calendar);\n }\n\n switch (row.getInteger(\"STATUS\").intValue())\n {\n case 1: // Planned\n {\n task.setStart(row.getDate(\"PLANNED_START\"));\n task.setFinish(task.getEffectiveCalendar().getDate(task.getStart(), task.getDuration(), false));\n break;\n }\n\n case 2: // Started\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setStart(task.getActualStart());\n task.setFinish(row.getDate(\"ESTIMATED_FINISH\"));\n if (task.getFinish() == null)\n {\n task.setFinish(row.getDate(\"PLANNED_FINISH\"));\n }\n break;\n }\n\n case 3: // Finished\n {\n task.setActualStart(row.getDate(\"ACTUAL_START\"));\n task.setActualFinish(row.getDate(\"ACTUAL_FINISH\"));\n task.setPercentageComplete(Double.valueOf(100.0));\n task.setStart(task.getActualStart());\n task.setFinish(task.getActualFinish());\n break;\n }\n }\n\n setConstraints(task, row);\n\n processChildTasks(task, row);\n\n m_taskMap.put(task.getGUID(), task);\n\n List<MapRow> predecessors = row.getRows(\"PREDECESSORS\");\n if (predecessors != null && !predecessors.isEmpty())\n {\n m_predecessorMap.put(task, predecessors);\n }\n\n List<MapRow> resourceAssignmnets = row.getRows(\"RESOURCE_ASSIGNMENTS\");\n if (resourceAssignmnets != null && !resourceAssignmnets.isEmpty())\n {\n processResourceAssignments(task, resourceAssignmnets);\n }\n }" ]
Prep for a new connection @return if stats are enabled, return the nanoTime when this connection was requested. @throws SQLException
[ "protected long preConnection() throws SQLException{\r\n\t\tlong statsObtainTime = 0;\r\n\t\t\r\n\t\tif (this.pool.poolShuttingDown){\r\n\t\t\tthrow new SQLException(this.pool.shutdownStackTrace);\r\n\t\t}\r\n\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tstatsObtainTime = System.nanoTime();\r\n\t\t\tthis.pool.statistics.incrementConnectionsRequested();\r\n\t\t}\r\n\t\t\r\n\t\treturn statsObtainTime;\r\n\t}" ]
[ "private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }", "private void instanceAlreadyLoaded(\n\t\tfinal Tuple resultset,\n\t\tfinal int i,\n\t\t\t//TODO create an interface for this usage\n\t\tfinal OgmEntityPersister persister,\n\t\tfinal org.hibernate.engine.spi.EntityKey key,\n\t\tfinal Object object,\n\t\tfinal LockMode lockMode,\n\t\tfinal SharedSessionContractImplementor session)\n\tthrows HibernateException {\n\t\tif ( !persister.isInstance( object ) ) {\n\t\t\tthrow new WrongClassException(\n\t\t\t\t\t\"loaded object was of wrong class \" + object.getClass(),\n\t\t\t\t\tkey.getIdentifier(),\n\t\t\t\t\tpersister.getEntityName()\n\t\t\t\t);\n\t\t}\n\n\t\tif ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested\n\n\t\t\tfinal boolean isVersionCheckNeeded = persister.isVersioned() &&\n\t\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t\t.getLockMode().lessThan( lockMode );\n\t\t\t// we don't need to worry about existing version being uninitialized\n\t\t\t// because this block isn't called by a re-entrant load (re-entrant\n\t\t\t// loads _always_ have lock mode NONE)\n\t\t\tif ( isVersionCheckNeeded ) {\n\t\t\t\t//we only check the version when _upgrading_ lock modes\n\t\t\t\tObject oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();\n\t\t\t\tpersister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );\n\t\t\t\t//we need to upgrade the lock mode to the mode requested\n\t\t\t\tsession.getPersistenceContext().getEntry( object )\n\t\t\t\t\t\t.setLockMode( lockMode );\n\t\t\t}\n\t\t}\n\t}", "public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException {\n return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, \"photo_id\", photoId, date, perPage, page);\n }", "private void injectAdditionalStyles() {\n\n try {\n Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();\n for (String stylesheet : stylesheets) {\n A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }", "public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "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 }", "private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }", "private static String qualifiedName(Options opt, String r) {\n\tif (opt.hideGenerics)\n\t r = removeTemplate(r);\n\t// Fast path - nothing to do:\n\tif (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0))\n\t return r;\n\tStringBuilder buf = new StringBuilder(r.length());\n\tqualifiedNameInner(opt, r, buf, 0, !opt.showQualified);\n\treturn buf.toString();\n }", "public <T> List<T> query(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n List<T> result = new ArrayList<T>();\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n if (json.has(\"rows\")) {\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement e : json.getAsJsonArray(\"rows\")) {\r\n result.add(jsonToObject(client.getGson(), e, \"doc\", classOfT));\r\n }\r\n } else {\r\n log.warning(\"No ungrouped result available. Use queryGroups() if grouping set\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }" ]
Adds a tag to the resource. @param key the key for the tag @param value the value for the tag @return the next stage of the definition/update
[ "@SuppressWarnings(\"unchecked\")\n public final FluentModelImplT withTag(String key, String value) {\n if (this.inner().getTags() == null) {\n this.inner().withTags(new HashMap<String, String>());\n }\n this.inner().getTags().put(key, value);\n return (FluentModelImplT) this;\n }" ]
[ "public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, oid, true);\r\n }", "public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}", "public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {\n // Evaluate the target filter of the ImporterService on the Declaration\n Filter filter = bindersManager.getTargetFilter(declarationBinderRef);\n return filter.matches(declaration.getMetadata());\n }", "public HttpConnection setRequestBody(final String input) {\n try {\n final byte[] inputBytes = input.getBytes(\"UTF-8\");\n return setRequestBody(inputBytes);\n } catch (UnsupportedEncodingException e) {\n // This should never happen as every implementation of the java platform is required\n // to support UTF-8.\n throw new RuntimeException(e);\n }\n }", "public List<TimephasedCost> getTimephasedCost()\n {\n if (m_timephasedCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedWork != null && m_timephasedWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedCost = getTimephasedCostMultipleRates(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n else\n {\n m_timephasedCost = getTimephasedCostSingleRate(getTimephasedWork(), getTimephasedOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedCost = getTimephasedCostFixedAmount();\n }\n\n }\n return m_timephasedCost;\n }", "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 }", "public static boolean checkConfiguredInModules() {\n\n Boolean result = m_moduleCheckCache.get();\n if (result == null) {\n result = Boolean.valueOf(getConfiguredTemplateMapping() != null);\n m_moduleCheckCache.set(result);\n }\n return result.booleanValue();\n }", "public List<File> getAutoAttachCacheFiles() {\n ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);\n Collections.sort(currentFiles, new Comparator<File>() {\n @Override\n public int compare(File o1, File o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n return Collections.unmodifiableList(currentFiles);\n }", "public static sslcertkey get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey obj = new sslcertkey();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey response = (sslcertkey) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Converts url path to the Transloadit full url. Returns the url passed if it is already full. @param url @return String
[ "private String getFullUrl(String url) {\n return url.startsWith(\"https://\") || url.startsWith(\"http://\") ? url : transloadit.getHostUrl() + url;\n }" ]
[ "public void add(final IndexableTaskItem taskItem) {\n this.dependsOnTaskGroup.addPostRunDependentTaskGroup(taskItem.taskGroup());\n this.collection.add(taskItem);\n }", "private void merge(Integer cid1, Integer cid2) {\n Collection<String> klass1 = classix.get(cid1);\n Collection<String> klass2 = classix.get(cid2);\n\n // if klass1 is the smaller, swap the two\n if (klass1.size() < klass2.size()) {\n Collection<String> tmp = klass2;\n klass2 = klass1;\n klass1 = tmp;\n\n Integer itmp = cid2;\n cid2 = cid1;\n cid1 = itmp;\n }\n\n // now perform the actual merge\n for (String id : klass2) {\n klass1.add(id);\n recordix.put(id, cid1);\n }\n\n // delete the smaller class, and we're done\n classix.remove(cid2);\n }", "private List<String> parseRssFeedForeCast(String feed) {\n String[] result = feed.split(\"<br />\");\n List<String> returnList = new ArrayList<String>();\n String[] result2 = result[2].split(\"<BR />\");\n\n returnList.add(result2[3] + \"\\n\");\n returnList.add(result[3] + \"\\n\");\n returnList.add(result[4] + \"\\n\");\n returnList.add(result[5] + \"\\n\");\n returnList.add(result[6] + \"\\n\");\n\n return returnList;\n }", "public static <V> V doWorkInPoolNicely(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) {\n final V result;\n try {\n result = doWorkInPool(pool, work);\n } catch (RuntimeException re) {\n throw re;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return result;\n }", "public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public void invert(DMatrixRBlock A_inv) {\n int M = Math.min(QR.numRows,QR.numCols);\n if( A_inv.numRows != M || A_inv.numCols != M )\n throw new IllegalArgumentException(\"A_inv must be square an have dimension \"+M);\n\n\n // Solve for A^-1\n // Q*R*A^-1 = I\n\n // Apply householder reflectors to the identity matrix\n // y = Q^T*I = Q^T\n MatrixOps_DDRB.setIdentity(A_inv);\n decomposer.applyQTran(A_inv);\n\n // Solve using upper triangular R matrix\n // R*A^-1 = y\n // A^-1 = R^-1*y\n TriangularSolver_DDRB.solve(QR.blockLength,true,\n new DSubmatrixD1(QR,0,M,0,M),new DSubmatrixD1(A_inv),false);\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 float MIN(float first, float second, float third) {\r\n\r\n float min = Integer.MAX_VALUE;\r\n if (first < min) {\r\n min = first;\r\n }\r\n if (second < min) {\r\n min = second;\r\n }\r\n if (third < min) {\r\n min = third;\r\n }\r\n return min;\r\n }", "public DocumentReaderAndWriter<IN> makeReaderAndWriter() {\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>)\r\n Class.forName(flags.readerAndWriter).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.readerAndWriter: '%s'\", flags.readerAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }" ]
Record the duration of a put operation, along with the size of the values returned.
[ "public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) {\n recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0);\n }" ]
[ "public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}", "private static BoxRetentionPolicyAssignment.Info createAssignment(BoxAPIConnection api, String policyID,\r\n JsonObject assignTo, JsonArray filter) {\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_id\", policyID)\r\n .add(\"assign_to\", assignTo);\r\n\r\n if (filter != null) {\r\n requestJSON.add(\"filter_fields\", filter);\r\n }\r\n\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicyAssignment createdAssignment\r\n = new BoxRetentionPolicyAssignment(api, responseJSON.get(\"id\").asString());\r\n return createdAssignment.new Info(responseJSON);\r\n }", "public static final Integer parseInteger(String value)\n {\n return (value == null || value.length() == 0 ? null : Integer.valueOf(Integer.parseInt(value)));\n }", "private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {\n if (!node.isDefined()) {\n return node;\n }\n\n ModelType type = node.getType();\n ModelNode resolved;\n if (type == ModelType.EXPRESSION) {\n resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);\n } else if (type == ModelType.OBJECT) {\n resolved = node.clone();\n for (Property prop : resolved.asPropertyList()) {\n resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));\n }\n } else if (type == ModelType.LIST) {\n resolved = node.clone();\n ModelNode list = new ModelNode();\n list.setEmptyList();\n for (ModelNode current : resolved.asList()) {\n list.add(resolveExpressionsRecursively(current));\n }\n resolved = list;\n } else if (type == ModelType.PROPERTY) {\n resolved = node.clone();\n resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));\n } else {\n resolved = node;\n }\n\n return resolved;\n }", "public double getValue(double x)\n\t{\n\t\tsynchronized(interpolatingRationalFunctionsLazyInitLock) {\n\t\t\tif(interpolatingRationalFunctions == null) {\n\t\t\t\tdoCreateRationalFunctions();\n\t\t\t}\n\t\t}\n\n\t\t// Get interpolating rational function for the given point x\n\t\tint pointIndex = java.util.Arrays.binarySearch(points, x);\n\t\tif(pointIndex >= 0) {\n\t\t\treturn values[pointIndex];\n\t\t}\n\n\t\tint intervallIndex = -pointIndex-2;\n\n\t\t// Check for extrapolation\n\t\tif(intervallIndex < 0) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[0];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[0]+(values[1]-values[0])/(points[1]-points[0])*(x-points[0]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = 0;\n\t\t\t}\n\t\t}\n\t\telse if(intervallIndex > points.length-2) {\n\t\t\t// Extrapolation\n\t\t\tif(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {\n\t\t\t\treturn values[points.length-1];\n\t\t\t} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {\n\t\t\t\treturn values[points.length-1]+(values[points.length-2]-values[points.length-1])/(points[points.length-2]-points[points.length-1])*(x-points[points.length-1]);\n\t\t\t} else {\n\t\t\t\tintervallIndex = points.length-2;\n\t\t\t}\n\t\t}\n\n\t\tRationalFunction rationalFunction = interpolatingRationalFunctions[intervallIndex];\n\n\t\t// Calculate interpolating value\n\t\treturn rationalFunction.getValue(x-points[intervallIndex]);\n\t}", "public void overrideCubeProperties(DockerCompositions overrideDockerCompositions) {\n final Set<String> containerIds = overrideDockerCompositions.getContainerIds();\n for (String containerId : containerIds) {\n\n // main definition of containers contains a container that must be overrode\n if (containers.containsKey(containerId)) {\n final CubeContainer cubeContainer = containers.get(containerId);\n final CubeContainer overrideCubeContainer = overrideDockerCompositions.get(containerId);\n\n cubeContainer.setRemoveVolumes(overrideCubeContainer.getRemoveVolumes());\n \n cubeContainer.setAlwaysPull(overrideCubeContainer.getAlwaysPull());\n\n if (overrideCubeContainer.hasAwait()) {\n cubeContainer.setAwait(overrideCubeContainer.getAwait());\n }\n\n if (overrideCubeContainer.hasBeforeStop()) {\n cubeContainer.setBeforeStop(overrideCubeContainer.getBeforeStop());\n }\n\n if (overrideCubeContainer.isManual()) {\n cubeContainer.setManual(overrideCubeContainer.isManual());\n }\n\n if (overrideCubeContainer.isKillContainer()) {\n cubeContainer.setKillContainer(overrideCubeContainer.isKillContainer());\n }\n } else {\n logger.warning(String.format(\"Overriding Container %s are not defined in main definition of containers.\",\n containerId));\n }\n }\n }", "private boolean renameKeyForAllLanguages(String oldKey, String newKey) {\n\n try {\n loadAllRemainingLocalizations();\n lockAllLocalizations(oldKey);\n if (hasDescriptor()) {\n lockDescriptor();\n }\n } catch (CmsException | IOException e) {\n LOG.error(e.getLocalizedMessage(), e);\n return false;\n }\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(oldKey)) {\n String value = localization.getProperty(oldKey);\n localization.remove(oldKey);\n localization.put(newKey, value);\n m_changedTranslations.add(entry.getKey());\n }\n }\n if (hasDescriptor()) {\n CmsXmlContentValueSequence messages = m_descContent.getValueSequence(\n Descriptor.N_MESSAGE,\n Descriptor.LOCALE);\n for (int i = 0; i < messages.getElementCount(); i++) {\n\n String prefix = messages.getValue(i).getPath() + \"/\";\n String key = m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).getStringValue(m_cms);\n if (key == oldKey) {\n m_descContent.getValue(prefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(m_cms, newKey);\n break;\n }\n }\n m_descriptorHasChanges = true;\n }\n m_keyset.renameKey(oldKey, newKey);\n return true;\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 }", "@SuppressWarnings(\"unchecked\")\n protected String addeDependency(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addDependency(dependency);\n }" ]
Obtains a local date in Ethiopic calendar system from the era, year-of-era, month-of-year and day-of-month fields. @param era the Ethiopic era, not null @param yearOfEra the year-of-era @param month the month-of-year @param dayOfMonth the day-of-month @return the Ethiopic local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code EthiopicEra}
[ "@Override\n public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) {\n return date(prolepticYear(era, yearOfEra), month, dayOfMonth);\n }" ]
[ "public <T> T callFunction(\n final String name,\n final List<?> args,\n final @Nullable Long requestTimeout,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return this.functionService\n .withCodecRegistry(codecRegistry)\n .callFunction(name, args, requestTimeout, resultClass);\n }", "public ReportWriter getReportWriter(final JasperPrint _jasperPrint, final String _format, final Map<JRExporterParameter,Object> _parameters) {\n final JRExporter exporter = FormatInfoRegistry.getInstance().getExporter(_format);\n exporter.setParameters(_parameters);\n\n if (_jasperPrint.getPages().size() > PAGES_THRESHHOLD) {\n return new FileReportWriter(_jasperPrint, exporter);\n } else {\n return new MemoryReportWriter(_jasperPrint, exporter);\n }\n }", "public JsonNode wbRemoveClaims(List<String> statementIds,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(statementIds,\n\t\t\t\t\"statementIds parameter cannot be null when deleting statements\");\n\t\tValidate.notEmpty(statementIds,\n\t\t\t\t\"statement ids to delete must be non-empty when deleting statements\");\n\t\tValidate.isTrue(statementIds.size() <= 50,\n\t\t\t\t\"At most 50 statements can be deleted at once\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"claim\", String.join(\"|\", statementIds));\n\t\t\n\t\treturn performAPIAction(\"wbremoveclaims\", null, null, null, null, parameters, summary, baserevid, bot);\n\t}", "public List<ChannelInfo> getChannels() {\n final URI uri = uriWithPath(\"./channels/\");\n return Arrays.asList(this.rt.getForObject(uri, ChannelInfo[].class));\n }", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }", "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 static Value.Builder makeValue(Value value1, Value value2, Value... rest) {\n ArrayValue.Builder arrayValue = ArrayValue.newBuilder();\n arrayValue.addValues(value1);\n arrayValue.addValues(value2);\n arrayValue.addAllValues(Arrays.asList(rest));\n return Value.newBuilder().setArrayValue(arrayValue);\n }", "public B importContext(AbstractContext context){\n Objects.requireNonNull(context);\n return importContext(context, false);\n }" ]
Adds a step to the steps. @param name {@link String} name of the step @param robot {@link String} name of the robot used by the step. @param options {@link Map} extra options required for the step.
[ "public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\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 }", "public OAuth1RequestToken getRequestToken(String callbackUrl) {\r\n String callback = (callbackUrl != null) ? callbackUrl : OUT_OF_BOUND_AUTH_METHOD;\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .callback(callback)\r\n .build(FlickrApi.instance());\r\n\r\n try {\r\n return service.getRequestToken();\r\n } catch (IOException | InterruptedException | ExecutionException e) {\r\n throw new FlickrRuntimeException(e);\r\n }\r\n }", "public void writeReferences() throws RDFHandlerException {\n\t\tIterator<Reference> referenceIterator = this.referenceQueue.iterator();\n\t\tfor (Resource resource : this.referenceSubjectQueue) {\n\t\t\tfinal Reference reference = referenceIterator.next();\n\t\t\tif (this.declaredReferences.add(resource)) {\n\t\t\t\twriteReference(reference, resource);\n\t\t\t}\n\t\t}\n\t\tthis.referenceSubjectQueue.clear();\n\t\tthis.referenceQueue.clear();\n\n\t\tthis.snakRdfConverter.writeAuxiliaryTriples();\n\t}", "protected String getExpectedMessage() {\r\n StringBuilder syntax = new StringBuilder(\"<tag> \");\r\n syntax.append(getName());\r\n\r\n String args = getArgSyntax();\r\n if (args != null && args.length() > 0) {\r\n syntax.append(' ');\r\n syntax.append(args);\r\n }\r\n\r\n return syntax.toString();\r\n }", "public boolean mapsCell(String cell) {\n return mappedCells.stream().anyMatch(x -> x.equals(cell));\n }", "public static <K, V> Map<K, V> of(K key, V value) {\n return new ImmutableMapEntry<K, V>(key, value);\n }", "public void sendMessageToAgentsWithExtraProperties(String[] agent_name,\n String msgtype, Object message_content,\n ArrayList<Object> properties, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n\n for (Object property : properties) {\n // Logger logger = Logger.getLogger(\"JadexMessenger\");\n // logger.info(\"Sending message with extra property: \"+property.get(0)+\", with value \"+property.get(1));\n hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));\n }\n\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }", "public void process() {\n // are we ready to process yet, or have we had an error, and are\n // waiting a bit longer in the hope that it will resolve itself?\n if (error_skips > 0) {\n error_skips--;\n return;\n }\n \n try {\n if (logger != null)\n logger.debug(\"Starting processing\");\n status = \"Processing\";\n lastCheck = System.currentTimeMillis();\n\n // FIXME: how to break off processing if we don't want to keep going?\n processor.deduplicate(batch_size);\n\n status = \"Sleeping\";\n if (logger != null)\n logger.debug(\"Finished processing\");\n } catch (Throwable e) {\n status = \"Thread blocked on error: \" + e;\n if (logger != null)\n logger.error(\"Error in processing; waiting\", e);\n error_skips = error_factor;\n }\n }", "public static spilloverpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tspilloverpolicy_stats obj = new spilloverpolicy_stats();\n\t\tspilloverpolicy_stats[] response = (spilloverpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}" ]
The parameter must never be null @param queryParameters
[ "public void init(final MultivaluedMap<String, String> queryParameters) {\n final String scopeCompileParam = queryParameters.getFirst(ServerAPI.SCOPE_COMPILE_PARAM);\n if(scopeCompileParam != null){\n this.scopeComp = Boolean.valueOf(scopeCompileParam);\n }\n final String scopeProvidedParam = queryParameters.getFirst(ServerAPI.SCOPE_PROVIDED_PARAM);\n if(scopeProvidedParam != null){\n this.scopePro = Boolean.valueOf(scopeProvidedParam);\n }\n final String scopeRuntimeParam = queryParameters.getFirst(ServerAPI.SCOPE_RUNTIME_PARAM);\n if(scopeRuntimeParam != null){\n this.scopeRun = Boolean.valueOf(scopeRuntimeParam);\n }\n final String scopeTestParam = queryParameters.getFirst(ServerAPI.SCOPE_TEST_PARAM);\n if(scopeTestParam != null){\n this.scopeTest = Boolean.valueOf(scopeTestParam);\n }\n }" ]
[ "void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }", "static SortedSet<String> createStatsItems(String statsType)\n throws IOException {\n SortedSet<String> statsItems = new TreeSet<>();\n SortedSet<String> functionItems = new TreeSet<>();\n if (statsType != null) {\n Matcher m = fpStatsItems.matcher(statsType.trim());\n while (m.find()) {\n String tmpStatsItem = m.group(2).trim();\n if (STATS_TYPES.contains(tmpStatsItem)) {\n statsItems.add(tmpStatsItem);\n } else if (tmpStatsItem.equals(STATS_TYPE_ALL)) {\n for (String type : STATS_TYPES) {\n statsItems.add(type);\n }\n } else if (STATS_FUNCTIONS.contains(tmpStatsItem)) {\n if (m.group(3) == null) {\n throw new IOException(\"'\" + tmpStatsItem + \"' should be called as '\"\n + tmpStatsItem + \"()' with an optional argument\");\n } else {\n functionItems.add(m.group(1).trim());\n }\n } else {\n throw new IOException(\"unknown statsType '\" + tmpStatsItem + \"'\");\n }\n }\n }\n if (statsItems.size() == 0 && functionItems.size() == 0) {\n statsItems.add(STATS_TYPE_SUM);\n statsItems.add(STATS_TYPE_N);\n statsItems.add(STATS_TYPE_MEAN);\n }\n if (functionItems.size() > 0) {\n statsItems.addAll(functionItems);\n }\n return statsItems;\n }", "public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\n\t}", "public synchronized void stop() {\n if (isRunning()) {\n socket.get().close();\n socket.set(null);\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "public String getCsv() {\n\n StringWriter writer = new StringWriter();\n try (CSVWriter csv = new CSVWriter(writer)) {\n List<String> headers = new ArrayList<>();\n for (String col : m_columns) {\n headers.add(col);\n }\n csv.writeNext(headers.toArray(new String[] {}));\n for (List<Object> row : m_data) {\n List<String> colCsv = new ArrayList<>();\n for (Object col : row) {\n colCsv.add(String.valueOf(col));\n }\n csv.writeNext(colCsv.toArray(new String[] {}));\n }\n return writer.toString();\n } catch (IOException e) {\n return null;\n }\n }", "private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER);\r\n\r\n if (rowReaderName == null)\r\n {\r\n return;\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+rowReaderName+\" specified as row-reader of class \"+classDef.getName()+\" does not implement the interface \"+ROW_READER_INTERFACE);\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 row-reader class \"+rowReaderName+\" of class \"+classDef.getName());\r\n }\r\n }", "public void cleanup() {\n synchronized (_sslMap) {\n for (SslRelayOdo relay : _sslMap.values()) {\n if (relay.getHttpServer() != null && relay.isStarted()) {\n relay.getHttpServer().removeListener(relay);\n }\n }\n\n sslRelays.clear();\n }\n }", "public int rank() {\n if( is64 ) {\n return SingularOps_DDRM.rank((SingularValueDecomposition_F64)svd, tol);\n } else {\n return SingularOps_FDRM.rank((SingularValueDecomposition_F32)svd, (float)tol);\n }\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 }" ]
Create a Deliverable inside the database that will track a file created by a JobInstance Must be called from inside a transaction @param path FilePath (relative to a root directory - cf. Node) @param originalFileName FileName @param fileFamily File family (may be null). E.g.: "daily report" @param jobId Job Instance ID @param cnx the DbConn to use.
[ "static int createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, DbConn cnx)\n {\n QueryResult qr = cnx.runUpdate(\"deliverable_insert\", fileFamily, path, jobId, originalFileName, UUID.randomUUID().toString());\n return qr.getGeneratedId();\n }" ]
[ "public static ReportGenerator.Format getFormat( String... args ) {\n ConfigOptionParser configParser = new ConfigOptionParser();\n List<ConfigOption> configOptions = Arrays.asList( format, help );\n\n for( ConfigOption co : configOptions ) {\n if( co.hasDefault() ) {\n configParser.parsedOptions.put( co.getLongName(), co.getValue() );\n }\n }\n\n for( String arg : args ) {\n configParser.commandLineLookup( arg, format, configOptions );\n }\n\n // TODO properties\n // TODO environment\n\n if( !configParser.hasValue( format ) ) {\n configParser.printUsageAndExit( configOptions );\n }\n return (ReportGenerator.Format) configParser.getValue( format );\n }", "public static void main(String[] args) {\n DirectoryIterator iter = new DirectoryIterator(args);\n while(iter.hasNext())\n System.out.println(iter.next().getAbsolutePath());\n }", "public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }", "public void setAssociation(String collectionRole, Association association) {\n\t\tif ( associations == null ) {\n\t\t\tassociations = new HashMap<>();\n\t\t}\n\t\tassociations.put( collectionRole, association );\n\t}", "public void update(StoreDefinition storeDef) {\n if(!useOneEnvPerStore)\n throw new VoldemortException(\"Memory foot print can be set only when using different environments per store\");\n\n String storeName = storeDef.getName();\n Environment environment = environments.get(storeName);\n // change reservation amount of reserved store\n if(!unreservedStores.contains(environment) && storeDef.hasMemoryFootprint()) {\n EnvironmentMutableConfig mConfig = environment.getMutableConfig();\n long currentCacheSize = mConfig.getCacheSize();\n long newCacheSize = storeDef.getMemoryFootprintMB() * ByteUtils.BYTES_PER_MB;\n if(currentCacheSize != newCacheSize) {\n long newReservedCacheSize = this.reservedCacheSize - currentCacheSize\n + newCacheSize;\n\n // check that we leave a 'minimum' shared cache\n if((voldemortConfig.getBdbCacheSize() - newReservedCacheSize) < voldemortConfig.getBdbMinimumSharedCache()) {\n throw new StorageInitializationException(\"Reservation of \"\n + storeDef.getMemoryFootprintMB()\n + \" MB for store \"\n + storeName\n + \" violates minimum shared cache size of \"\n + voldemortConfig.getBdbMinimumSharedCache());\n }\n\n this.reservedCacheSize = newReservedCacheSize;\n adjustCacheSizes();\n mConfig.setCacheSize(newCacheSize);\n environment.setMutableConfig(mConfig);\n logger.info(\"Setting private cache for store \" + storeDef.getName() + \" to \"\n + newCacheSize);\n }\n } else {\n // we cannot support changing a reserved store to unreserved or vice\n // versa since the sharedCache param is not mutable\n throw new VoldemortException(\"Cannot switch between shared and private cache dynamically\");\n }\n }", "public static String get(String language) {\n language = language.toLowerCase();\n if(\"ecmascript\".equals(language)) {\n language = \"javascript\";\n }\n\n String extension = extensions.get(language);\n if(extension == null) {\n return null;\n\n } else {\n return loadScriptEnv(language, extension);\n\n }\n }", "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 }", "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 }", "public Client getClient(int clientId) throws Exception {\n Client client = null;\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\";\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setInt(1, clientId);\n\n results = statement.executeQuery();\n if (results.next()) {\n client = this.getClientFromResultSet(results);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return client;\n }" ]
Shows a dialog with user information for given session. @param session to show information for
[ "public static void showUserInfo(CmsSessionInfo session) {\n\n final Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide);\n CmsUserInfoDialog dialog = new CmsUserInfoDialog(session, new Runnable() {\n\n public void run() {\n\n window.close();\n }\n\n });\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SHOW_USER_0));\n window.setContent(dialog);\n A_CmsUI.get().addWindow(window);\n }" ]
[ "private static Class<?> getGenericReturnType(Method method, Class<?> source, int typeIndex, int nestingLevel) {\n\t\treturn extractType(method.getGenericReturnType(), source, typeIndex, null, null, nestingLevel, 1);\n\t}", "private void processHyperlinkData(ResourceAssignment assignment, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n\n offset += 12;\n String hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n String address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n String subaddress = MPPUtility.getUnicodeString(data, offset);\n offset += ((subaddress.length() + 1) * 2);\n\n offset += 12;\n String screentip = MPPUtility.getUnicodeString(data, offset);\n\n assignment.setHyperlink(hyperlink);\n assignment.setHyperlinkAddress(address);\n assignment.setHyperlinkSubAddress(subaddress);\n assignment.setHyperlinkScreenTip(screentip);\n }\n }", "private ModelNode createOSNode() throws OperationFailedException {\n String osName = getProperty(\"os.name\");\n final ModelNode os = new ModelNode();\n if (osName != null && osName.toLowerCase().contains(\"linux\")) {\n try {\n os.set(GnuLinuxDistribution.discover());\n } catch (IOException ex) {\n throw new OperationFailedException(ex);\n }\n } else {\n os.set(osName);\n }\n return os;\n }", "public static <T> T load(String resourcePath, BeanSpec spec) {\n return load(resourcePath, spec, false);\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 }", "public void loadModel(GVRAndroidResource avatarResource, String attachBone)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n GVRSceneObject boneObject;\n int boneIndex;\n\n if (mSkeleton == null)\n {\n throw new IllegalArgumentException(\"Cannot attach model to avatar - there is no skeleton\");\n }\n boneIndex = mSkeleton.getBoneIndex(attachBone);\n if (boneIndex < 0)\n {\n throw new IllegalArgumentException(attachBone + \" is not a bone in the avatar skeleton\");\n }\n boneObject = mSkeleton.getBone(boneIndex);\n if (boneObject == null)\n {\n throw new IllegalArgumentException(attachBone +\n \" does not have a bone object in the avatar skeleton\");\n }\n boneObject.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }", "public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }", "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }", "public static responderparam get(nitro_service service) throws Exception{\n\t\tresponderparam obj = new responderparam();\n\t\tresponderparam[] response = (responderparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}" ]
Deals with the case where we have had to map a task ID to a new value. @param id task ID from database @return mapped task ID
[ "private Integer mapTaskID(Integer id)\n {\n Integer mappedID = m_clashMap.get(id);\n if (mappedID == null)\n {\n mappedID = id;\n }\n return (mappedID);\n }" ]
[ "public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute)\n\t{\n\t\t_mappedPublicKeys.put(original, substitute);\n\t\tif(persistImmediately) { persistPublicKeyMap(); }\n\t}", "private void writeResources() throws IOException\n {\n writeAttributeTypes(\"resource_types\", ResourceField.values());\n\n m_writer.writeStartList(\"resources\");\n for (Resource resource : m_projectFile.getResources())\n {\n writeFields(null, resource, ResourceField.values());\n }\n m_writer.writeEndList();\n }", "protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,\r\n int[][] labels, int offset) {\r\n for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {\r\n int dataIndex = i + offset;\r\n List<CRFDatum<Collection<String>, String>> document = processedData.get(i);\r\n int dsize = document.size();\r\n labels[dataIndex] = new int[dsize];\r\n data[dataIndex] = new int[dsize][][];\r\n for (int j = 0; j < dsize; j++) {\r\n CRFDatum<Collection<String>, String> crfDatum = document.get(j);\r\n // add label, they are offset by extra context\r\n labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());\r\n // add features\r\n List<Collection<String>> cliques = crfDatum.asFeatures();\r\n int csize = cliques.size();\r\n data[dataIndex][j] = new int[csize][];\r\n for (int k = 0; k < csize; k++) {\r\n Collection<String> features = cliques.get(k);\r\n\r\n // Debug only: Remove\r\n // if (j < windowSize) {\r\n // System.err.println(\"addProcessedData: Features Size: \" +\r\n // features.size());\r\n // }\r\n\r\n data[dataIndex][j][k] = new int[features.size()];\r\n\r\n int m = 0;\r\n try {\r\n for (String feature : features) {\r\n // System.err.println(\"feature \" + feature);\r\n // if (featureIndex.indexOf(feature)) ;\r\n if (featureIndex == null) {\r\n System.out.println(\"Feature is NULL!\");\r\n }\r\n data[dataIndex][j][k][m] = featureIndex.indexOf(feature);\r\n m++;\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n System.err.printf(\"[index=%d, j=%d, k=%d, m=%d]\\n\", dataIndex, j, k, m);\r\n System.err.println(\"data.length \" + data.length);\r\n System.err.println(\"data[dataIndex].length \" + data[dataIndex].length);\r\n System.err.println(\"data[dataIndex][j].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k].length \" + data[dataIndex][j].length);\r\n System.err.println(\"data[dataIndex][j][k][m] \" + data[dataIndex][j][k][m]);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }", "public static String encodeUserInfo(String userInfo, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(userInfo, encoding, HierarchicalUriComponents.Type.USER_INFO);\n\t}", "public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){\n\t\tfinal Artifact artifact = new Artifact();\n\n\t\tartifact.setGroupId(groupId);\n\t\tartifact.setArtifactId(artifactId);\n\t\tartifact.setVersion(version);\n\n\t\tif(classifier != null){\n\t\t\tartifact.setClassifier(classifier);\n\t\t}\n\n\t\tif(type != null){\n\t\t\tartifact.setType(type);\n\t\t}\n\n\t\tif(extension != null){\n\t\t\tartifact.setExtension(extension);\n\t\t}\n\n\t\tartifact.setOrigin(origin == null ? \"maven\" : origin);\n\n\t\treturn artifact;\n\t}", "public CompletableFuture<Void> stop() {\n numPendingStopRequests.incrementAndGet();\n return startStop.stop().thenRun(numPendingStopRequests::decrementAndGet);\n }", "public static boolean isConstructorCall(Expression expression, List<String> classNames) {\r\n return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName());\r\n }", "public static Integer getDay(Day day)\n {\n Integer result = null;\n if (day != null)\n {\n result = DAY_MAP.get(day);\n }\n return (result);\n }", "private void readTasks()\n {\n Integer rootID = Integer.valueOf(1);\n readWBS(m_projectFile, rootID);\n readTasks(rootID);\n m_projectFile.getTasks().synchronizeTaskIDToHierarchy();\n }" ]
Serialize a content into a targeted file, checking that the parent directory exists. @param folder File @param content String @param fileName String
[ "public static void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }" ]
[ "private <T> RequestBuilder doPrepareRequestBuilderImpl(\n ResponseReader responseReader, String methodName, RpcStatsContext statsContext,\n String requestData, AsyncCallback<T> callback) {\n\n if (getServiceEntryPoint() == null) {\n throw new NoServiceEntryPointSpecifiedException();\n }\n\n RequestCallback responseHandler = doCreateRequestCallback(responseReader,\n methodName, statsContext, callback);\n\n ensureRpcRequestBuilder();\n\n rpcRequestBuilder.create(getServiceEntryPoint());\n rpcRequestBuilder.setCallback(responseHandler);\n \n // changed code\n rpcRequestBuilder.setSync(isSync(methodName));\n // changed code\n \n rpcRequestBuilder.setContentType(RPC_CONTENT_TYPE);\n rpcRequestBuilder.setRequestData(requestData);\n rpcRequestBuilder.setRequestId(statsContext.getRequestId());\n return rpcRequestBuilder.finish();\n }", "private void writeResource(Resource mpxjResource, net.sf.mpxj.planner.schema.Resource plannerResource)\n {\n ProjectCalendar resourceCalendar = mpxjResource.getResourceCalendar();\n if (resourceCalendar != null)\n {\n plannerResource.setCalendar(getIntegerString(resourceCalendar.getUniqueID()));\n }\n\n plannerResource.setEmail(mpxjResource.getEmailAddress());\n plannerResource.setId(getIntegerString(mpxjResource.getUniqueID()));\n plannerResource.setName(getString(mpxjResource.getName()));\n plannerResource.setNote(mpxjResource.getNotes());\n plannerResource.setShortName(mpxjResource.getInitials());\n plannerResource.setType(mpxjResource.getType() == ResourceType.MATERIAL ? \"2\" : \"1\");\n //plannerResource.setStdRate();\n //plannerResource.setOvtRate();\n plannerResource.setUnits(\"0\");\n //plannerResource.setProperties();\n m_eventManager.fireResourceWrittenEvent(mpxjResource);\n }", "protected <T extends Listener> Collection<T> copyList(Class<T> listenerClass,\n Stream<Object> listeners, int sizeHint) {\n if (sizeHint == 0) {\n return Collections.emptyList();\n }\n return listeners\n .map(listenerClass::cast)\n .collect(Collectors.toCollection(() -> new ArrayList<>(sizeHint)));\n }", "public Label htmlLabel(String html) {\n\n Label label = new Label();\n label.setContentMode(ContentMode.HTML);\n label.setValue(html);\n return label;\n\n }", "public Date getNextWorkStart(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToNextWorkStart(cal);\n return cal.getTime();\n }", "public static IndexedContainer getPrincipalContainer(\n CmsObject cms,\n List<? extends I_CmsPrincipal> list,\n String captionID,\n String descID,\n String iconID,\n String ouID,\n String icon,\n List<FontIcon> iconList) {\n\n IndexedContainer res = new IndexedContainer();\n\n res.addContainerProperty(captionID, String.class, \"\");\n res.addContainerProperty(ouID, String.class, \"\");\n res.addContainerProperty(iconID, FontIcon.class, new CmsCssIcon(icon));\n if (descID != null) {\n res.addContainerProperty(descID, String.class, \"\");\n }\n\n for (I_CmsPrincipal group : list) {\n\n Item item = res.addItem(group);\n item.getItemProperty(captionID).setValue(group.getSimpleName());\n item.getItemProperty(ouID).setValue(group.getOuFqn());\n if (descID != null) {\n item.getItemProperty(descID).setValue(group.getDescription(A_CmsUI.get().getLocale()));\n }\n }\n\n for (int i = 0; i < iconList.size(); i++) {\n res.getItem(res.getIdByIndex(i)).getItemProperty(iconID).setValue(iconList.get(i));\n }\n\n return res;\n }", "public void waitForBuffer(long timeoutMilli) {\n //assert(callerProcessing.booleanValue() == false);\n\n synchronized(buffer) {\n if( dirtyBuffer )\n return;\n if( !foundEOF() ) {\n logger.trace(\"Waiting for things to come in, or until timeout\");\n try {\n if( timeoutMilli > 0 )\n buffer.wait(timeoutMilli);\n else\n buffer.wait();\n } catch(InterruptedException ie) {\n logger.trace(\"Woken up, while waiting for buffer\");\n }\n // this might went early, but running the processing again isn't a big deal\n logger.trace(\"Waited\");\n }\n }\n }", "public void setBorderWidth(int borderWidth) {\n\t\tthis.borderWidth = borderWidth;\n\t\tif(paintBorder != null)\n\t\t\tpaintBorder.setStrokeWidth(borderWidth);\n\t\trequestLayout();\n\t\tinvalidate();\n\t}", "public synchronized Object removeRoleMapping(final String roleName) {\n /*\n * Would not expect this to happen during boot so don't offer the 'immediate' optimisation.\n */\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName)) {\n RoleMappingImpl removed = newRoles.remove(roleName);\n Object removalKey = new Object();\n removedRoles.put(removalKey, removed);\n roleMappings = Collections.unmodifiableMap(newRoles);\n\n return removalKey;\n }\n\n return null;\n }" ]
Removes double-quotes from around a string @param str @return
[ "public static String createUnquotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n if (str.startsWith(\"\\\"\")) {\n str = str.substring(1);\n }\n if (str.endsWith(\"\\\"\")) {\n str = str.substring(0,\n str.length() - 1);\n }\n return str;\n }" ]
[ "public static Class<?> getRawType(Type type) {\n\t\tif (type instanceof Class) {\n\t\t\treturn (Class<?>) type;\n\t\t} else if (type instanceof ParameterizedType) {\n\t\t\tParameterizedType actualType = (ParameterizedType) type;\n\t\t\treturn getRawType(actualType.getRawType());\n\t\t} else if (type instanceof GenericArrayType) {\n\t\t\tGenericArrayType genericArrayType = (GenericArrayType) type;\n\t\t\tObject rawArrayType = Array.newInstance(getRawType(genericArrayType\n\t\t\t\t\t.getGenericComponentType()), 0);\n\t\t\treturn rawArrayType.getClass();\n\t\t} else if (type instanceof WildcardType) {\n\t\t\tWildcardType castedType = (WildcardType) type;\n\t\t\treturn getRawType(castedType.getUpperBounds()[0]);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Type \\'\"\n\t\t\t\t\t\t\t+ type\n\t\t\t\t\t\t\t+ \"\\' is not a Class, \"\n\t\t\t\t\t\t\t+ \"ParameterizedType, or GenericArrayType. Can't extract class.\");\n\t\t}\n\t}", "public static String join(Iterable<?> iterable, String separator) {\n if (iterable != null) {\n StringBuilder buf = new StringBuilder();\n Iterator<?> it = iterable.iterator();\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n while (it.hasNext()) {\n buf.append(it.next());\n if (it.hasNext()) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }", "public static final long getLong(byte[] data, int offset)\n {\n if (data.length != 8)\n {\n throw new UnexpectedStructureException();\n }\n\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 64; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "public void bindSelect(PreparedStatement stmt, Identity oid, ClassDescriptor cld, boolean callableStmt) throws SQLException\r\n {\r\n ValueContainer[] values = null;\r\n int i = 0;\r\n int j = 0;\r\n\r\n if (cld == null)\r\n {\r\n cld = m_broker.getClassDescriptor(oid.getObjectsRealClass());\r\n }\r\n try\r\n {\r\n if(callableStmt)\r\n {\r\n // First argument is the result set\r\n m_platform.registerOutResultSet((CallableStatement) stmt, 1);\r\n j++;\r\n }\r\n\r\n values = getKeyValues(m_broker, cld, oid);\r\n for (/*void*/; i < values.length; i++, j++)\r\n {\r\n setObjectForStatement(stmt, j + 1, values[i].getValue(), values[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindSelect failed for: \" + oid.toString() + \", PK: \" + i + \", value: \" + values[i]);\r\n throw e;\r\n }\r\n }", "public boolean getFlag(int index)\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(ResourceFieldLists.CUSTOM_FLAG, index)));\n }", "public void reformatFile() throws IOException\n {\n List<LineNumberPosition> lineBrokenPositions = new ArrayList<>();\n List<String> brokenLines = breakLines(lineBrokenPositions);\n emitFormatted(brokenLines, lineBrokenPositions);\n }", "public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}", "public static final Boolean parseExtendedAttributeBoolean(String value)\n {\n return ((value.equals(\"1\") ? Boolean.TRUE : Boolean.FALSE));\n }", "public void setWeeklyDaysFromBitmap(Integer days, int[] masks)\n {\n if (days != null)\n {\n int value = days.intValue();\n for (Day day : Day.values())\n {\n setWeeklyDay(day, ((value & masks[day.getValue()]) != 0));\n }\n }\n }" ]
returns a comparator that allows to sort a Vector of FieldMappingDecriptors according to their m_Order entries.
[ "public static Comparator getComparator()\r\n {\r\n return new Comparator()\r\n {\r\n public int compare(Object o1, Object o2)\r\n {\r\n FieldDescriptor fmd1 = (FieldDescriptor) o1;\r\n FieldDescriptor fmd2 = (FieldDescriptor) o2;\r\n if (fmd1.getColNo() < fmd2.getColNo())\r\n {\r\n return -1;\r\n }\r\n else if (fmd1.getColNo() > fmd2.getColNo())\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 0;\r\n }\r\n }\r\n };\r\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 GroovyMethodDoc[] methods() {\n Collections.sort(methods);\n return methods.toArray(new GroovyMethodDoc[methods.size()]);\n }", "public void writeBasicDeclarations() throws RDFHandlerException {\n\t\tfor (Map.Entry<String, String> uriType : Vocabulary\n\t\t\t\t.getKnownVocabularyTypes().entrySet()) {\n\t\t\tthis.rdfWriter.writeTripleUriObject(uriType.getKey(),\n\t\t\t\t\tRdfWriter.RDF_TYPE, uriType.getValue());\n\t\t}\n\t}", "public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}", "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 add(int field)\n {\n if (field < m_flags.length)\n {\n if (m_flags[field] == false)\n {\n m_flags[field] = true;\n m_fields[m_count] = field;\n ++m_count;\n }\n }\n }", "private void parseMacro( TokenList tokens , Sequence sequence ) {\n Macro macro = new Macro();\n\n TokenList.Token t = tokens.getFirst().next;\n\n if( t.word == null ) {\n throw new ParseError(\"Expected the macro's name after \"+tokens.getFirst().word);\n }\n List<TokenList.Token> variableTokens = new ArrayList<TokenList.Token>();\n\n macro.name = t.word;\n t = t.next;\n t = parseMacroInput(variableTokens, t);\n for( TokenList.Token a : variableTokens ) {\n if( a.word == null) throw new ParseError(\"expected word in macro header\");\n macro.inputs.add(a.word);\n }\n t = t.next;\n if( t == null || t.getSymbol() != Symbol.ASSIGN)\n throw new ParseError(\"Expected assignment\");\n t = t.next;\n macro.tokens = new TokenList(t,tokens.last);\n\n sequence.addOperation(macro.createOperation(macros));\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 }", "private static String wordShapeChris4(String s, boolean omitIfInBoundary, Collection<String> knownLCWords) {\r\n int len = s.length();\r\n if (len <= BOUNDARY_SIZE * 2) {\r\n return wordShapeChris4Short(s, len, knownLCWords);\r\n } else {\r\n return wordShapeChris4Long(s, omitIfInBoundary, len, knownLCWords);\r\n }\r\n }" ]
Inits the ws client. @param context the context @throws Exception the exception
[ "private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }" ]
[ "@Override public Integer getOffset(Integer id, Integer type)\n {\n Integer result = null;\n\n Map<Integer, Integer> map = m_table.get(id);\n if (map != null && type != null)\n {\n result = map.get(type);\n }\n\n return (result);\n }", "public static InstalledIdentity load(final InstalledImage installedImage, final ProductConfig productConfig, List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n return LayersFactory.load(installedImage, productConfig, moduleRoots, bundleRoots);\n }", "public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static String resourceProviderFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).providerNamespace() : null;\n }", "private CmsXmlContent unmarshalXmlContent(CmsFile file) throws CmsXmlException {\n\n CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);\n content.setAutoCorrectionEnabled(true);\n content.correctXmlStructure(m_cms);\n\n return content;\n }", "public static aaagroup_authorizationpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_authorizationpolicy_binding obj = new aaagroup_authorizationpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_authorizationpolicy_binding response[] = (aaagroup_authorizationpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "protected ClassDescriptor getClassDescriptor()\r\n {\r\n ClassDescriptor cld = (ClassDescriptor) m_classDescriptor.get();\r\n if(cld == null)\r\n {\r\n throw new OJBRuntimeException(\"Requested ClassDescriptor instance was already GC by JVM\");\r\n }\r\n return cld;\r\n }", "private static void checkPreconditions(final Map<Object, Object> mapping) {\n\t\tif( mapping == null ) {\n\t\t\tthrow new NullPointerException(\"mapping should not be null\");\n\t\t} else if( mapping.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"mapping should not be empty\");\n\t\t}\n\t}", "public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }" ]
Adds a data source to the configuration. If in deduplication mode groupno == 0, otherwise it gives the number of the group to which the data source belongs.
[ "public void addDataSource(int groupno, DataSource datasource) {\n // the loader takes care of validation\n if (groupno == 0)\n datasources.add(datasource);\n else if (groupno == 1)\n group1.add(datasource);\n else if (groupno == 2)\n group2.add(datasource);\n }" ]
[ "@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.fullString) == null) {\n\t\t\tstringCache.fullString = result = toNormalizedString(IPv4StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}", "public StatementGroup findStatementGroup(String propertyIdValue) {\n\t\tif (this.claims.containsKey(propertyIdValue)) {\n\t\t\treturn new StatementGroupImpl(this.claims.get(propertyIdValue));\n\t\t}\n\t\treturn null;\n\t}", "private void readCalendar(Calendar calendar)\n {\n // Create the calendar\n ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();\n mpxjCalendar.setName(calendar.getName());\n\n // Default all days to working\n for (Day day : Day.values())\n {\n mpxjCalendar.setWorkingDay(day, true);\n }\n\n // Mark non-working days\n List<NonWork> nonWorkingDays = calendar.getNonWork();\n for (NonWork nonWorkingDay : nonWorkingDays)\n {\n // TODO: handle recurring exceptions\n if (nonWorkingDay.getType().equals(\"internal_weekly\"))\n {\n mpxjCalendar.setWorkingDay(nonWorkingDay.getWeekday(), false);\n }\n }\n\n // Add default working hours for working days\n for (Day day : Day.values())\n {\n if (mpxjCalendar.isWorkingDay(day))\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "public void addExtentClass(String newExtentClassName)\r\n {\r\n extentClassNames.add(newExtentClassName);\r\n if(m_repository != null) m_repository.addExtent(newExtentClassName, this);\r\n }", "public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {\n final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();\n client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);\n return listener.retrievePreparedOperation();\n }", "private void addUDFValue(FieldTypeClass fieldType, FieldContainer container, Row row)\n {\n Integer fieldId = row.getInteger(\"udf_type_id\");\n String fieldName = m_udfFields.get(fieldId);\n\n Object value = null;\n FieldType field = m_project.getCustomFields().getFieldByAlias(fieldType, fieldName);\n if (field != null)\n {\n DataType fieldDataType = field.getDataType();\n\n switch (fieldDataType)\n {\n case DATE:\n {\n value = row.getDate(\"udf_date\");\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n {\n value = row.getDouble(\"udf_number\");\n break;\n }\n\n case GUID:\n case INTEGER:\n {\n value = row.getInteger(\"udf_code_id\");\n break;\n }\n\n case BOOLEAN:\n {\n String text = row.getString(\"udf_text\");\n if (text != null)\n {\n // before a normal boolean parse, we try to lookup the text as a P6 static type indicator UDF\n value = STATICTYPE_UDF_MAP.get(text);\n if (value == null)\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_text\"));\n }\n }\n else\n {\n value = Boolean.valueOf(row.getBoolean(\"udf_number\"));\n }\n break;\n }\n\n default:\n {\n value = row.getString(\"udf_text\");\n break;\n }\n }\n\n container.set(field, value);\n }\n }", "private void writeFields(String objectName, FieldContainer container, FieldType[] fields) throws IOException\n {\n m_writer.writeStartObject(objectName);\n for (FieldType field : fields)\n {\n Object value = container.getCurrentValue(field);\n if (value != null)\n {\n writeField(field, value);\n }\n }\n m_writer.writeEndObject();\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 parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }" ]
Wraps a StatisticsMatrix around 'm'. Does NOT create a copy of 'm' but saves a reference to it.
[ "public static StatisticsMatrix wrap( DMatrixRMaj m ) {\n StatisticsMatrix ret = new StatisticsMatrix();\n ret.setMatrix( m );\n\n return ret;\n }" ]
[ "static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) {\n int patIdxStart = 0;\n int patIdxEnd = tokenizedPattern.length - 1;\n int strIdxStart = 0;\n int strIdxEnd = strDirs.length - 1;\n\n // up to first '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxStart];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) {\n return false;\n }\n patIdxStart++;\n strIdxStart++;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n } else {\n if (patIdxStart > patIdxEnd) {\n // String not exhausted, but pattern is. Failure.\n return false;\n }\n }\n\n // up to last '**'\n while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {\n String patDir = tokenizedPattern[patIdxEnd];\n if (patDir.equals(DEEP_TREE_MATCH)) {\n break;\n }\n if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) {\n return false;\n }\n patIdxEnd--;\n strIdxEnd--;\n }\n if (strIdxStart > strIdxEnd) {\n // String is exhausted\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n return true;\n }\n\n while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {\n int patIdxTmp = -1;\n for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {\n if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n patIdxTmp = i;\n break;\n }\n }\n if (patIdxTmp == patIdxStart + 1) {\n // '**/**' situation, so skip one\n patIdxStart++;\n continue;\n }\n // Find the pattern between padIdxStart & padIdxTmp in str between\n // strIdxStart & strIdxEnd\n int patLength = (patIdxTmp - patIdxStart - 1);\n int strLength = (strIdxEnd - strIdxStart + 1);\n int foundIdx = -1;\n strLoop:\n for (int i = 0; i <= strLength - patLength; i++) {\n for (int j = 0; j < patLength; j++) {\n String subPat = tokenizedPattern[patIdxStart + j + 1];\n String subStr = strDirs[strIdxStart + i + j];\n if (!match(subPat, subStr, isCaseSensitive)) {\n continue strLoop;\n }\n }\n\n foundIdx = strIdxStart + i;\n break;\n }\n\n if (foundIdx == -1) {\n return false;\n }\n\n patIdxStart = patIdxTmp;\n strIdxStart = foundIdx + patLength;\n }\n\n for (int i = patIdxStart; i <= patIdxEnd; i++) {\n if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) {\n return false;\n }\n }\n\n return true;\n }", "public void purge(String cacheKey) {\n try {\n if (useMemoryCache) {\n if (memoryCache != null) {\n memoryCache.remove(cacheKey);\n }\n }\n\n if (useDiskCache) {\n if (diskLruCache != null) {\n diskLruCache.remove(cacheKey);\n }\n }\n } catch (Exception e) {\n Log.w(TAG, \"Could not remove entry in cache purge\", e);\n }\n }", "public static int convertBytesToInt(byte[] bytes, int offset)\n {\n return (BITWISE_BYTE_TO_INT & bytes[offset + 3])\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8)\n | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16)\n | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24);\n }", "private static DataHandler getDataHandlerForString(Event event) {\n try {\n return new DataHandler(new ByteDataSource(event.getContent().getBytes(\"UTF-8\")));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }", "public GVRAnimation setDuration(float start, float end)\n {\n if(start>end || start<0 || end>mDuration){\n throw new IllegalArgumentException(\"start and end values are wrong\");\n }\n animationOffset = start;\n mDuration = end-start;\n return this;\n }", "protected void append(Object object, String indentation, int index) {\n\t\tif (indentation.length() == 0) {\n\t\t\tappend(object, index);\n\t\t\treturn;\n\t\t}\n\t\tif (object == null)\n\t\t\treturn;\n\t\tif (object instanceof String) {\n\t\t\tappend(indentation, (String)object, index);\n\t\t} else if (object instanceof StringConcatenation) {\n\t\t\tStringConcatenation other = (StringConcatenation) object;\n\t\t\tList<String> otherSegments = other.getSignificantContent();\n\t\t\tappendSegments(indentation, index, otherSegments, other.lineDelimiter);\n\t\t} else if (object instanceof StringConcatenationClient) {\n\t\t\tStringConcatenationClient other = (StringConcatenationClient) object;\n\t\t\tother.appendTo(new IndentedTarget(this, indentation, index));\n\t\t} else {\n\t\t\tfinal String text = getStringRepresentation(object);\n\t\t\tif (text != null) {\n\t\t\t\tappend(indentation, text, index);\n\t\t\t}\n\t\t}\n\t}", "public static void extract( DMatrix src,\n int srcY0, int srcY1,\n int srcX0, int srcX1,\n DMatrix dst ) {\n ((ReshapeMatrix)dst).reshape(srcY1-srcY0,srcX1-srcX0);\n extract(src,srcY0,srcY1,srcX0,srcX1,dst,0,0);\n }", "public static Object[] filterMapToObjectArray(final Map<String, ?> values, final String[] nameMapping) {\n\t\t\n\t\tif( values == null ) {\n\t\t\tthrow new NullPointerException(\"values should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal Object[] targetArray = new Object[nameMapping.length];\n\t\tint i = 0;\n\t\tfor( final String name : nameMapping ) {\n\t\t\ttargetArray[i++] = values.get(name);\n\t\t}\n\t\treturn targetArray;\n\t}", "@SuppressWarnings(\"unchecked\")\n public static Properties readSingleClientConfigAvro(String configAvro) {\n Properties props = new Properties();\n try {\n JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIG_AVRO_SCHEMA, configAvro);\n GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIG_AVRO_SCHEMA);\n Map<Utf8, Utf8> flowMap = (Map<Utf8, Utf8>) datumReader.read(null, decoder);\n for(Utf8 key: flowMap.keySet()) {\n props.put(key.toString(), flowMap.get(key).toString());\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n return props;\n }" ]
1-D Gaussian kernel. @param size Kernel size (should be odd), [3, 101]. @return Returns 1-D Gaussian kernel of the specified size.
[ "public double[] Kernel1D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n int r = size / 2;\n // kernel\n double[] kernel = new double[size];\n\n // compute kernel\n for (int x = -r, i = 0; i < size; x++, i++) {\n kernel[i] = Function1D(x);\n }\n\n return kernel;\n }" ]
[ "public void deleteInactiveContent() throws PatchingException {\n List<File> dirs = getInactiveHistory();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n dirs = getInactiveOverlays();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n }", "public void setNodeMetaData(Object key, Object value) {\n if (key==null) throw new GroovyBugError(\"Tried to set meta data with null key on \"+this+\".\");\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n Object old = metaDataMap.put(key,value);\n if (old!=null) throw new GroovyBugError(\"Tried to overwrite existing meta data \"+this+\".\");\n }", "private void populateRelationList(Task task, TaskField field, String data)\n {\n DeferredRelationship dr = new DeferredRelationship();\n dr.setTask(task);\n dr.setField(field);\n dr.setData(data);\n m_deferredRelationships.add(dr);\n }", "protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{\r\n\t\t// fetch any configured setup sql.\r\n\t\tif (initSQL != null){\r\n\t\t\tStatement stmt = null;\r\n\t\t\ttry{\r\n\t\t\t\tstmt = connection.createStatement();\r\n\t\t\t\tstmt.execute(initSQL);\r\n\t\t\t\tif (testSupport){ // only to aid code coverage, normally set to false\r\n\t\t\t\t\tstmt = null;\r\n\t\t\t\t}\r\n\t\t\t} finally{\r\n\t\t\t\tif (stmt != null){\r\n\t\t\t\t\tstmt.close();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public synchronized void resumeControlPoint(final String entryPoint) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getEntryPoint().equals(entryPoint)) {\n ep.resume();\n }\n }\n }", "public Object copy(Object obj, PersistenceBroker broker)\r\n\t\t\tthrows ObjectCopyException\r\n\t{\r\n\t\tif (obj instanceof OjbCloneable)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\treturn ((OjbCloneable) obj).ojbClone();\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tthrow new ObjectCopyException(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthrow new ObjectCopyException(\"Object must implement OjbCloneable in order to use the\"\r\n\t\t\t\t\t\t\t\t\t\t + \" CloneableObjectCopyStrategy\");\r\n\t\t}\r\n\t}", "private boolean keyAlreadyExists(String newKey) {\n\n Collection<?> itemIds = m_table.getItemIds();\n for (Object itemId : itemIds) {\n if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {\n return true;\n }\n }\n return false;\n }", "public static onlinkipv6prefix get(nitro_service service, String ipv6prefix) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tobj.set_ipv6prefix(ipv6prefix);\n\t\tonlinkipv6prefix response = (onlinkipv6prefix) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {\n return getRetentions(api, new QueryFilter(), fields);\n }" ]
Gets a list of AssignmentRows based on the current Assignments @return
[ "public List<AssignmentRow> getAssignmentRows(VariableType varType) {\n List<AssignmentRow> rows = new ArrayList<AssignmentRow>();\n List<Variable> handledVariables = new ArrayList<Variable>();\n // Create an AssignmentRow for each Assignment\n for (Assignment assignment : assignments) {\n if (assignment.getVariableType() == varType) {\n String dataType = getDisplayNameFromDataType(assignment.getDataType());\n AssignmentRow row = new AssignmentRow(assignment.getName(),\n assignment.getVariableType(),\n dataType,\n assignment.getCustomDataType(),\n assignment.getProcessVarName(),\n assignment.getConstant());\n rows.add(row);\n handledVariables.add(assignment.getVariable());\n }\n }\n List<Variable> vars = null;\n if (varType == VariableType.INPUT) {\n vars = inputVariables;\n } else {\n vars = outputVariables;\n }\n // Create an AssignmentRow for each Variable that doesn't have an Assignment\n for (Variable var : vars) {\n if (!handledVariables.contains(var)) {\n AssignmentRow row = new AssignmentRow(var.getName(),\n var.getVariableType(),\n var.getDataType(),\n var.getCustomDataType(),\n null,\n null);\n rows.add(row);\n }\n }\n\n return rows;\n }" ]
[ "public static Map<String, String[]> mapUrlEncodedParameters(byte[] dataArray) throws Exception {\n Map<String, String[]> mapPostParameters = new HashMap<String, String[]>();\n\n try {\n ByteArrayOutputStream byteout = new ByteArrayOutputStream();\n for (int x = 0; x < dataArray.length; x++) {\n // split the data up by & to get the parts\n if (dataArray[x] == '&' || x == (dataArray.length - 1)) {\n if (x == (dataArray.length - 1)) {\n byteout.write(dataArray[x]);\n }\n // find '=' and split the data up into key value pairs\n int equalsPos = -1;\n ByteArrayOutputStream key = new ByteArrayOutputStream();\n ByteArrayOutputStream value = new ByteArrayOutputStream();\n byte[] byteArray = byteout.toByteArray();\n for (int xx = 0; xx < byteArray.length; xx++) {\n if (byteArray[xx] == '=') {\n equalsPos = xx;\n } else {\n if (equalsPos == -1) {\n key.write(byteArray[xx]);\n } else {\n value.write(byteArray[xx]);\n }\n }\n }\n\n ArrayList<String> values = new ArrayList<String>();\n\n if (mapPostParameters.containsKey(key.toString())) {\n values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(key.toString())));\n mapPostParameters.remove(key.toString());\n }\n\n values.add(value.toString());\n /**\n * If equalsPos is not -1, then there was a '=' for the key\n * If value.size is 0, then there is no value so want to add in the '='\n * Since it will not be added later like params with keys and valued\n */\n if (equalsPos != -1 && value.size() == 0) {\n key.write((byte) '=');\n }\n\n mapPostParameters.put(key.toString(), values.toArray(new String[values.size()]));\n\n byteout = new ByteArrayOutputStream();\n } else {\n byteout.write(dataArray[x]);\n }\n }\n } catch (Exception e) {\n throw new Exception(\"Could not parse request data: \" + e.getMessage());\n }\n\n return mapPostParameters;\n }", "private YearWeek with(int newYear, int newWeek) {\n if (year == newYear && week == newWeek) {\n return this;\n }\n return of(newYear, newWeek);\n }", "public static base_response apply(nitro_service client) throws Exception {\n\t\tnspbr6 applyresource = new nspbr6();\n\t\treturn applyresource.perform_operation(client,\"apply\");\n\t}", "public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) {\n try {\n synchronized(LOCK) {\n if(server.isRegistered(name))\n JmxUtils.unregisterMbean(server, name);\n server.registerMBean(mbean, name);\n }\n } catch(Exception e) {\n logger.error(\"Error registering mbean:\", e);\n }\n }", "private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "public static String changeFirstLetterToCapital(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toUpperCase(a);\n return new String(letras);\n }", "@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public static base_responses reset(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata resetresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new appfwlearningdata();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}", "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 }" ]
Extract the DatabaseTableConfig for a particular class by looking for class and field annotations. This is used by internal classes to configure a class.
[ "public static <T> DatabaseTableConfig<T> fromClass(DatabaseType databaseType, Class<T> clazz) throws SQLException {\n\t\tString tableName = extractTableName(databaseType, clazz);\n\t\tif (databaseType.isEntityNamesMustBeUpCase()) {\n\t\t\ttableName = databaseType.upCaseEntityName(tableName);\n\t\t}\n\t\treturn new DatabaseTableConfig<T>(databaseType, clazz, tableName,\n\t\t\t\textractFieldTypes(databaseType, clazz, tableName));\n\t}" ]
[ "@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}", "public static onlinkipv6prefix[] get(nitro_service service, String ipv6prefix[]) throws Exception{\n\t\tif (ipv6prefix !=null && ipv6prefix.length>0) {\n\t\t\tonlinkipv6prefix response[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tonlinkipv6prefix obj[] = new onlinkipv6prefix[ipv6prefix.length];\n\t\t\tfor (int i=0;i<ipv6prefix.length;i++) {\n\t\t\t\tobj[i] = new onlinkipv6prefix();\n\t\t\t\tobj[i].set_ipv6prefix(ipv6prefix[i]);\n\t\t\t\tresponse[i] = (onlinkipv6prefix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public Map<Integer, String> getSignatures() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<Integer, String>(signatures));\n }", "public RemoteMongoCollection<Document> getCollection(final String collectionName) {\n return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher);\n }", "public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }", "public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) {\n this.downloadRange(output, rangeStart, rangeEnd, null);\n }", "public static IPAddressSeqRange[] join(IPAddressSeqRange... ranges) {\n\t\tint joinedCount = 0;\n\t\tArrays.sort(ranges, Address.ADDRESS_LOW_VALUE_COMPARATOR);\n\t\tfor(int i = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int j = i + 1; j < ranges.length; j++) {\n\t\t\t\tIPAddressSeqRange range2 = ranges[j];\n\t\t\t\tif(range2 == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIPAddress upper = range.getUpper();\n\t\t\t\tIPAddress lower = range2.getLower();\n\t\t\t\tif(compareLowValues(upper, lower) >= 0\n\t\t\t\t\t\t|| upper.increment(1).equals(lower)) {\n\t\t\t\t\t//join them\n\t\t\t\t\tranges[i] = range = range.create(range.getLower(), range2.getUpper());\n\t\t\t\t\tranges[j] = null;\n\t\t\t\t\tjoinedCount++;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t}\n\t\tif(joinedCount == 0) {\n\t\t\treturn ranges;\n\t\t}\n\t\tIPAddressSeqRange joined[] = new IPAddressSeqRange[ranges.length - joinedCount];\n\t\tfor(int i = 0, j = 0; i < ranges.length; i++) {\n\t\t\tIPAddressSeqRange range = ranges[i];\n\t\t\tif(range == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tjoined[j++] = range;\n\t\t\tif(j >= joined.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn joined;\n\t}", "public static Cluster swapRandomPartitionsWithinZone(final Cluster nextCandidateCluster,\n final int zoneId) {\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n Random r = new Random();\n\n List<Integer> nodeIdsInZone = new ArrayList<Integer>(nextCandidateCluster.getNodeIdsInZone(zoneId));\n\n if(nodeIdsInZone.size() == 0) {\n return returnCluster;\n }\n\n // Select random stealer node\n int stealerNodeOffset = r.nextInt(nodeIdsInZone.size());\n Integer stealerNodeId = nodeIdsInZone.get(stealerNodeOffset);\n\n // Select random stealer partition\n List<Integer> stealerPartitions = returnCluster.getNodeById(stealerNodeId)\n .getPartitionIds();\n if(stealerPartitions.size() == 0) {\n return nextCandidateCluster;\n }\n int stealerPartitionOffset = r.nextInt(stealerPartitions.size());\n int stealerPartitionId = stealerPartitions.get(stealerPartitionOffset);\n\n // Select random donor node\n List<Integer> donorNodeIds = new ArrayList<Integer>();\n donorNodeIds.addAll(nodeIdsInZone);\n donorNodeIds.remove(stealerNodeId);\n\n if(donorNodeIds.isEmpty()) { // No donor nodes!\n return returnCluster;\n }\n int donorIdOffset = r.nextInt(donorNodeIds.size());\n Integer donorNodeId = donorNodeIds.get(donorIdOffset);\n\n // Select random donor partition\n List<Integer> donorPartitions = returnCluster.getNodeById(donorNodeId).getPartitionIds();\n int donorPartitionOffset = r.nextInt(donorPartitions.size());\n int donorPartitionId = donorPartitions.get(donorPartitionOffset);\n\n return swapPartitions(returnCluster,\n stealerNodeId,\n stealerPartitionId,\n donorNodeId,\n donorPartitionId);\n }", "public static void registerDataPersisters(DataPersister... dataPersisters) {\n\t\t// we build the map and replace it to lower the chance of concurrency issues\n\t\tList<DataPersister> newList = new ArrayList<DataPersister>();\n\t\tif (registeredPersisters != null) {\n\t\t\tnewList.addAll(registeredPersisters);\n\t\t}\n\t\tfor (DataPersister persister : dataPersisters) {\n\t\t\tnewList.add(persister);\n\t\t}\n\t\tregisteredPersisters = newList;\n\t}" ]
Old SOAP client uses new SOAP service
[ "public void useNewSOAPServiceWithOldClient() throws Exception {\n \n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServicePort();\n\n // The outgoing new Customer data needs to be transformed for \n // the old service to understand it and the response from the old service\n // needs to be transformed for this new client to understand it.\n Client client = ClientProxy.getClient(customerService);\n addTransformInterceptors(client.getInInterceptors(),\n client.getOutInterceptors(),\n false);\n \n System.out.println(\"Using new SOAP CustomerService with old client\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP\");\n printOldCustomerDetails(customer);\n }" ]
[ "private GeometryCoordinateSequenceTransformer getTransformer() {\n\t\tif (unitToPixel == null) {\n\t\t\tunitToPixel = new GeometryCoordinateSequenceTransformer();\n\t\t\tunitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale\n\t\t\t\t\t* panOrigin.x, scale * panOrigin.y)));\n\t\t}\n\t\treturn unitToPixel;\n\t}", "private ProjectFile readFile(File file) throws MPXJException\n {\n try\n {\n String url = \"jdbc:sqlite:\" + file.getAbsolutePath();\n Properties props = new Properties();\n m_connection = org.sqlite.JDBC.createConnection(url, props);\n\n m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n m_dayTimeIntervals = xpath.compile(\"/array/dayTimeInterval\");\n m_entityMap = new HashMap<String, Integer>();\n return read();\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.INVALID_FORMAT, ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n\n m_documentBuilder = null;\n m_dayTimeIntervals = null;\n m_entityMap = null;\n }\n }", "@Override\n public final synchronized void stopService(long millis) {\n running = false;\n try {\n if (keepRunning) {\n keepRunning = false;\n interrupt();\n quit();\n if (0L == millis) {\n join();\n } else {\n join(millis);\n }\n }\n } catch (InterruptedException e) {\n //its possible that the thread exits between the lines keepRunning=false and interrupt above\n log.warn(\"Got interrupted while stopping {}\", this, e);\n\n Thread.currentThread().interrupt();\n }\n }", "public ItemRequest<Project> findById(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"GET\");\n }", "public static float Sum(float[] data) {\r\n float sum = 0;\r\n for (int i = 0; i < data.length; i++) {\r\n sum += data[i];\r\n }\r\n return sum;\r\n }", "public String getSearchJsonModel() throws IOException {\n DbSearch search = new DbSearch();\n search.setArtifacts(new ArrayList<>());\n search.setModules(new ArrayList<>());\n return JsonUtils.serialize(search);\n }", "public void bindSelect(PreparedStatement stmt, Identity oid, ClassDescriptor cld, boolean callableStmt) throws SQLException\r\n {\r\n ValueContainer[] values = null;\r\n int i = 0;\r\n int j = 0;\r\n\r\n if (cld == null)\r\n {\r\n cld = m_broker.getClassDescriptor(oid.getObjectsRealClass());\r\n }\r\n try\r\n {\r\n if(callableStmt)\r\n {\r\n // First argument is the result set\r\n m_platform.registerOutResultSet((CallableStatement) stmt, 1);\r\n j++;\r\n }\r\n\r\n values = getKeyValues(m_broker, cld, oid);\r\n for (/*void*/; i < values.length; i++, j++)\r\n {\r\n setObjectForStatement(stmt, j + 1, values[i].getValue(), values[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindSelect failed for: \" + oid.toString() + \", PK: \" + i + \", value: \" + values[i]);\r\n throw e;\r\n }\r\n }", "public static base_responses unset(nitro_service client, String acl6name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 unsetresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tunsetresources[i] = new nsacl6();\n\t\t\t\tunsetresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "public static void directoryCheck(String dir) throws IOException {\n\t\tfinal File file = new File(dir);\n\n\t\tif (!file.exists()) {\n\t\t\tFileUtils.forceMkdir(file);\n\t\t}\n\t}" ]
Parse request parameters and files. @param request @param response
[ "protected void parseRequest(HttpServletRequest request,\n HttpServletResponse response) {\n requestParams = new HashMap<String, Object>();\n listFiles = new ArrayList<FileItemStream>();\n listFileStreams = new ArrayList<ByteArrayOutputStream>();\n\n // Parse the request\n if (ServletFileUpload.isMultipartContent(request)) {\n // multipart request\n try {\n ServletFileUpload upload = new ServletFileUpload();\n FileItemIterator iter = upload.getItemIterator(request);\n while (iter.hasNext()) {\n FileItemStream item = iter.next();\n String name = item.getFieldName();\n InputStream stream = item.openStream();\n if (item.isFormField()) {\n requestParams.put(name,\n Streams.asString(stream));\n } else {\n String fileName = item.getName();\n if (fileName != null && !\"\".equals(fileName.trim())) {\n listFiles.add(item);\n\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n IOUtils.copy(stream,\n os);\n listFileStreams.add(os);\n }\n }\n }\n } catch (Exception e) {\n logger.error(\"Unexpected error parsing multipart content\",\n e);\n }\n } else {\n // not a multipart\n for (Object mapKey : request.getParameterMap().keySet()) {\n String mapKeyString = (String) mapKey;\n\n if (mapKeyString.endsWith(\"[]\")) {\n // multiple values\n String values[] = request.getParameterValues(mapKeyString);\n List<String> listeValues = new ArrayList<String>();\n for (String value : values) {\n listeValues.add(value);\n }\n requestParams.put(mapKeyString,\n listeValues);\n } else {\n // single value\n String value = request.getParameter(mapKeyString);\n requestParams.put(mapKeyString,\n value);\n }\n }\n }\n }" ]
[ "private LocatorSelectionStrategy getLocatorSelectionStrategy(String locatorSelectionStrategy) {\n if (null == locatorSelectionStrategy) {\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Strategy \" + locatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n\n if (locatorSelectionStrategyMap.containsKey(locatorSelectionStrategy)) {\n return locatorSelectionStrategyMap.get(locatorSelectionStrategy).getInstance();\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"LocatorSelectionStrategy \" + locatorSelectionStrategy\n + \" not registered at LocatorClientEnabler.\");\n }\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n }", "public float rotateToFaceCamera(final Widget widget) {\n final float yaw = getMainCameraRigYaw();\n GVRTransform t = getMainCameraRig().getHeadTransform();\n widget.rotateWithPivot(t.getRotationW(), 0, t.getRotationY(), 0, 0, 0, 0);\n return yaw;\n }", "protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (variableName == null)\n {\n setVariableName(Iteration.getPayloadVariableName(event, context));\n }\n }", "private List<T> computePagedList(List<T> result, HeaderAndBody httpResponse, JSONObject where, Pipe<T> requestingPipe) {\n ReadFilter previousRead = null;\n ReadFilter nextRead = null;\n\n if (PageConfig.MetadataLocations.WEB_LINKING.equals(pageConfig.getMetadataLocation())) {\n String webLinksRaw = \"\";\n final String relHeader = \"rel\";\n final String nextIdentifier = pageConfig.getNextIdentifier();\n final String prevIdentifier = pageConfig.getPreviousIdentifier();\n try {\n webLinksRaw = getWebLinkHeader(httpResponse);\n if (webLinksRaw == null) { // no paging, return result\n return result;\n }\n List<WebLink> webLinksParsed = WebLinkParser.parse(webLinksRaw);\n for (WebLink link : webLinksParsed) {\n if (nextIdentifier.equals(link.getParameters().get(relHeader))) {\n nextRead = new ReadFilter();\n nextRead.setLinkUri(new URI(link.getUri()));\n } else if (prevIdentifier.equals(link.getParameters().get(relHeader))) {\n previousRead = new ReadFilter();\n previousRead.setLinkUri(new URI(link.getUri()));\n }\n\n }\n } catch (URISyntaxException ex) {\n Log.e(TAG, webLinksRaw + \" did not contain a valid context URI\", ex);\n throw new RuntimeException(ex);\n } catch (ParseException ex) {\n Log.e(TAG, webLinksRaw + \" could not be parsed as a web link header\", ex);\n throw new RuntimeException(ex);\n }\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.HEADERS)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.BODY)) {\n nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);\n previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);\n } else {\n throw new IllegalStateException(\"Not supported\");\n }\n if (nextRead != null) {\n nextRead.setWhere(where);\n }\n\n if (previousRead != null) {\n previousRead.setWhere(where);\n }\n\n return new WrappingPagedList<T>(requestingPipe, result, nextRead, previousRead);\n }", "public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }", "void sendError(HttpResponseStatus status, Throwable ex) {\n String msg;\n\n if (ex instanceof InvocationTargetException) {\n msg = String.format(\"Exception Encountered while processing request : %s\", ex.getCause().getMessage());\n } else {\n msg = String.format(\"Exception Encountered while processing request: %s\", ex.getMessage());\n }\n\n // Send the status and message, followed by closing of the connection.\n responder.sendString(status, msg, new DefaultHttpHeaders().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE));\n if (bodyConsumer != null) {\n bodyConsumerError(ex);\n }\n }", "public int getMinutesPerMonth()\n {\n return m_minutesPerMonth == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerMonth()) : m_minutesPerMonth.intValue();\n }", "public void setOccurrences(String occurrences) {\r\n\r\n int o = CmsSerialDateUtil.toIntWithDefault(occurrences, -1);\r\n if (m_model.getOccurrences() != o) {\r\n m_model.setOccurrences(o);\r\n valueChanged();\r\n }\r\n }", "protected String getQueryModifier() {\n\n String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER);\n return (null == queryModifier) && (null != m_baseConfig)\n ? m_baseConfig.getGeneralConfig().getQueryModifier()\n : queryModifier;\n }" ]
Use this API to fetch all the transformpolicy resources that are configured on netscaler.
[ "public static transformpolicy[] get(nitro_service service) throws Exception{\n\t\ttransformpolicy obj = new transformpolicy();\n\t\ttransformpolicy[] response = (transformpolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static <T> String extractTableName(DatabaseType databaseType, Class<T> clazz) {\n\t\tDatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class);\n\t\tString name = null;\n\t\tif (databaseTable != null && databaseTable.tableName() != null && databaseTable.tableName().length() > 0) {\n\t\t\tname = databaseTable.tableName();\n\t\t}\n\t\tif (name == null && javaxPersistenceConfigurer != null) {\n\t\t\tname = javaxPersistenceConfigurer.getEntityName(clazz);\n\t\t}\n\t\tif (name == null) {\n\t\t\t// if the name isn't specified, it is the class name lowercased\n\t\t\tif (databaseType == null) {\n\t\t\t\t// database-type is optional so if it is not specified we just use english\n\t\t\t\tname = clazz.getSimpleName().toLowerCase(Locale.ENGLISH);\n\t\t\t} else {\n\t\t\t\tname = databaseType.downCaseString(clazz.getSimpleName(), true);\n\t\t\t}\n\t\t}\n\t\treturn name;\n\t}", "public static base_responses add(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 addresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new systemuser();\n\t\t\t\taddresources[i].username = resources[i].username;\n\t\t\t\taddresources[i].password = resources[i].password;\n\t\t\t\taddresources[i].externalauth = resources[i].externalauth;\n\t\t\t\taddresources[i].promptstring = resources[i].promptstring;\n\t\t\t\taddresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "@Nullable\n public StitchUserT getUser() {\n authLock.readLock().lock();\n try {\n return activeUser;\n } finally {\n authLock.readLock().unlock();\n }\n }", "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 }", "private Integer getNumId(String idString, boolean isUri) {\n\t\tString numString;\n\t\tif (isUri) {\n\t\t\tif (!idString.startsWith(\"http://www.wikidata.org/entity/\")) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tnumString = idString.substring(\"http://www.wikidata.org/entity/Q\"\n\t\t\t\t\t.length());\n\t\t} else {\n\t\t\tnumString = idString.substring(1);\n\t\t}\n\t\treturn Integer.parseInt(numString);\n\t}", "public static base_response add(nitro_service client, vpath resource) throws Exception {\n\t\tvpath addresource = new vpath();\n\t\taddresource.name = resource.name;\n\t\taddresource.destip = resource.destip;\n\t\taddresource.encapmode = resource.encapmode;\n\t\treturn addresource.add_resource(client);\n\t}", "public static <E> void registerTypeConverter(Class<E> cls, TypeConverter<E> converter) {\n TYPE_CONVERTERS.put(cls, converter);\n }", "public static Type[] getActualTypeArguments(Class<?> clazz) {\n Type type = Types.getCanonicalType(clazz);\n if (type instanceof ParameterizedType) {\n return ((ParameterizedType) type).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\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}" ]
Returns a list of all parts that have been uploaded to an upload session. @param offset paging marker for the list of parts. @param limit maximum number of parts to return. @return the list of parts.
[ "public BoxFileUploadSessionPartList listParts(int offset, int limit) {\n URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint();\n URLTemplate template = new URLTemplate(listPartsURL.toString());\n\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(OFFSET_QUERY_STRING, offset);\n String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString();\n\n //Template is initalized with the full URL. So empty string for the path.\n URL url = template.buildWithQuery(\"\", queryString);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n return new BoxFileUploadSessionPartList(jsonObject);\n }" ]
[ "@SuppressWarnings(\"WeakerAccess\")\n protected boolean isJettyWithJMX(ClassLoaderLeakPreventor preventor) {\n final ClassLoader classLoader = preventor.getClassLoader();\n try {\n // If package org.eclipse.jetty is found, we may be running under jetty\n if (classLoader.getResource(\"org/eclipse/jetty\") == null) {\n return false;\n }\n\n Class.forName(\"org.eclipse.jetty.jmx.MBeanContainer\", false, classLoader.getParent()); // JMX enabled?\n Class.forName(\"org.eclipse.jetty.webapp.WebAppContext\", false, classLoader.getParent());\n }\n catch(Exception ex) { // For example ClassNotFoundException\n return false;\n }\n \n // Seems we are running in Jetty with JMX enabled\n return true;\n }", "public <V> V getAttachment(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.get(key));\n }", "public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }", "public static String multiply(CharSequence self, Number factor) {\n String s = self.toString();\n int size = factor.intValue();\n if (size == 0)\n return \"\";\n else if (size < 0) {\n throw new IllegalArgumentException(\"multiply() should be called with a number of 0 or greater not: \" + size);\n }\n StringBuilder answer = new StringBuilder(s);\n for (int i = 1; i < size; i++) {\n answer.append(s);\n }\n return answer.toString();\n }", "public void setManyToOneAttribute(String name, AssociationValue value) {\n\t\tensureAttributes();\n\t\tAttribute attribute = new ManyToOneAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetAllAttributes().put(name, attribute);\n\n\t}", "public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }", "private RgbaColor withHsl(int index, float value) {\n float[] HSL = convertToHsl();\n HSL[index] = value;\n return RgbaColor.fromHsl(HSL);\n }", "public static base_response Reboot(nitro_service client, reboot resource) throws Exception {\n\t\treboot Rebootresource = new reboot();\n\t\tRebootresource.warm = resource.warm;\n\t\treturn Rebootresource.perform_operation(client);\n\t}", "public static ClientBuilder account(String account) {\n logger.config(\"Account: \" + account);\n return ClientBuilder.url(\n convertStringToURL(String.format(\"https://%s.cloudant.com\", account)));\n }" ]
Find the the qualfied container port of the target service Uses java annotations first or returns the container port. @param service The target service. @param qualifiers The set of qualifiers. @return Returns the resolved containerPort of '0' as a fallback.
[ "private static int getContainerPort(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Port) {\n Port port = (Port) q;\n if (port.value() > 0) {\n return port.value();\n }\n }\n }\n\n ServicePort servicePort = findQualifiedServicePort(service, qualifiers);\n if (servicePort != null) {\n return servicePort.getTargetPort().getIntVal();\n }\n return 0;\n }" ]
[ "public static <K, V> Map<K, V> immutableMapView(Map<K, V> map) {\n if (map instanceof ImmutableMap<?, ?>) {\n return map;\n }\n return Collections.unmodifiableMap(map);\n }", "public static EventType map(Event event) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(event.getTimestamp()));\n eventType.setEventType(convertEventType(event.getEventType()));\n OriginatorType origType = mapOriginator(event.getOriginator());\n eventType.setOriginator(origType);\n MessageInfoType miType = mapMessageInfo(event.getMessageInfo());\n eventType.setMessageInfo(miType);\n eventType.setCustomInfo(convertCustomInfo(event.getCustomInfo()));\n eventType.setContentCut(event.isContentCut());\n if (event.getContent() != null) {\n DataHandler datHandler = getDataHandlerForString(event);\n eventType.setContent(datHandler);\n }\n return eventType;\n }", "public static base_response add(nitro_service client, onlinkipv6prefix resource) throws Exception {\n\t\tonlinkipv6prefix addresource = new onlinkipv6prefix();\n\t\taddresource.ipv6prefix = resource.ipv6prefix;\n\t\taddresource.onlinkprefix = resource.onlinkprefix;\n\t\taddresource.autonomusprefix = resource.autonomusprefix;\n\t\taddresource.depricateprefix = resource.depricateprefix;\n\t\taddresource.decrementprefixlifetimes = resource.decrementprefixlifetimes;\n\t\taddresource.prefixvalidelifetime = resource.prefixvalidelifetime;\n\t\taddresource.prefixpreferredlifetime = resource.prefixpreferredlifetime;\n\t\treturn addresource.add_resource(client);\n\t}", "private Month readOptionalMonth(JSONValue val) {\n\n String str = readOptionalString(val);\n if (null != str) {\n try {\n return Month.valueOf(str);\n } catch (@SuppressWarnings(\"unused\") IllegalArgumentException e) {\n // Do nothing -return the default value\n }\n }\n return null;\n }", "protected String getExtraSolrParams() {\n\n try {\n return m_configObject.getString(JSON_KEY_EXTRASOLRPARAMS);\n } catch (JSONException e) {\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_EXTRA_PARAMETERS_0), e);\n }\n return \"\";\n } else {\n return m_baseConfig.getGeneralConfig().getExtraSolrParams();\n }\n }\n }", "public String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "protected String findPath(String start, String end) {\n if (start.equals(end)) {\n return start;\n } else {\n return findPath(start, parent.get(end)) + \" -> \" + end;\n }\n }", "private String commaSeparate(Collection<String> strings)\n {\n StringBuilder buffer = new StringBuilder();\n Iterator<String> iterator = strings.iterator();\n while (iterator.hasNext())\n {\n String string = iterator.next();\n buffer.append(string);\n if (iterator.hasNext())\n {\n buffer.append(\", \");\n }\n }\n return buffer.toString();\n }", "public ResponseFromManager generateUpdateExecuteTask(ParallelTask task) {\n\n // add to map now; as can only pass final\n ParallelTaskManager.getInstance().addTaskToInProgressMap(\n task.getTaskId(), task);\n logger.info(\"Added task {} to the running inprogress map...\",\n task.getTaskId());\n\n boolean useReplacementVarMap = false;\n boolean useReplacementVarMapNodeSpecific = false;\n Map<String, StrStrMap> replacementVarMapNodeSpecific = null;\n Map<String, String> replacementVarMap = null;\n\n ResponseFromManager batchResponseFromManager = null;\n\n switch (task.getRequestReplacementType()) {\n case UNIFORM_VAR_REPLACEMENT:\n useReplacementVarMap = true;\n useReplacementVarMapNodeSpecific = false;\n replacementVarMap = task.getReplacementVarMap();\n break;\n case TARGET_HOST_SPECIFIC_VAR_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = true;\n replacementVarMapNodeSpecific = task\n .getReplacementVarMapNodeSpecific();\n break;\n case NO_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = false;\n break;\n default:\n logger.error(\"error request replacement type. default as no replacement\");\n }// end switch\n\n // generate content in nodedata\n InternalDataProvider dp = InternalDataProvider.getInstance();\n dp.genNodeDataMap(task);\n\n VarReplacementProvider.getInstance()\n .updateRequestWithReplacement(task, useReplacementVarMap,\n replacementVarMap, useReplacementVarMapNodeSpecific,\n replacementVarMapNodeSpecific);\n\n batchResponseFromManager = \n sendTaskToExecutionManager(task);\n\n removeTaskFromInProgressMap(task.getTaskId());\n logger.info(\n \"Removed task {} from the running inprogress map... \"\n + \". This task should be garbage collected if there are no other pointers.\",\n task.getTaskId());\n return batchResponseFromManager;\n\n }" ]
Obtain host header value for a hostname @param hostName @return
[ "private String getHostHeaderForHost(String hostName) {\n List<ServerRedirect> servers = serverRedirectService.tableServers(requestInformation.get().client.getId());\n for (ServerRedirect server : servers) {\n if (server.getSrcUrl().compareTo(hostName) == 0) {\n String hostHeader = server.getHostHeader();\n if (hostHeader == null || hostHeader.length() == 0) {\n return null;\n }\n return hostHeader;\n }\n }\n return null;\n }" ]
[ "public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }", "private Class getDynamicProxyClass(Class baseClass) {\r\n Class[] m_dynamicProxyClassInterfaces;\r\n if (foundInterfaces.containsKey(baseClass)) {\r\n m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);\r\n } else {\r\n m_dynamicProxyClassInterfaces = getInterfaces(baseClass);\r\n foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);\r\n }\r\n\r\n // return dynymic Proxy Class implementing all interfaces\r\n Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);\r\n return proxyClazz;\r\n }", "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 Release getReleaseInfo(String appName, String releaseName) {\n return connection.execute(new ReleaseInfo(appName, releaseName), apiKey);\n }", "@SuppressWarnings(\"unchecked\")\n public B setTargetType(Class<?> type) {\n Objects.requireNonNull(type);\n set(AbstractQuery.KEY_QUERY_TARGET_TYPE, type);\n return (B) this;\n }", "public static final String printFinishDateTime(Date value)\n {\n if (value != null)\n {\n value = DateHelper.addDays(value, 1);\n }\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }", "public void startAnimation()\n {\n Date time = new Date();\n this.beginAnimation = time.getTime();\n this.endAnimation = beginAnimation + (long) (animationTime * 1000);\n this.animate = true;\n }", "public static String decodeUrl(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"UTF-8\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }", "protected Declaration createDeclaration(String property, Term<?> term)\n {\n Declaration d = CSSFactory.getRuleFactory().createDeclaration();\n d.unlock();\n d.setProperty(property);\n d.add(term);\n return d;\n }" ]
Joins a collection in a string using a delimiter @param col Collection @param delim Delimiter @return String
[ "public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }" ]
[ "public int[] next()\n {\n boolean hasNewPerm = false;\n\n escape:while( level >= 0) {\n// boolean foundZero = false;\n for( int i = iter[level]; i < data.length; i = iter[level] ) {\n iter[level]++;\n\n if( data[i] == -1 ) {\n level++;\n data[i] = level-1;\n\n if( level >= data.length ) {\n // a new permutation has been created return the results.\n hasNewPerm = true;\n System.arraycopy(data,0,ret,0,ret.length);\n level = level-1;\n data[i] = -1;\n break escape;\n } else {\n valk[level] = i;\n }\n }\n }\n\n data[valk[level]] = -1;\n iter[level] = 0;\n level = level-1;\n\n }\n\n if( hasNewPerm )\n return ret;\n return null;\n }", "public static final String printExtendedAttribute(MSPDIWriter writer, Object value, DataType type)\n {\n String result;\n\n if (type == DataType.DATE)\n {\n result = printExtendedAttributeDate((Date) value);\n }\n else\n {\n if (value instanceof Boolean)\n {\n result = printExtendedAttributeBoolean((Boolean) value);\n }\n else\n {\n if (value instanceof Duration)\n {\n result = printDuration(writer, (Duration) value);\n }\n else\n {\n if (type == DataType.CURRENCY)\n {\n result = printExtendedAttributeCurrency((Number) value);\n }\n else\n {\n if (value instanceof Number)\n {\n result = printExtendedAttributeNumber((Number) value);\n }\n else\n {\n result = value.toString();\n }\n }\n }\n }\n }\n\n return (result);\n }", "@Override\n public void process(Step step) {\n step.setName(getName());\n step.setStatus(Status.PASSED);\n step.setStart(System.currentTimeMillis());\n step.setTitle(getTitle());\n }", "@Pure\n\t@Inline(value = \"$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))\",\n\t\t\timported = { MapExtensions.class, Collections.class })\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn union(left, Collections.singletonMap(right.getKey(), right.getValue()));\n\t}", "public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}", "private Date adjustForWholeDay(Date date, boolean isEnd) {\n\n Calendar result = new GregorianCalendar();\n result.setTime(date);\n result.set(Calendar.HOUR_OF_DAY, 0);\n result.set(Calendar.MINUTE, 0);\n result.set(Calendar.SECOND, 0);\n result.set(Calendar.MILLISECOND, 0);\n if (isEnd) {\n result.add(Calendar.DATE, 1);\n }\n\n return result.getTime();\n }", "public void addEvent(Event event) {\n if(event == null)\n throw new IllegalStateException(\"event must be non-null\");\n\n if(logger.isTraceEnabled())\n logger.trace(\"Adding event \" + event);\n\n eventQueue.add(event);\n }", "public static InstalledIdentity load(final InstalledImage installedImage, final ProductConfig productConfig, List<File> moduleRoots, final List<File> bundleRoots) throws IOException {\n return LayersFactory.load(installedImage, productConfig, moduleRoots, bundleRoots);\n }", "private RandomVariable getShortRate(int timeIndex) throws CalculationException {\n\t\tdouble time = getProcess().getTime(timeIndex);\n\t\tdouble timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time;\n\t\tdouble timeNext = getProcess().getTime(timeIndex+1);\n\n\t\tRandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);\n\n\t\tRandomVariable alpha = getDV(0, time);\n\n\t\tRandomVariable value = getProcess().getProcessValue(timeIndex, 0);\n\t\tvalue = value.add(alpha);\n\t\t//\t\tvalue = value.sub(Math.log(value.exp().getAverage()));\n\n\t\tvalue = value.add(zeroRate);\n\n\t\treturn value;\n\t}" ]
1.5 and on, 2.0 and on, 3.0 and on.
[ "private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {\n ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);\n ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);\n\n list.add(ldapAuthorization);\n\n Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n required.remove(attribute);\n switch (attribute) {\n case CONNECTION: {\n LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);\n break;\n }\n default: {\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n }\n\n if (required.isEmpty() == false) {\n throw missingRequired(reader, required);\n }\n\n Set<Element> foundElements = new HashSet<Element>();\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n if (foundElements.add(element) == false) {\n throw unexpectedElement(reader); // Only one of each allowed.\n }\n switch (element) {\n case USERNAME_TO_DN: {\n switch (namespace.getMajorVersion()) {\n case 1: // 1.5 up to but not including 2.0\n parseUsernameToDn_1_5(reader, addr, list);\n break;\n default: // 2.0 and onwards\n parseUsernameToDn_2_0(reader, addr, list);\n break;\n }\n\n break;\n }\n case GROUP_SEARCH: {\n switch (namespace) {\n case DOMAIN_1_5:\n case DOMAIN_1_6:\n parseGroupSearch_1_5(reader, addr, list);\n break;\n default:\n parseGroupSearch_1_7_and_2_0(reader, addr, list);\n break;\n }\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }" ]
[ "public ItemRequest<Tag> findById(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"GET\");\n }", "public static void validate(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n try {\n validateEmpty(bic);\n validateLength(bic);\n validateCase(bic);\n validateBankCode(bic);\n validateCountryCode(bic);\n validateLocationCode(bic);\n\n if(hasBranchCode(bic)) {\n validateBranchCode(bic);\n }\n } catch (UnsupportedCountryException e) {\n throw e;\n } catch (RuntimeException e) {\n throw new BicFormatException(UNKNOWN, e.getMessage());\n }\n }", "private static String loadUA(ClassLoader loader, String filename){\n String ua = \"cloudant-http\";\n String version = \"unknown\";\n final InputStream propStream = loader.getResourceAsStream(filename);\n final Properties properties = new Properties();\n try {\n if (propStream != null) {\n try {\n properties.load(propStream);\n } finally {\n propStream.close();\n }\n }\n ua = properties.getProperty(\"user.agent.name\", ua);\n version = properties.getProperty(\"user.agent.version\", version);\n } catch (IOException e) {\n // Swallow exception and use default values.\n }\n\n return String.format(Locale.ENGLISH, \"%s/%s\", ua,version);\n }", "public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }", "public JSONObject toJSON() {\n try {\n return new JSONObject(properties).putOpt(\"name\", getName());\n } catch (JSONException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"toJSON()\");\n throw new RuntimeAssertion(\"NodeEntry.toJSON() failed for '%s'\", this);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }", "void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }", "@Override\n public final String getString(final int i) {\n String val = this.array.optString(i, null);\n if (val == null) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return val;\n }", "public Day getDayOfWeek()\n {\n Day result = null;\n if (!m_days.isEmpty())\n {\n result = m_days.iterator().next();\n }\n return result;\n }" ]
Try to get the line number associated with the given member. The reflection API does not expose such an info and so we need to analyse the bytecode. Unfortunately, it seems there is no way to get this kind of information for fields. Moreover, the <code>LineNumberTable</code> attribute is just optional, i.e. the compiler is not required to store this information at all. See also <a href="http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.1">Java Virtual Machine Specification</a> Implementation note: it wouldn't be appropriate to add a bytecode scanning dependency just for this functionality, therefore Apache BCEL included in Oracle JDK 1.5+ and OpenJDK 1.6+ is used. Other JVMs should not crash as we only use it if it's on the classpath and by means of reflection calls. @param member @param resourceLoader @return the line number or 0 if it's not possible to find it
[ "public static int getLineNumber(Member member) {\n\n if (!(member instanceof Method || member instanceof Constructor)) {\n // We are not able to get this info for fields\n return 0;\n }\n\n // BCEL is an optional dependency, if we cannot load it, simply return 0\n if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) {\n return 0;\n }\n\n String classFile = member.getDeclaringClass().getName().replace('.', '/');\n ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader());\n InputStream in = null;\n\n try {\n URL classFileUrl = classFileResourceLoader.getResource(classFile + \".class\");\n\n if (classFileUrl == null) {\n // The class file is not available\n return 0;\n }\n in = classFileUrl.openStream();\n\n ClassParser cp = new ClassParser(in, classFile);\n JavaClass javaClass = cp.parse();\n\n // First get all declared methods and constructors\n // Note that in bytecode constructor is translated into a method\n org.apache.bcel.classfile.Method[] methods = javaClass.getMethods();\n org.apache.bcel.classfile.Method match = null;\n\n String signature;\n String name;\n if (member instanceof Method) {\n signature = DescriptorUtils.methodDescriptor((Method) member);\n name = member.getName();\n } else if (member instanceof Constructor) {\n signature = DescriptorUtils.makeDescriptor((Constructor<?>) member);\n name = INIT_METHOD_NAME;\n } else {\n return 0;\n }\n\n for (org.apache.bcel.classfile.Method method : methods) {\n // Matching method must have the same name, modifiers and signature\n if (method.getName().equals(name)\n && member.getModifiers() == method.getModifiers()\n && method.getSignature().equals(signature)) {\n match = method;\n }\n }\n if (match != null) {\n // If a method is found, try to obtain the optional LineNumberTable attribute\n LineNumberTable lineNumberTable = match.getLineNumberTable();\n if (lineNumberTable != null) {\n int line = lineNumberTable.getSourceLine(0);\n return line == -1 ? 0 : line;\n }\n }\n // No suitable method found\n return 0;\n\n } catch (Throwable t) {\n return 0;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (Exception e) {\n return 0;\n }\n }\n }\n }" ]
[ "public void setText(String text) {\n span.setText(text);\n\n if (!span.isAttached()) {\n add(span);\n }\n }", "ResultAction executeOperation() {\n\n assert isControllingThread();\n try {\n /** Execution has begun */\n executing = true;\n\n processStages();\n\n if (resultAction == ResultAction.KEEP) {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());\n } else {\n report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());\n }\n } catch (RuntimeException e) {\n handleUncaughtException(e);\n ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);\n } finally {\n // On failure close any attached response streams\n if (resultAction != ResultAction.KEEP && !isBooting()) {\n synchronized (this) {\n if (responseStreams != null) {\n int i = 0;\n for (OperationResponse.StreamEntry is : responseStreams.values()) {\n try {\n is.getStream().close();\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.debugf(e, \"Failed closing stream at index %d\", i);\n }\n i++;\n }\n responseStreams.clear();\n }\n }\n }\n }\n\n\n return resultAction;\n }", "public List<Integer> getConnectionRetries() {\n List<Integer> items = new ArrayList<Integer>();\n for (int i = 0; i < 10; i++) {\n items.add(i);\n }\n return items;\n }", "public boolean isIdentical(T a, double tol) {\n if( a.getType() != getType() )\n return false;\n return ops.isIdentical(mat,a.mat,tol);\n }", "public AT_Row setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private boolean matchesFingerprint(byte[] buffer, byte[] fingerprint)\n {\n return Arrays.equals(fingerprint, Arrays.copyOf(buffer, fingerprint.length));\n }", "public int getShort(Integer id, Integer type)\n {\n int result = 0;\n\n Integer offset = m_meta.getOffset(id, type);\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n\n if (value != null && value.length >= 2)\n {\n result = MPPUtility.getShort(value, 0);\n }\n }\n\n return (result);\n }", "public static AccumuloClient getClient(FluoConfiguration config) {\n return Accumulo.newClient().to(config.getAccumuloInstance(), config.getAccumuloZookeepers())\n .as(config.getAccumuloUser(), config.getAccumuloPassword()).build();\n }", "public <T> T fetchObject(String objectId, Class<T> type) {\n\t\tURI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build();\n\t\treturn getRestTemplate().getForObject(uri, type);\n\t}" ]
Register the given object under the package name of the object's class with the given type name. this method using the platform mbean server as returned by ManagementFactory.getPlatformMBeanServer() @param typeName The name of the type to register @param obj The object to register as an mbean
[ "public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }" ]
[ "public void reset() {\n\t\tCrawlSession session = context.getSession();\n\t\tif (crawlpath != null) {\n\t\t\tsession.addCrawlPath(crawlpath);\n\t\t}\n\t\tList<StateVertex> onURLSetTemp = new ArrayList<>();\n\t\tif (stateMachine != null)\n\t\t\tonURLSetTemp = stateMachine.getOnURLSet();\n\t\tstateMachine = new StateMachine(graphProvider.get(), crawlRules.getInvariants(), plugins,\n\t\t\t\tstateComparator, onURLSetTemp);\n\t\tcontext.setStateMachine(stateMachine);\n\t\tcrawlpath = new CrawlPath();\n\t\tcontext.setCrawlPath(crawlpath);\n\t\tbrowser.handlePopups();\n\t\tbrowser.goToUrl(url);\n\t\t// Checks the landing page for URL and sets the current page accordingly\n\t\tcheckOnURLState();\n\t\tplugins.runOnUrlLoadPlugins(context);\n\t\tcrawlDepth.set(0);\n\t}", "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "public static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }", "private void setTempoMaster(DeviceUpdate newMaster) {\n DeviceUpdate oldMaster = tempoMaster.getAndSet(newMaster);\n if ((newMaster == null && oldMaster != null) ||\n (newMaster != null && ((oldMaster == null) || !newMaster.getAddress().equals(oldMaster.getAddress())))) {\n // This is a change in master, so report it to any registered listeners\n deliverMasterChangedAnnouncement(newMaster);\n }\n }", "public PhotoContext getContext(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n PhotoContext photoContext = new PhotoContext();\r\n Collection<Element> payload = response.getPayloadCollection();\r\n for (Element payloadElement : payload) {\r\n String tagName = payloadElement.getTagName();\r\n if (tagName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (tagName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setNextPhoto(photo);\r\n }\r\n }\r\n return photoContext;\r\n }", "private void processHyperlinkData(ResourceAssignment assignment, byte[] data)\n {\n if (data != null)\n {\n int offset = 12;\n\n offset += 12;\n String hyperlink = MPPUtility.getUnicodeString(data, offset);\n offset += ((hyperlink.length() + 1) * 2);\n\n offset += 12;\n String address = MPPUtility.getUnicodeString(data, offset);\n offset += ((address.length() + 1) * 2);\n\n offset += 12;\n String subaddress = MPPUtility.getUnicodeString(data, offset);\n offset += ((subaddress.length() + 1) * 2);\n\n offset += 12;\n String screentip = MPPUtility.getUnicodeString(data, offset);\n\n assignment.setHyperlink(hyperlink);\n assignment.setHyperlinkAddress(address);\n assignment.setHyperlinkSubAddress(subaddress);\n assignment.setHyperlinkScreenTip(screentip);\n }\n }", "private static void listResources(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Resource: \" + resource.getName() + \" (Unique ID=\" + resource.getUniqueID() + \") Start=\" + resource.getStart() + \" Finish=\" + resource.getFinish());\n }\n System.out.println();\n }", "public void rotateWithPivot(float w, float x, float y, float z,\n float pivotX, float pivotY, float pivotZ) {\n getTransform().rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ);\n if (mTransformCache.rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ)) {\n onTransformChanged();\n }\n }" ]
Use this API to enable the feature on Netscaler. @param feature feature to be enabled. @return status of the operation performed. @throws Exception Nitro exception.
[ "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 PhotoList<Photo> searchInterestingness(SearchParameters params, 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_INTERESTINGNESS);\r\n\r\n parameters.putAll(params.getAsParameters());\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 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 Photo photo = new Photo();\r\n photo.setId(photoElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photoElement.getAttribute(\"owner\"));\r\n photo.setOwner(owner);\r\n\r\n photo.setSecret(photoElement.getAttribute(\"secret\"));\r\n photo.setServer(photoElement.getAttribute(\"server\"));\r\n photo.setFarm(photoElement.getAttribute(\"farm\"));\r\n photo.setTitle(photoElement.getAttribute(\"title\"));\r\n photo.setPublicFlag(\"1\".equals(photoElement.getAttribute(\"ispublic\")));\r\n photo.setFriendFlag(\"1\".equals(photoElement.getAttribute(\"isfriend\")));\r\n photo.setFamilyFlag(\"1\".equals(photoElement.getAttribute(\"isfamily\")));\r\n photos.add(photo);\r\n }\r\n return photos;\r\n }", "private List<StyleFilter> initStyleFilters(List<FeatureStyleInfo> styleDefinitions) throws GeomajasException {\n\t\tList<StyleFilter> styleFilters = new ArrayList<StyleFilter>();\n\t\tif (styleDefinitions == null || styleDefinitions.size() == 0) {\n\t\t\tstyleFilters.add(new StyleFilterImpl()); // use default.\n\t\t} else {\n\t\t\tfor (FeatureStyleInfo styleDef : styleDefinitions) {\n\t\t\t\tStyleFilterImpl styleFilterImpl = null;\n\t\t\t\tString formula = styleDef.getFormula();\n\t\t\t\tif (null != formula && formula.length() > 0) {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(filterService.parseFilter(formula), styleDef);\n\t\t\t\t} else {\n\t\t\t\t\tstyleFilterImpl = new StyleFilterImpl(Filter.INCLUDE, styleDef);\n\t\t\t\t}\n\t\t\t\tstyleFilters.add(styleFilterImpl);\n\t\t\t}\n\t\t}\n\t\treturn styleFilters;\n\t}", "private static boolean isDpiSet(final Multimap<String, String> extraParams) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n for (String value: extraParams.get(key)) {\n if (value.toLowerCase().contains(\"dpi:\")) {\n return true;\n }\n }\n }\n }\n return false;\n }", "private void reply(final String response, final boolean error,\n final String errorMessage, final String stackTrace,\n final String statusCode, final int statusCodeInt) {\n\n \n if (!sentReply) {\n \n //must update sentReply first to avoid duplicated msg.\n sentReply = true;\n // Close the connection. Make sure the close operation ends because\n // all I/O operations are asynchronous in Netty.\n if(channel!=null && channel.isOpen())\n channel.close().awaitUninterruptibly();\n final ResponseOnSingeRequest res = new ResponseOnSingeRequest(\n response, error, errorMessage, stackTrace, statusCode,\n statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(), null);\n if (!getContext().system().deadLetters().equals(sender)) {\n sender.tell(res, getSelf());\n }\n if (getContext() != null) {\n getContext().stop(getSelf());\n }\n }\n\n }", "private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }", "public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> iterators) {\n Preconditions.checkArgumentNotNull(iterators, \"iterators\");\n return new CombinedIterator<T>(iterators);\n }", "@SuppressWarnings(\"deprecation\")\n @RequestMapping(value = \"/api/backup\", method = RequestMethod.GET)\n public\n @ResponseBody\n String getBackup(Model model, HttpServletResponse response) throws Exception {\n response.addHeader(\"Content-Disposition\", \"attachment; filename=backup.json\");\n response.setContentType(\"application/json\");\n\n Backup backup = BackupService.getInstance().getBackupData();\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();\n\n return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);\n }", "private JSONValue dateToJson(Date d) {\n\n return null != d ? new JSONString(Long.toString(d.getTime())) : null;\n }", "public static void dumpRow(Map<String, Object> row)\n {\n for (Entry<String, Object> entry : row.entrySet())\n {\n Object value = entry.getValue();\n System.out.println(entry.getKey() + \" = \" + value + \" ( \" + (value == null ? \"\" : value.getClass().getName()) + \")\");\n }\n }" ]
Opens file for editing. @param currentChangeListId The current change list id to open the file for editing at @param filePath The filePath which contains the file we need to edit @throws IOException Thrown in case of perforce communication errors @throws InterruptedException
[ "public void edit(int currentChangeListId, FilePath filePath) throws Exception {\n establishConnection().editFile(currentChangeListId, new File(filePath.getRemote()));\n }" ]
[ "public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException {\n\t\tString[] split = signedRequest.split(\"\\\\.\");\n\t\tString encodedSignature = split[0];\n\t\tString payload = split[1];\t\t\n\t\tString decoded = base64DecodeToString(payload);\t\t\n\t\tbyte[] signature = base64DecodeToBytes(encodedSignature);\n\t\ttry {\n\t\t\tT data = objectMapper.readValue(decoded, type);\t\t\t\n\t\t\tString algorithm = objectMapper.readTree(decoded).get(\"algorithm\").textValue();\n\t\t\tif (algorithm == null || !algorithm.equals(\"HMAC-SHA256\")) {\n\t\t\t\tthrow new SignedRequestException(\"Unknown encryption algorithm: \" + algorithm);\n\t\t\t}\t\t\t\n\t\t\tbyte[] expectedSignature = encrypt(payload, secret);\n\t\t\tif (!Arrays.equals(expectedSignature, signature)) {\n\t\t\t\tthrow new SignedRequestException(\"Invalid signature.\");\n\t\t\t}\t\t\t\n\t\t\treturn data;\n\t\t} catch (IOException e) {\n\t\t\tthrow new SignedRequestException(\"Error parsing payload.\", e);\n\t\t}\n\t}", "public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize,\n long totalSizeOfFile) {\n\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n //Read the partSize bytes from the stream\n byte[] bytes = new byte[partSize];\n try {\n stream.read(bytes);\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading data from stream failed.\", ioe);\n }\n\n return this.uploadPart(bytes, offset, partSize, totalSizeOfFile);\n }", "public ImmutableMap<String, String> getConfigurationTweak(String dbModuleName)\n {\n final DbInfo db = cluster.getNextDb();\n return ImmutableMap.of(\"ness.db.\" + dbModuleName + \".uri\", getJdbcUri(db),\n \"ness.db.\" + dbModuleName + \".ds.user\", db.user);\n }", "boolean lockShared(final Integer permit, final long timeout, final TimeUnit unit) {\n boolean result = false;\n try {\n result = lockSharedInterruptibly(permit, timeout, unit);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return result;\n }", "public static ResourceField getMpxjField(int value)\n {\n ResourceField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }", "public Character getCharacter(int field)\n {\n Character result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Character.valueOf(m_fields[field].charAt(0));\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public boolean forall(PixelPredicate predicate) {\n return Arrays.stream(points()).allMatch(p -> predicate.test(p.x, p.y, pixel(p)));\n }", "public int getCount(Class target)\r\n {\r\n PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();\r\n int result = broker.getCount(new QueryByCriteria(target));\r\n return result;\r\n }", "public void refreshConnection() throws SQLException{\r\n\t\tthis.connection.close(); // if it's still in use, close it.\r\n\t\ttry{\r\n\t\t\tthis.connection = this.pool.obtainRawInternalConnection();\r\n\t\t} catch(SQLException e){\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}" ]
Tries to load a property file with the specified name. @param localizedName the name @return the resource bundle if it was loaded, otherwise the backup
[ "private static I_CmsResourceBundle tryBundle(String localizedName) {\n\n I_CmsResourceBundle result = null;\n\n try {\n\n String resourceName = localizedName.replace('.', '/') + \".properties\";\n URL url = CmsResourceBundleLoader.class.getClassLoader().getResource(resourceName);\n\n I_CmsResourceBundle additionalBundle = m_permanentCache.get(localizedName);\n if (additionalBundle != null) {\n result = additionalBundle.getClone();\n } else if (url != null) {\n // the resource was found on the file system\n InputStream is = null;\n String path = CmsFileUtil.normalizePath(url);\n File file = new File(path);\n try {\n // try to load the resource bundle from a file, NOT with the resource loader first\n // this is important since using #getResourceAsStream() may return cached results,\n // for example Tomcat by default does cache all resources loaded by the class loader\n // this means a changed resource bundle file is not loaded\n is = new FileInputStream(file);\n } catch (IOException ex) {\n // this will happen if the resource is contained for example in a .jar file\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n } catch (AccessControlException acex) {\n // fixed bug #1550\n // this will happen if the resource is contained for example in a .jar file\n // and security manager is turned on.\n is = CmsResourceBundleLoader.class.getClassLoader().getResourceAsStream(resourceName);\n }\n if (is != null) {\n result = new CmsPropertyResourceBundle(is);\n }\n }\n } catch (IOException ex) {\n // can't localized these message since this may lead to a chicken-egg problem\n MissingResourceException mre = new MissingResourceException(\n \"Failed to load bundle '\" + localizedName + \"'\",\n localizedName,\n \"\");\n mre.initCause(ex);\n throw mre;\n }\n\n return result;\n }" ]
[ "private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) {\n if (soyMsgBundles.isEmpty()) {\n return Optional.absent();\n }\n\n final List<SoyMsg> msgs = Lists.newArrayList();\n for (final SoyMsgBundle smb : soyMsgBundles) {\n for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) {\n msgs.add(it.next());\n }\n }\n\n return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs));\n }", "public boolean startsWith(Bytes prefix) {\n Objects.requireNonNull(prefix, \"startWith(Bytes prefix) cannot have null parameter\");\n\n if (prefix.length > this.length) {\n return false;\n } else {\n int end = this.offset + prefix.length;\n for (int i = this.offset, j = prefix.offset; i < end; i++, j++) {\n if (this.data[i] != prefix.data[j]) {\n return false;\n }\n }\n }\n return true;\n }", "public void setDynamicValue(String attribute, String value) {\n\n if (null == m_dynamicValues) {\n m_dynamicValues = new ConcurrentHashMap<String, String>();\n }\n m_dynamicValues.put(attribute, value);\n }", "private void initKeySetForXmlBundle() {\n\n // consider only available locales\n for (Locale l : m_locales) {\n if (m_xmlBundle.hasLocale(l)) {\n Set<Object> keys = new HashSet<Object>();\n for (I_CmsXmlContentValue msg : m_xmlBundle.getValueSequence(\"Message\", l).getValues()) {\n String msgpath = msg.getPath();\n keys.add(m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", l));\n }\n m_keyset.updateKeySet(null, keys);\n }\n }\n\n }", "public TransformersSubRegistration getDomainRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS;\n return new TransformersSubRegistrationImpl(range, domain, address);\n }", "public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() {\n\t\treturn Collections.unmodifiableMap( associationsKeyValueStorage );\n\t}", "public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }", "@Override\n public void run() {\n try {\n threadContext.activate();\n // run the original thread\n runnable.run();\n } finally {\n threadContext.invalidate();\n threadContext.deactivate();\n }\n\n }", "private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) {\n if (soyMsgBundles.isEmpty()) {\n return Optional.absent();\n }\n\n final List<SoyMsg> msgs = Lists.newArrayList();\n for (final SoyMsgBundle smb : soyMsgBundles) {\n for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) {\n msgs.add(it.next());\n }\n }\n\n return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs));\n }" ]
Deserialize a directory of javascript design documents to a List of DesignDocument objects. @param directory the directory containing javascript files @return {@link DesignDocument} @throws FileNotFoundException if the file does not exist or cannot be read
[ "public static List<DesignDocument> fromDirectory(File directory) throws FileNotFoundException {\r\n List<DesignDocument> designDocuments = new ArrayList<DesignDocument>();\r\n if (directory.isDirectory()) {\r\n Collection<File> files = FileUtils.listFiles(directory, null, true);\r\n for (File designDocFile : files) {\r\n designDocuments.add(fromFile(designDocFile));\r\n }\r\n } else {\r\n designDocuments.add(fromFile(directory));\r\n }\r\n return designDocuments;\r\n }" ]
[ "public void clearMarkers() {\n if (markers != null && !markers.isEmpty()) {\n markers.forEach((m) -> {\n m.setMap(null);\n });\n markers.clear();\n }", "@Override\r\n public String upload(byte[] data, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(data);\r\n return sendUploadRequest(metaData, payload);\r\n }", "public void setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(charTranslator!=null){\r\n\t\t\tthis.charTranslator = charTranslator;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}", "public void layoutChildren() {\n\n Set<Integer> copySet;\n synchronized (mMeasuredChildren) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"layoutChildren [%d] layout = %s\",\n mMeasuredChildren.size(), this);\n copySet = new HashSet<>(mMeasuredChildren);\n }\n for (int nextMeasured: copySet) {\n Widget child = mContainer.get(nextMeasured);\n if (child != null) {\n child.preventTransformChanged(true);\n layoutChild(nextMeasured);\n postLayoutChild(nextMeasured);\n child.preventTransformChanged(false);\n }\n\n }\n }", "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 spilloverpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy_lbvserver_binding obj = new spilloverpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy_lbvserver_binding response[] = (spilloverpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void sendJsonToUrl(Object data, String url) {\n sendToUrl(JSON.toJSONString(data), url);\n }", "private void injectAdditionalStyles() {\n\n try {\n Collection<String> stylesheets = OpenCms.getWorkplaceAppManager().getAdditionalStyleSheets();\n for (String stylesheet : stylesheets) {\n A_CmsUI.get().getPage().addDependency(new Dependency(Type.STYLESHEET, stylesheet));\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n }", "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 }" ]
Closes any registered stream entries that have not yet been consumed
[ "public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }" ]
[ "public 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 static void zeroTriangle( boolean upper , DMatrixRBlock A )\n {\n int blockLength = A.blockLength;\n\n if( upper ) {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = i; j < A.numCols; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n for( int l = k+1; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n } else {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = 0; j <= i; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n int z = Math.min(k,w);\n for( int l = 0; l < z; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n }\n }", "public void setInitialSequence(int[] sequence) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].setInitialSequence(sequence);\r\n return;\r\n }\r\n model1.setInitialSequence(sequence);\r\n model2.setInitialSequence(sequence);\r\n }", "public Optional<URL> getRoute(String routeName) {\n Route route = getClient().routes()\n .inNamespace(namespace).withName(routeName).get();\n\n return route != null ? Optional.ofNullable(createUrlFromRoute(route)) : Optional.empty();\n }", "public EventBus emitSync(String event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }", "PollingState<T> withStatus(String status, int statusCode) throws IllegalArgumentException {\n if (status == null) {\n throw new IllegalArgumentException(\"Status is null.\");\n }\n this.status = status;\n this.statusCode = statusCode;\n return this;\n }", "protected int _countPeriods(String str)\n {\n int commas = 0;\n for (int i = 0, end = str.length(); i < end; ++i) {\n int ch = str.charAt(i);\n if (ch < '0' || ch > '9') {\n if (ch == '.') {\n ++commas;\n } else {\n return -1;\n }\n }\n }\n return commas;\n }", "protected void cacheCollection() {\n this.clear();\n for (FluentModelTImpl childResource : this.listChildResources()) {\n this.childCollection.put(childResource.childResourceKey(), childResource);\n }\n }", "private void createAndLockDescriptorFile() throws CmsException {\n\n String sitePath = m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX;\n m_desc = m_cms.createResource(\n sitePath,\n OpenCms.getResourceManager().getResourceType(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString()));\n m_descFile = LockedFile.lockResource(m_cms, m_desc);\n m_descFile.setCreated(true);\n }" ]
Use this API to fetch lbmonitor_binding resources of given names .
[ "public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{\n\t\tif (monitorname !=null && monitorname.length>0) {\n\t\t\tlbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];\n\t\t\tlbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];\n\t\t\tfor (int i=0;i<monitorname.length;i++) {\n\t\t\t\tobj[i] = new lbmonitor_binding();\n\t\t\t\tobj[i].set_monitorname(monitorname[i]);\n\t\t\t\tresponse[i] = (lbmonitor_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "public static int getXPathLocation(String dom, String xpath) {\n\t\tString dom_lower = dom.toLowerCase();\n\t\tString xpath_lower = xpath.toLowerCase();\n\t\tString[] elements = xpath_lower.split(\"/\");\n\t\tint pos = 0;\n\t\tint temp;\n\t\tint number;\n\t\tfor (String element : elements) {\n\t\t\tif (!element.isEmpty() && !element.startsWith(\"@\") && !element.contains(\"()\")) {\n\t\t\t\tif (element.contains(\"[\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnumber =\n\t\t\t\t\t\t\t\tInteger.parseInt(element.substring(element.indexOf(\"[\") + 1,\n\t\t\t\t\t\t\t\t\t\telement.indexOf(\"]\")));\n\t\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnumber = 1;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < number; i++) {\n\t\t\t\t\t// find new open element\n\t\t\t\t\ttemp = dom_lower.indexOf(\"<\" + stripEndSquareBrackets(element), pos);\n\n\t\t\t\t\tif (temp > -1) {\n\t\t\t\t\t\tpos = temp + 1;\n\n\t\t\t\t\t\t// if depth>1 then goto end of current element\n\t\t\t\t\t\tif (number > 1 && i < number - 1) {\n\t\t\t\t\t\t\tpos =\n\t\t\t\t\t\t\t\t\tgetCloseElementLocation(dom_lower, pos,\n\t\t\t\t\t\t\t\t\t\t\tstripEndSquareBrackets(element));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pos - 1;\n\t}", "public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }", "protected void appenHtmlFooter(StringBuffer buffer) {\n\n if (m_configuredFooter != null) {\n buffer.append(m_configuredFooter);\n } else {\n buffer.append(\" </body>\\r\\n\" + \"</html>\");\n }\n }", "public static final String printDuration(Duration value)\n {\n return value == null ? null : Double.toString(value.getDuration());\n }", "public RenderScript getRenderScript() {\n if (renderScript == null) {\n renderScript = RenderScript.create(context, renderScriptContextType);\n }\n return renderScript;\n }", "protected TokenList.Token parseBlockNoParentheses(TokenList tokens, Sequence sequence, boolean insideMatrixConstructor) {\n\n // search for matrix bracket operations\n if( !insideMatrixConstructor ) {\n parseBracketCreateMatrix(tokens, sequence);\n }\n\n // First create sequences from anything involving a colon\n parseSequencesWithColons(tokens, sequence );\n\n // process operators depending on their priority\n parseNegOp(tokens, sequence);\n parseOperationsL(tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.POWER, Symbol.ELEMENT_POWER}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.TIMES, Symbol.RDIVIDE, Symbol.LDIVIDE, Symbol.ELEMENT_TIMES, Symbol.ELEMENT_DIVIDE}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.PLUS, Symbol.MINUS}, tokens, sequence);\n\n // Commas are used in integer sequences. Can be used to force to compiler to treat - as negative not\n // minus. They can now be removed since they have served their purpose\n stripCommas(tokens);\n\n // now construct rest of the lists and combine them together\n parseIntegerLists(tokens);\n parseCombineIntegerLists(tokens);\n\n if( !insideMatrixConstructor ) {\n if (tokens.size() > 1) {\n System.err.println(\"Remaining tokens: \"+tokens.size);\n TokenList.Token t = tokens.first;\n while( t != null ) {\n System.err.println(\" \"+t);\n t = t.next;\n }\n throw new RuntimeException(\"BUG in parser. There should only be a single token left\");\n }\n return tokens.first;\n } else {\n return null;\n }\n }", "@Override\n public Symmetry010Date date(int prolepticYear, int month, int dayOfMonth) {\n return Symmetry010Date.of(prolepticYear, month, dayOfMonth);\n }", "public static BoxDeveloperEditionAPIConnection getAppUserConnection(String userId, BoxConfig boxConfig) {\n return getAppUserConnection(userId, boxConfig.getClientId(), boxConfig.getClientSecret(),\n boxConfig.getJWTEncryptionPreferences());\n }" ]
Sets the target implementation type required. This can be used to explicitly acquire a specific implementation type and use a query to configure the instance or factory to be returned. @param type the target implementation type, not null. @return this query builder for chaining.
[ "@SuppressWarnings(\"unchecked\")\n public B setTargetType(Class<?> type) {\n Objects.requireNonNull(type);\n set(AbstractQuery.KEY_QUERY_TARGET_TYPE, type);\n return (B) this;\n }" ]
[ "public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags)\n {\n Map<Set<String>, Vertex> cache = getCache(event);\n Vertex vertex = cache.get(tags);\n if (vertex == null)\n {\n TagSetModel model = create();\n model.setTags(tags);\n cache.put(tags, model.getElement());\n return model;\n }\n else\n {\n return frame(vertex);\n }\n }", "@SuppressWarnings(\"UnusedDeclaration\")\n public void init() throws Exception {\n initBuilderSpecific();\n resetFields();\n if (!UserPluginInfo.NO_PLUGIN_KEY.equals(getSelectedStagingPluginName())) {\n PluginSettings selectedStagingPluginSettings = getSelectedStagingPlugin();\n try {\n stagingStrategy = getArtifactoryServer().getStagingStrategy(selectedStagingPluginSettings, Util.rawEncode(project.getName()), project);\n } catch (Exception e) {\n log.log(Level.WARNING, \"Failed to obtain staging strategy: \" + e.getMessage(), e);\n strategyRequestFailed = true;\n strategyRequestErrorMessage = \"Failed to obtain staging strategy '\" +\n selectedStagingPluginSettings.getPluginName() + \"': \" + e.getMessage() +\n \".\\nPlease review the log for further information.\";\n stagingStrategy = null;\n }\n strategyPluginExists = (stagingStrategy != null) && !stagingStrategy.isEmpty();\n }\n\n prepareDefaultVersioning();\n prepareDefaultGlobalModule();\n prepareDefaultModules();\n prepareDefaultVcsSettings();\n prepareDefaultPromotionConfig();\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 }", "public static <T extends WindupVertexFrame> WindupVertexFrame removeTypeFromModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().removeTypeFromElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, WindupVertexFrame.class);\n }", "public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\n }", "public static final String printDuration(Duration duration)\n {\n String result = null;\n if (duration != null)\n {\n result = duration.getDuration() + \" \" + printTimeUnits(duration.getUnits());\n }\n return result;\n }", "private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {\n String separator = launcher.isUnix() ? \"/\" : \"\\\\\";\n String java_home = extendedEnv.get(\"JAVA_HOME\");\n if (StringUtils.isNotEmpty(java_home)) {\n if (!StringUtils.endsWith(java_home, separator)) {\n java_home += separator;\n }\n extendedEnv.put(\"PATH+JDK\", java_home + \"bin\");\n }\n }", "private static OriginatorType mapOriginator(Originator originator) {\n if (originator == null) {\n return null;\n }\n OriginatorType origType = new OriginatorType();\n origType.setProcessId(originator.getProcessId());\n origType.setIp(originator.getIp());\n origType.setHostname(originator.getHostname());\n origType.setCustomId(originator.getCustomId());\n origType.setPrincipal(originator.getPrincipal());\n return origType;\n }", "private Path getPath(PropertyWriter writer, JsonStreamContext sc) {\n LinkedList<PathElement> elements = new LinkedList<>();\n\n if (sc != null) {\n elements.add(new PathElement(writer.getName(), sc.getCurrentValue()));\n sc = sc.getParent();\n }\n\n while (sc != null) {\n if (sc.getCurrentName() != null && sc.getCurrentValue() != null) {\n elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue()));\n }\n sc = sc.getParent();\n }\n\n return new Path(elements);\n }" ]
Handles an initial response from a PUT or PATCH operation response by polling the status of the operation asynchronously, once the operation finishes emits the final response. @param observable the initial observable from the PUT or PATCH operation. @param resourceType the java.lang.reflect.Type of the resource. @param <T> the return type of the caller. @return the observable of which a subscription will lead to a final response.
[ "public <T> Observable<ServiceResponse<T>> getPutOrPatchResultAsync(Observable<Response<ResponseBody>> observable, final Type resourceType) {\n return this.<T>beginPutOrPatchAsync(observable, resourceType)\n .toObservable()\n .flatMap(new Func1<PollingState<T>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(PollingState<T> pollingState) {\n return pollPutOrPatchAsync(pollingState, resourceType);\n }\n })\n .last()\n .map(new Func1<PollingState<T>, ServiceResponse<T>>() {\n @Override\n public ServiceResponse<T> call(PollingState<T> pollingState) {\n return new ServiceResponse<>(pollingState.resource(), pollingState.response());\n }\n });\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}", "@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 }", "private void writeAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n Project.Assignments.Assignment.ExtendedAttribute attrib;\n List<Project.Assignments.Assignment.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (AssignmentField mpxFieldID : getAllAssignmentExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPAssignmentField.getID(mpxFieldID) | MPPAssignmentField.ASSIGNMENT_FIELD_BASE);\n\n attrib = m_factory.createProjectAssignmentsAssignmentExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }", "public History[] filterHistory(String... filters) throws Exception {\n BasicNameValuePair[] params;\n if (filters.length > 0) {\n params = new BasicNameValuePair[filters.length];\n for (int i = 0; i < filters.length; i++) {\n params[i] = new BasicNameValuePair(\"source_uri[]\", filters[i]);\n }\n } else {\n return refreshHistory();\n }\n\n return constructHistory(params);\n }", "public static final int findValueInListBox(ListBox list, String value) {\n\tfor (int i=0; i<list.getItemCount(); i++) {\n\t if (value.equals(list.getValue(i))) {\n\t\treturn i;\n\t }\n\t}\n\treturn -1;\n }", "protected String stringValue(COSBase value)\n {\n if (value instanceof COSString)\n return ((COSString) value).getString();\n else if (value instanceof COSNumber)\n return String.valueOf(((COSNumber) value).floatValue());\n else\n return \"\";\n }", "public void setCapture(boolean capture, float fps) {\n capturing = capture;\n NativeTextureCapturer.setCapture(getNative(), capture, fps);\n }", "public Collection<Tag> getListUser(String userId) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_LIST_USER);\n\n parameters.put(\"user_id\", userId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element whoElement = response.getPayload();\n\n List<Tag> tags = new ArrayList<Tag>();\n Element tagsElement = (Element) whoElement.getElementsByTagName(\"tags\").item(0);\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag tag = new Tag();\n tag.setValue(((Text) tagElement.getFirstChild()).getData());\n tags.add(tag);\n }\n return tags;\n }", "public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }" ]
Use this API to update nsrpcnode resources.
[ "public static base_responses update(nitro_service client, nsrpcnode resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsrpcnode updateresources[] = new nsrpcnode[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsrpcnode();\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].srcip = resources[i].srcip;\n\t\t\t\tupdateresources[i].secure = resources[i].secure;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public PeriodicEvent runEvery(Runnable task, float delay, float period,\n KeepRunning callback) {\n validateDelay(delay);\n validatePeriod(period);\n return new Event(task, delay, period, callback);\n }", "public String load() {\n this.paginator = new Paginator();\n this.codes = null;\n\n // Perform a search\n\n this.codes = codeFragmentManager.searchCodeFragments(this.codeFragmentPrototype, this.page, this.paginator);\n return \"history\";\n }", "public void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }", "void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }", "synchronized void started() {\n try {\n if(isConnected()) {\n channelHandler.executeRequest(new ServerStartedRequest(), null).getResult().await();\n }\n } catch (Exception e) {\n ServerLogger.AS_ROOT_LOGGER.debugf(e, \"failed to send started notification\");\n }\n }", "public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }", "@Override\n public synchronized void stop(final StopContext context) {\n final boolean shutdownServers = runningModeControl.getRestartMode() == RestartMode.SERVERS;\n if (shutdownServers) {\n Runnable task = new Runnable() {\n @Override\n public void run() {\n try {\n serverInventory.shutdown(true, -1, true); // TODO graceful shutdown\n serverInventory = null;\n // client.getValue().setServerInventory(null);\n } finally {\n serverCallback.getValue().setCallbackHandler(null);\n context.complete();\n }\n }\n };\n try {\n executorService.getValue().execute(task);\n } catch (RejectedExecutionException e) {\n task.run();\n } finally {\n context.asynchronous();\n }\n } else {\n // We have to set the shutdown flag in any case\n serverInventory.shutdown(false, -1, true);\n serverInventory = null;\n }\n }", "public static <T> T splitEachLine(File self, String regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure<T> closure) throws IOException {\n return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);\n }", "public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\n }" ]
Obtain newline-delimited headers from request @param request HttpServletRequest to scan @return newline-delimited headers
[ "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 }" ]
[ "public void forAllClassDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _model.getClasses(); it.hasNext(); )\r\n {\r\n _curClassDef = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curClassDef = null;\r\n\r\n LogHelper.debug(true, OjbTagsHandler.class, \"forAllClassDefinitions\", \"Processed \"+_model.getNumClasses()+\" types\");\r\n }", "public final PJsonObject optJSONObject(final String key) {\n final JSONObject val = this.obj.optJSONObject(key);\n return val != null ? new PJsonObject(this, val, key) : null;\n }", "public boolean clearParameters() {\n this.query = null;\n this.fields = null;\n this.scope = null;\n this.fileExtensions = null;\n this.createdRange = null;\n this.updatedRange = null;\n this.sizeRange = null;\n this.ownerUserIds = null;\n this.ancestorFolderIds = null;\n this.contentTypes = null;\n this.type = null;\n this.trashContent = null;\n this.metadataFilter = null;\n this.sort = null;\n this.direction = null;\n return true;\n }", "public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }", "public double distanceSquared(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return dx * dx + dy * dy + dz * dz;\n }", "private void getMonthlyRelativeDates(Calendar calendar, int frequency, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int dayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n if (dayNumber > 4)\n {\n setCalendarToLastRelativeDay(calendar);\n }\n else\n {\n setCalendarToOrdinalRelativeDay(calendar, dayNumber);\n }\n\n if (calendar.getTimeInMillis() > startDate)\n {\n dates.add(calendar.getTime());\n if (!moreDates(calendar, dates))\n {\n break;\n }\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }", "public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}", "public static double getHaltonNumberForGivenBase(long index, int base) {\n\t\tindex += 1;\n\n\t\tdouble x = 0.0;\n\t\tdouble factor = 1.0 / base;\n\t\twhile(index > 0) {\n\t\t\tx += (index % base) * factor;\n\t\t\tfactor /= base;\n\t\t\tindex /= base;\n\t\t}\n\n\t\treturn x;\n\t}", "public static Calendar popCalendar()\n {\n Calendar result;\n Deque<Calendar> calendars = CALENDARS.get();\n if (calendars.isEmpty())\n {\n result = Calendar.getInstance();\n }\n else\n {\n result = calendars.pop();\n }\n return result;\n }" ]
Main database initialization. To be called only when _ds is a valid DataSource.
[ "private void init(boolean upgrade)\n {\n initAdapter();\n initQueries();\n if (upgrade)\n {\n dbUpgrade();\n }\n\n // First contact with the DB is version checking (if no connection opened by pool).\n // If DB is in wrong version or not available, just wait for it to be ready.\n boolean versionValid = false;\n while (!versionValid)\n {\n try\n {\n checkSchemaVersion();\n versionValid = true;\n }\n catch (Exception e)\n {\n String msg = e.getLocalizedMessage();\n if (e.getCause() != null)\n {\n msg += \" - \" + e.getCause().getLocalizedMessage();\n }\n jqmlogger.error(\"Database not ready: \" + msg + \". Waiting for database...\");\n try\n {\n Thread.sleep(10000);\n }\n catch (Exception e2)\n {\n }\n }\n }\n }" ]
[ "private void writeCustomInfo(Event event) {\n // insert customInfo (key/value) into DB\n for (Map.Entry<String, String> customInfo : event.getCustomInfo().entrySet()) {\n long cust_id = dbDialect.getIncrementer().nextLongValue();\n getJdbcTemplate()\n .update(\"insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)\"\n + \" values (?,?,?,?)\",\n cust_id, event.getPersistedId(), customInfo.getKey(), customInfo.getValue());\n }\n }", "public PayloadBuilder sound(final String sound) {\n if (sound != null) {\n aps.put(\"sound\", sound);\n } else {\n aps.remove(\"sound\");\n }\n return this;\n }", "public static void reset() {\n for (Object name : Collections.list(MAP_KEY_TO_SCOPE.keys())) {\n closeScope(name);\n }\n ConfigurationHolder.configuration.onScopeForestReset();\n ScopeImpl.resetUnBoundProviders();\n }", "private void processFields(Map<FieldType, String> map, Row row, FieldContainer container)\n {\n for (Map.Entry<FieldType, String> entry : map.entrySet())\n {\n FieldType field = entry.getKey();\n String name = entry.getValue();\n\n Object value;\n switch (field.getDataType())\n {\n case INTEGER:\n {\n value = row.getInteger(name);\n break;\n }\n\n case BOOLEAN:\n {\n value = Boolean.valueOf(row.getBoolean(name));\n break;\n }\n\n case DATE:\n {\n value = row.getDate(name);\n break;\n }\n\n case CURRENCY:\n case NUMERIC:\n case PERCENTAGE:\n {\n value = row.getDouble(name);\n break;\n }\n\n case DELAY:\n case WORK:\n case DURATION:\n {\n value = row.getDuration(name);\n break;\n }\n\n case RESOURCE_TYPE:\n {\n value = RESOURCE_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case TASK_TYPE:\n {\n value = TASK_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case CONSTRAINT:\n {\n value = CONSTRAINT_TYPE_MAP.get(row.getString(name));\n break;\n }\n\n case PRIORITY:\n {\n value = PRIORITY_MAP.get(row.getString(name));\n break;\n }\n\n case GUID:\n {\n value = row.getUUID(name);\n break;\n }\n\n default:\n {\n value = row.getString(name);\n break;\n }\n }\n\n container.set(field, value);\n }\n }", "public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\n }", "public static int getProfileIdFromPathID(int path_id) throws Exception {\n return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH);\n }", "synchronized int read(byte[] data) {\n this.header = getHeaderParser().setData(data).parseHeader();\n if (data != null) {\n setData(header, data);\n }\n\n return status;\n }", "public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }", "private void deleteUnusedCaseSteps( ReportModel model ) {\n\n for( ScenarioModel scenarioModel : model.getScenarios() ) {\n if( scenarioModel.isCasesAsTable() && !hasAttachment( scenarioModel ) ) {\n List<ScenarioCaseModel> cases = scenarioModel.getScenarioCases();\n for( int i = 1; i < cases.size(); i++ ) {\n ScenarioCaseModel caseModel = cases.get( i );\n caseModel.setSteps( Collections.<StepModel>emptyList() );\n }\n }\n }\n }" ]
Notification that a connection was closed. @param closed the closed connection
[ "private void onConnectionClose(final Connection closed) {\n synchronized (this) {\n if(connection == closed) {\n connection = null;\n if(shutdown) {\n connectTask = DISCONNECTED;\n return;\n }\n final ConnectTask previous = connectTask;\n connectTask = previous.connectionClosed();\n }\n }\n }" ]
[ "public final void info(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.INFO, pObject, null);\r\n\t}", "public boolean setCustomResponse(String pathName, String customResponse) throws Exception {\n // figure out the new ordinal\n int nextOrdinal = this.getNextOrdinalForMethodId(-1, pathName);\n\n // add override\n this.addMethodToResponseOverride(pathName, \"-1\");\n\n // set argument\n return this.setMethodArguments(pathName, \"-1\", nextOrdinal, customResponse);\n }", "protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException {\n updateModel(operation, resource.getModel());\n }", "protected void addEnumList(String key, List<? extends Enum> list) {\n optionsMap.put(key, list.stream().map(i -> i.toString()).collect(Collectors.toList()));\n }", "public long removeRangeByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zremrangeByLex(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }", "protected Boolean getEscapeQueryChars() {\n\n Boolean isEscape = parseOptionalBooleanValue(m_configObject, JSON_KEY_ESCAPE_QUERY_CHARACTERS);\n return (null == isEscape) && (m_baseConfig != null)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getEscapeQueryChars())\n : isEscape;\n }", "@Override public ProjectFile read(String accessDatabaseFileName) throws MPXJException\n {\n try\n {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n String url = \"jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=\" + accessDatabaseFileName;\n m_connection = DriverManager.getConnection(url);\n m_projectID = Integer.valueOf(1);\n return (read());\n }\n\n catch (ClassNotFoundException ex)\n {\n throw new MPXJException(\"Failed to load JDBC driver\", ex);\n }\n\n catch (SQLException ex)\n {\n throw new MPXJException(\"Failed to create connection\", ex);\n }\n\n finally\n {\n if (m_connection != null)\n {\n try\n {\n m_connection.close();\n }\n\n catch (SQLException ex)\n {\n // silently ignore exceptions when closing connection\n }\n }\n }\n }", "public boolean evaluate(Object feature) {\n\t\t// Checks to ensure that the attribute has been set\n\t\tif (attribute == null) {\n\t\t\treturn false;\n\t\t}\n\t\t// Note that this converts the attribute to a string\n\t\t// for comparison. Unlike the math or geometry filters, which\n\t\t// require specific types to function correctly, this filter\n\t\t// using the mandatory string representation in Java\n\t\t// Of course, this does not guarantee a meaningful result, but it\n\t\t// does guarantee a valid result.\n\t\t// LOGGER.finest(\"pattern: \" + pattern);\n\t\t// LOGGER.finest(\"string: \" + attribute.getValue(feature));\n\t\t// return attribute.getValue(feature).toString().matches(pattern);\n\t\tObject value = attribute.evaluate(feature);\n\n\t\tif (null == value) {\n\t\t\treturn false;\n\t\t}\n\n\t\tMatcher matcher = getMatcher();\n\t\tmatcher.reset(value.toString());\n\n\t\treturn matcher.matches();\n\t}", "public static SQLService getInstance() throws Exception {\n if (_instance == null) {\n _instance = new SQLService();\n _instance.startServer();\n\n // default pool size is 20\n // can be overriden by env variable\n int dbPool = 20;\n if (Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE) != null) {\n dbPool = Integer.valueOf(Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE));\n }\n\n // initialize connection pool\n PoolProperties p = new PoolProperties();\n String connectString = \"jdbc:h2:tcp://\" + _instance.databaseHost + \":\" + String.valueOf(_instance.port) + \"/\" +\n _instance.databaseName + \"/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON\";\n p.setUrl(connectString);\n p.setDriverClassName(\"org.h2.Driver\");\n p.setUsername(\"sa\");\n p.setJmxEnabled(true);\n p.setTestWhileIdle(false);\n p.setTestOnBorrow(true);\n p.setValidationQuery(\"SELECT 1\");\n p.setTestOnReturn(false);\n p.setValidationInterval(5000);\n p.setTimeBetweenEvictionRunsMillis(30000);\n p.setMaxActive(dbPool);\n p.setInitialSize(5);\n p.setMaxWait(30000);\n p.setRemoveAbandonedTimeout(60);\n p.setMinEvictableIdleTimeMillis(30000);\n p.setMinIdle(10);\n p.setLogAbandoned(true);\n p.setRemoveAbandoned(true);\n _instance.datasource = new DataSource();\n _instance.datasource.setPoolProperties(p);\n }\n return _instance;\n }" ]
Retrieve the "complete through" date. @return complete through date
[ "public Date getCompleteThrough()\n {\n Date value = (Date) getCachedValue(TaskField.COMPLETE_THROUGH);\n if (value == null)\n {\n int percentComplete = NumberHelper.getInt(getPercentageComplete());\n switch (percentComplete)\n {\n case 0:\n {\n break;\n }\n\n case 100:\n {\n value = getActualFinish();\n break;\n }\n\n default:\n {\n Date actualStart = getActualStart();\n Duration duration = getDuration();\n if (actualStart != null && duration != null)\n {\n double durationValue = (duration.getDuration() * percentComplete) / 100d;\n duration = Duration.getInstance(durationValue, duration.getUnits());\n ProjectCalendar calendar = getEffectiveCalendar();\n value = calendar.getDate(actualStart, duration, true);\n }\n break;\n }\n }\n\n set(TaskField.COMPLETE_THROUGH, value);\n }\n return value;\n }" ]
[ "public static base_responses enable(nitro_service client, Long clid[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance enableresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tenableresources[i] = new clusterinstance();\n\t\t\t\tenableresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}", "private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {\n ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);\n ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);\n\n list.add(ldapAuthorization);\n\n Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n final String value = reader.getAttributeValue(i);\n if (!isNoNamespaceAttribute(reader, i)) {\n throw unexpectedAttribute(reader, i);\n } else {\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n required.remove(attribute);\n switch (attribute) {\n case CONNECTION: {\n LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);\n break;\n }\n default: {\n throw unexpectedAttribute(reader, i);\n }\n }\n }\n }\n\n if (required.isEmpty() == false) {\n throw missingRequired(reader, required);\n }\n\n Set<Element> foundElements = new HashSet<Element>();\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n if (foundElements.add(element) == false) {\n throw unexpectedElement(reader); // Only one of each allowed.\n }\n switch (element) {\n case USERNAME_TO_DN: {\n switch (namespace.getMajorVersion()) {\n case 1: // 1.5 up to but not including 2.0\n parseUsernameToDn_1_5(reader, addr, list);\n break;\n default: // 2.0 and onwards\n parseUsernameToDn_2_0(reader, addr, list);\n break;\n }\n\n break;\n }\n case GROUP_SEARCH: {\n switch (namespace) {\n case DOMAIN_1_5:\n case DOMAIN_1_6:\n parseGroupSearch_1_5(reader, addr, list);\n break;\n default:\n parseGroupSearch_1_7_and_2_0(reader, addr, list);\n break;\n }\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }", "public void addConverter(int index, IConverter converter) {\r\n\t\tconverterList.add(index, converter);\r\n\t\tif (converter instanceof IContainerConverter) {\r\n\t\t\tIContainerConverter containerConverter = (IContainerConverter) converter;\r\n\t\t\tif (containerConverter.getElementConverter() == null) {\r\n\t\t\t\tcontainerConverter.setElementConverter(elementConverter);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public int size() {\n\t\tint size = cleared ? 0 : snapshot.size();\n\t\tfor ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {\n\t\t\tswitch ( op.getValue().getType() ) {\n\t\t\t\tcase PUT:\n\t\t\t\t\tif ( cleared || !snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize++;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tif ( !cleared && snapshot.containsKey( op.getKey() ) ) {\n\t\t\t\t\t\tsize--;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn size;\n\t}", "public void writeNameValuePair(String name, int value) throws IOException\n {\n internalWriteNameValuePair(name, Integer.toString(value));\n }", "public final SimpleFeatureCollection autoTreat(final Template template, final String features)\n throws IOException {\n SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features);\n if (featuresCollection == null) {\n featuresCollection = treatStringAsGeoJson(features);\n }\n return featuresCollection;\n }", "public static base_responses restore(nitro_service client, appfwprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwprofile restoreresources[] = new appfwprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trestoreresources[i] = new appfwprofile();\n\t\t\t\trestoreresources[i].archivename = resources[i].archivename;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, restoreresources,\"restore\");\n\t\t}\n\t\treturn result;\n\t}", "public static base_response update(nitro_service client, filterhtmlinjectionparameter resource) throws Exception {\n\t\tfilterhtmlinjectionparameter updateresource = new filterhtmlinjectionparameter();\n\t\tupdateresource.rate = resource.rate;\n\t\tupdateresource.frequency = resource.frequency;\n\t\tupdateresource.strict = resource.strict;\n\t\tupdateresource.htmlsearchlen = resource.htmlsearchlen;\n\t\treturn updateresource.update_resource(client);\n\t}", "public double Function2D(double x, double y) {\n double frequency = initFrequency;\n double amplitude = initAmplitude;\n double sum = 0;\n\n // octaves\n for (int i = 0; i < octaves; i++) {\n sum += SmoothedNoise(x * frequency, y * frequency) * amplitude;\n\n frequency *= 2;\n amplitude *= persistence;\n }\n return sum;\n }" ]
Set the "everyWorkingDay" flag. @param isEveryWorkingDay flag, indicating if the event should take place every working day.
[ "public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }" ]
[ "private LoggingConfigurationService configure(final ResourceRoot root, final VirtualFile configFile, final ClassLoader classLoader, final LogContext logContext) throws DeploymentUnitProcessingException {\n InputStream configStream = null;\n try {\n LoggingLogger.ROOT_LOGGER.debugf(\"Found logging configuration file: %s\", configFile);\n\n // Get the filname and open the stream\n final String fileName = configFile.getName();\n configStream = configFile.openStream();\n\n // Check the type of the configuration file\n if (isLog4jConfiguration(fileName)) {\n final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();\n final LogContext old = logContextSelector.getAndSet(CONTEXT_LOCK, logContext);\n try {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);\n if (LOG4J_XML.equals(fileName) || JBOSS_LOG4J_XML.equals(fileName)) {\n new DOMConfigurator().doConfigure(configStream, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n } else {\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n new org.apache.log4j.PropertyConfigurator().doConfigure(properties, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n }\n } finally {\n logContextSelector.getAndSet(CONTEXT_LOCK, old);\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);\n }\n return new LoggingConfigurationService(null, resolveRelativePath(root, configFile));\n } else {\n // Create a properties file\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n // Attempt to see if this is a J.U.L. configuration file\n if (isJulConfiguration(properties)) {\n LoggingLogger.ROOT_LOGGER.julConfigurationFileFound(configFile.getName());\n } else {\n // Load non-log4j types\n final PropertyConfigurator propertyConfigurator = new PropertyConfigurator(logContext);\n propertyConfigurator.configure(properties);\n return new LoggingConfigurationService(propertyConfigurator.getLogContextConfiguration(), resolveRelativePath(root, configFile));\n }\n }\n } catch (Exception e) {\n throw LoggingLogger.ROOT_LOGGER.failedToConfigureLogging(e, configFile.getName());\n } finally {\n safeClose(configStream);\n }\n return null;\n }", "private void modifyBeliefCount(int count){\n introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null);\n }", "private static JSONObject parseStencil(String stencilId) throws JSONException {\n JSONObject stencilObject = new JSONObject();\n\n stencilObject.put(\"id\",\n stencilId.toString());\n\n return stencilObject;\n }", "public int compareTo(WordTag wordTag) { \r\n int first = (word != null ? word().compareTo(wordTag.word()) : 0);\r\n if(first != 0)\r\n return first;\r\n else {\r\n if (tag() == null) {\r\n if (wordTag.tag() == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return tag().compareTo(wordTag.tag());\r\n }\r\n }", "public static int getChunkId(String fileName) {\n Pattern pattern = Pattern.compile(\"_[\\\\d]+\\\\.\");\n Matcher matcher = pattern.matcher(fileName);\n\n if(matcher.find()) {\n return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1));\n } else {\n throw new VoldemortException(\"Could not extract out chunk id from \" + fileName);\n }\n }", "public static String getContent(String stringUrl) throws IOException {\n InputStream stream = getContentStream(stringUrl);\n return MyStreamUtils.readContent(stream);\n }", "public ItemRequest<Team> addUser(String team) {\n \n String path = String.format(\"/teams/%s/addUser\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"POST\");\n }", "public void render(OutputStream outputStream, Format format, int dpi) throws PrintingException {\n\t\ttry {\n\t\t\tif (baos == null) {\n\t\t\t\tprepare();\n\t\t\t}\n\t\t\twriteDocument(outputStream, format, dpi);\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);\n\t\t}\n\t}", "private static MonetaryFormatsSingletonSpi loadMonetaryFormatsSingletonSpi() {\n try {\n return Optional.ofNullable(Bootstrap.getService(MonetaryFormatsSingletonSpi.class))\n .orElseGet(DefaultMonetaryFormatsSingletonSpi::new);\n } catch (Exception e) {\n Logger.getLogger(MonetaryFormats.class.getName())\n .log(Level.WARNING, \"Failed to load MonetaryFormatsSingletonSpi, using default.\", e);\n return new DefaultMonetaryFormatsSingletonSpi();\n }\n }" ]
Used for DI frameworks to inject values into stages.
[ "public void wireSteps( CanWire canWire ) {\n for( StageState steps : stages.values() ) {\n canWire.wire( steps.instance );\n }\n }" ]
[ "public Optional<URL> getServiceUrl() {\n Optional<Service> optionalService = client.services().inNamespace(namespace)\n .list().getItems()\n .stream()\n .findFirst();\n\n return optionalService\n .map(this::createUrlForService)\n .orElse(Optional.empty());\n }", "public void notifyHeaderItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart, itemCount);\n }", "public static nsfeature get(nitro_service service) throws Exception{\n\t\tnsfeature obj = new nsfeature();\n\t\tnsfeature[] response = (nsfeature[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static void zeroTriangle( boolean upper , DMatrixRBlock A )\n {\n int blockLength = A.blockLength;\n\n if( upper ) {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = i; j < A.numCols; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n for( int l = k+1; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n } else {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = 0; j <= i; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n int z = Math.min(k,w);\n for( int l = 0; l < z; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n }\n }", "@Override\n public void stop()\n {\n synchronized (killHook)\n {\n jqmlogger.info(\"JQM engine \" + this.node.getName() + \" has received a stop order\");\n\n // Kill hook should be removed\n try\n {\n if (!Runtime.getRuntime().removeShutdownHook(killHook))\n {\n jqmlogger.error(\"The engine could not unregister its shutdown hook\");\n }\n }\n catch (IllegalStateException e)\n {\n // This happens if the stop sequence is initiated by the shutdown hook itself.\n jqmlogger.info(\"Stop order is due to an admin operation (KILL/INT)\");\n }\n }\n\n // Stop pollers\n int pollerCount = pollers.size();\n for (QueuePoller p : pollers.values())\n {\n p.stop();\n }\n\n // Scheduler\n this.scheduler.stop();\n\n // Jetty is closed automatically when all pollers are down\n\n // Wait for the end of the world\n if (pollerCount > 0)\n {\n try\n {\n this.ended.acquire();\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n // Send a KILL signal to remaining job instances, and wait some more.\n if (this.getCurrentlyRunningJobCount() > 0)\n {\n this.runningJobInstanceManager.killAll();\n try\n {\n Thread.sleep(10000);\n }\n catch (InterruptedException e)\n {\n jqmlogger.error(\"interrupted\", e);\n }\n }\n\n jqmlogger.debug(\"Stop order was correctly handled. Engine for node \" + this.node.getName() + \" has stopped.\");\n }", "public static base_response add(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction addresource = new vpnsessionaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.httpport = resource.httpport;\n\t\taddresource.winsip = resource.winsip;\n\t\taddresource.dnsvservername = resource.dnsvservername;\n\t\taddresource.splitdns = resource.splitdns;\n\t\taddresource.sesstimeout = resource.sesstimeout;\n\t\taddresource.clientsecurity = resource.clientsecurity;\n\t\taddresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\taddresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\taddresource.clientsecuritylog = resource.clientsecuritylog;\n\t\taddresource.splittunnel = resource.splittunnel;\n\t\taddresource.locallanaccess = resource.locallanaccess;\n\t\taddresource.rfc1918 = resource.rfc1918;\n\t\taddresource.spoofiip = resource.spoofiip;\n\t\taddresource.killconnections = resource.killconnections;\n\t\taddresource.transparentinterception = resource.transparentinterception;\n\t\taddresource.windowsclienttype = resource.windowsclienttype;\n\t\taddresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\taddresource.authorizationgroup = resource.authorizationgroup;\n\t\taddresource.clientidletimeout = resource.clientidletimeout;\n\t\taddresource.proxy = resource.proxy;\n\t\taddresource.allprotocolproxy = resource.allprotocolproxy;\n\t\taddresource.httpproxy = resource.httpproxy;\n\t\taddresource.ftpproxy = resource.ftpproxy;\n\t\taddresource.socksproxy = resource.socksproxy;\n\t\taddresource.gopherproxy = resource.gopherproxy;\n\t\taddresource.sslproxy = resource.sslproxy;\n\t\taddresource.proxyexception = resource.proxyexception;\n\t\taddresource.proxylocalbypass = resource.proxylocalbypass;\n\t\taddresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\taddresource.forcecleanup = resource.forcecleanup;\n\t\taddresource.clientoptions = resource.clientoptions;\n\t\taddresource.clientconfiguration = resource.clientconfiguration;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.ssocredential = resource.ssocredential;\n\t\taddresource.windowsautologon = resource.windowsautologon;\n\t\taddresource.usemip = resource.usemip;\n\t\taddresource.useiip = resource.useiip;\n\t\taddresource.clientdebug = resource.clientdebug;\n\t\taddresource.loginscript = resource.loginscript;\n\t\taddresource.logoutscript = resource.logoutscript;\n\t\taddresource.homepage = resource.homepage;\n\t\taddresource.icaproxy = resource.icaproxy;\n\t\taddresource.wihome = resource.wihome;\n\t\taddresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\taddresource.wiportalmode = resource.wiportalmode;\n\t\taddresource.clientchoices = resource.clientchoices;\n\t\taddresource.epaclienttype = resource.epaclienttype;\n\t\taddresource.iipdnssuffix = resource.iipdnssuffix;\n\t\taddresource.forcedtimeout = resource.forcedtimeout;\n\t\taddresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\taddresource.ntdomain = resource.ntdomain;\n\t\taddresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\taddresource.emailhome = resource.emailhome;\n\t\taddresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\taddresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\taddresource.allowedlogingroups = resource.allowedlogingroups;\n\t\taddresource.securebrowse = resource.securebrowse;\n\t\taddresource.storefronturl = resource.storefronturl;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\treturn addresource.add_resource(client);\n\t}", "protected static PropertyDescriptor findPropertyDescriptor(Class aClass, String aPropertyName)\r\n {\r\n BeanInfo info;\r\n PropertyDescriptor[] pd;\r\n PropertyDescriptor descriptor = null;\r\n\r\n try\r\n {\r\n info = Introspector.getBeanInfo(aClass);\r\n pd = info.getPropertyDescriptors();\r\n for (int i = 0; i < pd.length; i++)\r\n {\r\n if (pd[i].getName().equals(aPropertyName))\r\n {\r\n descriptor = pd[i];\r\n break;\r\n }\r\n }\r\n if (descriptor == null)\r\n {\r\n /*\r\n\t\t\t\t * Daren Drummond: \tThrow here so we are consistent\r\n\t\t\t\t * \t\t\t\t\twith PersistentFieldDefaultImpl.\r\n\t\t\t\t */\r\n throw new MetadataException(\"Can't find property \" + aPropertyName + \" in \" + aClass.getName());\r\n }\r\n return descriptor;\r\n }\r\n catch (IntrospectionException ex)\r\n {\r\n /*\r\n\t\t\t * Daren Drummond: \tThrow here so we are consistent\r\n\t\t\t * \t\t\t\t\twith PersistentFieldDefaultImpl.\r\n\t\t\t */\r\n throw new MetadataException(\"Can't find property \" + aPropertyName + \" in \" + aClass.getName(), ex);\r\n }\r\n }", "public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }", "public void setAngularUpperLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setAngularUpperLimits(getNative(), limitX, limitY, limitZ);\n }" ]
Add several jvm metrics.
[ "@PostConstruct\n public void init() {\n this.metricRegistry.register(name(\"gc\"), new GarbageCollectorMetricSet());\n this.metricRegistry.register(name(\"memory\"), new MemoryUsageGaugeSet());\n this.metricRegistry.register(name(\"thread-states\"), new ThreadStatesGaugeSet());\n this.metricRegistry.register(name(\"fd-usage\"), new FileDescriptorRatioGauge());\n }" ]
[ "public static nsdiameter get(nitro_service service) throws Exception{\n\t\tnsdiameter obj = new nsdiameter();\n\t\tnsdiameter[] response = (nsdiameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "private void getMonthlyAbsoluteDates(Calendar calendar, int frequency, List<Date> dates)\n {\n int currentDayNumber = calendar.get(Calendar.DAY_OF_MONTH);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n int requiredDayNumber = NumberHelper.getInt(m_dayNumber);\n if (requiredDayNumber < currentDayNumber)\n {\n calendar.add(Calendar.MONTH, 1);\n }\n\n while (moreDates(calendar, dates))\n {\n int useDayNumber = requiredDayNumber;\n int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n if (useDayNumber > maxDayNumber)\n {\n useDayNumber = maxDayNumber;\n }\n calendar.set(Calendar.DAY_OF_MONTH, useDayNumber);\n dates.add(calendar.getTime());\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.MONTH, frequency);\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }", "public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = 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 query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\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 (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }", "public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }", "public IntervalFrequency getRefreshFrequency() {\n switch (mRefreshInterval) {\n case REALTIME_REFRESH_INTERVAL:\n return IntervalFrequency.REALTIME;\n case HIGH_REFRESH_INTERVAL:\n return IntervalFrequency.HIGH;\n case LOW_REFRESH_INTERVAL:\n return IntervalFrequency.LOW;\n case MEDIUM_REFRESH_INTERVAL:\n return IntervalFrequency.MEDIUM;\n default:\n return IntervalFrequency.NONE;\n }\n }", "public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }", "public boolean isIPv4Mapped() {\n\t\t//::ffff:x:x/96 indicates IPv6 address mapped to IPv4\n\t\tif(getSegment(5).matches(IPv6Address.MAX_VALUE_PER_SEGMENT)) {\n\t\t\tfor(int i = 0; i < 5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "public float getBoundsHeight(){\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.y - v.minCorner.y;\n }\n return 0f;\n }" ]
Mirrors the given bitmap
[ "public static Bitmap flip(Bitmap src) {\n Matrix m = new Matrix();\n m.preScale(-1, 1);\n return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);\n }" ]
[ "private WmsLayer getLayer(String layerId) {\n\t\tRasterLayer layer = configurationService.getRasterLayer(layerId);\n\t\tif (layer instanceof WmsLayer) {\n\t\t\treturn (WmsLayer) layer;\n\t\t}\n\t\treturn null;\n\t}", "public synchronized int put(byte[] src, int off, int len) {\n if (available == capacity) {\n return 0;\n }\n\n // limit is last index to put + 1\n int limit = idxPut < idxGet ? idxGet : capacity;\n int count = Math.min(limit - idxPut, len);\n System.arraycopy(src, off, buffer, idxPut, count);\n idxPut += count;\n\n if (idxPut == capacity) {\n // Array end reached, check if we have more\n int count2 = Math.min(len - count, idxGet);\n if (count2 > 0) {\n System.arraycopy(src, off + count, buffer, 0, count2);\n idxPut = count2;\n count += count2;\n } else {\n idxPut = 0;\n }\n }\n available += count;\n return count;\n }", "@Override\n\tpublic void handlePopups() {\n\t\t/*\n\t\t * try { executeJavaScript(\"window.alert = function(msg){return true;};\" +\n\t\t * \"window.confirm = function(msg){return true;};\" +\n\t\t * \"window.prompt = function(msg){return true;};\"); } catch (CrawljaxException e) {\n\t\t * LOGGER.error(\"Handling of PopUp windows failed\", e); }\n\t\t */\n\n\t\t/* Workaround: Popups handling currently not supported in PhantomJS. */\n\t\tif (browser instanceof PhantomJSDriver) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (ExpectedConditions.alertIsPresent().apply(browser) != null) {\n\t\t\ttry {\n\t\t\t\tbrowser.switchTo().alert().accept();\n\t\t\t\tLOGGER.info(\"Alert accepted\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"Handling of PopUp windows failed\");\n\t\t\t}\n\t\t}\n\t}", "private boolean findBinding(Injector injector, Class<?> type) {\n boolean found = false;\n for (Key<?> key : injector.getBindings().keySet()) {\n if (key.getTypeLiteral().getRawType().equals(type)) {\n found = true;\n break;\n }\n }\n if (!found && injector.getParent() != null) {\n return findBinding(injector.getParent(), type);\n }\n\n return found;\n }", "@UiHandler(\"m_atDay\")\r\n void onWeekDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekDay(event.getValue());\r\n }\r\n }", "public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver)\r\n {\r\n String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol);\r\n\r\n if (platform == null)\r\n {\r\n platform = (String)jdbcDriverToPlatform.get(jdbcDriver);\r\n }\r\n return platform;\r\n }", "private void writePropertyStatisticsToFile(UsageStatistics usageStatistics,\n\t\t\tString fileName) {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(fileName))) {\n\n\t\t\tout.println(\"Property id,in statements,in qualifiers,in references,total\");\n\n\t\t\tfor (Entry<PropertyIdValue, Integer> entry : usageStatistics.propertyCountsMain\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tint qCount = usageStatistics.propertyCountsQualifier.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint rCount = usageStatistics.propertyCountsReferences.get(entry\n\t\t\t\t\t\t.getKey());\n\t\t\t\tint total = entry.getValue() + qCount + rCount;\n\t\t\t\tout.println(entry.getKey().getId() + \",\" + entry.getValue()\n\t\t\t\t\t\t+ \",\" + qCount + \",\" + rCount + \",\" + total);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public Object getJavaDefaultValueDefault() {\n\t\tif (field.getType() == boolean.class) {\n\t\t\treturn DEFAULT_VALUE_BOOLEAN;\n\t\t} else if (field.getType() == byte.class || field.getType() == Byte.class) {\n\t\t\treturn DEFAULT_VALUE_BYTE;\n\t\t} else if (field.getType() == char.class || field.getType() == Character.class) {\n\t\t\treturn DEFAULT_VALUE_CHAR;\n\t\t} else if (field.getType() == short.class || field.getType() == Short.class) {\n\t\t\treturn DEFAULT_VALUE_SHORT;\n\t\t} else if (field.getType() == int.class || field.getType() == Integer.class) {\n\t\t\treturn DEFAULT_VALUE_INT;\n\t\t} else if (field.getType() == long.class || field.getType() == Long.class) {\n\t\t\treturn DEFAULT_VALUE_LONG;\n\t\t} else if (field.getType() == float.class || field.getType() == Float.class) {\n\t\t\treturn DEFAULT_VALUE_FLOAT;\n\t\t} else if (field.getType() == double.class || field.getType() == Double.class) {\n\t\t\treturn DEFAULT_VALUE_DOUBLE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}", "protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }" ]
Send an error to the client with an exception. @param httpServletResponse the http response to send the error to @param e the error that occurred
[ "protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {\n httpServletResponse.setContentType(\"text/plain\");\n httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());\n try (PrintWriter out = httpServletResponse.getWriter()) {\n out.println(\"Error while processing request:\");\n LOGGER.error(\"Error while processing request\", e);\n } catch (IOException ex) {\n throw ExceptionUtils.getRuntimeException(ex);\n }\n }" ]
[ "public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) {\n\t\treturn ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator);\n\t}", "public static String getString(byte[] bytes, String encoding) {\n try {\n return new String(bytes, encoding);\n } catch(UnsupportedEncodingException e) {\n throw new IllegalArgumentException(encoding + \" is not a known encoding name.\", e);\n }\n }", "public static final BigInteger printWorkUnits(TimeUnit value)\n {\n int result;\n\n if (value == null)\n {\n value = TimeUnit.HOURS;\n }\n\n switch (value)\n {\n case MINUTES:\n {\n result = 1;\n break;\n }\n\n case DAYS:\n {\n result = 3;\n break;\n }\n\n case WEEKS:\n {\n result = 4;\n break;\n }\n\n case MONTHS:\n {\n result = 5;\n break;\n }\n\n case YEARS:\n {\n result = 7;\n break;\n }\n\n default:\n case HOURS:\n {\n result = 2;\n break;\n }\n }\n\n return (BigInteger.valueOf(result));\n }", "public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {\r\n\r\n ComplexNumber conj = ComplexNumber.Conjugate(z2);\r\n\r\n double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);\r\n double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);\r\n\r\n double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);\r\n\r\n return new ComplexNumber(a / c, b / c);\r\n }", "public void retrieveProxyCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, true);\r\n }", "@Override\n\tpublic String getFirst(String headerName) {\n\t\tList<String> headerValues = headers.get(headerName);\n\t\treturn headerValues != null ? headerValues.get(0) : null;\n\t}", "protected I_CmsFacetQueryItem parseFacetQueryItem(JSONObject item) {\n\n String query;\n try {\n query = item.getString(JSON_KEY_QUERY_FACET_QUERY_QUERY);\n } catch (JSONException e) {\n // TODO: Log\n return null;\n }\n String label = parseOptionalStringValue(item, JSON_KEY_QUERY_FACET_QUERY_LABEL);\n return new CmsFacetQueryItem(query, label);\n }", "public void ojbAdd(Object anObject)\r\n {\r\n DSetEntry entry = prepareEntry(anObject);\r\n entry.setPosition(elements.size());\r\n elements.add(entry);\r\n }", "public static appfwwsdl get(nitro_service service, String name) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tobj.set_name(name);\n\t\tappfwwsdl response = (appfwwsdl) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Makes an RPC call using the client. Logs how long it took and any exceptions. NOTE: The request could be an InputStream too, but the http client will need to find its length, which will require buffering it anyways. @throws DatastoreException if the RPC fails.
[ "public InputStream call(String methodName, MessageLite request) throws DatastoreException {\n logger.fine(\"remote datastore call \" + methodName);\n\n long startTime = System.currentTimeMillis();\n try {\n HttpResponse httpResponse;\n try {\n rpcCount.incrementAndGet();\n ProtoHttpContent payload = new ProtoHttpContent(request);\n HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload);\n httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION);\n // Don't throw an HTTPResponseException on error. It converts the response to a String and\n // throws away the original, whereas we need the raw bytes to parse it as a proto.\n httpRequest.setThrowExceptionOnExecuteError(false);\n // Datastore requests typically time out after 60s; set the read timeout to slightly longer\n // than that by default (can be overridden via the HttpRequestInitializer).\n httpRequest.setReadTimeout(65 * 1000);\n if (initializer != null) {\n initializer.initialize(httpRequest);\n }\n httpResponse = httpRequest.execute();\n if (!httpResponse.isSuccessStatusCode()) {\n try (InputStream content = GzipFixingInputStream.maybeWrap(httpResponse.getContent())) {\n throw makeException(url, methodName, content,\n httpResponse.getContentType(), httpResponse.getContentCharset(), null,\n httpResponse.getStatusCode());\n }\n }\n return GzipFixingInputStream.maybeWrap(httpResponse.getContent());\n } catch (SocketTimeoutException e) {\n throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, \"Deadline exceeded\", e);\n } catch (IOException e) {\n throw makeException(url, methodName, Code.UNAVAILABLE, \"I/O error\", e);\n }\n } finally {\n long elapsedTime = System.currentTimeMillis() - startTime;\n logger.fine(\"remote datastore call \" + methodName + \" took \" + elapsedTime + \" ms\");\n }\n }" ]
[ "public static DMatrixRMaj[] splitIntoVectors(DMatrix1Row A , boolean column )\n {\n int w = column ? A.numCols : A.numRows;\n\n int M = column ? A.numRows : 1;\n int N = column ? 1 : A.numCols;\n\n int o = Math.max(M,N);\n\n DMatrixRMaj[] ret = new DMatrixRMaj[w];\n\n for( int i = 0; i < w; i++ ) {\n DMatrixRMaj a = new DMatrixRMaj(M,N);\n\n if( column )\n subvector(A,0,i,o,false,0,a);\n else\n subvector(A,i,0,o,true,0,a);\n\n ret[i] = a;\n }\n\n return ret;\n }", "public T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}", "public static ModelMBean createModelMBean(Object o) {\n try {\n ModelMBean mbean = new RequiredModelMBean();\n JmxManaged annotation = o.getClass().getAnnotation(JmxManaged.class);\n String description = annotation == null ? \"\" : annotation.description();\n ModelMBeanInfo info = new ModelMBeanInfoSupport(o.getClass().getName(),\n description,\n extractAttributeInfo(o),\n new ModelMBeanConstructorInfo[0],\n extractOperationInfo(o),\n new ModelMBeanNotificationInfo[0]);\n mbean.setModelMBeanInfo(info);\n mbean.setManagedResource(o, \"ObjectReference\");\n\n return mbean;\n } catch(MBeanException e) {\n throw new VoldemortException(e);\n } catch(InvalidTargetObjectTypeException e) {\n throw new VoldemortException(e);\n } catch(InstanceNotFoundException e) {\n throw new VoldemortException(e);\n }\n }", "public static sslcertkey_sslvserver_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslvserver_binding obj = new sslcertkey_sslvserver_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslvserver_binding response[] = (sslcertkey_sslvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String readTag(Reader r) throws IOException {\r\n if ( ! r.ready()) {\r\n return null;\r\n }\r\n StringBuilder b = new StringBuilder(\"<\");\r\n int c = r.read();\r\n while (c >= 0) {\r\n b.append((char) c);\r\n if (c == '>') {\r\n break;\r\n }\r\n c = r.read();\r\n }\r\n if (b.length() == 1) {\r\n return null;\r\n }\r\n return b.toString();\r\n }", "private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }", "public static double Exp(double x, int nTerms) {\r\n if (nTerms < 2) return 1 + x;\r\n if (nTerms == 2) {\r\n return 1 + x + (x * x) / 2;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n double result = 1 + x + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x;\r\n fact *= i;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }", "@Programmatic\n public <T> Blob toExcelPivot(\n final List<T> domainObjects,\n final Class<T> cls,\n final String fileName) throws ExcelService.Exception {\n return toExcelPivot(domainObjects, cls, null, fileName);\n }", "public static <T> OptionalValue<T> ofNullable(T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);\n }" ]
All address strings are comparable. If two address strings are invalid, their strings are compared. Otherwise, address strings are compared according to which type or version of string, and then within each type or version they are compared using the comparison rules for addresses. @param other @return
[ "@Override\n\tpublic int compareTo(IPAddressString other) {\n\t\tif(this == other) {\n\t\t\treturn 0;\n\t\t}\n\t\tboolean isValid = isValid();\n\t\tboolean otherIsValid = other.isValid();\n\t\tif(!isValid && !otherIsValid) {\n\t\t\treturn toString().compareTo(other.toString());\n\t\t}\n\t\treturn addressProvider.providerCompare(other.addressProvider);\n\t}" ]
[ "public void sendJsonToUser(Object data, String username) {\n sendToUser(JSON.toJSONString(data), username);\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 double calculateBoundedness(double D, int N, double timelag, double confRadius){\n\t\tdouble r = confRadius;\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble res = cov_area/(4*r*r);\n\t\treturn res;\n\t}", "public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }", "private void addAllProjectModels(ApplicationReportIndexModel navIdx, ProjectModel projectModel)\n {\n navIdx.addProjectModel(projectModel);\n for (ProjectModel childProject : projectModel.getChildProjects())\n {\n if (!Iterators.asSet(navIdx.getProjectModels()).contains(childProject))\n addAllProjectModels(navIdx, childProject);\n }\n }", "public static String getMemberName() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getName();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n return MethodTagsHandler.getPropertyNameFor(getCurrentMethod());\r\n }\r\n else {\r\n return null;\r\n }\r\n }", "public static byte[] explodeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItem = getContentItem(deploymentResource);\n ModelNode explodedPath = DEPLOYMENT_CONTENT_PATH.resolveModelAttribute(context, operation);\n byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItem).asBytes();\n final byte[] hash;\n if (explodedPath.isDefined()) {\n hash = contentRepository.explodeSubContent(oldHash, explodedPath.asString());\n } else {\n hash = contentRepository.explodeContent(oldHash);\n }\n\n // Clear the contents and update with the hash\n final ModelNode slave = operation.clone();\n ModelNode addedContent = new ModelNode().setEmptyObject();\n addedContent.get(HASH).set(hash);\n addedContent.get(TARGET_PATH.getName()).set(\"./\");\n slave.get(CONTENT).setEmptyList().add(addedContent);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }", "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 void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationForLocations(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {alert('rec:'+status);\\ndocument.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n LOG.trace(\"ElevationService direct call: \" + r.toString());\n \n getJSObject().eval(r.toString());\n \n }" ]
generates a Meta Object Protocol method, that is used to call a non public method, or to make a call to super. @param mopCalls list of methods a mop call method should be generated for @param useThis true if "this" should be used for the naming
[ "protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {\n for (MethodNode method : mopCalls) {\n String name = getMopMethodName(method, useThis);\n Parameter[] parameters = method.getParameters();\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());\n MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);\n controller.setMethodVisitor(mv);\n mv.visitVarInsn(ALOAD, 0);\n int newRegister = 1;\n OperandStack operandStack = controller.getOperandStack();\n for (Parameter parameter : parameters) {\n ClassNode type = parameter.getType();\n operandStack.load(parameter.getType(), newRegister);\n // increment to next register, double/long are using two places\n newRegister++;\n if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;\n }\n operandStack.remove(parameters.length);\n ClassNode declaringClass = method.getDeclaringClass();\n // JDK 8 support for default methods in interfaces\n // this should probably be strenghtened when we support the A.super.foo() syntax\n int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;\n mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);\n BytecodeHelper.doReturn(mv, method.getReturnType());\n mv.visitMaxs(0, 0);\n mv.visitEnd();\n controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);\n }\n }" ]
[ "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }", "public void setEnable(boolean flag)\n {\n if (mEnabled == flag)\n {\n return;\n }\n mEnabled = flag;\n if (flag)\n {\n mContext.registerDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().addListener(this);\n mAudioEngine.resume();\n }\n else\n {\n mContext.unregisterDrawFrameListener(this);\n mContext.getApplication().getEventReceiver().removeListener(this);\n mAudioEngine.pause();\n }\n }", "public static base_response add(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec addresource = new dnsaaaarec();\n\t\taddresource.hostname = resource.hostname;\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}", "private static void listResources(ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n System.out.println(\"Resource: \" + resource.getName() + \" (Unique ID=\" + resource.getUniqueID() + \") Start=\" + resource.getStart() + \" Finish=\" + resource.getFinish());\n }\n System.out.println();\n }", "public void setBackgroundColor(int color) {\n setBackgroundColorR(Colors.byteToGl(Color.red(color)));\n setBackgroundColorG(Colors.byteToGl(Color.green(color)));\n setBackgroundColorB(Colors.byteToGl(Color.blue(color)));\n setBackgroundColorA(Colors.byteToGl(Color.alpha(color)));\n }", "private String parsePropertyName(String orgPropertyName, Object userData) {\n\t\t// try to assure the correct separator is used\n\t\tString propertyName = orgPropertyName.replace(HibernateLayerUtil.XPATH_SEPARATOR, HibernateLayerUtil.SEPARATOR);\n\n\t\t// split the path (separator is defined in the HibernateLayerUtil)\n\t\tString[] props = propertyName.split(HibernateLayerUtil.SEPARATOR_REGEXP);\n\t\tString finalName;\n\t\tif (props.length > 1 && userData instanceof Criteria) {\n\t\t\t// the criteria API requires an alias for each join table !!!\n\t\t\tString prevAlias = null;\n\t\t\tfor (int i = 0; i < props.length - 1; i++) {\n\t\t\t\tString alias = props[i] + \"_alias\";\n\t\t\t\tif (!aliases.contains(alias)) {\n\t\t\t\t\tCriteria criteria = (Criteria) userData;\n\t\t\t\t\tif (i == 0) {\n\t\t\t\t\t\tcriteria.createAlias(props[0], alias);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcriteria.createAlias(prevAlias + \".\" + props[i], alias);\n\t\t\t\t\t}\n\t\t\t\t\taliases.add(alias);\n\t\t\t\t}\n\t\t\t\tprevAlias = alias;\n\t\t\t}\n\t\t\tfinalName = prevAlias + \".\" + props[props.length - 1];\n\t\t} else {\n\t\t\tfinalName = propertyName;\n\t\t}\n\t\treturn finalName;\n\t}", "private synchronized void finishTransition(final InternalState current, final InternalState next) {\n internalSetState(getTransitionTask(next), current, next);\n transition();\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 }", "protected void createBulge( int x1 , double p , boolean byAngle ) {\n double a11 = diag[x1];\n double a22 = diag[x1+1];\n double a12 = off[x1];\n double a23 = off[x1+1];\n\n if( byAngle ) {\n c = Math.cos(p);\n s = Math.sin(p);\n\n c2 = c*c;\n s2 = s*s;\n cs = c*s;\n } else {\n computeRotation(a11-p, a12);\n }\n\n // multiply the rotator on the top left.\n diag[x1] = c2*a11 + 2.0*cs*a12 + s2*a22;\n diag[x1+1] = c2*a22 - 2.0*cs*a12 + s2*a11;\n off[x1] = a12*(c2-s2) + cs*(a22 - a11);\n off[x1+1] = c*a23;\n bulge = s*a23;\n\n if( Q != null )\n updateQ(x1,x1+1,c,s);\n }" ]
Checks whether the given set of properties is available. @param keys the keys to check @return true if all properties are available, false otherwise
[ "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 }" ]
[ "String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }", "private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,\r\n\t\t\tDayCountConvention daycountConvention) {\r\n\r\n\t\tboolean isFixed = leg.getElementsByTagName(\"interestType\").item(0).getTextContent().equalsIgnoreCase(\"FIX\");\r\n\r\n\t\tArrayList<Period> periods \t\t= new ArrayList<>();\r\n\t\tArrayList<Double> notionalsList\t= new ArrayList<>();\r\n\t\tArrayList<Double> rates\t\t\t= new ArrayList<>();\r\n\r\n\t\t//extracting data for each period\r\n\t\tNodeList periodsXML = leg.getElementsByTagName(\"incomePayment\");\r\n\t\tfor(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {\r\n\r\n\t\t\tElement periodXML = (Element) periodsXML.item(periodIndex);\r\n\r\n\t\t\tLocalDate startDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"startDate\").item(0).getTextContent());\r\n\t\t\tLocalDate endDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"endDate\").item(0).getTextContent());\r\n\r\n\t\t\tLocalDate fixingDate\t= startDate;\r\n\t\t\tLocalDate paymentDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"payDate\").item(0).getTextContent());\r\n\r\n\t\t\tif(! isFixed) {\r\n\t\t\t\tfixingDate = LocalDate.parse(periodXML.getElementsByTagName(\"fixingDate\").item(0).getTextContent());\r\n\t\t\t}\r\n\r\n\t\t\tperiods.add(new Period(fixingDate, paymentDate, startDate, endDate));\r\n\r\n\t\t\tdouble notional\t\t= Double.parseDouble(periodXML.getElementsByTagName(\"nominal\").item(0).getTextContent());\r\n\t\t\tnotionalsList.add(new Double(notional));\r\n\r\n\t\t\tif(isFixed) {\r\n\t\t\t\tdouble fixedRate\t= Double.parseDouble(periodXML.getElementsByTagName(\"fixedRate\").item(0).getTextContent());\r\n\t\t\t\trates.add(new Double(fixedRate));\r\n\t\t\t} else {\r\n\t\t\t\trates.add(new Double(0));\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);\r\n\t\tdouble[] notionals\t= notionalsList.stream().mapToDouble(Double::doubleValue).toArray();\r\n\t\tdouble[] spreads\t= rates.stream().mapToDouble(Double::doubleValue).toArray();\r\n\r\n\t\treturn new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);\r\n\t}", "public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }", "ArgumentsBuilder param(String param, String value) {\n if (value != null) {\n args.add(param);\n args.add(value);\n }\n return this;\n }", "public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }", "public static sslcertlink[] get(nitro_service service) throws Exception{\n\t\tsslcertlink obj = new sslcertlink();\n\t\tsslcertlink[] response = (sslcertlink[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, String name, String type,\r\n int length, String action,\r\n RetentionPolicyParams optionalParams) {\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.build(api.getBaseURL());\r\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\r\n JsonObject requestJSON = new JsonObject()\r\n .add(\"policy_name\", name)\r\n .add(\"policy_type\", type)\r\n .add(\"disposition_action\", action);\r\n if (!type.equals(TYPE_INDEFINITE)) {\r\n requestJSON.add(\"retention_length\", length);\r\n }\r\n if (optionalParams != null) {\r\n requestJSON.add(\"can_owner_extend_retention\", optionalParams.getCanOwnerExtendRetention());\r\n requestJSON.add(\"are_owners_notified\", optionalParams.getAreOwnersNotified());\r\n\r\n List<BoxUser.Info> customNotificationRecipients = optionalParams.getCustomNotificationRecipients();\r\n if (customNotificationRecipients.size() > 0) {\r\n JsonArray users = new JsonArray();\r\n for (BoxUser.Info user : customNotificationRecipients) {\r\n JsonObject userJSON = new JsonObject()\r\n .add(\"type\", \"user\")\r\n .add(\"id\", user.getID());\r\n users.add(userJSON);\r\n }\r\n requestJSON.add(\"custom_notification_recipients\", users);\r\n }\r\n }\r\n request.setBody(requestJSON.toString());\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n BoxRetentionPolicy createdPolicy = new BoxRetentionPolicy(api, responseJSON.get(\"id\").asString());\r\n return createdPolicy.new Info(responseJSON);\r\n }", "public void openBlockingInterruptable()\n throws InterruptedException {\n // We need to thread this call in order to interrupt it (when Ctrl-C occurs).\n connectionThread = new Thread(() -> {\n // This thread can't be interrupted from another thread.\n // Will stay alive until System.exit is called.\n Thread thr = new Thread(() -> super.openBlocking(),\n \"CLI Terminal Connection (uninterruptable)\");\n thr.start();\n try {\n thr.join();\n } catch (InterruptedException ex) {\n // XXX OK, interrupted, just leaving.\n }\n }, \"CLI Terminal Connection (interruptable)\");\n connectionThread.start();\n connectionThread.join();\n }", "private BigInteger getDaysOfTheWeek(RecurringData data)\n {\n int value = 0;\n for (Day day : Day.values())\n {\n if (data.getWeeklyDay(day))\n {\n value = value | DAY_MASKS[day.getValue()];\n }\n }\n return BigInteger.valueOf(value);\n }" ]
Close the open stream. Close the stream if it was opened before
[ "public synchronized final void closeStream() {\n try {\n if ((stream != null) && (streamState == StreamStates.OPEN)) {\n stream.close();\n stream = null;\n }\n streamState = StreamStates.CLOSED;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }" ]
[ "@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 }", "@Override\n public void setBody(String body) {\n super.setBody(body);\n this.jsonValue = JsonValue.readFrom(body);\n }", "public static nsip6[] get(nitro_service service) throws Exception{\n\t\tnsip6 obj = new nsip6();\n\t\tnsip6[] response = (nsip6[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void sendJsonToUrl(Object data, String url) {\n sendToUrl(JSON.toJSONString(data), url);\n }", "public void sendMessageToAgentsWithExtraProperties(String[] agent_name,\n String msgtype, Object message_content,\n ArrayList<Object> properties, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n\n for (Object property : properties) {\n // Logger logger = Logger.getLogger(\"JadexMessenger\");\n // logger.info(\"Sending message with extra property: \"+property.get(0)+\", with value \"+property.get(1));\n hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));\n }\n\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }", "protected void beforeMaterialization()\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\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.beforeMaterialization(this, _id);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public static int writeVint(byte[] dest, int offset, int i) {\n if (i >= -112 && i <= 127) {\n dest[offset++] = (byte) i;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n dest[offset++] = (byte) len;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n for (int idx = len; idx != 0; idx--) {\n int shiftbits = (idx - 1) * 8;\n long mask = 0xFFL << shiftbits;\n dest[offset++] = (byte) ((i & mask) >> shiftbits);\n }\n }\n\n return offset;\n }", "public Date getCompleteThrough()\n {\n Date value = (Date) getCachedValue(TaskField.COMPLETE_THROUGH);\n if (value == null)\n {\n int percentComplete = NumberHelper.getInt(getPercentageComplete());\n switch (percentComplete)\n {\n case 0:\n {\n break;\n }\n\n case 100:\n {\n value = getActualFinish();\n break;\n }\n\n default:\n {\n Date actualStart = getActualStart();\n Duration duration = getDuration();\n if (actualStart != null && duration != null)\n {\n double durationValue = (duration.getDuration() * percentComplete) / 100d;\n duration = Duration.getInstance(durationValue, duration.getUnits());\n ProjectCalendar calendar = getEffectiveCalendar();\n value = calendar.getDate(actualStart, duration, true);\n }\n break;\n }\n }\n\n set(TaskField.COMPLETE_THROUGH, value);\n }\n return value;\n }", "public void validateOperations(final List<ModelNode> operations) {\n if (operations == null) {\n return;\n }\n\n for (ModelNode operation : operations) {\n try {\n validateOperation(operation);\n } catch (RuntimeException e) {\n if (exitOnError) {\n throw e;\n } else {\n System.out.println(\"---- Operation validation error:\");\n System.out.println(e.getMessage());\n }\n\n }\n }\n }" ]
Adds a new role to the list of defined roles. @param roleName - The name of the role being added.
[ "public synchronized void addRoleMapping(final String roleName) {\n HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);\n if (newRoles.containsKey(roleName) == false) {\n newRoles.put(roleName, new RoleMappingImpl(roleName));\n roleMappings = Collections.unmodifiableMap(newRoles);\n }\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 }", "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 void fillRect(int x, int y, int w, int h, Color c) {\n int color = c.getRGB();\n for (int i = x; i < x + w; i++) {\n for (int j = y; j < y + h; j++) {\n setIntColor(i, j, color);\n }\n }\n }", "private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}", "public void drawText(String text, Font font, Rectangle box, Color fontColor) {\n\t\ttemplate.saveState();\n\t\t// get the font\n\t\tDefaultFontMapper mapper = new DefaultFontMapper();\n\t\tBaseFont bf = mapper.awtToPdf(font);\n\t\ttemplate.setFontAndSize(bf, font.getSize());\n\n\t\t// calculate descent\n\t\tfloat descent = 0;\n\t\tif (text != null) {\n\t\t\tdescent = bf.getDescentPoint(text, font.getSize());\n\t\t}\n\n\t\t// calculate the fitting size\n\t\tRectangle fit = getTextSize(text, font);\n\n\t\t// draw text if necessary\n\t\ttemplate.setColorFill(fontColor);\n\t\ttemplate.beginText();\n\t\ttemplate.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f\n\t\t\t\t* (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f\n\t\t\t\t* (box.getHeight() - fit.getHeight()) - descent, 0);\n\t\ttemplate.endText();\n\t\ttemplate.restoreState();\n\t}", "public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) {\n\t\tif (s3 == null || s3BucketName == null) {\n\t\t\tString errorMessage = \"S3 client and/or S3 bucket name cannot be null.\";\n\t\t\tLOG.error(errorMessage);\n\t\t\tthrow new AmazonClientException(errorMessage);\n\t\t}\n\t\tif (isLargePayloadSupportEnabled()) {\n\t\t\tLOG.warn(\"Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName.\");\n\t\t}\n\t\tthis.s3 = s3;\n\t\tthis.s3BucketName = s3BucketName;\n\t\tlargePayloadSupport = true;\n\t\tLOG.info(\"Large-payload support enabled.\");\n\t}", "public static String getPrettyMapOfContiguousPartitionRunLengths(final Cluster cluster,\n int zoneId) {\n Map<Integer, Integer> runLengthToCount = getMapOfContiguousPartitionRunLengths(cluster,\n zoneId);\n String prettyHistogram = \"[\";\n boolean first = true;\n Set<Integer> runLengths = new TreeSet<Integer>(runLengthToCount.keySet());\n for(int runLength: runLengths) {\n if(first) {\n first = false;\n } else {\n prettyHistogram += \", \";\n }\n prettyHistogram += \"{\" + runLength + \" : \" + runLengthToCount.get(runLength) + \"}\";\n }\n prettyHistogram += \"]\";\n return prettyHistogram;\n }", "private String addPathProperty(final List<String> command, final String typeName, final String propertyName, final Map<String, String> properties, final DirectoryGrouping directoryGrouping,\n final File typeDir, File serverDir) {\n final String result;\n final String value = properties.get(propertyName);\n if (value == null) {\n switch (directoryGrouping) {\n case BY_TYPE:\n result = getAbsolutePath(typeDir, \"servers\", serverName);\n break;\n case BY_SERVER:\n default:\n result = getAbsolutePath(serverDir, typeName);\n break;\n }\n properties.put(propertyName, result);\n } else {\n final File dir = new File(value);\n switch (directoryGrouping) {\n case BY_TYPE:\n result = getAbsolutePath(dir, \"servers\", serverName);\n break;\n case BY_SERVER:\n default:\n result = getAbsolutePath(dir, serverName);\n break;\n }\n }\n command.add(String.format(\"-D%s=%s\", propertyName, result));\n return result;\n }", "public static byte[] toUnixLineEndings( InputStream input ) throws IOException {\n String encoding = \"ISO-8859-1\";\n FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding));\n filter.setEol(FixCrLfFilter.CrLf.newInstance(\"unix\"));\n\n ByteArrayOutputStream filteredFile = new ByteArrayOutputStream();\n Utils.copy(new ReaderInputStream(filter, encoding), filteredFile);\n\n return filteredFile.toByteArray();\n }" ]
Adds an alias to the currently configured site. @param alias the URL of the alias server @param redirect <code>true</code> to always redirect to main URL @param offset the optional time offset for this alias
[ "public void addAliasToConfigSite(String alias, String redirect, String offset) {\n\n long timeOffset = 0;\n try {\n timeOffset = Long.parseLong(offset);\n } catch (Throwable e) {\n // ignore\n }\n CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset);\n boolean redirectVal = new Boolean(redirect).booleanValue();\n siteMatcher.setRedirect(redirectVal);\n m_aliases.add(siteMatcher);\n }" ]
[ "public static service_dospolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tservice_dospolicy_binding obj = new service_dospolicy_binding();\n\t\tobj.set_name(name);\n\t\tservice_dospolicy_binding response[] = (service_dospolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private File getDisabledMarkerFile(long version) throws PersistenceFailureException {\n File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version);\n if (versionDirArray.length == 0) {\n throw new PersistenceFailureException(\"getDisabledMarkerFile did not find the requested version directory\" +\n \" on disk. Version: \" + version + \", rootDir: \" + rootDir);\n }\n File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME);\n return disabledMarkerFile;\n }", "public static DMatrixRMaj diagonal(int numRows , int numCols , double min , double max , Random rand ) {\n if( max < min )\n throw new IllegalArgumentException(\"The max must be >= the min\");\n\n DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);\n\n int N = Math.min(numRows,numCols);\n\n double r = max-min;\n\n for( int i = 0; i < N; i++ ) {\n ret.set(i,i, rand.nextDouble()*r+min);\n }\n\n return ret;\n }", "public static float[][] toFloat(int[][] array) {\n float[][] n = new float[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (float) array[i][j];\n }\n }\n return n;\n }", "static WeldContainer startInitialization(String id, Deployment deployment, Bootstrap bootstrap) {\n if (SINGLETON.isSet(id)) {\n throw WeldSELogger.LOG.weldContainerAlreadyRunning(id);\n }\n WeldContainer weldContainer = new WeldContainer(id, deployment, bootstrap);\n SINGLETON.set(id, weldContainer);\n RUNNING_CONTAINER_IDS.add(id);\n return weldContainer;\n }", "public static DMatrixRMaj symmetricWithEigenvalues(int num, Random rand , double ...eigenvalues ) {\n DMatrixRMaj V = RandomMatrices_DDRM.orthogonal(num,num,rand);\n DMatrixRMaj D = CommonOps_DDRM.diag(eigenvalues);\n\n DMatrixRMaj temp = new DMatrixRMaj(num,num);\n\n CommonOps_DDRM.mult(V,D,temp);\n CommonOps_DDRM.multTransB(temp,V,D);\n\n return D;\n }", "public static appflowpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tappflowpolicylabel obj = new appflowpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tappflowpolicylabel response = (appflowpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }", "public static Collection<String> getKnownPGPSecureRingLocations() {\n final LinkedHashSet<String> locations = new LinkedHashSet<String>();\n\n final String os = System.getProperty(\"os.name\");\n final boolean runOnWindows = os == null || os.toLowerCase().contains(\"win\");\n\n if (runOnWindows) {\n // The user's roaming profile on Windows, via environment\n final String windowsRoaming = System.getenv(\"APPDATA\");\n if (windowsRoaming != null) {\n locations.add(joinLocalPath(windowsRoaming, \"gnupg\", \"secring.gpg\"));\n }\n\n // The user's local profile on Windows, via environment\n final String windowsLocal = System.getenv(\"LOCALAPPDATA\");\n if (windowsLocal != null) {\n locations.add(joinLocalPath(windowsLocal, \"gnupg\", \"secring.gpg\"));\n }\n\n // The Windows installation directory\n final String windir = System.getProperty(\"WINDIR\");\n if (windir != null) {\n // Local Profile on Windows 98 and ME\n locations.add(joinLocalPath(windir, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n }\n\n final String home = System.getProperty(\"user.home\");\n\n if (home != null && runOnWindows) {\n // These are for various flavours of Windows\n // if the environment variables above have failed\n\n // Roaming profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Roaming\", \"gnupg\", \"secring.gpg\"));\n // Local profile on Vista and later\n locations.add(joinLocalPath(home, \"AppData\", \"Local\", \"gnupg\", \"secring.gpg\"));\n // Roaming profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Application Data\", \"gnupg\", \"secring.gpg\"));\n // Local profile on 2000 and XP\n locations.add(joinLocalPath(home, \"Local Settings\", \"Application Data\", \"gnupg\", \"secring.gpg\"));\n }\n\n // *nix, including OS X\n if (home != null) {\n locations.add(joinLocalPath(home, \".gnupg\", \"secring.gpg\"));\n }\n\n return locations;\n }" ]
Extracts a house holder vector from the rows of A and stores it in u @param A Complex matrix with householder vectors stored in the upper right triangle @param row Row in A @param col0 first row in A (implicitly assumed to be r + i0) @param col1 last row +1 in A @param u Output array storage @param offsetU first index in U
[ "public static void extractHouseholderRow( ZMatrixRMaj A ,\n int row ,\n int col0, int col1 , double u[], int offsetU )\n {\n int indexU = (offsetU+col0)*2;\n u[indexU] = 1;\n u[indexU+1] = 0;\n\n int indexA = (row*A.numCols + (col0+1))*2;\n System.arraycopy(A.data,indexA,u,indexU+2,(col1-col0-1)*2);\n }" ]
[ "public static void initializeInternalProject(CommandExecutor executor) {\n final long creationTimeMillis = System.currentTimeMillis();\n try {\n executor.execute(createProject(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof ProjectExistsException)) {\n throw new Error(\"failed to initialize an internal project\", cause);\n }\n }\n // These repositories might be created when creating an internal project, but we try to create them\n // again here in order to make sure them exist because sometimes their names are changed.\n for (final String repo : ImmutableList.of(Project.REPO_META, Project.REPO_DOGMA)) {\n try {\n executor.execute(createRepository(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ, repo))\n .get();\n } catch (Throwable cause) {\n cause = Exceptions.peel(cause);\n if (!(cause instanceof RepositoryExistsException)) {\n throw new Error(cause);\n }\n }\n }\n }", "public void setDefault() {\n try {\n TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);\n String phone = telephonyManager.getLine1Number();\n if (phone != null && !phone.isEmpty()) {\n this.setNumber(phone);\n } else {\n String iso = telephonyManager.getNetworkCountryIso();\n setEmptyDefault(iso);\n }\n } catch (SecurityException e) {\n setEmptyDefault();\n }\n }", "Item newStringishItem(final int type, final String value) {\n key2.set(type, value, null, null);\n Item result = get(key2);\n if (result == null) {\n pool.put12(type, newUTF8(value));\n result = new Item(index++, key2);\n put(result);\n }\n return result;\n }", "private void processStages() {\n\n // Locate the next step to execute.\n ModelNode primaryResponse = null;\n Step step;\n do {\n step = steps.get(currentStage).pollFirst();\n if (step == null) {\n\n if (currentStage == Stage.MODEL && addModelValidationSteps()) {\n continue;\n }\n // No steps remain in this stage; give subclasses a chance to check status\n // and approve moving to the next stage\n if (!tryStageCompleted(currentStage)) {\n // Can't continue\n resultAction = ResultAction.ROLLBACK;\n executeResultHandlerPhase(null);\n return;\n }\n // Proceed to the next stage\n if (currentStage.hasNext()) {\n currentStage = currentStage.next();\n if (currentStage == Stage.VERIFY) {\n // a change was made to the runtime. Thus, we must wait\n // for stability before resuming in to verify.\n try {\n awaitServiceContainerStability();\n } catch (InterruptedException e) {\n cancelled = true;\n handleContainerStabilityFailure(primaryResponse, e);\n executeResultHandlerPhase(null);\n return;\n } catch (TimeoutException te) {\n // The service container is in an unknown state; but we don't require restart\n // because rollback may allow the container to stabilize. We force require-restart\n // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)\n //processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback\n handleContainerStabilityFailure(primaryResponse, te);\n executeResultHandlerPhase(null);\n return;\n }\n }\n }\n } else {\n // The response to the first step is what goes to the outside caller\n if (primaryResponse == null) {\n primaryResponse = step.response;\n }\n // Execute the step, but make sure we always finalize any steps\n Throwable toThrow = null;\n // Whether to return after try/finally\n boolean exit = false;\n try {\n CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step);\n if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) {\n executeStep(step);\n } else {\n String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED\n ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD;\n step.response.get(RESPONSE_HEADERS, header).set(true);\n }\n } catch (RuntimeException | Error re) {\n resultAction = ResultAction.ROLLBACK;\n toThrow = re;\n } finally {\n // See if executeStep put us in a state where we shouldn't do any more\n if (toThrow != null || !canContinueProcessing()) {\n // We're done.\n executeResultHandlerPhase(toThrow);\n exit = true; // we're on the return path\n }\n }\n if (exit) {\n return;\n }\n }\n } while (currentStage != Stage.DONE);\n\n assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps\n\n // All steps ran and canContinueProcessing returned true for the last one, so...\n executeDoneStage(primaryResponse);\n }", "public static base_response delete(nitro_service client, String fipskeyname) throws Exception {\n\t\tsslfipskey deleteresource = new sslfipskey();\n\t\tdeleteresource.fipskeyname = fipskeyname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void delete(Vertex vtx) {\n if (vtx.prev == null) {\n head = vtx.next;\n } else {\n vtx.prev.next = vtx.next;\n }\n if (vtx.next == null) {\n tail = vtx.prev;\n } else {\n vtx.next.prev = vtx.prev;\n }\n }", "private void checkLocking(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);\r\n\r\n if (!\"TIMESTAMP\".equals(jdbcType) && !\"INTEGER\".equals(jdbcType))\r\n {\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_LOCKING, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has locking set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UPDATE_LOCK, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has update-lock set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n }\r\n }", "public void addSource(GVRAudioSource audioSource)\n {\n synchronized (mAudioSources)\n {\n if (!mAudioSources.contains(audioSource))\n {\n audioSource.setListener(this);\n mAudioSources.add(audioSource);\n }\n }\n }", "public Request option(String key, Object value) {\n this.options.put(key, value);\n return this;\n }" ]
Sets the appropriate headers to response of this request. @param response The HttpServletResponse response object.
[ "private void setResponeHeaders(HttpServletResponse response) {\n\n response.setHeader(\"Cache-Control\", \"no-store, no-cache\");\n response.setHeader(\"Pragma\", \"no-cache\");\n response.setDateHeader(\"Expires\", System.currentTimeMillis());\n response.setContentType(\"text/plain; charset=utf-8\");\n response.setCharacterEncoding(\"utf-8\");\n }" ]
[ "public static base_responses add(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 addresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nsip6();\n\t\t\t\taddresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\taddresources[i].scope = resources[i].scope;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].nd = resources[i].nd;\n\t\t\t\taddresources[i].icmp = resources[i].icmp;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t\taddresources[i].telnet = resources[i].telnet;\n\t\t\t\taddresources[i].ftp = resources[i].ftp;\n\t\t\t\taddresources[i].gui = resources[i].gui;\n\t\t\t\taddresources[i].ssh = resources[i].ssh;\n\t\t\t\taddresources[i].snmp = resources[i].snmp;\n\t\t\t\taddresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\taddresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\taddresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\taddresources[i].hostroute = resources[i].hostroute;\n\t\t\t\taddresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\taddresources[i].metric = resources[i].metric;\n\t\t\t\taddresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\taddresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\taddresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].map = resources[i].map;\n\t\t\t\taddresources[i].ownernode = resources[i].ownernode;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }", "public Rectangle toRelative(Rectangle rect) {\n\t\treturn new Rectangle(rect.getLeft() - origX, rect.getBottom() - origY, rect.getRight() - origX, rect.getTop()\n\t\t\t\t- origY);\n\t}", "protected void add(Widget child, Element container) {\n\n // Detach new child.\n child.removeFromParent();\n\n // Logical attach.\n getChildren().add(child);\n\n // Physical attach.\n DOM.appendChild(container, child.getElement());\n\n // Adopt.\n adopt(child);\n }", "public WebhookResponse send(String url, Payload payload) throws IOException {\n SlackHttpClient httpClient = getHttpClient();\n Response httpResponse = httpClient.postJsonPostRequest(url, payload);\n String body = httpResponse.body().string();\n httpClient.runHttpResponseListeners(httpResponse, body);\n\n return WebhookResponse.builder()\n .code(httpResponse.code())\n .message(httpResponse.message())\n .body(body)\n .build();\n }", "public void deleteServerGroup(int id) {\n try {\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = \" + id + \";\");\n\n sqlService.executeUpdate(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = \" + id);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "@Override\n public void removeNamespace(final MongoNamespace namespace) {\n this.instanceLock.writeLock().lock();\n try {\n if (!this.nsStreamers.containsKey(namespace)) {\n return;\n }\n final NamespaceChangeStreamListener streamer = this.nsStreamers.get(namespace);\n streamer.stop();\n this.nsStreamers.remove(namespace);\n } finally {\n this.instanceLock.writeLock().unlock();\n }\n }", "public long[] keys() {\n long[] values = new long[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n values[idx++] = entry.key;\n entry = entry.next;\n }\n }\n return values;\n }", "public WebSocketContext sendJsonToUser(Object data, String username) {\n return sendToTagged(JSON.toJSONString(data), username);\n }" ]
Get the bone index for the bone with the given name. @param bonename string identifying the bone whose index you want @return 0 based bone index or -1 if bone with that name is not found.
[ "public int getBoneIndex(String bonename)\n {\n for (int i = 0; i < getNumBones(); ++i)\n\n if (mBoneNames[i].equals(bonename))\n return i;\n return -1;\n }" ]
[ "public static QRDecomposition<DoubleMatrix> qr(DoubleMatrix A) {\n int minmn = min(A.rows, A.columns);\n DoubleMatrix result = A.dup();\n DoubleMatrix tau = new DoubleMatrix(minmn);\n SimpleBlas.geqrf(result, tau);\n DoubleMatrix R = new DoubleMatrix(A.rows, A.columns);\n for (int i = 0; i < A.rows; i++) {\n for (int j = i; j < A.columns; j++) {\n R.put(i, j, result.get(i, j));\n }\n }\n DoubleMatrix Q = DoubleMatrix.eye(A.rows);\n SimpleBlas.ormqr('L', 'N', result, tau, Q);\n return new QRDecomposition<DoubleMatrix>(Q, R);\n }", "private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns)\n {\n Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>();\n for (ColumnDefinition def : columns)\n {\n map.put(def.getName(), def);\n }\n return map;\n }", "private void refreshMetadataCache(final Queue<WindupMetadataSystem> metadataSystemCache, final DecompilerSettings settings)\n {\n metadataSystemCache.clear();\n for (int i = 0; i < this.getNumberOfThreads(); i++)\n {\n metadataSystemCache.add(new NoRetryMetadataSystem(settings.getTypeLoader()));\n }\n }", "public static int cudnnActivationForward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnActivationForwardNative(handle, activationDesc, alpha, xDesc, x, beta, yDesc, y));\n }", "private String getIndirectionTableColName(TableAlias mnAlias, String path)\r\n {\r\n int dotIdx = path.lastIndexOf(\".\");\r\n String column = path.substring(dotIdx);\r\n return mnAlias.alias + column;\r\n }", "protected FluentModelTImpl find(String key) {\n for (Map.Entry<String, FluentModelTImpl> entry : this.childCollection.entrySet()) {\n if (entry.getKey().equalsIgnoreCase(key)) {\n return entry.getValue();\n }\n }\n return null;\n }", "public static tmtrafficaction get(nitro_service service, String name) throws Exception{\n\t\ttmtrafficaction obj = new tmtrafficaction();\n\t\tobj.set_name(name);\n\t\ttmtrafficaction response = (tmtrafficaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "final void begin() {\n if (LogFileCompressionStrategy.existsFor(this.properties)) {\n final Thread thread = new Thread(this, \"Log4J File Compressor\");\n thread.setDaemon(true);\n thread.start();\n this.threadRef = thread;\n }\n }", "public static double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }" ]
Convert the continuous values into discrete values by chopping up the distribution into several equally-sized intervals.
[ "protected static Map<Double, Double> doQuantization(double max,\n double min,\n double[] values)\n {\n double range = max - min;\n int noIntervals = 20;\n double intervalSize = range / noIntervals;\n int[] intervals = new int[noIntervals];\n for (double value : values)\n {\n int interval = Math.min(noIntervals - 1,\n (int) Math.floor((value - min) / intervalSize));\n assert interval >= 0 && interval < noIntervals : \"Invalid interval: \" + interval;\n ++intervals[interval];\n }\n Map<Double, Double> discretisedValues = new HashMap<Double, Double>();\n for (int i = 0; i < intervals.length; i++)\n {\n // Correct the value to take into account the size of the interval.\n double value = (1 / intervalSize) * (double) intervals[i];\n discretisedValues.put(min + ((i + 0.5) * intervalSize), value);\n }\n return discretisedValues;\n }" ]
[ "public static cacheobject[] get(nitro_service service) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service);\n\t\treturn response;\n\t}", "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 }", "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 static <K, V> Map<K, V> of(K key, V value) {\n return new ImmutableMapEntry<K, V>(key, value);\n }", "@Subscribe\n public void onEnd(AggregatedQuitEvent e) {\n try {\n writeHints(hintsFile, hints);\n } catch (IOException exception) {\n outer.log(\"Could not write back the hints file.\", exception, Project.MSG_ERR);\n }\n }", "protected void addPoint(double time, RandomVariable value, boolean isParameter) {\n\t\tsynchronized (rationalFunctionInterpolationLazyInitLock) {\n\t\t\tif(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {\n\t\t\t\tboolean containsOne = false; int index=0;\n\t\t\t\tfor(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}\n\t\t\t\tif(containsOne && isParameter == false) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index\" + index + \").\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);\n\n\t\t\tint index = getTimeIndex(time);\n\t\t\tif(index >= 0) {\n\t\t\t\tif(points.get(index).value == interpolationEntityValue) {\n\t\t\t\t\treturn;\t\t\t// Already in list\n\t\t\t\t} else if(isParameter) {\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeException(\"Trying to add a value for a time for which another value already exists.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Insert the new point, retain ordering.\n\t\t\t\tPoint point = new Point(time, interpolationEntityValue, isParameter);\n\t\t\t\tpoints.add(-index-1, point);\n\n\t\t\t\tif(isParameter) {\n\t\t\t\t\t// Add this point also to the list of parameters\n\t\t\t\t\tint parameterIndex = getParameterIndex(time);\n\t\t\t\t\tif(parameterIndex >= 0) {\n\t\t\t\t\t\tnew RuntimeException(\"CurveFromInterpolationPoints inconsistent.\");\n\t\t\t\t\t}\n\t\t\t\t\tpointsBeingParameters.add(-parameterIndex-1, point);\n\t\t\t\t}\n\t\t\t}\n\t\t\trationalFunctionInterpolation = null;\n\t\t\tcurveCacheReference = null;\n\t\t}\n\t}", "public void removeCollaborator(String appName, String collaborator) {\n connection.execute(new SharingRemove(appName, collaborator), apiKey);\n }", "private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }", "public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) {\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final DependencyReport report = new DependencyReport(moduleId);\n final List<String> done = new ArrayList<String>();\n for(final DbModule submodule: DataUtils.getAllSubmodules(module)){\n done.add(submodule.getId());\n }\n\n addModuleToReport(report, module, filters, done, 1);\n\n return report;\n }" ]
Get the unique set of declared methods on the leaf class and all superclasses. Leaf class methods are included first and while traversing the superclass hierarchy any methods found with signatures matching a method already included are filtered out.
[ "public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }" ]
[ "private static Class<?> getRawClass(Type type) {\n if (type instanceof Class) {\n return (Class<?>) type;\n }\n if (type instanceof ParameterizedType) {\n return getRawClass(((ParameterizedType) type).getRawType());\n }\n // For TypeVariable and WildcardType, returns the first upper bound.\n if (type instanceof TypeVariable) {\n return getRawClass(((TypeVariable) type).getBounds()[0]);\n }\n if (type instanceof WildcardType) {\n return getRawClass(((WildcardType) type).getUpperBounds()[0]);\n }\n if (type instanceof GenericArrayType) {\n Class<?> componentClass = getRawClass(((GenericArrayType) type).getGenericComponentType());\n return Array.newInstance(componentClass, 0).getClass();\n }\n // This shouldn't happen as we captured all implementations of Type above (as or Java 8)\n throw new IllegalArgumentException(\"Unsupported type \" + type + \" of type class \" + type.getClass());\n }", "public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }", "public static double[][] toDouble(int[][] array) {\n double[][] n = new double[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (double) array[i][j];\n }\n }\n return n;\n }", "private static JSONObject parseBounds(Bounds bounds) throws JSONException {\n if (bounds != null) {\n JSONObject boundsObject = new JSONObject();\n JSONObject lowerRight = new JSONObject();\n JSONObject upperLeft = new JSONObject();\n\n lowerRight.put(\"x\",\n bounds.getLowerRight().getX().doubleValue());\n lowerRight.put(\"y\",\n bounds.getLowerRight().getY().doubleValue());\n\n upperLeft.put(\"x\",\n bounds.getUpperLeft().getX().doubleValue());\n upperLeft.put(\"y\",\n bounds.getUpperLeft().getY().doubleValue());\n\n boundsObject.put(\"lowerRight\",\n lowerRight);\n boundsObject.put(\"upperLeft\",\n upperLeft);\n\n return boundsObject;\n }\n\n return new JSONObject();\n }", "@SuppressWarnings(\"unchecked\")\n public void setVars(final Map<String, ? extends Object> vars) {\n this.vars = (Map<String, Object>)vars;\n }", "public static String getDatatypeIriFromJsonDatatype(String jsonDatatype) {\n\t\tswitch (jsonDatatype) {\n\t\tcase JSON_DT_ITEM:\n\t\t\treturn DT_ITEM;\n\t\tcase JSON_DT_PROPERTY:\n\t\t\treturn DT_PROPERTY;\n\t\tcase JSON_DT_GLOBE_COORDINATES:\n\t\t\treturn DT_GLOBE_COORDINATES;\n\t\tcase JSON_DT_URL:\n\t\t\treturn DT_URL;\n\t\tcase JSON_DT_COMMONS_MEDIA:\n\t\t\treturn DT_COMMONS_MEDIA;\n\t\tcase JSON_DT_TIME:\n\t\t\treturn DT_TIME;\n\t\tcase JSON_DT_QUANTITY:\n\t\t\treturn DT_QUANTITY;\n\t\tcase JSON_DT_STRING:\n\t\t\treturn DT_STRING;\n\t\tcase JSON_DT_MONOLINGUAL_TEXT:\n\t\t\treturn DT_MONOLINGUAL_TEXT;\n\t\tdefault:\n\t\t\tif(!JSON_DATATYPE_PATTERN.matcher(jsonDatatype).matches()) {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid JSON datatype \\\"\" + jsonDatatype + \"\\\"\");\n\t\t\t}\n\n\t\t\tString[] parts = jsonDatatype.split(\"-\");\n\t\t\tfor(int i = 0; i < parts.length; i++) {\n\t\t\t\tparts[i] = StringUtils.capitalize(parts[i]);\n\t\t\t}\n\t\t\treturn \"http://wikiba.se/ontology#\" + StringUtils.join(parts);\n\t\t}\n\t}", "public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}", "public static String detokenize(List<String> tokens) {\n return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens));\n }", "private void setup(DMatrixRBlock orig) {\n blockLength = orig.blockLength;\n dataW.blockLength = blockLength;\n dataWTA.blockLength = blockLength;\n\n this.dataA = orig;\n A.original = dataA;\n\n int l = Math.min(blockLength,orig.numCols);\n dataW.reshape(orig.numRows,l,false);\n dataWTA.reshape(l,orig.numRows,false);\n Y.original = orig;\n Y.row1 = W.row1 = orig.numRows;\n if( temp.length < blockLength )\n temp = new double[blockLength];\n if( gammas.length < orig.numCols )\n gammas = new double[ orig.numCols ];\n\n if( saveW ) {\n dataW.reshape(orig.numRows,orig.numCols,false);\n }\n }" ]
Returns the Organization that produce this artifact or null if there is none @param dbArtifact DbArtifact @return DbOrganization
[ "public DbOrganization getOrganization(final DbArtifact dbArtifact) {\n final DbModule module = getModule(dbArtifact);\n\n if(module == null || module.getOrganization() == null){\n return null;\n }\n\n return repositoryHandler.getOrganization(module.getOrganization());\n }" ]
[ "private void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }", "public Where<T, ID> eq(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "public static String capitalizePropertyName(String s) {\r\n\t\tif (s.length() == 0) {\r\n\t\t\treturn s;\r\n\t\t}\r\n\r\n\t\tchar[] chars = s.toCharArray();\r\n\t\tchars[0] = Character.toUpperCase(chars[0]);\r\n\t\treturn new String(chars);\r\n\t}", "public synchronized Object next() throws NoSuchElementException\r\n {\r\n try\r\n {\r\n if (!isHasCalledCheck())\r\n {\r\n hasNext();\r\n }\r\n setHasCalledCheck(false);\r\n if (getHasNext())\r\n {\r\n Object obj = getObjectFromResultSet();\r\n m_current_row++;\r\n\r\n // Invoke events on PersistenceBrokerAware instances and listeners\r\n // set target object\r\n if (!disableLifeCycleEvents)\r\n {\r\n getAfterLookupEvent().setTarget(obj);\r\n getBroker().fireBrokerEvent(getAfterLookupEvent());\r\n getAfterLookupEvent().setTarget(null);\r\n } \r\n return obj;\r\n }\r\n else\r\n {\r\n throw new NoSuchElementException(\"inner hasNext was false\");\r\n }\r\n }\r\n catch (ResourceClosedException ex)\r\n {\r\n autoReleaseDbResources();\r\n throw ex;\r\n }\r\n catch (NoSuchElementException ex)\r\n {\r\n autoReleaseDbResources();\r\n logger.error(\"Error while iterate ResultSet for query \" + m_queryObject, ex);\r\n throw new NoSuchElementException(\"Could not obtain next object: \" + ex.getMessage());\r\n }\r\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 }", "public static <K,V> MultiValueMap<K,V> unmodifiableMultiValueMap(MultiValueMap<? extends K, ? extends V> map) {\n\t\tAssert.notNull(map, \"'map' must not be null\");\n\t\tMap<K, List<V>> result = new LinkedHashMap<K, List<V>>(map.size());\n\t\tfor (Map.Entry<? extends K, ? extends List<? extends V>> entry : map.entrySet()) {\n\t\t\tList<V> values = Collections.unmodifiableList(entry.getValue());\n\t\t\tresult.put(entry.getKey(), values);\n\t\t}\n\t\tMap<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result);\n\t\treturn toMultiValueMap(unmodifiableMap);\n\t}", "protected List<I_CmsFacetQueryItem> parseFacetQueryItems(final String path) throws Exception {\n\n final List<I_CmsXmlContentValue> values = m_xml.getValues(path, m_locale);\n if (values == null) {\n return null;\n } else {\n List<I_CmsFacetQueryItem> parsedItems = new ArrayList<I_CmsFacetQueryItem>(values.size());\n for (I_CmsXmlContentValue value : values) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(value.getPath() + \"/\");\n if (null != item) {\n parsedItems.add(item);\n } else {\n // TODO: log\n }\n }\n return parsedItems;\n }\n }", "public void startDockerMachine(String cliPathExec, String machineName) {\n commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec), \"start\", machineName);\n this.manuallyStarted = true;\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 }" ]
Get list of Jobs from a queue. @param jedis @param queueName @param jobOffset @param jobCount @return
[ "private List<Job> getJobs(final Jedis jedis, final String queueName, final long jobOffset, final long jobCount) throws Exception {\n final String key = key(QUEUE, queueName);\n final List<Job> jobs = new ArrayList<>();\n if (JedisUtils.isDelayedQueue(jedis, key)) { // If delayed queue, use ZRANGEWITHSCORES\n final Set<Tuple> elements = jedis.zrangeWithScores(key, jobOffset, jobOffset + jobCount - 1);\n for (final Tuple elementWithScore : elements) {\n final Job job = ObjectMapperFactory.get().readValue(elementWithScore.getElement(), Job.class);\n job.setRunAt(elementWithScore.getScore());\n jobs.add(job);\n }\n } else { // Else, use LRANGE\n final List<String> elements = jedis.lrange(key, jobOffset, jobOffset + jobCount - 1);\n for (final String element : elements) {\n jobs.add(ObjectMapperFactory.get().readValue(element, Job.class));\n }\n }\n return jobs;\n }" ]
[ "private void query(String zipcode) {\n /* Setup YQL query statement using dynamic zipcode. The statement searches geo.places\n for the zipcode and returns XML which includes the WOEID. For more info about YQL go\n to: http://developer.yahoo.com/yql/ */\n String qry = URLEncoder.encode(\"SELECT woeid FROM geo.places WHERE text=\" + zipcode + \" LIMIT 1\");\n\n // Generate request URI using the query statement\n URL url;\n try {\n // get URL content\n url = new URL(\"http://query.yahooapis.com/v1/public/yql?q=\" + qry);\n URLConnection conn = url.openConnection();\n\n InputStream content = conn.getInputStream();\n parseResponse(content);\n\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }", "public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }", "public void postModule(final Module module, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.moduleResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, module);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST module\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "public static base_responses add(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction addresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].profilename = resources[i].profilename;\n\t\t\t\taddresources[i].parameters = resources[i].parameters;\n\t\t\t\taddresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\taddresources[i].quiettime = resources[i].quiettime;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public String[] init(String[] argv, int min, int max,\n Collection<CommandLineParser.Option> options)\n throws IOException, SAXException {\n // parse command line\n parser = new CommandLineParser();\n parser.setMinimumArguments(min);\n parser.setMaximumArguments(max);\n parser.registerOption(new CommandLineParser.BooleanOption(\"reindex\", 'I'));\n if (options != null)\n for (CommandLineParser.Option option : options)\n parser.registerOption(option);\n\n try {\n argv = parser.parse(argv);\n } catch (CommandLineParser.CommandLineParserException e) {\n System.err.println(\"ERROR: \" + e.getMessage());\n usage();\n System.exit(1);\n }\n\n // do we need to reindex?\n boolean reindex = parser.getOptionState(\"reindex\");\n\n // load configuration\n config = ConfigLoader.load(argv[0]);\n database = config.getDatabase(reindex); // overwrite iff reindex\n if (database.isInMemory())\n reindex = true; // no other way to do it in this case\n\n // reindex, if requested\n if (reindex)\n reindex(config, database);\n\n return argv;\n }", "public 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 }", "public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,\n final int greedyAttempts,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<Integer> greedySwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(greedySwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(greedySwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n for(int i = 0; i < greedyAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,\n nodeIds,\n greedySwapMaxPartitionsPerNode,\n greedySwapMaxPartitionsPerZone,\n storeDefs);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (swap attempt \" + i + \" in zone \"\n + zoneIds.get(zoneIdOffset) + \")\");\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n return returnCluster;\n }", "public static String formatTimeISO8601(TimeValue value) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tDecimalFormat yearForm = new DecimalFormat(FORMAT_YEAR);\n\t\tDecimalFormat timeForm = new DecimalFormat(FORMAT_OTHER);\n\t\tif (value.getYear() > 0) {\n\t\t\tbuilder.append(\"+\");\n\t\t}\n\t\tbuilder.append(yearForm.format(value.getYear()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getMonth()));\n\t\tbuilder.append(\"-\");\n\t\tbuilder.append(timeForm.format(value.getDay()));\n\t\tbuilder.append(\"T\");\n\t\tbuilder.append(timeForm.format(value.getHour()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getMinute()));\n\t\tbuilder.append(\":\");\n\t\tbuilder.append(timeForm.format(value.getSecond()));\n\t\tbuilder.append(\"Z\");\n\t\treturn builder.toString();\n\t}", "@Override\r\n public void putAll(Map<? extends K, ? extends V> in) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n temp.putAll(in);\r\n map = temp;\r\n }\r\n } else {\r\n synchronized (map) {\r\n map.putAll(in);\r\n }\r\n }\r\n }" ]
Called when a previously created loader has finished its load. @param loader The Loader that has finished. @param data The data generated by the Loader.
[ "@Override\n public void onLoadFinished(final Loader<SortedList<T>> loader,\n final SortedList<T> data) {\n isLoading = false;\n mCheckedItems.clear();\n mCheckedVisibleViewHolders.clear();\n mFiles = data;\n mAdapter.setList(data);\n if (mCurrentDirView != null) {\n mCurrentDirView.setText(getFullPath(mCurrentPath));\n }\n // Stop loading now to avoid a refresh clearing the user's selections\n getLoaderManager().destroyLoader( 0 );\n }" ]
[ "public void copyNodeMetaData(ASTNode other) {\n if (other.metaDataMap == null) {\n return;\n }\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n metaDataMap.putAll(other.metaDataMap);\n }", "protected String getDBManipulationUrl()\r\n {\r\n JdbcConnectionDescriptor jcd = getConnection();\r\n\r\n return jcd.getProtocol()+\":\"+jcd.getSubProtocol()+\":\"+jcd.getDbAlias();\r\n }", "public static Observable<byte[]> downloadFileAsync(String url, Retrofit retrofit) {\n FileService service = retrofit.create(FileService.class);\n Observable<ResponseBody> response = service.download(url);\n return response.map(new Func1<ResponseBody, byte[]>() {\n @Override\n public byte[] call(ResponseBody responseBody) {\n try {\n return responseBody.bytes();\n } catch (IOException e) {\n throw Exceptions.propagate(e);\n }\n }\n });\n }", "public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }", "public static final Date getTime(byte[] data, int offset)\n {\n int time = getShort(data, offset) / 10;\n Calendar cal = DateHelper.popCalendar(EPOCH_DATE);\n cal.set(Calendar.HOUR_OF_DAY, (time / 60));\n cal.set(Calendar.MINUTE, (time % 60));\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n DateHelper.pushCalendar(cal);\n return (cal.getTime());\n }", "private void sendSyncControlCommand(DeviceUpdate target, byte command) throws IOException {\n ensureRunning();\n byte[] payload = new byte[SYNC_CONTROL_PAYLOAD.length];\n System.arraycopy(SYNC_CONTROL_PAYLOAD, 0, payload, 0, SYNC_CONTROL_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n payload[8] = getDeviceNumber();\n payload[12] = command;\n assembleAndSendPacket(Util.PacketType.SYNC_CONTROL, payload, target.getAddress(), BeatFinder.BEAT_PORT);\n }", "public TransformersSubRegistration getDomainRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS;\n return new TransformersSubRegistrationImpl(range, domain, address);\n }", "public static RgbaColor fromRgba(String rgba) {\n if (rgba.length() == 0) return getDefaultColor();\n\n String[] parts = getRgbaParts(rgba).split(\",\");\n if (parts.length == 4) {\n return new RgbaColor(parseInt(parts[0]),\n parseInt(parts[1]),\n parseInt(parts[2]),\n parseFloat(parts[3]));\n }\n else {\n return getDefaultColor();\n }\n }", "public void retrieveEngine() throws GeneralSecurityException, IOException {\n if (serverEngineFactory == null) {\n return;\n }\n engine = serverEngineFactory.retrieveHTTPServerEngine(nurl.getPort());\n if (engine == null) {\n engine = serverEngineFactory.getHTTPServerEngine(nurl.getHost(), nurl.getPort(), nurl.getProtocol());\n }\n\n assert engine != null;\n TLSServerParameters serverParameters = engine.getTlsServerParameters();\n if (serverParameters != null && serverParameters.getCertConstraints() != null) {\n CertificateConstraintsType constraints = serverParameters.getCertConstraints();\n if (constraints != null) {\n certConstraints = CertConstraintsJaxBUtils.createCertConstraints(constraints);\n }\n }\n\n // When configuring for \"http\", however, it is still possible that\n // Spring configuration has configured the port for https.\n if (!nurl.getProtocol().equals(engine.getProtocol())) {\n throw new IllegalStateException(\"Port \" + engine.getPort() + \" is configured with wrong protocol \\\"\" + engine.getProtocol() + \"\\\" for \\\"\" + nurl + \"\\\"\");\n }\n }" ]