query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Update an object in the database to change its id to the newId parameter. | [
"public int updateId(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache)\n\t\t\tthrows SQLException {\n\t\tif (mappedUpdateId == null) {\n\t\t\tmappedUpdateId = MappedUpdateId.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedUpdateId.execute(databaseConnection, data, newId, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);\n\t}",
"public String getName()\n {\n GVRSceneObject owner = getOwnerObject();\n String name = \"\";\n\n if (owner != null)\n {\n name = owner.getName();\n if (name == null)\n return \"\";\n }\n return name;\n }",
"public static base_response reset(nitro_service client, Interface resource) throws Exception {\n\t\tInterface resetresource = new Interface();\n\t\tresetresource.id = resource.id;\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}",
"public void setVolume(float volume)\n {\n // Save this in case this audio source is not being played yet\n mVolume = volume;\n if (isPlaying() && (getSourceId() != GvrAudioEngine.INVALID_ID))\n {\n // This will actually work only if the sound file is being played\n mAudioListener.getAudioEngine().setSoundVolume(getSourceId(), getVolume());\n }\n }",
"public static void resize(GVRMesh mesh, float xsize, float ysize, float zsize) {\n float dim[] = getBoundingSize(mesh);\n\n scale(mesh, xsize / dim[0], ysize / dim[1], zsize / dim[2]);\n }",
"private void clearWaveforms(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(previewHotCache.keySet())) {\n if (deck.player == player) {\n previewHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformPreviewUpdate(player, null); // Inform listeners that preview is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(detailHotCache.keySet())) {\n if (deck.player == player) {\n detailHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformDetailUpdate(player, null); // Inform listeners that detail is gone.\n }\n }\n }\n }",
"public void updateInfo(BoxWebLink.Info info) {\n URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(info.getPendingChanges());\n String body = info.getPendingChanges();\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n info.update(jsonObject);\n }",
"public static Document readDocumentFromString(String s) throws Exception {\r\n InputSource in = new InputSource(new StringReader(s));\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(false);\r\n return factory.newDocumentBuilder().parse(in);\r\n }",
"public void addBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final boolean statementBatchingSupported = m_batchStatementsInProgress.containsKey(stmt);\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n stmt.executeUpdate();\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.addBatch(stmt);\r\n }\r\n }"
] |
Creates a householder reflection.
(I-gamma*v*v')*x = tau*e1
<p>NOTE: Same as cs_house in csparse</p>
@param x (Input) Vector x (Output) Vector v. Modified.
@param xStart First index in X that is to be processed
@param xEnd Last + 1 index in x that is to be processed.
@param gamma (Output) Storage for computed gamma
@return variable tau | [
"public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) {\n double tau = 0;\n for (int i = xStart; i < xEnd ; i++) {\n double val = x[i] /= max;\n tau += val*val;\n }\n tau = Math.sqrt(tau);\n if( x[xStart] < 0 ) {\n tau = -tau;\n }\n double u_0 = x[xStart] + tau;\n gamma.value = u_0/tau;\n x[xStart] = 1;\n for (int i = xStart+1; i < xEnd ; i++) {\n x[i] /= u_0;\n }\n\n return -tau*max;\n }"
] | [
"public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) {\n return (List<Map<String, Object>>) collectify(mapper, source, List.class);\n }",
"public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }",
"public void setStringValue(String value) {\n\n if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {\n try {\n m_editValue = CmsLocationValue.parse(value);\n m_currentValue = m_editValue.cloneValue();\n displayValue();\n if ((m_popup != null) && m_popup.isVisible()) {\n m_popupContent.displayValues(m_editValue);\n updateMarkerPosition();\n }\n } catch (Exception e) {\n CmsLog.log(e.getLocalizedMessage() + \"\\n\" + CmsClientStringUtil.getStackTrace(e, \"\\n\"));\n }\n } else {\n m_currentValue = null;\n displayValue();\n }\n }",
"public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {\n\t\tMap<Double, RandomVariable> sum = new HashMap<>();\n\n\t\tfor(double time: timeDiscretization) {\n\t\t\tsum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));\n\t\t}\n\n\t\treturn new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);\n\t}",
"protected View postDeclineView() {\n\t\treturn new TopLevelWindowRedirect() {\n\t\t\t@Override\n\t\t\tprotected String getRedirectUrl(Map<String, ?> model) {\n\t\t\t\treturn postDeclineUrl;\n\t\t\t}\n\t\t};\n\t}",
"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 }",
"private boolean addonDependsOnReporting(Addon addon)\n {\n for (AddonDependency dep : addon.getDependencies())\n {\n if (dep.getDependency().equals(this.addon))\n {\n return true;\n }\n boolean subDep = addonDependsOnReporting(dep.getDependency());\n if (subDep)\n {\n return true;\n }\n }\n return false;\n }",
"private void RunScript(InteractiveObject interactiveObject, String functionName, Object[] parameters) {\n boolean complete = false;\n if ( V8JavaScriptEngine) {\n GVRJavascriptV8File gvrJavascriptV8File = interactiveObject.getScriptObject().getGVRJavascriptV8File();\n String paramString = \"var params =[\";\n for (int i = 0; i < parameters.length; i++ ) {\n paramString += (parameters[i] + \", \");\n }\n paramString = paramString.substring(0, (paramString.length()-2)) + \"];\";\n\n final GVRJavascriptV8File gvrJavascriptV8FileFinal = gvrJavascriptV8File;\n final InteractiveObject interactiveObjectFinal = interactiveObject;\n final String functionNameFinal = functionName;\n final Object[] parametersFinal = parameters;\n final String paramStringFinal = paramString;\n gvrContext.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n RunScriptThread (gvrJavascriptV8FileFinal, interactiveObjectFinal, functionNameFinal, parametersFinal, paramStringFinal);\n }\n });\n } // end V8JavaScriptEngine\n else {\n // Mozilla Rhino engine\n GVRJavascriptScriptFile gvrJavascriptFile = interactiveObject.getScriptObject().getGVRJavascriptScriptFile();\n\n complete = gvrJavascriptFile.invokeFunction(functionName, parameters);\n if (complete) {\n // The JavaScript (JS) ran. Now get the return\n // values (saved as X3D data types such as SFColor)\n // stored in 'localBindings'.\n // Then call SetResultsFromScript() to set the GearVR values\n Bindings localBindings = gvrJavascriptFile.getLocalBindings();\n SetResultsFromScript(interactiveObject, localBindings);\n } else {\n Log.e(TAG, \"Error in SCRIPT node '\" + interactiveObject.getScriptObject().getName() +\n \"' running Rhino Engine JavaScript function '\" + functionName + \"'\");\n }\n }\n }",
"public void update()\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n char decimalSeparator = properties.getDecimalSeparator();\n char thousandsSeparator = properties.getThousandsSeparator();\n m_unitsDecimalFormat.applyPattern(\"#.##\", null, decimalSeparator, thousandsSeparator);\n m_decimalFormat.applyPattern(\"0.00#\", null, decimalSeparator, thousandsSeparator);\n m_durationDecimalFormat.applyPattern(\"#.##\", null, decimalSeparator, thousandsSeparator);\n m_percentageDecimalFormat.applyPattern(\"##0.##\", null, decimalSeparator, thousandsSeparator);\n updateCurrencyFormats(properties, decimalSeparator, thousandsSeparator);\n updateDateTimeFormats(properties);\n }"
] |
Create an `AppDescriptor` with appName and package name specified
If `appName` is `null` or blank, it will try the following
approach to get app name:
1. check the {@link Version#getArtifactId() artifact id} and use it unless
2. if artifact id is null or empty, then infer app name using {@link AppNameInferer}
@param appName
the app name
@param packageName
the package name of the app
@return
an `AppDescriptor` instance | [
"public static AppDescriptor of(String appName, String packageName) {\n String[] packages = packageName.split(S.COMMON_SEP);\n return of(appName, packageName, Version.ofPackage(packages[0]));\n }"
] | [
"@Override\n\tprotected void clearReference(EObject obj, EReference ref) {\n\t\tsuper.clearReference(obj, ref);\n\t\tif (obj.eIsSet(ref) && ref.getEType().equals(XtextPackage.Literals.TYPE_REF)) {\n\t\t\tINode node = NodeModelUtils.getNode((EObject) obj.eGet(ref));\n\t\t\tif (node == null)\n\t\t\t\tobj.eUnset(ref);\n\t\t}\n\t\tif (obj.eIsSet(ref) && ref == XtextPackage.Literals.CROSS_REFERENCE__TERMINAL) {\n\t\t\tINode node = NodeModelUtils.getNode((EObject) obj.eGet(ref));\n\t\t\tif (node == null)\n\t\t\t\tobj.eUnset(ref);\n\t\t}\n\t\tif (ref == XtextPackage.Literals.RULE_CALL__RULE) {\n\t\t\tobj.eUnset(XtextPackage.Literals.RULE_CALL__EXPLICITLY_CALLED);\n\t\t}\n\t}",
"protected void appendStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) {\n\t\tif (isVarcharFieldWidthSupported()) {\n\t\t\tsb.append(\"VARCHAR(\").append(fieldWidth).append(')');\n\t\t} else {\n\t\t\tsb.append(\"VARCHAR\");\n\t\t}\n\t}",
"public static <T> List<T> flatten(Collection<List<T>> nestedList) {\r\n List<T> result = new ArrayList<T>();\r\n for (List<T> list : nestedList) {\r\n result.addAll(list);\r\n }\r\n return result;\r\n }",
"public static String createCustomExpressionInvocationText(CustomExpression customExpression, String customExpName, boolean usePreviousFieldValues) {\n String stringExpression;\n if (customExpression instanceof DJSimpleExpression) {\n DJSimpleExpression varexp = (DJSimpleExpression) customExpression;\n String symbol;\n switch (varexp.getType()) {\n case DJSimpleExpression.TYPE_FIELD:\n symbol = \"F\";\n break;\n case DJSimpleExpression.TYPE_VARIABLE:\n symbol = \"V\";\n break;\n case DJSimpleExpression.TYPE_PARAMATER:\n symbol = \"P\";\n break;\n default:\n throw new DJException(\"Invalid DJSimpleExpression, type must be FIELD, VARIABLE or PARAMETER\");\n }\n stringExpression = \"$\" + symbol + \"{\" + varexp.getVariableName() + \"}\";\n\n } else {\n String fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentFields()\";\n if (usePreviousFieldValues) {\n fieldsMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getPreviousFields()\";\n }\n\n String parametersMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentParams()\";\n String variablesMap = \"((\" + DJDefaultScriptlet.class.getName() + \")$P{REPORT_SCRIPTLET}).getCurrentVariables()\";\n\n stringExpression = \"((\" + CustomExpression.class.getName() + \")$P{REPORT_PARAMETERS_MAP}.get(\\\"\" + customExpName + \"\\\")).\"\n + CustomExpression.EVAL_METHOD_NAME + \"( \" + fieldsMap + \", \" + variablesMap + \", \" + parametersMap + \" )\";\n }\n\n return stringExpression;\n }",
"@Override\n public final PArray getArray(final String key) {\n PArray result = optArray(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n try {\n FileUtils.writeStringToFile(new File(outputDirName, \"plan.out\"), plan.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpPlanToFile: \" + e);\n }\n }\n }",
"public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) {\n\t\tfinal DbModule module = getModule(dbArtifact);\n\t\tif(module == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tfinal String jenkinsJobUrl = module.getBuildInfo().get(\"jenkins-job-url\");\n\t\t\n\t\tif(jenkinsJobUrl == null){\n\t\t\treturn \"\";\t\t\t\n\t\t}\n\n\t\treturn jenkinsJobUrl;\n\t}",
"public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }"
] |
Merge the source skeleton with this one.
The result will be that this skeleton has all of its
original bones and all the bones in the new skeleton.
@param newSkel skeleton to merge with this one | [
"public void merge(GVRSkeleton newSkel)\n {\n int numBones = getNumBones();\n List<Integer> parentBoneIds = new ArrayList<Integer>(numBones + newSkel.getNumBones());\n List<String> newBoneNames = new ArrayList<String>(newSkel.getNumBones());\n List<Matrix4f> newMatrices = new ArrayList<Matrix4f>(newSkel.getNumBones());\n GVRPose oldBindPose = getBindPose();\n GVRPose curPose = getPose();\n\n for (int i = 0; i < numBones; ++i)\n {\n parentBoneIds.add(mParentBones[i]);\n }\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n String boneName = newSkel.getBoneName(j);\n int boneId = getBoneIndex(boneName);\n if (boneId < 0)\n {\n int parentId = newSkel.getParentBoneIndex(j);\n Matrix4f m = new Matrix4f();\n\n newSkel.getBindPose().getLocalMatrix(j, m);\n newMatrices.add(m);\n newBoneNames.add(boneName);\n if (parentId >= 0)\n {\n boneName = newSkel.getBoneName(parentId);\n parentId = getBoneIndex(boneName);\n }\n parentBoneIds.add(parentId);\n }\n }\n if (parentBoneIds.size() == numBones)\n {\n return;\n }\n int n = numBones + parentBoneIds.size();\n int[] parentIds = Arrays.copyOf(mParentBones, n);\n int[] boneOptions = Arrays.copyOf(mBoneOptions, n);\n String[] boneNames = Arrays.copyOf(mBoneNames, n);\n\n mBones = Arrays.copyOf(mBones, n);\n mPoseMatrices = new float[n * 16];\n for (int i = 0; i < parentBoneIds.size(); ++i)\n {\n n = numBones + i;\n parentIds[n] = parentBoneIds.get(i);\n boneNames[n] = newBoneNames.get(i);\n boneOptions[n] = BONE_ANIMATE;\n }\n mBoneOptions = boneOptions;\n mBoneNames = boneNames;\n mParentBones = parentIds;\n mPose = new GVRPose(this);\n mBindPose = new GVRPose(this);\n mBindPose.copy(oldBindPose);\n mPose.copy(curPose);\n mBindPose.sync();\n for (int j = 0; j < newSkel.getNumBones(); ++j)\n {\n mBindPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n mPose.setLocalMatrix(numBones + j, newMatrices.get(j));\n }\n setBindPose(mBindPose);\n mPose.sync();\n updateBonePose();\n }"
] | [
"private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }",
"private void internalCleanup()\r\n {\r\n if(hasBroker())\r\n {\r\n PersistenceBroker broker = getBroker();\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Do internal cleanup and close the internal used connection without\" +\r\n \" closing the used broker\");\r\n }\r\n ConnectionManagerIF cm = broker.serviceConnectionManager();\r\n if(cm.isInLocalTransaction())\r\n {\r\n /*\r\n arminw:\r\n in managed environment this call will be ignored because, the JTA transaction\r\n manager control the connection status. But to make connectionManager happy we\r\n have to complete the \"local tx\" of the connectionManager before release the\r\n connection\r\n */\r\n cm.localCommit();\r\n }\r\n cm.releaseConnection();\r\n }\r\n }",
"public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }",
"public static void transformChar(Reader self, Writer writer, @ClosureParams(value=SimpleType.class, options=\"java.lang.String\") Closure closure) throws IOException {\n int c;\n try {\n char[] chars = new char[1];\n while ((c = self.read()) != -1) {\n chars[0] = (char) c;\n writer.write((String) closure.call(new String(chars)));\n }\n writer.flush();\n\n Writer temp2 = writer;\n writer = null;\n temp2.close();\n Reader temp1 = self;\n self = null;\n temp1.close();\n } finally {\n closeWithWarning(self);\n closeWithWarning(writer);\n }\n }",
"protected final void setParentNode(final DiffNode parentNode)\n\t{\n\t\tif (this.parentNode != null && this.parentNode != parentNode)\n\t\t{\n\t\t\tthrow new IllegalStateException(\"The parent of a node cannot be changed, once it's set.\");\n\t\t}\n\t\tthis.parentNode = parentNode;\n\t}",
"public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }",
"public ParallelTaskBuilder prepareHttpHead(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.HEAD);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }",
"public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) {\n login(userIdentifier);\n RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);\n }",
"private List<Point2D> merge(final List<Point2D> one, final List<Point2D> two) {\n final Set<Point2D> oneSet = new HashSet<Point2D>(one);\n for (Point2D item : two) {\n if (!oneSet.contains(item)) {\n one.add(item);\n }\n }\n return one;\n }"
] |
Wait for the template resources to come up after the test container has
been started. This allows the test container and the template resources
to come up in parallel. | [
"public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,\n CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)\n throws Exception {\n if (testClass == null) {\n // nothing to do, since we're not in ClassScoped context\n return;\n }\n if (details == null) {\n log.warning(String.format(\"No environment for %s\", testClass.getName()));\n return;\n }\n log.info(String.format(\"Waiting for environment for %s\", testClass.getName()));\n try {\n delay(client, details.getResources());\n } catch (Throwable t) {\n throw new IllegalArgumentException(\"Error waiting for template resources to deploy: \" + testClass.getName(), t);\n }\n }"
] | [
"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 <L extends Listener> void popEvent(Event<?, L> expected) {\n synchronized (this.stack) {\n final Event<?, ?> actual = this.stack.pop();\n if (actual != expected) {\n throw new IllegalStateException(String.format(\n \"Unbalanced pop: expected '%s' but encountered '%s'\",\n expected.getListenerClass(), actual));\n }\n }\n }",
"public void removeMetadataProvider(MetadataProvider provider) {\n for (Set<MetadataProvider> providers : metadataProviders.values()) {\n providers.remove(provider);\n }\n }",
"public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) {\n this.downloadRange(output, rangeStart, rangeEnd, null);\n }",
"public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\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 static StringTemplateGroup readStringTemplateGroup(InputStream stream) {\n\n try {\n return new StringTemplateGroup(\n new InputStreamReader(stream, \"UTF-8\"),\n DefaultTemplateLexer.class,\n new StringTemplateErrorListener() {\n\n @SuppressWarnings(\"synthetic-access\")\n public void error(String arg0, Throwable arg1) {\n\n LOG.error(arg0 + \": \" + arg1.getMessage(), arg1);\n }\n\n @SuppressWarnings(\"synthetic-access\")\n public void warning(String arg0) {\n\n LOG.warn(arg0);\n\n }\n });\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n return new StringTemplateGroup(\"dummy\");\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}",
"public static vrid6 get(nitro_service service, Long id) throws Exception{\n\t\tvrid6 obj = new vrid6();\n\t\tobj.set_id(id);\n\t\tvrid6 response = (vrid6) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Use this API to delete cacheselector of given name. | [
"public static base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }",
"public SerialMessage getMultiInstanceGetMessage(CommandClass commandClass) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_INSTANCE_GET for node {} and command class {}\", this.getNode().getNodeId(), commandClass.getLabel());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, 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) MULTI_INSTANCE_GET,\r\n\t\t\t\t\t\t\t\t(byte) commandClass.getKey()\r\n\t\t\t\t\t\t\t\t};\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public final void setDefaultStyle(final Map<String, Style> defaultStyle) {\n this.defaultStyle = new HashMap<>(defaultStyle.size());\n for (Map.Entry<String, Style> entry: defaultStyle.entrySet()) {\n String normalizedName = GEOMETRY_NAME_ALIASES.get(entry.getKey().toLowerCase());\n\n if (normalizedName == null) {\n normalizedName = entry.getKey().toLowerCase();\n }\n\n this.defaultStyle.put(normalizedName, entry.getValue());\n }\n }",
"public void add(final String source, final T destination) {\n\n // replace multiple slashes with a single slash.\n String path = source.replaceAll(\"/+\", \"/\");\n\n path = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n\n String[] parts = path.split(\"/\", maxPathParts + 2);\n if (parts.length - 1 > maxPathParts) {\n throw new IllegalArgumentException(String.format(\"Number of parts of path %s exceeds allowed limit %s\",\n source, maxPathParts));\n }\n StringBuilder sb = new StringBuilder();\n List<String> groupNames = new ArrayList<>();\n\n for (String part : parts) {\n Matcher groupMatcher = GROUP_PATTERN.matcher(part);\n if (groupMatcher.matches()) {\n groupNames.add(groupMatcher.group(1));\n sb.append(\"([^/]+?)\");\n } else if (WILD_CARD_PATTERN.matcher(part).matches()) {\n sb.append(\".*?\");\n } else {\n sb.append(part);\n }\n sb.append(\"/\");\n }\n\n //Ignore the last \"/\"\n sb.setLength(sb.length() - 1);\n\n Pattern pattern = Pattern.compile(sb.toString());\n patternRouteList.add(ImmutablePair.of(pattern, new RouteDestinationWithGroups(destination, groupNames)));\n }",
"public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Iterator getReportQueryIteratorByQuery(Query query) throws PersistenceBrokerException\n {\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return getReportQueryIteratorFromQuery(query, cld);\n }",
"static boolean isOnClasspath(String className) {\n boolean isOnClassPath = true;\n try {\n Class.forName(className);\n } catch (ClassNotFoundException exception) {\n isOnClassPath = false;\n }\n return isOnClassPath;\n }",
"public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }",
"public static List<String> splitAndTrimAsList(String text, String sep) {\n ArrayList<String> answer = new ArrayList<>();\n if (text != null && text.length() > 0) {\n for (String v : text.split(sep)) {\n String trim = v.trim();\n if (trim.length() > 0) {\n answer.add(trim);\n }\n }\n }\n return answer;\n }"
] |
Specifies the container object class to be instantiated
@param containerObjectClass
container object class to be instantiated
@return the current builder instance | [
"public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }"
] | [
"public String format() {\r\n if (getName().equals(\"*\")) {\r\n return \"*\";\r\n }\r\n else {\r\n StringBuilder sb = new StringBuilder();\r\n if (isWeak()) {\r\n sb.append(\"W/\");\r\n }\r\n return sb.append('\"').append(getName()).append('\"').toString();\r\n }\r\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 }",
"public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }",
"public static BoxAPIConnection getTransactionConnection(String accessToken, String scope, String resource) {\n BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken);\n\n URL url;\n try {\n url = new URL(apiConnection.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 urlParameters;\n try {\n urlParameters = String.format(\"grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s\", GRANT_TYPE,\n URLEncoder.encode(accessToken, \"UTF-8\"), SUBJECT_TOKEN_TYPE, URLEncoder.encode(scope, \"UTF-8\"));\n\n if (resource != null) {\n urlParameters += \"&resource=\" + URLEncoder.encode(resource, \"UTF-8\");\n }\n } catch (UnsupportedEncodingException e) {\n throw new BoxAPIException(\n \"An error occurred while attempting to encode url parameters for a transactional token request\"\n );\n }\n\n BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n final String fileToken = responseJSON.get(\"access_token\").asString();\n BoxTransactionalAPIConnection transactionConnection = new BoxTransactionalAPIConnection(fileToken);\n transactionConnection.setExpires(responseJSON.get(\"expires_in\").asLong() * 1000);\n\n return transactionConnection;\n }",
"@Override public Task addTask()\n {\n ProjectFile parent = getParentFile();\n\n Task task = new Task(parent, this);\n\n m_children.add(task);\n\n parent.getTasks().add(task);\n\n setSummary(true);\n\n return (task);\n }",
"public String getPendingChanges() {\n JsonObject jsonObject = this.getPendingJSONObject();\n if (jsonObject == null) {\n return null;\n }\n\n return jsonObject.toString();\n }",
"public static java.sql.Timestamp toTimestamp(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Timestamp) {\n return (java.sql.Timestamp) value;\n }\n if (value instanceof String) {\n\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime());\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<JulianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<JulianDate>) super.localDateTime(temporal);\n }",
"@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}"
] |
Total count of partition-stores moved in this task.
@return number of partition stores moved in this task. | [
"public synchronized int getPartitionStoreMoves() {\n int count = 0;\n for (List<Integer> entry : storeToPartitionIds.values())\n count += entry.size();\n return count;\n }"
] | [
"public void set(final Argument argument) {\n if (argument != null) {\n map.put(argument.getKey(), Collections.singleton(argument));\n }\n }",
"public static ModelNode createRemoveOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createRemoveOperation(address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }",
"private void createResults(List<ISuite> suites,\n File outputDirectory,\n boolean onlyShowFailures) throws Exception\n {\n int index = 1;\n for (ISuite suite : suites)\n {\n int index2 = 1;\n for (ISuiteResult result : suite.getResults().values())\n {\n boolean failuresExist = result.getTestContext().getFailedTests().size() > 0\n || result.getTestContext().getFailedConfigurations().size() > 0;\n if (!onlyShowFailures || failuresExist)\n {\n VelocityContext context = createContext();\n context.put(RESULT_KEY, result);\n context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));\n context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));\n context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));\n context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));\n context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));\n String fileName = String.format(\"suite%d_test%d_%s\", index, index2, RESULTS_FILE);\n generateFile(new File(outputDirectory, fileName),\n RESULTS_FILE + TEMPLATE_EXTENSION,\n context);\n }\n ++index2;\n }\n ++index;\n }\n }",
"public AT_Context setFrameLeftRightMargin(int frameLeft, int frameRight){\r\n\t\tif(frameRight>-1 && frameLeft>-1){\r\n\t\t\tthis.frameLeftMargin = frameLeft;\r\n\t\t\tthis.frameRightMargin = frameRight;\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static String termPrefix(String term) {\n int i = term.indexOf(MtasToken.DELIMITER);\n String prefix = term;\n if (i >= 0) {\n prefix = term.substring(0, i);\n }\n return prefix.replace(\"\\u0000\", \"\");\n }",
"public void initialize() {\n\t\tif (dataClass == null) {\n\t\t\tthrow new IllegalStateException(\"dataClass was never set on \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableName == null) {\n\t\t\ttableName = extractTableName(databaseType, dataClass);\n\t\t}\n\t}",
"public static boolean isResourceTypeIdFree(int id) {\n\n try {\n OpenCms.getResourceManager().getResourceType(id);\n } catch (CmsLoaderException e) {\n return true;\n }\n return false;\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 }",
"public BlockHeader read(byte[] buffer, int offset, int postHeaderSkipBytes)\n {\n m_offset = offset;\n\n System.arraycopy(buffer, m_offset, m_header, 0, 8);\n m_offset += 8;\n\n int nameLength = FastTrackUtility.getInt(buffer, m_offset);\n m_offset += 4;\n\n if (nameLength < 1 || nameLength > 255)\n {\n throw new UnexpectedStructureException();\n }\n\n m_name = new String(buffer, m_offset, nameLength, CharsetHelper.UTF16LE);\n m_offset += nameLength;\n\n m_columnType = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_flags = FastTrackUtility.getShort(buffer, m_offset);\n m_offset += 2;\n\n m_skip = new byte[postHeaderSkipBytes];\n System.arraycopy(buffer, m_offset, m_skip, 0, postHeaderSkipBytes);\n m_offset += postHeaderSkipBytes;\n\n return this;\n }"
] |
Handles reports by consumers
@param name the name of the reporting consumer
@param report the number of lines the consumer has written since last report
@return "exit" if maxScenarios has been reached, "ok" otherwise | [
"public String makeReport(String name, String report) {\n long increment = Long.valueOf(report);\n long currentLineCount = globalLineCounter.addAndGet(increment);\n\n if (currentLineCount >= maxScenarios) {\n return \"exit\";\n } else {\n return \"ok\";\n }\n }"
] | [
"public static <T extends Publisher> T getPublisher(AbstractProject<?, ?> project, Class<T> type) {\n // Search for a publisher of the given type in the project and return it if found:\n T publisher = new PublisherFindImpl<T>().find(project, type);\n if (publisher != null) {\n return publisher;\n }\n // If not found, the publisher might be wrapped by a \"Flexible Publish\" publisher. The below searches for it inside the\n // Flexible Publisher:\n publisher = new PublisherFlexible<T>().find(project, type);\n return publisher;\n }",
"public final static int readXMLUntil(final StringBuilder out, final String in, final int start, final char... end)\n {\n int pos = start;\n boolean inString = false;\n char stringChar = 0;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (inString)\n {\n if (ch == '\\\\')\n {\n out.append(ch);\n pos++;\n if (pos < in.length())\n {\n out.append(ch);\n pos++;\n }\n continue;\n }\n if (ch == stringChar)\n {\n inString = false;\n out.append(ch);\n pos++;\n continue;\n }\n }\n switch (ch)\n {\n case '\"':\n case '\\'':\n inString = true;\n stringChar = ch;\n break;\n }\n if (!inString)\n {\n boolean endReached = false;\n for (int n = 0; n < end.length; n++)\n {\n if (ch == end[n])\n {\n endReached = true;\n break;\n }\n }\n if (endReached)\n {\n break;\n }\n }\n out.append(ch);\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }",
"private String getResourceType(Resource resource)\n {\n String result;\n net.sf.mpxj.ResourceType type = resource.getType();\n if (type == null)\n {\n type = net.sf.mpxj.ResourceType.WORK;\n }\n\n switch (type)\n {\n case MATERIAL:\n {\n result = \"Material\";\n break;\n }\n\n case COST:\n {\n result = \"Nonlabor\";\n break;\n }\n\n default:\n {\n result = \"Labor\";\n break;\n }\n }\n\n return result;\n }",
"public static java.util.Date toDateTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.util.Date) {\n return (java.util.Date) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return IN_DATETIME_FORMAT.parse((String) value);\n }\n\n return IN_DATETIME_FORMAT.parse(value.toString());\n }",
"public List<com.groupon.odo.proxylib.models.Method> getMethodsNotInGroup(int groupId) throws Exception {\n List<com.groupon.odo.proxylib.models.Method> allMethods = getAllMethods();\n List<com.groupon.odo.proxylib.models.Method> methodsNotInGroup = new ArrayList<com.groupon.odo.proxylib.models.Method>();\n List<com.groupon.odo.proxylib.models.Method> methodsInGroup = editService.getMethodsFromGroupId(groupId, null);\n\n for (int i = 0; i < allMethods.size(); i++) {\n boolean add = true;\n String methodName = allMethods.get(i).getMethodName();\n String className = allMethods.get(i).getClassName();\n\n for (int j = 0; j < methodsInGroup.size(); j++) {\n if ((methodName.equals(methodsInGroup.get(j).getMethodName())) &&\n (className.equals(methodsInGroup.get(j).getClassName()))) {\n add = false;\n }\n }\n if (add) {\n methodsNotInGroup.add(allMethods.get(i));\n }\n }\n return methodsNotInGroup;\n }",
"public void addAuxHandler(Object handler, String prefix) {\n if (handler == null) {\n throw new NullPointerException();\n }\n auxHandlers.put(prefix, handler);\n allHandlers.add(handler);\n\n addDeclaredMethods(handler, prefix);\n inputConverter.addDeclaredConverters(handler);\n outputConverter.addDeclaredConverters(handler);\n\n if (handler instanceof ShellDependent) {\n ((ShellDependent)handler).cliSetShell(this);\n }\n }",
"public static int serialize(final File directory, String name, Object obj) {\n try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) {\n return serialize(stream, obj);\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }",
"private static Map<String, Integer> findClasses(Path path)\n {\n List<String> paths = findPaths(path, true);\n Map<String, Integer> results = new HashMap<>();\n for (String subPath : paths)\n {\n if (subPath.endsWith(\".java\") || subPath.endsWith(\".class\"))\n {\n String qualifiedName = PathUtil.classFilePathToClassname(subPath);\n addClassToMap(results, qualifiedName);\n }\n }\n return results;\n }",
"private void readRelation(Relationship relation)\n {\n Task predecessor = m_activityMap.get(relation.getPredecessor());\n Task successor = m_activityMap.get(relation.getSuccessor());\n if (predecessor != null && successor != null)\n {\n Duration lag = relation.getLag();\n RelationType type = relation.getType();\n successor.addPredecessor(predecessor, type, lag);\n }\n }"
] |
Log an audit record of this operation. | [
"void logAuditRecord() {\n trackConfigurationChange();\n if (!auditLogged) {\n try {\n AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();\n Caller caller = getCaller();\n auditLogger.log(\n isReadOnly(),\n resultAction,\n caller == null ? null : caller.getName(),\n accessContext == null ? null : accessContext.getDomainUuid(),\n accessContext == null ? null : accessContext.getAccessMechanism(),\n accessContext == null ? null : accessContext.getRemoteAddress(),\n getModel(),\n controllerOperations);\n auditLogged = true;\n } catch (Exception e) {\n ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);\n }\n }\n }"
] | [
"public static cacheobject[] get(nitro_service service, cacheobject_args args) throws Exception{\n\t\tcacheobject obj = new cacheobject();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tcacheobject[] response = (cacheobject[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public ILog getLog(String topic, int partition) {\n TopicNameValidator.validate(topic);\n Pool<Integer, Log> p = getLogPool(topic, partition);\n return p == null ? null : p.get(partition);\n }",
"public String putDocument(Document document) {\n\t\tString key = UUID.randomUUID().toString();\n\t\tdocumentMap.put(key, document);\n\t\treturn key;\n\t}",
"public static MetaClassRegistry getInstance(int includeExtension) {\n if (includeExtension != DONT_LOAD_DEFAULT) {\n if (instanceInclude == null) {\n instanceInclude = new MetaClassRegistryImpl();\n }\n return instanceInclude;\n } else {\n if (instanceExclude == null) {\n instanceExclude = new MetaClassRegistryImpl(DONT_LOAD_DEFAULT);\n }\n return instanceExclude;\n }\n }",
"public final static String process(final File file, final boolean safeMode) throws IOException\n {\n return process(file, Configuration.builder().setSafeMode(safeMode).build());\n }",
"public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public void setLocale(Locale locale)\n {\n List<SimpleDateFormat> formats = new ArrayList<SimpleDateFormat>();\n for (SimpleDateFormat format : m_formats)\n {\n formats.add(new SimpleDateFormat(format.toPattern(), locale));\n }\n\n m_formats = formats.toArray(new SimpleDateFormat[formats.size()]);\n }",
"protected void clearStatementCaches(boolean internalClose) {\r\n\r\n\t\tif (this.statementCachingEnabled){ // safety\r\n\r\n\t\t\tif (internalClose){\r\n\t\t\t\tthis.callableStatementCache.clear();\r\n\t\t\t\tthis.preparedStatementCache.clear();\r\n\t\t\t} else {\r\n\t\t\t\tif (this.pool.closeConnectionWatch){ // debugging enabled?\r\n\t\t\t\t\tthis.callableStatementCache.checkForProperClosure();\r\n\t\t\t\t\tthis.preparedStatementCache.checkForProperClosure();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"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 }"
] |
Detects if the current browser is a Sony Mylo device.
@return detection of a Sony Mylo device | [
"public boolean detectSonyMylo() {\r\n\r\n if ((userAgent.indexOf(manuSony) != -1)\r\n && ((userAgent.indexOf(qtembedded) != -1) || (userAgent.indexOf(mylocom2) != -1))) {\r\n return true;\r\n }\r\n return false;\r\n }"
] | [
"public DateTimeZone getZone(String id) {\n if (id == null) {\n return null;\n }\n\n Object obj = iZoneInfoMap.get(id);\n if (obj == null) {\n return null;\n }\n\n if (id.equals(obj)) {\n // Load zone data for the first time.\n return loadZoneData(id);\n }\n\n if (obj instanceof SoftReference<?>) {\n @SuppressWarnings(\"unchecked\")\n SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;\n DateTimeZone tz = ref.get();\n if (tz != null) {\n return tz;\n }\n // Reference cleared; load data again.\n return loadZoneData(id);\n }\n\n // If this point is reached, mapping must link to another.\n return getZone((String) obj);\n }",
"public static boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }",
"public static ipset_nsip6_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip6_binding obj = new ipset_nsip6_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip6_binding response[] = (ipset_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String createQuotedConstant(String str) {\n if (str == null || str.isEmpty()) {\n return str;\n }\n try {\n Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return \"\\\"\" + str + \"\\\"\";\n }\n return str;\n }",
"public Future<HazeltaskTask<GROUP>> addPendingTaskAsync(HazeltaskTask<GROUP> task) {\n return pendingTask.putAsync(task.getId(), task);\n }",
"private void setCalendarToOrdinalRelativeDay(Calendar calendar, int dayNumber)\n {\n int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n int requiredDayOfWeek = getDayOfWeek().getValue();\n int dayOfWeekOffset = 0;\n if (requiredDayOfWeek > currentDayOfWeek)\n {\n dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek;\n }\n else\n {\n if (requiredDayOfWeek < currentDayOfWeek)\n {\n dayOfWeekOffset = 7 - (currentDayOfWeek - requiredDayOfWeek);\n }\n }\n\n if (dayOfWeekOffset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset);\n }\n\n if (dayNumber > 1)\n {\n calendar.add(Calendar.DAY_OF_YEAR, (7 * (dayNumber - 1)));\n }\n }",
"public ItemRequest<Project> removeFollowers(String project) {\n \n String path = String.format(\"/projects/%s/removeFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }",
"public List<String> getArtifactVersions(final String gavc) {\n final DbArtifact artifact = getArtifact(gavc);\n return repositoryHandler.getArtifactVersions(artifact);\n }",
"private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}"
] |
Pass the activity you use the drawer in ;)
This is required if you want to set any values by resource
@param activity
@return | [
"public MaterializeBuilder withActivity(Activity activity) {\n this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);\n this.mActivity = activity;\n return this;\n }"
] | [
"protected String sourceLine(ASTNode node) {\r\n return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }",
"@Override\n public Object[] getAgentPlans(String agent_name, Connector connector) {\n // Not supported in JADE\n connector.getLogger().warning(\"Non suported method for Jade Platform. There is no plans in Jade platform.\");\n throw new java.lang.UnsupportedOperationException(\"Non suported method for Jade Platform. There is no extra properties.\");\n }",
"public long nextUniqueTransaction(long timeMs) {\n long id = timeMs;\n for (; ; ) {\n long old = transactionID.get();\n if (old >= id)\n id = old + 1;\n if (transactionID.compareAndSet(old, id))\n break;\n }\n return id;\n }",
"public 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}",
"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 }",
"@Override\n public final Optional<Boolean> tryOverrideValidation(final MatchInfo matchInfo) throws SocketException,\n UnknownHostException, MalformedURLException {\n for (AddressHostMatcher addressHostMatcher: this.matchersForHost) {\n if (addressHostMatcher.matches(matchInfo)) {\n return Optional.empty();\n }\n }\n\n return Optional.of(false);\n }",
"public void startup() {\n if (config.getEnableZookeeper()) {\n serverRegister.registerBrokerInZk();\n for (String topic : getAllTopics()) {\n serverRegister.processTask(new TopicTask(TopicTask.TaskType.CREATE, topic));\n }\n startupLatch.countDown();\n }\n logger.debug(\"Starting log flusher every {} ms with the following overrides {}\", config.getFlushSchedulerThreadRate(), logFlushIntervalMap);\n logFlusherScheduler.scheduleWithRate(new Runnable() {\n\n public void run() {\n flushAllLogs(false);\n }\n }, config.getFlushSchedulerThreadRate(), config.getFlushSchedulerThreadRate());\n }",
"public static boolean sameNetwork(int prefixLength, InetAddress address1, InetAddress address2) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Comparing address \" + address1.getHostAddress() + \" with \" + address2.getHostAddress() + \", prefixLength=\" + prefixLength);\n }\n long prefixMask = 0xffffffffL & (-1 << (32 - prefixLength));\n return (addressToLong(address1) & prefixMask) == (addressToLong(address2) & prefixMask);\n }",
"public static String getVariablesMapExpression(Collection variables) {\n StringBuilder variablesMap = new StringBuilder(\"new \" + PropertiesMap.class.getName() + \"()\");\n for (Object variable : variables) {\n JRVariable jrvar = (JRVariable) variable;\n String varname = jrvar.getName();\n variablesMap.append(\".with(\\\"\").append(varname).append(\"\\\",$V{\").append(varname).append(\"})\");\n }\n return variablesMap.toString();\n }"
] |
get all consumers for the group
@param zkClient the zookeeper client
@param group the group name
@return topic->(consumerIdStringA-0,consumerIdStringA-1...consumerIdStringB-0,consumerIdStringB-1) | [
"public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) {\n ZkGroupDirs dirs = new ZkGroupDirs(group);\n List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir);\n //\n Map<String, List<String>> consumersPerTopicMap = new HashMap<String, List<String>>();\n for (String consumer : consumers) {\n TopicCount topicCount = getTopicCount(zkClient, group, consumer);\n for (Map.Entry<String, Set<String>> e : topicCount.getConsumerThreadIdsPerTopic().entrySet()) {\n final String topic = e.getKey();\n for (String consumerThreadId : e.getValue()) {\n List<String> list = consumersPerTopicMap.get(topic);\n if (list == null) {\n list = new ArrayList<String>();\n consumersPerTopicMap.put(topic, list);\n }\n //\n list.add(consumerThreadId);\n }\n }\n }\n //\n for (Map.Entry<String, List<String>> e : consumersPerTopicMap.entrySet()) {\n Collections.sort(e.getValue());\n }\n return consumersPerTopicMap;\n }"
] | [
"void setFilters(Map<Object, Object> filters) {\n\n for (Object column : filters.keySet()) {\n Object filterValue = filters.get(column);\n if ((filterValue != null) && !filterValue.toString().isEmpty() && !m_table.isColumnCollapsed(column)) {\n m_table.setFilterFieldValue(column, filterValue);\n }\n }\n }",
"private void initializeVideoInfo() {\n VIDEO_INFO.put(\"The Big Bang Theory\", \"http://thetvdb.com/banners/_cache/posters/80379-9.jpg\");\n VIDEO_INFO.put(\"Breaking Bad\", \"http://thetvdb.com/banners/_cache/posters/81189-22.jpg\");\n VIDEO_INFO.put(\"Arrow\", \"http://thetvdb.com/banners/_cache/posters/257655-15.jpg\");\n VIDEO_INFO.put(\"Game of Thrones\", \"http://thetvdb.com/banners/_cache/posters/121361-26.jpg\");\n VIDEO_INFO.put(\"Lost\", \"http://thetvdb.com/banners/_cache/posters/73739-2.jpg\");\n VIDEO_INFO.put(\"How I met your mother\",\n \"http://thetvdb.com/banners/_cache/posters/75760-29.jpg\");\n VIDEO_INFO.put(\"Dexter\", \"http://thetvdb.com/banners/_cache/posters/79349-24.jpg\");\n VIDEO_INFO.put(\"Sleepy Hollow\", \"http://thetvdb.com/banners/_cache/posters/269578-5.jpg\");\n VIDEO_INFO.put(\"The Vampire Diaries\", \"http://thetvdb.com/banners/_cache/posters/95491-27.jpg\");\n VIDEO_INFO.put(\"Friends\", \"http://thetvdb.com/banners/_cache/posters/79168-4.jpg\");\n VIDEO_INFO.put(\"New Girl\", \"http://thetvdb.com/banners/_cache/posters/248682-9.jpg\");\n VIDEO_INFO.put(\"The Mentalist\", \"http://thetvdb.com/banners/_cache/posters/82459-1.jpg\");\n VIDEO_INFO.put(\"Sons of Anarchy\", \"http://thetvdb.com/banners/_cache/posters/82696-1.jpg\");\n }",
"@RequestMapping(value = \"/api/plugins\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addPluginPath(Model model, Plugin add) throws Exception {\n PluginManager.getInstance().addPluginPath(add.getPath());\n\n return pluginInformation();\n }",
"@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }",
"private int runCommitScript() {\n\n if (m_checkout && !m_fetchAndResetBeforeImport) {\n m_logStream.println(\"Skipping script....\");\n return 0;\n }\n try {\n m_logStream.flush();\n String commandParam;\n if (m_resetRemoteHead) {\n commandParam = resetRemoteHeadScriptCommand();\n } else if (m_resetHead) {\n commandParam = resetHeadScriptCommand();\n } else if (m_checkout) {\n commandParam = checkoutScriptCommand();\n } else {\n commandParam = checkinScriptCommand();\n }\n String[] cmd = {\"bash\", \"-c\", commandParam};\n m_logStream.println(\"Calling the script as follows:\");\n m_logStream.println();\n m_logStream.println(cmd[0] + \" \" + cmd[1] + \" \" + cmd[2]);\n ProcessBuilder builder = new ProcessBuilder(cmd);\n m_logStream.close();\n m_logStream = null;\n Redirect redirect = Redirect.appendTo(new File(DEFAULT_LOGFILE_PATH));\n builder.redirectOutput(redirect);\n builder.redirectError(redirect);\n Process scriptProcess = builder.start();\n int exitCode = scriptProcess.waitFor();\n scriptProcess.getOutputStream().close();\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, true));\n return exitCode;\n } catch (InterruptedException | IOException e) {\n e.printStackTrace(m_logStream);\n return -1;\n }\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 }",
"public RedwoodConfiguration printChannels(final int width){\r\n tasks.add(new Runnable() { public void run() { Redwood.Util.printChannels(width);} });\r\n return this;\r\n }",
"public static String format(String pattern, Object... arguments) {\n String msg = pattern;\n if (arguments != null) {\n for (int index = 0; index < arguments.length; index++) {\n msg = msg.replaceAll(\"\\\\{\" + (index + 1) + \"\\\\}\", String.valueOf(arguments[index]));\n }\n }\n return msg;\n }",
"public double estimateExcludedVolumeFraction(){\n\t\t//Calculate volume/area of the of the scene without obstacles\n\t\tif(recalculateVolumeFraction){\n\t\t\tCentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();\n\t\t\tboolean firstRandomDraw = false;\n\t\t\tif(randomNumbers==null){\n\t\t\t\trandomNumbers = new double[nRandPoints*dimension];\n\t\t\t\tfirstRandomDraw = true;\n\t\t\t}\n\t\t\tint countCollision = 0;\n\t\t\tfor(int i = 0; i< nRandPoints; i++){\n\t\t\t\tdouble[] pos = new double[dimension];\n\t\t\t\tfor(int j = 0; j < dimension; j++){\n\t\t\t\t\tif(firstRandomDraw){\n\t\t\t\t\t\trandomNumbers[i*dimension + j] = r.nextDouble();\n\t\t\t\t\t}\n\t\t\t\t\tpos[j] = randomNumbers[i*dimension + j]*size[j];\n\t\t\t\t}\n\t\t\t\tif(checkCollision(pos)){\n\t\t\t\t\tcountCollision++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfraction = countCollision*1.0/nRandPoints;\n\t\t\trecalculateVolumeFraction = false;\n\t\t}\n\t\treturn fraction;\n\t}"
] |
If the not a bitmap itself, this will read the file's meta data.
@param resources {@link android.content.Context#getResources()}
@return Point where x = width and y = height | [
"public Point measureImage(Resources resources) {\n BitmapFactory.Options justBoundsOptions = new BitmapFactory.Options();\n justBoundsOptions.inJustDecodeBounds = true;\n\n if (bitmap != null) {\n return new Point(bitmap.getWidth(), bitmap.getHeight());\n } else if (resId != null) {\n BitmapFactory.decodeResource(resources, resId, justBoundsOptions);\n float scale = (float) justBoundsOptions.inTargetDensity / justBoundsOptions.inDensity;\n return new Point((int) (justBoundsOptions.outWidth * scale + 0.5f), (int) (justBoundsOptions.outHeight * scale + 0.5f));\n } else if (fileToBitmap != null) {\n BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), justBoundsOptions);\n } else if (inputStream != null) {\n BitmapFactory.decodeStream(inputStream, null, justBoundsOptions);\n try {\n inputStream.reset();\n } catch (IOException ignored) {\n }\n } else if (view != null) {\n return new Point(view.getWidth(), view.getHeight());\n }\n return new Point(justBoundsOptions.outWidth, justBoundsOptions.outHeight);\n }"
] | [
"private static boolean hasSelfPermissions(Context context, String... permissions) {\n for (String permission : permissions) {\n if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {\n return true;\n }\n }\n return false;\n }",
"public Map<Integer, List<Row>> createWorkPatternAssignmentMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer calendarID = row.getInteger(\"WORK_PATTERN_ASSIGNMENTID\");\n List<Row> list = map.get(calendarID);\n if (list == null)\n {\n list = new LinkedList<Row>();\n map.put(calendarID, list);\n }\n list.add(row);\n }\n return map;\n }",
"public static gslbrunningconfig get(nitro_service service) throws Exception{\n\t\tgslbrunningconfig obj = new gslbrunningconfig();\n\t\tgslbrunningconfig[] response = (gslbrunningconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"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 }",
"void pumpEvents(InputStream eventStream) {\n try {\n Deserializer deserializer = new Deserializer(eventStream, refLoader);\n\n IEvent event = null;\n while ((event = deserializer.deserialize()) != null) {\n switch (event.getType()) {\n case APPEND_STDERR:\n case APPEND_STDOUT:\n // Ignore these two on activity heartbeats. GH-117\n break;\n default:\n lastActivity = System.currentTimeMillis();\n break;\n }\n\n try {\n switch (event.getType()) {\n case QUIT:\n eventBus.post(event);\n return;\n\n case IDLE:\n eventBus.post(new SlaveIdle(stdinWriter));\n break;\n\n case BOOTSTRAP:\n clientCharset = Charset.forName(((BootstrapEvent) event).getDefaultCharsetName());\n stdinWriter = new OutputStreamWriter(stdin, clientCharset);\n eventBus.post(event);\n break;\n\n case APPEND_STDERR:\n case APPEND_STDOUT:\n assert streamsBuffer.getFilePointer() == streamsBuffer.length();\n final long bufferStart = streamsBuffer.getFilePointer();\n IStreamEvent streamEvent = (IStreamEvent) event;\n streamEvent.copyTo(streamsBufferWrapper);\n final long bufferEnd = streamsBuffer.getFilePointer();\n\n event = new OnDiskStreamEvent(event.getType(), streamsBuffer, bufferStart, bufferEnd);\n eventBus.post(event);\n break;\n \n default:\n eventBus.post(event);\n }\n } catch (Throwable t) {\n warnStream.println(\"Event bus dispatch error: \" + t.toString());\n t.printStackTrace(warnStream);\n }\n }\n lastActivity = null;\n } catch (Throwable e) {\n if (!stopping) {\n warnStream.println(\"Event stream error: \" + e.toString());\n e.printStackTrace(warnStream);\n }\n }\n }",
"public static void loadCubemapTexture(final GVRContext context,\n ResourceCache<GVRImage> textureCache,\n final TextureCallback callback,\n final GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap)\n throws IllegalArgumentException\n {\n validatePriorityCallbackParameters(context, callback, resource,\n priority);\n final GVRImage cached = textureCache == null\n ? null\n : (GVRImage) textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Texture: %s loaded from cache\", cached.getFileName());\n context.runOnGlThread(new Runnable()\n {\n @Override\n public void run()\n {\n callback.loaded(cached, resource);\n }\n });\n }\n else\n {\n TextureCallback actualCallback = (textureCache == null) ? callback\n : ResourceCache.wrapCallback(textureCache, callback);\n AsyncCubemapTexture.loadTexture(context,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, actualCallback),\n resource, priority, faceIndexMap);\n }\n }",
"public void setCategoryDisplayOptions(\n String displayCategoriesByRepository,\n String displayCategorySelectionCollapsed) {\n\n m_displayCategoriesByRepository = Boolean.parseBoolean(displayCategoriesByRepository);\n m_displayCategorySelectionCollapsed = Boolean.parseBoolean(displayCategorySelectionCollapsed);\n }",
"public static <T> DatabaseTableConfig<T> fromClass(DatabaseType databaseType, Class<T> clazz) throws SQLException {\n\t\tString tableName = extractTableName(databaseType, clazz);\n\t\tif (databaseType.isEntityNamesMustBeUpCase()) {\n\t\t\ttableName = databaseType.upCaseEntityName(tableName);\n\t\t}\n\t\treturn new DatabaseTableConfig<T>(databaseType, clazz, tableName,\n\t\t\t\textractFieldTypes(databaseType, clazz, tableName));\n\t}",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, oid, true);\r\n }"
] |
Decomposes the input matrix 'a' and makes sure it isn't modified. | [
"public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }"
] | [
"private boolean checkAndSetManifestAndImagePathCandidates(String manifestPath, String candidateImagePath, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateManifest = getManifestFromArtifactory(dependenciesClient, manifestPath);\n if (candidateManifest == null) {\n return false;\n }\n\n String imageDigest = DockerUtils.getConfigDigest(candidateManifest);\n if (imageDigest.equals(imageId)) {\n manifest = candidateManifest;\n imagePath = candidateImagePath;\n return true;\n }\n\n listener.getLogger().println(String.format(\"Found incorrect manifest.json file in Artifactory in the following path: %s\\nExpecting: %s got: %s\", manifestPath, imageId, imageDigest));\n return false;\n }",
"public QueryBuilder useIndex(String designDocument, String indexName) {\n useIndex = new String[]{designDocument, indexName};\n return this;\n }",
"public boolean isValidStore(String name) {\n readLock.lock();\n try {\n if(this.storeNames.contains(name)) {\n return true;\n }\n return false;\n } finally {\n readLock.unlock();\n }\n }",
"public static Double checkLatitude(String name, Double latitude) {\n if (latitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LATITUDE,\n MAX_LATITUDE,\n latitude);\n }\n return latitude;\n }",
"private TableAlias getTableAliasForPath(String aPath, List hintClasses)\r\n {\r\n return (TableAlias) m_pathToAlias.get(buildAliasKey(aPath, hintClasses));\r\n }",
"public static sslaction[] get(nitro_service service) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tsslaction[] response = (sslaction[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize,\n long totalSizeOfFile) {\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 MessageDigest digestInstance = null;\n try {\n digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);\n } catch (NoSuchAlgorithmException ae) {\n throw new BoxAPIException(\"Digest algorithm not found\", ae);\n }\n\n //Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.\n byte[] digestBytes = digestInstance.digest(data);\n String digest = Base64.encode(digestBytes);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n //Content-Range: bytes offset-part/totalSize\n request.addHeader(HttpHeaders.CONTENT_RANGE,\n \"bytes \" + offset + \"-\" + (offset + partSize - 1) + \"/\" + totalSizeOfFile);\n\n //Creates the body\n request.setBody(new ByteArrayInputStream(data));\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) jsonObject.get(\"part\"));\n return part;\n }",
"@SuppressWarnings(\"unchecked\")\n public List<Field> getValueAsList() {\n return (List<Field>) type.convert(getValue(), Type.LIST);\n }",
"public AsciiTable setPaddingTop(int paddingTop) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingTop(paddingTop);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] |
Use this API to update snmpalarm resources. | [
"public static base_responses update(nitro_service client, snmpalarm resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpalarm updateresources[] = new snmpalarm[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpalarm();\n\t\t\t\tupdateresources[i].trapname = resources[i].trapname;\n\t\t\t\tupdateresources[i].thresholdvalue = resources[i].thresholdvalue;\n\t\t\t\tupdateresources[i].normalvalue = resources[i].normalvalue;\n\t\t\t\tupdateresources[i].time = resources[i].time;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].severity = resources[i].severity;\n\t\t\t\tupdateresources[i].logging = resources[i].logging;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\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 }",
"public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)\r\n throws SQLException\r\n {\r\n return getObjectFromColumn(rs, null, jdbcType, null, columnId);\r\n }",
"public ItemRequest<CustomField> insertEnumOption(String customField) {\n \n String path = String.format(\"/custom_fields/%s/enum_options/insert\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"POST\");\n }",
"public LayerType toDto(Class<? extends com.vividsolutions.jts.geom.Geometry> geometryClass) {\n\t\tif (geometryClass == LineString.class) {\n\t\t\treturn LayerType.LINESTRING;\n\t\t} else if (geometryClass == MultiLineString.class) {\n\t\t\treturn LayerType.MULTILINESTRING;\n\t\t} else if (geometryClass == Point.class) {\n\t\t\treturn LayerType.POINT;\n\t\t} else if (geometryClass == MultiPoint.class) {\n\t\t\treturn LayerType.MULTIPOINT;\n\t\t} else if (geometryClass == Polygon.class) {\n\t\t\treturn LayerType.POLYGON;\n\t\t} else if (geometryClass == MultiPolygon.class) {\n\t\t\treturn LayerType.MULTIPOLYGON;\n\t\t} else {\n\t\t\treturn LayerType.GEOMETRY;\n\t\t}\n\t}",
"private void refreshInstance(Object cachedInstance, Identity oid, ClassDescriptor cld)\n {\n // read in fresh copy from the db, but do not cache it\n Object freshInstance = getPlainDBObject(cld, oid);\n\n // update all primitive typed attributes\n FieldDescriptor[] fields = cld.getFieldDescriptions();\n FieldDescriptor fmd;\n PersistentField fld;\n for (int i = 0; i < fields.length; i++)\n {\n fmd = fields[i];\n fld = fmd.getPersistentField();\n fld.set(cachedInstance, fld.get(freshInstance));\n }\n }",
"public com.squareup.okhttp.Call postUiAutopilotWaypointCall(Boolean addToBeginning, Boolean clearOtherWaypoints,\n Long destinationId, String datasource, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v2/ui/autopilot/waypoint/\";\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (addToBeginning != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"add_to_beginning\", addToBeginning));\n }\n\n if (clearOtherWaypoints != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"clear_other_waypoints\", clearOtherWaypoints));\n }\n\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (destinationId != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"destination_id\", destinationId));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = {\n\n };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"POST\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\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 }",
"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 }"
] |
Registers your facet filters, adding them to this InstantSearch's widgets.
@param filters a List of facet filters. | [
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public void registerFilters(List<AlgoliaFilter> filters) {\n for (final AlgoliaFilter filter : filters) {\n searcher.addFacet(filter.getAttribute());\n }\n }"
] | [
"private JSONObject getJsonFormattedSpellcheckResult(CmsSpellcheckingRequest request) {\n\n final JSONObject response = new JSONObject();\n\n try {\n if (null != request.m_id) {\n response.put(JSON_ID, request.m_id);\n }\n\n response.put(JSON_RESULT, request.m_wordSuggestions);\n\n } catch (Exception e) {\n try {\n response.put(JSON_ERROR, true);\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", e);\n } catch (JSONException ex) {\n LOG.debug(\"Error while assembling spellcheck response in JSON format.\", ex);\n }\n }\n\n return response;\n }",
"private void processCalendarHours(ProjectCalendar calendar, Row row, int dayIndex)\n {\n Day day = Day.getInstance(dayIndex);\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n calendar.setWorkingDay(day, working);\n if (working == true)\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Date start = row.getDate(\"CD_FROM_TIME1\");\n Date end = row.getDate(\"CD_TO_TIME1\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME2\");\n end = row.getDate(\"CD_TO_TIME2\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME3\");\n end = row.getDate(\"CD_TO_TIME3\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME4\");\n end = row.getDate(\"CD_TO_TIME4\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n\n start = row.getDate(\"CD_FROM_TIME5\");\n end = row.getDate(\"CD_TO_TIME5\");\n if (start != null && end != null)\n {\n hours.addRange(new DateRange(start, end));\n }\n }\n }",
"public static base_responses delete(nitro_service client, String network[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (network != null && network.length > 0) {\n\t\t\troute6 deleteresources[] = new route6[network.length];\n\t\t\tfor (int i=0;i<network.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = network[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static DeploymentUnit getTopDeploymentUnit(DeploymentUnit unit) {\n Assert.checkNotNullParam(\"unit\", unit);\n\n DeploymentUnit parent = unit.getParent();\n while (parent != null) {\n unit = parent;\n parent = unit.getParent();\n }\n return unit;\n }",
"public BoxFile.Info uploadFile(FileUploadParams uploadParams) {\n URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL());\n BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);\n\n JsonObject fieldJSON = new JsonObject();\n JsonObject parentIdJSON = new JsonObject();\n parentIdJSON.add(\"id\", getID());\n fieldJSON.add(\"name\", uploadParams.getName());\n fieldJSON.add(\"parent\", parentIdJSON);\n\n if (uploadParams.getCreated() != null) {\n fieldJSON.add(\"content_created_at\", BoxDateFormat.format(uploadParams.getCreated()));\n }\n\n if (uploadParams.getModified() != null) {\n fieldJSON.add(\"content_modified_at\", BoxDateFormat.format(uploadParams.getModified()));\n }\n\n if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) {\n request.setContentSHA1(uploadParams.getSHA1());\n }\n\n if (uploadParams.getDescription() != null) {\n fieldJSON.add(\"description\", uploadParams.getDescription());\n }\n\n request.putField(\"attributes\", fieldJSON.toString());\n\n if (uploadParams.getSize() > 0) {\n request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize());\n } else if (uploadParams.getContent() != null) {\n request.setFile(uploadParams.getContent(), uploadParams.getName());\n } else {\n request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName());\n }\n\n BoxJSONResponse response;\n if (uploadParams.getProgressListener() == null) {\n response = (BoxJSONResponse) request.send();\n } else {\n response = (BoxJSONResponse) request.send(uploadParams.getProgressListener());\n }\n JsonObject collection = JsonObject.readFrom(response.getJSON());\n JsonArray entries = collection.get(\"entries\").asArray();\n JsonObject fileInfoJSON = entries.get(0).asObject();\n String uploadedFileID = fileInfoJSON.get(\"id\").asString();\n\n BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID);\n return uploadedFile.new Info(fileInfoJSON);\n }",
"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 }",
"private GridLines getGridLines(byte[] data, int offset)\n {\n Color normalLineColor = ColorType.getInstance(data[offset]).getColor();\n LineStyle normalLineStyle = LineStyle.getInstance(data[offset + 3]);\n int intervalNumber = data[offset + 4];\n LineStyle intervalLineStyle = LineStyle.getInstance(data[offset + 5]);\n Color intervalLineColor = ColorType.getInstance(data[offset + 6]).getColor();\n return new GridLines(normalLineColor, normalLineStyle, intervalNumber, intervalLineStyle, intervalLineColor);\n }",
"public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n try {\n FileUtils.writeStringToFile(new File(outputDirName, \"plan.out\"), plan.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpPlanToFile: \" + e);\n }\n }\n }",
"public static String encodeQuery(String query, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(query, encoding, HierarchicalUriComponents.Type.QUERY);\n\t}"
] |
Send a fader start command to all registered listeners.
@param playersToStart contains the device numbers of all players that should start playing
@param playersToStop contains the device numbers of all players that should stop playing | [
"private void deliverFaderStartCommand(Set<Integer> playersToStart, Set<Integer> playersToStop) {\n for (final FaderStartListener listener : getFaderStartListeners()) {\n try {\n listener.fadersChanged(playersToStart, playersToStop);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering fader start command to listener\", t);\n }\n }\n }"
] | [
"public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\n }\n }",
"public static ScheduledExecutorService newScheduledDaemonThreadPool(int corePoolSize) {\n return Executors.newScheduledThreadPool(corePoolSize, r -> {\n Thread t = Executors.defaultThreadFactory().newThread(r);\n t.setDaemon(true);\n return t;\n });\n }",
"public void close() {\n Closer.closeQuietly(acceptor);\n for (Processor processor : processors) {\n Closer.closeQuietly(processor);\n }\n }",
"public static String getJsonDatatypeFromDatatypeIri(String datatypeIri) {\n\t\tswitch (datatypeIri) {\n\t\t\tcase DatatypeIdValue.DT_ITEM:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_ITEM;\n\t\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_GLOBE_COORDINATES;\n\t\t\tcase DatatypeIdValue.DT_URL:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_URL;\n\t\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_COMMONS_MEDIA;\n\t\t\tcase DatatypeIdValue.DT_TIME:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_TIME;\n\t\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_QUANTITY;\n\t\t\tcase DatatypeIdValue.DT_STRING:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_STRING;\n\t\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_MONOLINGUAL_TEXT;\n\t\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_PROPERTY;\n\t\t\tdefault:\n\t\t\t\t//We apply the reverse algorithm of JacksonDatatypeId::getDatatypeIriFromJsonDatatype\n\t\t\t\tMatcher matcher = DATATYPE_ID_PATTERN.matcher(datatypeIri);\n\t\t\t\tif(!matcher.matches()) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown datatype: \" + datatypeIri);\n\t\t\t\t}\n\t\t\n\t\t\t\tStringBuilder jsonDatatypeBuilder = new StringBuilder();\n\t\t\t\tfor(char ch : StringUtils.uncapitalize(matcher.group(1)).toCharArray()) {\n\t\t\t\t\tif(Character.isUpperCase(ch)) {\n\t\t\t\t\t\tjsonDatatypeBuilder\n\t\t\t\t\t\t\t\t.append('-')\n\t\t\t\t\t\t\t\t.append(Character.toLowerCase(ch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjsonDatatypeBuilder.append(ch);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonDatatypeBuilder.toString();\n\t\t}\n\t}",
"private void setFields(Map<String, FieldType> map, MapRow row, FieldContainer container)\n {\n if (row != null)\n {\n for (Map.Entry<String, FieldType> entry : map.entrySet())\n {\n container.set(entry.getValue(), row.getObject(entry.getKey()));\n }\n }\n }",
"private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }",
"public void addTags(String photoId, String[] tags) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_TAGS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"tags\", StringUtilities.join(tags, \" \", true));\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public boolean matches(HostName host) {\n\t\tif(this == host) {\n\t\t\treturn true;\n\t\t}\n\t\tif(isValid()) {\n\t\t\tif(host.isValid()) {\n\t\t\t\tif(isAddressString()) {\n\t\t\t\t\treturn host.isAddressString()\n\t\t\t\t\t\t\t&& asAddressString().equals(host.asAddressString())\n\t\t\t\t\t\t\t&& Objects.equals(getPort(), host.getPort())\n\t\t\t\t\t\t\t&& Objects.equals(getService(), host.getService());\n\t\t\t\t}\n\t\t\t\tif(host.isAddressString()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tString thisHost = parsedHost.getHost();\n\t\t\t\tString otherHost = host.parsedHost.getHost();\n\t\t\t\tif(!thisHost.equals(otherHost)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn Objects.equals(parsedHost.getEquivalentPrefixLength(), host.parsedHost.getEquivalentPrefixLength()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getMask(), host.parsedHost.getMask()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getPort(), host.parsedHost.getPort()) &&\n\t\t\t\t\t\tObjects.equals(parsedHost.getService(), host.parsedHost.getService());\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\treturn !host.isValid() && toString().equals(host.toString());\n\t}",
"private boolean hasMultipleCostRates()\n {\n boolean result = false;\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n //\n // We assume here that if there is just one entry in the cost rate\n // table, this is an open ended rate which covers any work, it won't\n // have specific dates attached to it.\n //\n if (table.size() > 1)\n {\n //\n // If we have multiple rates in the table, see if the same rate\n // is in force at the start and the end of the aaaignment.\n //\n CostRateTableEntry startEntry = table.getEntryByDate(getStart());\n CostRateTableEntry finishEntry = table.getEntryByDate(getFinish());\n result = (startEntry != finishEntry);\n }\n }\n return result;\n }"
] |
Adds OPT_U | OPT_URL option to OptionParser, with multiple arguments.
@param parser OptionParser to be modified
@param required Tells if this option is required or optional | [
"public static void acceptsUrlMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_U, OPT_URL), \"coordinator bootstrap urls\")\n .withRequiredArg()\n .describedAs(\"url-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }"
] | [
"@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n rendererBuilder.withParent(viewGroup);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext()));\n rendererBuilder.withViewType(viewType);\n RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder();\n if (viewHolder == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null viewHolder\");\n }\n return viewHolder;\n }",
"public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }",
"public void setJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n checkJobTypes(jobTypes);\n this.jobTypes.clear();\n this.jobTypes.putAll(jobTypes);\n }",
"final void dispatchToAppender(final String message) {\n // dispatch a copy, since events should be treated as being immutable\n final FoundationFileRollingAppender appender = this.getSource();\n if (appender != null) {\n appender.append(new FileRollEvent(this, message));\n }\n }",
"public static dnsnsecrec[] get(nitro_service service, dnsnsecrec_args args) throws Exception{\n\t\tdnsnsecrec obj = new dnsnsecrec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsnsecrec[] response = (dnsnsecrec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private void copyResources(File outputDirectory) throws IOException\n {\n copyClasspathResource(outputDirectory, \"reportng.css\", \"reportng.css\");\n copyClasspathResource(outputDirectory, \"reportng.js\", \"reportng.js\");\n // If there is a custom stylesheet, copy that.\n File customStylesheet = META.getStylesheetPath();\n\n if (customStylesheet != null)\n {\n if (customStylesheet.exists())\n {\n copyFile(outputDirectory, customStylesheet, CUSTOM_STYLE_FILE);\n }\n else\n {\n // If not found, try to read the file as a resource on the classpath\n // useful when reportng is called by a jarred up library\n InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(customStylesheet.getPath());\n if (stream != null)\n {\n copyStream(outputDirectory, stream, CUSTOM_STYLE_FILE);\n }\n }\n }\n }",
"public static clusternodegroup get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup obj = new clusternodegroup();\n\t\tobj.set_name(name);\n\t\tclusternodegroup response = (clusternodegroup) obj.get_resource(service);\n\t\treturn response;\n\t}",
"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 }",
"@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }"
] |
Check that the ranges and sizes add up, otherwise we have lost some data somewhere | [
"private void validateSegments(List<LogSegment> segments) {\n synchronized (lock) {\n for (int i = 0; i < segments.size() - 1; i++) {\n LogSegment curr = segments.get(i);\n LogSegment next = segments.get(i + 1);\n if (curr.start() + curr.size() != next.start()) {\n throw new IllegalStateException(\"The following segments don't validate: \" + curr.getFile()\n .getAbsolutePath() + \", \" + next.getFile().getAbsolutePath());\n }\n }\n }\n }"
] | [
"@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 }",
"@Deprecated\n private static ListAttributeDefinition wrapAsList(final AttributeDefinition def) {\n final ListAttributeDefinition list = new ListAttributeDefinition(new SimpleListAttributeDefinition.Builder(def.getName(), def)\n .setElementValidator(def.getValidator())) {\n\n\n @Override\n public ModelNode getNoTextDescription(boolean forOperation) {\n final ModelNode model = super.getNoTextDescription(forOperation);\n setValueType(model);\n return model;\n }\n\n @Override\n protected void addValueTypeDescription(final ModelNode node, final ResourceBundle bundle) {\n setValueType(node);\n }\n\n @Override\n public void marshallAsElement(final ModelNode resourceModel, final boolean marshalDefault, final XMLStreamWriter writer) throws XMLStreamException {\n throw new RuntimeException();\n }\n\n @Override\n protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {\n setValueType(node);\n }\n\n @Override\n protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {\n setValueType(node);\n }\n\n private void setValueType(ModelNode node) {\n node.get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.STRING);\n }\n };\n return list;\n }",
"public static Calendar parseDividendDate(String date) {\n if (!Utils.isParseable(date)) {\n return null;\n }\n date = date.trim();\n SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US);\n format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n try {\n Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));\n parsedDate.setTime(format.parse(date));\n\n if (parsedDate.get(Calendar.YEAR) == 1970) {\n // Not really clear which year the dividend date is... making a reasonable guess.\n int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH);\n int year = today.get(Calendar.YEAR);\n if (monthDiff > 6) {\n year -= 1;\n } else if (monthDiff < -6) {\n year += 1;\n }\n parsedDate.set(Calendar.YEAR, year);\n }\n\n return parsedDate;\n } catch (ParseException ex) {\n log.warn(\"Failed to parse dividend date: \" + date);\n log.debug(\"Failed to parse dividend date: \" + date, ex);\n return null;\n }\n }",
"void setDayOfMonth(String day) {\n\n final int i = CmsSerialDateUtil.toIntWithDefault(day, -1);\n if (m_model.getDayOfMonth() != i) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setDayOfMonth(i);\n onValueChange();\n }\n });\n }\n }",
"public static OgmCollectionPersister getInverseCollectionPersister(OgmCollectionPersister mainSidePersister) {\n\t\tif ( mainSidePersister.isInverse() || !mainSidePersister.isManyToMany() || !mainSidePersister.getElementType().isEntityType() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tEntityPersister inverseSidePersister = mainSidePersister.getElementPersister();\n\n\t\t// process collection-typed properties of inverse side and try to find association back to main side\n\t\tfor ( Type type : inverseSidePersister.getPropertyTypes() ) {\n\t\t\tif ( type.isCollectionType() ) {\n\t\t\t\tOgmCollectionPersister inverseCollectionPersister = getPersister( mainSidePersister.getFactory(), (CollectionType) type );\n\t\t\t\tif ( isCollectionMatching( mainSidePersister, inverseCollectionPersister ) ) {\n\t\t\t\t\treturn inverseCollectionPersister;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"protected static boolean isOperatorLR( Symbol s ) {\n if( s == null )\n return false;\n\n switch( s ) {\n case ELEMENT_DIVIDE:\n case ELEMENT_TIMES:\n case ELEMENT_POWER:\n case RDIVIDE:\n case LDIVIDE:\n case TIMES:\n case POWER:\n case PLUS:\n case MINUS:\n case ASSIGN:\n return true;\n }\n return false;\n }",
"protected void createSequence(PersistenceBroker broker, FieldDescriptor field,\r\n String sequenceName, long maxKey) throws Exception\r\n {\r\n Statement stmt = null;\r\n try\r\n {\r\n stmt = broker.serviceStatementManager().getGenericStatement(field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n stmt.execute(sp_createSequenceQuery(sequenceName, maxKey));\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(e);\r\n throw new SequenceManagerException(\"Could not create new row in \"+SEQ_TABLE_NAME+\" table - TABLENAME=\" +\r\n sequenceName + \" field=\" + field.getColumnName(), e);\r\n }\r\n finally\r\n {\r\n try\r\n {\r\n if (stmt != null) stmt.close();\r\n }\r\n catch (SQLException sqle)\r\n {\r\n if(log.isDebugEnabled())\r\n log.debug(\"Threw SQLException while in createSequence and closing stmt\", sqle);\r\n // ignore it\r\n }\r\n }\r\n }",
"public void setEmptyDefault(String iso) {\n if (iso == null || iso.isEmpty()) {\n iso = DEFAULT_COUNTRY;\n }\n int defaultIdx = mCountries.indexOfIso(iso);\n mSelectedCountry = mCountries.get(defaultIdx);\n mCountrySpinner.setSelection(defaultIdx);\n }",
"public Tuple get(RowKey key) {\n\t\tAssociationOperation result = currentState.get( key );\n\t\tif ( result == null ) {\n\t\t\treturn cleared ? null : snapshot.get( key );\n\t\t}\n\t\telse if ( result.getType() == REMOVE ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn result.getValue();\n\t}"
] |
Expands the cluster to include density-reachable items.
@param cluster Cluster to expand
@param point Point to add to cluster
@param neighbors List of neighbors
@param points the data set
@param visited the set of already visited points
@return the expanded cluster | [
"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 }"
] | [
"protected void runScript(File script) {\n if (!script.exists()) {\n JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + \" does not exist.\",\n \"Unable to run script.\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), \"Run CLI script \" + script.getName() + \"?\",\n \"Confirm run script\", JOptionPane.YES_NO_OPTION);\n if (choice != JOptionPane.YES_OPTION) return;\n\n menu.addScript(script);\n\n cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output\n output.post(\"\\n\");\n\n SwingWorker scriptRunner = new ScriptRunner(script);\n scriptRunner.execute();\n }",
"public static void doEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) {\n jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n jedis.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }",
"public Enumeration getPKEnumerationByQuery(Class primaryKeyClass, Query query) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled()) logger.debug(\"getPKEnumerationByQuery \" + query);\n\n query.setFetchSize(1);\n ClassDescriptor cld = getClassDescriptor(query.getSearchClass());\n return new PkEnumeration(query, cld, primaryKeyClass, this);\n }",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addProfile(Model model, String name) throws Exception {\n logger.info(\"Should be adding the profile name when I hit the enter button={}\", name);\n return Utils.getJQGridJSON(profileService.add(name), \"profile\");\n }",
"public FinishRequest toFinishRequest(boolean includeHeaders) {\n if (includeHeaders) {\n return new FinishRequest(body, copyHeaders(headers), statusCode);\n } else {\n String mime = null;\n if (body!=null) {\n mime = \"text/plain\";\n if (headers!=null && (headers.containsKey(\"Content-Type\") || headers.containsKey(\"content-type\"))) {\n mime = headers.get(\"Content-Type\");\n if (mime==null) {\n mime = headers.get(\"content-type\");\n }\n }\n }\n\n return new FinishRequest(body, mime, statusCode);\n }\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }",
"public void log(Level level, String msg) {\n\t\tlogIfEnabled(level, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}",
"public BufferedImage getImage() {\n ByteBuffer artwork = getRawBytes();\n artwork.rewind();\n byte[] imageBytes = new byte[artwork.remaining()];\n artwork.get(imageBytes);\n try {\n return ImageIO.read(new ByteArrayInputStream(imageBytes));\n } catch (IOException e) {\n logger.error(\"Weird! Caught exception creating image from artwork bytes\", e);\n return null;\n }\n }",
"@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (flatPosition == RecyclerView.NO_POSITION) {\n return flatPosition;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }"
] |
Called when a payload thread has ended. This also notifies the poller to poll once again. | [
"void releaseResources(JobInstance ji)\n {\n this.peremption.remove(ji.getId());\n this.actualNbThread.decrementAndGet();\n\n for (ResourceManagerBase rm : this.resourceManagers)\n {\n rm.releaseResource(ji);\n }\n\n if (!this.strictPollingPeriod)\n {\n // Force a new loop at once. This makes queues more fluid.\n loop.release(1);\n }\n this.engine.signalEndOfRun();\n }"
] | [
"@RequestMapping(value = \"/scripts\", method = RequestMethod.GET)\n public String scriptView(Model model) throws Exception {\n return \"script\";\n }",
"public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)\n throws InstantiationException, IllegalAccessException, IntrospectionException,\n IllegalArgumentException, InvocationTargetException {\n return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());\n }",
"void update(JsonObject jsonObject) {\n for (JsonObject.Member member : jsonObject) {\n if (member.getValue().isNull()) {\n continue;\n }\n\n this.parseJSONMember(member);\n }\n\n this.clearPendingChanges();\n }",
"public ReferenceBuilder withPropertyValue(PropertyIdValue propertyIdValue,\n\t\t\tValue value) {\n\t\tgetSnakList(propertyIdValue).add(\n\t\t\t\tfactory.getValueSnak(propertyIdValue, value));\n\t\treturn getThis();\n\t}",
"private static BundleCapability getExportedPackage(BundleContext context, String packageName) {\n List<BundleCapability> packages = new ArrayList<BundleCapability>();\n for (Bundle bundle : context.getBundles()) {\n BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);\n for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {\n String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);\n if (pName.equalsIgnoreCase(packageName)) {\n packages.add(packageCapability);\n }\n }\n }\n\n Version max = Version.emptyVersion;\n BundleCapability maxVersion = null;\n for (BundleCapability aPackage : packages) {\n Version version = (Version) aPackage.getAttributes().get(\"version\");\n if (max.compareTo(version) <= 0) {\n max = version;\n maxVersion = aPackage;\n }\n }\n\n return maxVersion;\n }",
"public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {\n\t\tif (x < a1 || x >= b2)\n\t\t\treturn 0;\n\t\tif (x >= a2) {\n\t\t\tif (x < b1)\n\t\t\t\treturn 1.0f;\n\t\t\tx = (x - b1) / (b2 - b1);\n\t\t\treturn 1.0f - (x*x * (3.0f - 2.0f*x));\n\t\t}\n\t\tx = (x - a1) / (a2 - a1);\n\t\treturn x*x * (3.0f - 2.0f*x);\n\t}",
"protected void reportWorked(int workIncrement, int currentUnitIndex) {\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.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1);\n }\n }",
"public static policydataset[] get(nitro_service service) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tpolicydataset[] response = (policydataset[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"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}"
] |
Save a weak reference to the resource | [
"public void put(GVRAndroidResource androidResource, T resource) {\n Log.d(TAG, \"put resource %s to cache\", androidResource);\n\n super.put(androidResource, resource);\n }"
] | [
"private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) {\n if (mn==null) {\n return;\n }\n ClassNode declaringClass = mn.getDeclaringClass();\n ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();\n if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) {\n int mods = mn.getModifiers();\n boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule();\n String packageName = declaringClass.getPackageName();\n if (packageName==null) {\n packageName = \"\";\n }\n if ((Modifier.isPrivate(mods) && sameModule)\n || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) {\n addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn);\n }\n }\n }",
"@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }",
"public void refresh(String[] configLocations) throws GeomajasException {\n\t\ttry {\n\t\t\tsetConfigLocations(configLocations);\n\t\t\trefresh();\n\t\t} catch (Exception e) {\n\t\t\tthrow new GeomajasException(e, ExceptionCode.REFRESH_CONFIGURATION_FAILED);\n\t\t}\n\t}",
"@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }",
"public void setAlias(String alias)\r\n\t{\r\n\t\tif (alias == null || alias.trim().equals(\"\"))\r\n\t\t{\r\n\t\t\tm_alias = null;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tm_alias = alias;\r\n\t\t}\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(m_alias);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public String toText() {\n StringBuilder sb = new StringBuilder();\n if (!description.isEmpty()) {\n sb.append(description.toText());\n sb.append(EOL);\n }\n if (!blockTags.isEmpty()) {\n sb.append(EOL);\n }\n for (JavadocBlockTag tag : blockTags) {\n sb.append(tag.toText()).append(EOL);\n }\n return sb.toString();\n }",
"public static DatagramPacket buildPacket(PacketType type, ByteBuffer deviceName, ByteBuffer payload) {\n ByteBuffer content = ByteBuffer.allocate(0x1f + payload.remaining());\n content.put(getMagicHeader());\n content.put(type.protocolValue);\n content.put(deviceName);\n content.put(payload);\n return new DatagramPacket(content.array(), content.capacity());\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 }",
"public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }"
] |
Gets the numeric codes. Setting it to -1 search for currencies that have no numeric code.
@return the query for chaining. | [
"public Collection<Integer> getNumericCodes() {\n Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }"
] | [
"private Boolean readOptionalBoolean(JSONValue val) {\n\n JSONBoolean b = null == val ? null : val.isBoolean();\n if (b != null) {\n return Boolean.valueOf(b.booleanValue());\n }\n return null;\n }",
"protected Class<?> getPropertyClass(ClassMetadata meta, String propertyName) throws HibernateLayerException {\n\t\t// try to assure the correct separator is used\n\t\tpropertyName = propertyName.replace(XPATH_SEPARATOR, SEPARATOR);\n\n\t\tif (propertyName.contains(SEPARATOR)) {\n\t\t\tString directProperty = propertyName.substring(0, propertyName.indexOf(SEPARATOR));\n\t\t\ttry {\n\t\t\t\tType prop = meta.getPropertyType(directProperty);\n\t\t\t\tif (prop.isCollectionType()) {\n\t\t\t\t\tCollectionType coll = (CollectionType) prop;\n\t\t\t\t\tprop = coll.getElementType((SessionFactoryImplementor) sessionFactory);\n\t\t\t\t}\n\t\t\t\tClassMetadata propMeta = sessionFactory.getClassMetadata(prop.getReturnedClass());\n\t\t\t\treturn getPropertyClass(propMeta, propertyName.substring(propertyName.indexOf(SEPARATOR) + 1));\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn meta.getPropertyType(propertyName).getReturnedClass();\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t}\n\t}",
"protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }",
"public ContentAssistContext.Builder copy() {\n\t\tBuilder result = builderProvider.get();\n\t\tresult.copyFrom(this);\n\t\treturn result;\n\t}",
"public boolean isPrivate() {\n\t\t// refer to RFC 1918\n // 10/8 prefix\n // 172.16/12 prefix (172.16.0.0 – 172.31.255.255)\n // 192.168/16 prefix\n\t\tIPv4AddressSegment seg0 = getSegment(0);\n\t\tIPv4AddressSegment seg1 = getSegment(1);\n\t\treturn seg0.matches(10)\n\t\t\t|| seg0.matches(172) && seg1.matchesWithPrefixMask(16, 4)\n\t\t\t|| seg0.matches(192) && seg1.matches(168);\n\t}",
"private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) {\n\t\tSet<Class<?>> entities = new HashSet<Class<?>>();\n\t\t//first build the \"entities\" set containing all indexed subtypes of \"selection\".\n\t\tfor ( Class<?> entityType : selection ) {\n\t\t\tIndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( IndexedTypeSets.fromClass( entityType ) );\n\t\t\tif ( targetedClasses.isEmpty() ) {\n\t\t\t\tString msg = entityType.getName() + \" is not an indexed entity or a subclass of an indexed entity\";\n\t\t\t\tthrow new IllegalArgumentException( msg );\n\t\t\t}\n\t\t\tentities.addAll( targetedClasses.toPojosSet() );\n\t\t}\n\t\tSet<Class<?>> cleaned = new HashSet<Class<?>>();\n\t\tSet<Class<?>> toRemove = new HashSet<Class<?>>();\n\t\t//now remove all repeated types to avoid duplicate loading by polymorphic query loading\n\t\tfor ( Class<?> type : entities ) {\n\t\t\tboolean typeIsOk = true;\n\t\t\tfor ( Class<?> existing : cleaned ) {\n\t\t\t\tif ( existing.isAssignableFrom( type ) ) {\n\t\t\t\t\ttypeIsOk = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( type.isAssignableFrom( existing ) ) {\n\t\t\t\t\ttoRemove.add( existing );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( typeIsOk ) {\n\t\t\t\tcleaned.add( type );\n\t\t\t}\n\t\t}\n\t\tcleaned.removeAll( toRemove );\n\t\tlog.debugf( \"Targets for indexing job: %s\", cleaned );\n\t\treturn IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) );\n\t}",
"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 }",
"void checkRmModelConformance() {\n final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());\n ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());\n }",
"public static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}"
] |
Gets information about this collaboration.
@return info about this collaboration. | [
"public Info getInfo() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }"
] | [
"public void setTimeWarp(String l) {\n\n long warp = CmsContextInfo.CURRENT_TIME;\n try {\n warp = Long.parseLong(l);\n } catch (NumberFormatException e) {\n // if parsing the time warp fails, it will be set to -1 (i.e. disabled)\n }\n m_settings.setTimeWarp(warp);\n }",
"@Nullable\n public ResultT first() {\n final CoreRemoteMongoCursor<ResultT> cursor = iterator();\n if (!cursor.hasNext()) {\n return null;\n }\n return cursor.next();\n }",
"private void readExceptionDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay day)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod timePeriod = day.getTimePeriod();\n Date fromDate = timePeriod.getFromDate();\n Date toDate = timePeriod.getToDate();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = day.getWorkingTimes();\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n\n if (times != null)\n {\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> time = times.getWorkingTime();\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : time)\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n exception.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"public BoxFile.Info getFileInfo(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }",
"public static final Number parseUnits(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() * 100));\n }",
"private void allInput(List<FileModel> vertices, GraphRewrite event, ParameterStore store)\n {\n if (StringUtils.isBlank(getInputVariablesName()) && this.filenamePattern == null)\n {\n FileService fileModelService = new FileService(event.getGraphContext());\n for (FileModel fileModel : fileModelService.findAll())\n {\n vertices.add(fileModel);\n }\n }\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 List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths,\n Path sourceFile)\n {\n ASTParser parser = ASTParser.newParser(AST.JLS11);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n String fileName = sourceFile.getFileName().toString();\n parser.setUnitName(fileName);\n try\n {\n parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray());\n }\n catch (IOException e)\n {\n throw new ASTException(\"Failed to get source for file: \" + sourceFile.toString() + \" due to: \" + e.getMessage(), e);\n }\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n CompilationUnit cu = (CompilationUnit) parser.createAST(null);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString());\n cu.accept(visitor);\n return visitor.getJavaClassReferences();\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}"
] |
Tries to load a the bundle for a given locale, also loads the backup
locales with the same language.
@param baseName the raw bundle name, without locale qualifiers
@param locale the locale
@param wantBase whether a resource bundle made only from the base name
(with no locale information attached) should be returned.
@return the resource bundle if it was loaded, otherwise the backup | [
"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 }"
] | [
"public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}",
"public void processCalendar(Row row)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n\n Integer id = row.getInteger(\"clndr_id\");\n m_calMap.put(id, calendar);\n calendar.setName(row.getString(\"clndr_name\"));\n\n try\n {\n calendar.setMinutesPerDay(Integer.valueOf((int) NumberHelper.getDouble(row.getDouble(\"day_hr_cnt\")) * 60));\n calendar.setMinutesPerWeek(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"week_hr_cnt\")) * 60)));\n calendar.setMinutesPerMonth(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"month_hr_cnt\")) * 60)));\n calendar.setMinutesPerYear(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"year_hr_cnt\")) * 60)));\n }\n catch (ClassCastException ex)\n {\n // We have seen examples of malformed calendar data where fields have been missing\n // from the record. We'll typically get a class cast exception here as we're trying\n // to process something which isn't a double.\n // We'll just return at this point as it's not clear that we can salvage anything\n // sensible from this record.\n return;\n }\n\n // Process data\n String calendarData = row.getString(\"clndr_data\");\n if (calendarData != null && !calendarData.isEmpty())\n {\n Record root = Record.getRecord(calendarData);\n if (root != null)\n {\n processCalendarDays(calendar, root);\n processCalendarExceptions(calendar, root);\n }\n }\n else\n {\n // if there is not DaysOfWeek data, Primavera seems to default to Mon-Fri, 8:00-16:00\n DateRange defaultHourRange = new DateRange(DateHelper.getTime(8, 0), DateHelper.getTime(16, 0));\n for (Day day : Day.values())\n {\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n calendar.setWorkingDay(day, true);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n hours.addRange(defaultHourRange);\n }\n else\n {\n calendar.setWorkingDay(day, false);\n }\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getInboxMessageUnreadCount(){\n synchronized (inboxControllerLock) {\n if (this.ctInboxController != null) {\n return ctInboxController.unreadCount();\n } else {\n getConfigLogger().debug(getAccountId(), \"Notification Inbox not initialized\");\n return -1;\n }\n }\n }",
"private Set<String> checkModel(final ModelNode model, TransformationContext context) throws OperationFailedException {\n final Set<String> attributes = new HashSet<String>();\n AttributeTransformationRequirementChecker checker;\n for (final String attribute : attributeNames) {\n if (model.hasDefined(attribute)) {\n if (attributeCheckers != null && (checker = attributeCheckers.get(attribute)) != null) {\n if (checker.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n } else if (SIMPLE_EXPRESSIONS.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n }\n }\n return attributes;\n }",
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }",
"public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }",
"public static cachepolicy_cacheglobal_binding[] get(nitro_service service, String policyname) throws Exception{\n\t\tcachepolicy_cacheglobal_binding obj = new cachepolicy_cacheglobal_binding();\n\t\tobj.set_policyname(policyname);\n\t\tcachepolicy_cacheglobal_binding response[] = (cachepolicy_cacheglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }",
"private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml)\n {\n if (m_writeTimphasedData && mpx.getHasTimephasedData())\n {\n List<TimephasedDataType> list = xml.getTimephasedData();\n ProjectCalendar calendar = mpx.getCalendar();\n BigInteger assignmentID = xml.getUID();\n\n List<TimephasedWork> complete = mpx.getTimephasedActualWork();\n List<TimephasedWork> planned = mpx.getTimephasedWork();\n\n if (m_splitTimephasedAsDays)\n {\n TimephasedWork lastComplete = null;\n if (complete != null && !complete.isEmpty())\n {\n lastComplete = complete.get(complete.size() - 1);\n }\n\n TimephasedWork firstPlanned = null;\n if (planned != null && !planned.isEmpty())\n {\n firstPlanned = planned.get(0);\n }\n\n if (planned != null)\n {\n planned = splitDays(calendar, mpx.getTimephasedWork(), null, lastComplete);\n }\n\n if (complete != null)\n {\n complete = splitDays(calendar, complete, firstPlanned, null);\n }\n }\n\n if (planned != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, planned, 1);\n }\n\n if (complete != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, complete, 2);\n }\n }\n }"
] |
Sets the indirection handler class.
@param indirectionHandlerClass The class for indirection handlers | [
"public void setIndirectionHandlerClass(Class indirectionHandlerClass)\r\n {\r\n if(indirectionHandlerClass == null)\r\n {\r\n //throw new MetadataException(\"No IndirectionHandlerClass specified.\");\r\n /**\r\n * andrew.clute\r\n * Allow the default IndirectionHandler for the given ProxyFactory implementation\r\n * when the parameter is not given\r\n */\r\n indirectionHandlerClass = getDefaultIndirectionHandlerClass();\r\n }\r\n if(indirectionHandlerClass.isInterface()\r\n || Modifier.isAbstract(indirectionHandlerClass.getModifiers())\r\n || !getIndirectionHandlerBaseClass().isAssignableFrom(indirectionHandlerClass))\r\n {\r\n throw new MetadataException(\"Illegal class \"\r\n + indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass. Must be a concrete subclass of \"\r\n + getIndirectionHandlerBaseClass().getName());\r\n }\r\n _indirectionHandlerClass = indirectionHandlerClass;\r\n }"
] | [
"public static sslaction get(nitro_service service, String name) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tobj.set_name(name);\n\t\tsslaction response = (sslaction) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private static void handlePing(final Channel channel, final ManagementProtocolHeader header) throws IOException {\n final ManagementProtocolHeader response = new ManagementPongHeader(header.getVersion());\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }",
"public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate(\n String listStr, boolean removeDuplicate) {\n\n List<String> nodes = new ArrayList<String>();\n\n for (String token : listStr.split(\"[\\\\r?\\\\n| +]+\")) {\n\n // 20131025: fix if fqdn has space in the end.\n if (token != null && !token.trim().isEmpty()) {\n nodes.add(token.trim());\n\n }\n }\n\n if (removeDuplicate) {\n removeDuplicateNodeList(nodes);\n }\n logger.info(\"Target hosts size : \" + nodes.size());\n\n return nodes;\n\n }",
"private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"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 }",
"private static JSONArray parseStencilSetExtensions(ArrayList<String> extensions) {\n if (extensions != null) {\n JSONArray extensionsArray = new JSONArray();\n\n for (String extension : extensions) {\n extensionsArray.put(extension.toString());\n }\n\n return extensionsArray;\n }\n\n return new JSONArray();\n }",
"public static double KumarJohnsonDivergence(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n r += Math.pow(p[i] * p[i] - q[i] * q[i], 2) / 2 * Math.pow(p[i] * q[i], 1.5);\n }\n }\n return r;\n }",
"public void set1Value(int index, String newValue) {\n try {\n value.set( index, newValue );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) exception \" + e);\n }\n }",
"public Collection<BoxGroupMembership.Info> getMemberships() {\n BoxAPIConnection api = this.getAPI();\n URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get(\"id\").asString());\n BoxGroupMembership.Info info = membership.new Info(entryObject);\n memberships.add(info);\n }\n\n return memberships;\n }"
] |
Extracts the elements from the source matrix by their 1D index.
@param src Source matrix. Not modified.
@param indexes array of row indexes
@param length maximum element in row array
@param dst output matrix. Must be a vector of the correct length. | [
"public static void extract(DMatrixRMaj src, int indexes[] , int length , DMatrixRMaj dst ) {\n if( !MatrixFeatures_DDRM.isVector(dst))\n throw new MatrixDimensionException(\"Dst must be a vector\");\n if( length != dst.getNumElements())\n throw new MatrixDimensionException(\"Unexpected number of elements in dst vector\");\n\n for (int i = 0; i < length; i++) {\n dst.data[i] = src.data[indexes[i]];\n }\n }"
] | [
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void recordScreen(String screenName){\n if(screenName == null || (!currentScreenName.isEmpty() && currentScreenName.equals(screenName))) return;\n getConfigLogger().debug(getAccountId(), \"Screen changed to \" + screenName);\n currentScreenName = screenName;\n recordPageEventWithExtras(null);\n }",
"public void applyToBackground(View view) {\n if (mColorInt != 0) {\n view.setBackgroundColor(mColorInt);\n } else if (mColorRes != -1) {\n view.setBackgroundResource(mColorRes);\n }\n }",
"private static void unregisterMBean(String name) {\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n try {\n synchronized (mbs) {\n ObjectName objName = new ObjectName(name);\n if (mbs.isRegistered(objName)) {\n mbs.unregisterMBean(objName);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }",
"public IGoal[] getAgentGoals(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n\n goals = bia.getGoalbase().getGoals();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return goals;\n }",
"public static ProducerRequest readFrom(ByteBuffer buffer) {\n String topic = Utils.readShortString(buffer);\n int partition = buffer.getInt();\n int messageSetSize = buffer.getInt();\n ByteBuffer messageSetBuffer = buffer.slice();\n messageSetBuffer.limit(messageSetSize);\n buffer.position(buffer.position() + messageSetSize);\n return new ProducerRequest(topic, partition, new ByteBufferMessageSet(messageSetBuffer));\n }",
"public String astring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n return atom(request);\n }\n }",
"public ItemRequest<Task> removeDependents(String task) {\n \n String path = String.format(\"/tasks/%s/removeDependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public List<String> getServiceImplementations(String serviceTypeName) {\n final List<String> strings = services.get(serviceTypeName);\n return strings == null ? Collections.<String>emptyList() : Collections.unmodifiableList(strings);\n }",
"private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n for (Relation relation : relationList)\n {\n if (relation.getTargetTask() == targetTask)\n {\n if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)\n {\n matchFound = relationList.remove(relation);\n break;\n }\n }\n }\n return matchFound;\n }"
] |
Creates the main component of the editor with all sub-components.
@return the completely filled main component of the editor.
@throws IOException thrown if setting the table's content data source fails.
@throws CmsException thrown if setting the table's content data source fails. | [
"private Component createMainComponent() throws IOException, CmsException {\n\n VerticalLayout mainComponent = new VerticalLayout();\n mainComponent.setSizeFull();\n mainComponent.addStyleName(\"o-message-bundle-editor\");\n m_table = createTable();\n Panel navigator = new Panel();\n navigator.setSizeFull();\n navigator.setContent(m_table);\n navigator.addActionHandler(new CmsMessageBundleEditorTypes.TableKeyboardHandler(m_table));\n navigator.addStyleName(\"v-panel-borderless\");\n\n mainComponent.addComponent(m_options.getOptionsComponent());\n mainComponent.addComponent(navigator);\n mainComponent.setExpandRatio(navigator, 1f);\n m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());\n return mainComponent;\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 }",
"public void stop()\n {\n synchronized (mAnimQueue)\n {\n if (mIsRunning && (mAnimQueue.size() > 0))\n {\n mIsRunning = false;\n GVRAnimator animator = mAnimQueue.get(0);\n mAnimQueue.clear();\n animator.stop();\n }\n }\n }",
"protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) {\n if (jobTypes == null) {\n throw new IllegalArgumentException(\"jobTypes must not be null\");\n }\n for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) {\n try {\n checkJobType(entry.getKey(), entry.getValue());\n } catch (IllegalArgumentException iae) {\n throw new IllegalArgumentException(\"jobTypes contained invalid value\", iae);\n }\n }\n }",
"@Deprecated\n public ModelNode navigate(ModelNode model, boolean create) throws NoSuchElementException {\n final Iterator<PathElement> i = pathAddressList.iterator();\n while (i.hasNext()) {\n final PathElement element = i.next();\n if (create && !i.hasNext()) {\n if (element.isMultiTarget()) {\n throw new IllegalStateException();\n }\n model = model.require(element.getKey()).get(element.getValue());\n } else {\n model = model.require(element.getKey()).require(element.getValue());\n }\n }\n return model;\n }",
"private static QName getServiceName(Server server) {\n QName serviceName;\n String bindingId = getBindingId(server);\n EndpointInfo eInfo = server.getEndpoint().getEndpointInfo();\n \n if (JAXRS_BINDING_ID.equals(bindingId)) {\n serviceName = eInfo.getName();\n } else {\n ServiceInfo serviceInfo = eInfo.getService();\n serviceName = serviceInfo.getName();\n }\n return serviceName;\n }",
"private static String getUnexpectedTypeMessage(final Class<?> expectedType, final Object actualValue) {\n\t\tif( expectedType == null ) {\n\t\t\tthrow new NullPointerException(\"expectedType should not be null\");\n\t\t}\n\t\tString expectedClassName = expectedType.getName();\n\t\tString actualClassName = (actualValue != null) ? actualValue.getClass().getName() : \"null\";\n\t\treturn String.format(\"the input value should be of type %s but is %s\", expectedClassName, actualClassName);\n\t}",
"public void setBodyFilter(int pathId, String bodyFilter) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_BODY_FILTER + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, bodyFilter);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\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 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 }",
"private void processKnownType(FieldType type)\n {\n //System.out.println(\"Header: \" + type);\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, 36, false, 16, \"\"));\n\n GraphicalIndicator indicator = m_container.getCustomField(type).getGraphicalIndicator();\n indicator.setFieldType(type);\n int flags = m_data[m_dataOffset];\n indicator.setProjectSummaryInheritsFromSummaryRows((flags & 0x08) != 0);\n indicator.setSummaryRowsInheritFromNonSummaryRows((flags & 0x04) != 0);\n indicator.setDisplayGraphicalIndicators((flags & 0x02) != 0);\n indicator.setShowDataValuesInToolTips((flags & 0x01) != 0);\n m_dataOffset += 20;\n\n int nonSummaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int summaryRowOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int projectSummaryOffset = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n int dataSize = MPPUtility.getInt(m_data, m_dataOffset) - 36;\n m_dataOffset += 4;\n\n //System.out.println(\"Data\");\n //System.out.println(ByteArrayHelper.hexdump(m_data, m_dataOffset, dataSize, false, 16, \"\"));\n\n int maxNonSummaryRowOffset = m_dataOffset + summaryRowOffset;\n int maxSummaryRowOffset = m_dataOffset + projectSummaryOffset;\n int maxProjectSummaryOffset = m_dataOffset + dataSize;\n\n m_dataOffset += nonSummaryRowOffset;\n\n while (m_dataOffset + 2 < maxNonSummaryRowOffset)\n {\n indicator.addNonSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxSummaryRowOffset)\n {\n indicator.addSummaryRowCriteria(processCriteria(type));\n }\n\n while (m_dataOffset + 2 < maxProjectSummaryOffset)\n {\n indicator.addProjectSummaryCriteria(processCriteria(type));\n }\n }"
] |
Returns the RPC service for serial dates.
@return the RPC service for serial dates. | [
"I_CmsSerialDateServiceAsync getService() {\r\n\r\n if (SERVICE == null) {\r\n SERVICE = GWT.create(I_CmsSerialDateService.class);\r\n String serviceUrl = CmsCoreProvider.get().link(\"org.opencms.ade.contenteditor.CmsSerialDateService.gwt\");\r\n ((ServiceDefTarget)SERVICE).setServiceEntryPoint(serviceUrl);\r\n }\r\n return SERVICE;\r\n }"
] | [
"public static base_response unset(nitro_service client, cmpparameter resource, String[] args) throws Exception{\n\t\tcmpparameter unsetresource = new cmpparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"private void processUDF(UDFTypeType udf)\n {\n FieldTypeClass fieldType = FIELD_TYPE_MAP.get(udf.getSubjectArea());\n if (fieldType != null)\n {\n UserFieldDataType dataType = UserFieldDataType.getInstanceFromXmlName(udf.getDataType());\n String name = udf.getTitle();\n FieldType field = addUserDefinedField(fieldType, dataType, name);\n if (field != null)\n {\n m_fieldTypeMap.put(udf.getObjectId(), field);\n }\n }\n }",
"public static int hoursDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / HOUR_MILLIS) - (earlierDate.getTime() / HOUR_MILLIS));\n }",
"public void stop()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"stopping audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().stopSound(getSourceId());\n }\n }",
"public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T\n stateObjectToStore) {\n Map<String, Object> state = interceptorStates.get(interceptor);\n if (state == null) {\n interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>()));\n }\n state.put(stateName, stateObjectToStore);\n }",
"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 ProjectCalendar addDefaultDerivedCalendar()\n {\n ProjectCalendar calendar = add();\n\n calendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n calendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n\n return (calendar);\n }",
"public ManagementModelNode getSelectedNode() {\n if (tree.getSelectionPath() == null) return null;\n return (ManagementModelNode)tree.getSelectionPath().getLastPathComponent();\n }",
"public Map<DeckReference, AlbumArt> getLoadedArt() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, AlbumArt>(hotCache));\n }"
] |
Copies information between specified streams and then closes
both of the streams.
@throws java.io.IOException | [
"public static void copyThenClose(InputStream input, OutputStream output)\r\n throws IOException {\r\n copy(input, output);\r\n input.close();\r\n output.close();\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 UUID getUUID(FastTrackField type)\n {\n String value = getString(type);\n UUID result = null;\n if (value != null && !value.isEmpty() && value.length() >= 36)\n {\n if (value.startsWith(\"{\"))\n {\n value = value.substring(1, value.length() - 1);\n }\n if (value.length() > 16)\n {\n value = value.substring(0, 36);\n }\n result = UUID.fromString(value);\n }\n return result;\n }",
"private void notifyIfStopped() {\n if (isAcceptingNewJobs() || !this.runningTasksFutures.isEmpty()) {\n return;\n }\n final File stoppedFile = new File(this.workingDirectories.getWorking(), \"stopped\");\n try {\n LOGGER.info(\"The print has finished processing jobs and can now stop\");\n stoppedFile.createNewFile();\n } catch (IOException e) {\n LOGGER.warn(\"Cannot create the {} file\", stoppedFile, e);\n }\n }",
"public ArrayList getPrimaryKeys()\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n result.add(fieldDef);\r\n }\r\n }\r\n return result;\r\n }",
"public void createEnvironment(@Observes(precedence = 10) BeforeClass event, OpenShiftAdapter client,\n CubeOpenShiftConfiguration cubeOpenShiftConfiguration) {\n final TestClass testClass = event.getTestClass();\n log.info(String.format(\"Creating environment for %s\", testClass.getName()));\n OpenShiftResourceFactory.createResources(testClass.getName(), client, testClass.getJavaClass(),\n cubeOpenShiftConfiguration.getProperties());\n classTemplateProcessor = new ClassTemplateProcessor(client, cubeOpenShiftConfiguration, testClass);\n final List<? extends OpenShiftResource> templateResources = classTemplateProcessor.processTemplateResources();\n templateDetailsProducer.set(() -> templateResources);\n }",
"public static String getJsonDatatypeFromDatatypeIri(String datatypeIri) {\n\t\tswitch (datatypeIri) {\n\t\t\tcase DatatypeIdValue.DT_ITEM:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_ITEM;\n\t\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_GLOBE_COORDINATES;\n\t\t\tcase DatatypeIdValue.DT_URL:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_URL;\n\t\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_COMMONS_MEDIA;\n\t\t\tcase DatatypeIdValue.DT_TIME:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_TIME;\n\t\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_QUANTITY;\n\t\t\tcase DatatypeIdValue.DT_STRING:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_STRING;\n\t\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_MONOLINGUAL_TEXT;\n\t\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_PROPERTY;\n\t\t\tdefault:\n\t\t\t\t//We apply the reverse algorithm of JacksonDatatypeId::getDatatypeIriFromJsonDatatype\n\t\t\t\tMatcher matcher = DATATYPE_ID_PATTERN.matcher(datatypeIri);\n\t\t\t\tif(!matcher.matches()) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown datatype: \" + datatypeIri);\n\t\t\t\t}\n\t\t\n\t\t\t\tStringBuilder jsonDatatypeBuilder = new StringBuilder();\n\t\t\t\tfor(char ch : StringUtils.uncapitalize(matcher.group(1)).toCharArray()) {\n\t\t\t\t\tif(Character.isUpperCase(ch)) {\n\t\t\t\t\t\tjsonDatatypeBuilder\n\t\t\t\t\t\t\t\t.append('-')\n\t\t\t\t\t\t\t\t.append(Character.toLowerCase(ch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjsonDatatypeBuilder.append(ch);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonDatatypeBuilder.toString();\n\t\t}\n\t}",
"public final void notifyContentItemRangeRemoved(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (contentItemCount - 1) + \"].\");\n }\n notifyItemRangeRemoved(positionStart + headerItemCount, itemCount);\n }",
"public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\n }",
"public void setValue(Quaternionf rot) {\n mX = rot.x;\n mY = rot.y;\n mZ = rot.z;\n mW = rot.w;\n }"
] |
Prints the URL of a thumbnail for the given item document to the output,
or a default image if no image is given for the item.
@param out
the output to write to
@param itemDocument
the document that may provide the image information | [
"private void printImage(PrintStream out, ItemDocument itemDocument) {\n\t\tString imageFile = null;\n\n\t\tif (itemDocument != null) {\n\t\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t\tboolean isImage = \"P18\".equals(sg.getProperty().getId());\n\t\t\t\tif (!isImage) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Statement s : sg) {\n\t\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\t\tValue value = s.getMainSnak().getValue();\n\t\t\t\t\t\tif (value instanceof StringValue) {\n\t\t\t\t\t\t\timageFile = ((StringValue) value).getString();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (imageFile != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (imageFile == null) {\n\t\t\tout.print(\",\\\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\\\"\");\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tString imageFileEncoded;\n\t\t\t\timageFileEncoded = URLEncoder.encode(\n\t\t\t\t\t\timageFile.replace(\" \", \"_\"), \"utf-8\");\n\t\t\t\t// Keep special title symbols unescaped:\n\t\t\t\timageFileEncoded = imageFileEncoded.replace(\"%3A\", \":\")\n\t\t\t\t\t\t.replace(\"%2F\", \"/\");\n\t\t\t\tout.print(\",\"\n\t\t\t\t\t\t+ csvStringEscape(\"http://commons.wikimedia.org/w/thumb.php?f=\"\n\t\t\t\t\t\t\t\t+ imageFileEncoded) + \"&w=50\");\n\t\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\t\"Your JRE does not support UTF-8 encoding. Srsly?!\", e);\n\t\t\t}\n\t\t}\n\t}"
] | [
"private I_CmsFacetQueryItem parseFacetQueryItem(final String prefix) {\n\n I_CmsXmlContentValue query = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_QUERY, m_locale);\n if (null != query) {\n String queryString = query.getStringValue(null);\n I_CmsXmlContentValue label = m_xml.getValue(prefix + XML_ELEMENT_QUERY_FACET_QUERY_LABEL, m_locale);\n String labelString = null != label ? label.getStringValue(null) : null;\n return new CmsFacetQueryItem(queryString, labelString);\n } else {\n return null;\n }\n }",
"protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {\n\n m_foundResources = new ArrayList<I_CmsSearchResourceBean>();\n for (final CmsSearchResource searchResult : searchResults) {\n m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));\n }\n }",
"public void setColorSchemeResources(int... colorResIds) {\n final Resources res = getResources();\n int[] colorRes = new int[colorResIds.length];\n for (int i = 0; i < colorResIds.length; i++) {\n colorRes[i] = res.getColor(colorResIds[i]);\n }\n setColorSchemeColors(colorRes);\n }",
"public Response executeToResponse(HttpConnection connection) {\n InputStream is = null;\n try {\n is = this.executeToInputStream(connection);\n Response response = getResponse(is, Response.class, getGson());\n response.setStatusCode(connection.getConnection().getResponseCode());\n response.setReason(connection.getConnection().getResponseMessage());\n return response;\n } catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response code or message.\", e);\n } finally {\n close(is);\n }\n }",
"public AiTextureInfo getTextureInfo(AiTextureType type, int index) {\n return new AiTextureInfo(type, index, getTextureFile(type, index), \n getTextureUVIndex(type, index), getBlendFactor(type, index), \n getTextureOp(type, index), getTextureMapModeW(type, index), \n getTextureMapModeW(type, index), \n getTextureMapModeW(type, index));\n }",
"public void close() throws IOException {\n final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);\n if (binding == null) {\n return;\n }\n binding.close();\n }",
"public void attachHoursToDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = hours;\n }",
"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 }",
"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 }"
] |
Calculates the bounds of the non-transparent parts of the given image.
@param p the image
@return the bounds of the non-transparent area | [
"public static Rectangle getSelectedBounds(BufferedImage p) {\n\t\tint width = p.getWidth();\n int height = p.getHeight();\n\t\tint maxX = 0, maxY = 0, minX = width, minY = height;\n\t\tboolean anySelected = false;\n\t\tint y1;\n\t\tint [] pixels = null;\n\t\t\n\t\tfor (y1 = height-1; y1 >= 0; y1--) {\n\t\t\tpixels = getRGB( p, 0, y1, width, 1, pixels );\n\t\t\tfor (int x = 0; x < minX; x++) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tminX = x;\n\t\t\t\t\tmaxY = y1;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int x = width-1; x >= maxX; x--) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tmaxX = x;\n\t\t\t\t\tmaxY = y1;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( anySelected )\n\t\t\t\tbreak;\n\t\t}\n\t\tpixels = null;\n\t\tfor (int y = 0; y < y1; y++) {\n\t\t\tpixels = getRGB( p, 0, y, width, 1, pixels );\n\t\t\tfor (int x = 0; x < minX; x++) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tminX = x;\n\t\t\t\t\tif ( y < minY )\n\t\t\t\t\t\tminY = y;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int x = width-1; x >= maxX; x--) {\n\t\t\t\tif ((pixels[x] & 0xff000000) != 0) {\n\t\t\t\t\tmaxX = x;\n\t\t\t\t\tif ( y < minY )\n\t\t\t\t\t\tminY = y;\n\t\t\t\t\tanySelected = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( anySelected )\n\t\t\treturn new Rectangle( minX, minY, maxX-minX+1, maxY-minY+1 );\n\t\treturn null;\n\t}"
] | [
"@Override\n public int add(DownloadRequest request) throws IllegalArgumentException {\n checkReleased(\"add(...) called on a released ThinDownloadManager.\");\n if (request == null) {\n throw new IllegalArgumentException(\"DownloadRequest cannot be null\");\n }\n return mRequestQueue.add(request);\n }",
"public Date toDate(String dateString) {\n Date date = null;\n DateFormat df = new SimpleDateFormat(\"yyyy-MM-dd\");\n try {\n date = df.parse(dateString);\n } catch (ParseException ex) {\n System.out.println(ex.fillInStackTrace());\n }\n return date;\n }",
"private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }",
"public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }",
"public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }",
"public void registerDatatype(Class<? extends GVRHybridObject> textureClass,\n AsyncLoaderFactory<? extends GVRHybridObject, ?> asyncLoaderFactory) {\n mFactories.put(textureClass, asyncLoaderFactory);\n }",
"protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }",
"public void addNode(NodeT node) {\n node.setOwner(this);\n nodeTable.put(node.key(), node);\n }",
"public ParallelTaskBuilder preparePing() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.PING);\n return cb;\n }"
] |
Use this API to add snmpmanager resources. | [
"public static base_responses add(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager addresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpmanager();\n\t\t\t\taddresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\taddresources[i].netmask = resources[i].netmask;\n\t\t\t\taddresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"private void createFrameset(File outputDirectory) throws Exception\n {\n VelocityContext context = createContext();\n generateFile(new File(outputDirectory, INDEX_FILE),\n INDEX_FILE + TEMPLATE_EXTENSION,\n context);\n }",
"private void removeXmlBundleFile() throws CmsException {\n\n lockLocalization(null);\n m_cms.deleteResource(m_resource, CmsResource.DELETE_PRESERVE_SIBLINGS);\n m_resource = null;\n\n }",
"public static final PatchOperationTarget createStandalone(final ModelControllerClient controllerClient) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(CORE_SERVICES);\n return new RemotePatchOperationTarget(address, controllerClient);\n }",
"private FullTypeSignature getTypeSignature(Class<?> clazz) {\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\tif (clazz.isArray()) {\r\n\t\t\tsb.append(clazz.getName());\r\n\t\t} else if (clazz.isPrimitive()) {\r\n\t\t\tsb.append(primitiveTypesMap.get(clazz).toString());\r\n\t\t} else {\r\n\t\t\tsb.append('L').append(clazz.getName()).append(';');\r\n\t\t}\r\n\t\treturn TypeSignatureFactory.getTypeSignature(sb.toString(), false);\r\n\r\n\t}",
"public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }",
"public synchronized void stop() throws DatastoreEmulatorException {\n // We intentionally don't check the internal state. If people want to try and stop the server\n // multiple times that's fine.\n stopEmulatorInternal();\n if (state != State.STOPPED) {\n state = State.STOPPED;\n if (projectDirectory != null) {\n try {\n Process process =\n new ProcessBuilder(\"rm\", \"-r\", projectDirectory.getAbsolutePath()).start();\n if (process.waitFor() != 0) {\n throw new IOException(\n \"Temporary project directory deletion exited with \" + process.exitValue());\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(\"Could not delete temporary project directory\", e);\n }\n }\n }\n }",
"public void set(int numRows, int numCols, boolean rowMajor, double ...data)\n {\n reshape(numRows,numCols);\n int length = numRows*numCols;\n\n if( length > this.data.length )\n throw new IllegalArgumentException(\"The length of this matrix's data array is too small.\");\n\n if( rowMajor ) {\n System.arraycopy(data,0,this.data,0,length);\n } else {\n int index = 0;\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n this.data[index++] = data[j*numRows+i];\n }\n }\n }\n }",
"public List<MapRow> readTable(TableReader reader) throws IOException\n {\n reader.read();\n return reader.getRows();\n }",
"protected String extractHeaderComment( File xmlFile )\n throws MojoExecutionException\n {\n\n try\n {\n SAXParser parser = SAXParserFactory.newInstance().newSAXParser();\n SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler();\n parser.setProperty( \"http://xml.org/sax/properties/lexical-handler\", handler );\n parser.parse( xmlFile, handler );\n return handler.getHeaderComment();\n }\n catch ( Exception e )\n {\n throw new MojoExecutionException( \"Failed to parse XML from \" + xmlFile, e );\n }\n }"
] |
Retrieve the dir pointed to by 'latest' symbolic-link or the current
version dir
@return Current version directory, else null | [
"public static File getCurrentVersion(File storeDirectory) {\n File latestDir = getLatestDir(storeDirectory);\n if(latestDir != null)\n return latestDir;\n\n File[] versionDirs = getVersionDirs(storeDirectory);\n if(versionDirs == null || versionDirs.length == 0) {\n return null;\n } else {\n return findKthVersionedDir(versionDirs, versionDirs.length - 1, versionDirs.length - 1)[0];\n }\n }"
] | [
"public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }",
"@Override\n @Deprecated\n public List<CardWithActions> getBoardMemberActivity(String boardId, String memberId,\n String actionFilter, Argument... args) {\n if (actionFilter == null)\n actionFilter = \"all\";\n Argument[] argsAndFilter = Arrays.copyOf(args, args.length + 1);\n argsAndFilter[args.length] = new Argument(\"actions\", actionFilter);\n\n return asList(() -> get(createUrl(GET_BOARD_MEMBER_CARDS).params(argsAndFilter).asString(),\n CardWithActions[].class, boardId, memberId));\n }",
"public static scpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tscpolicy_stats obj = new scpolicy_stats();\n\t\tobj.set_name(name);\n\t\tscpolicy_stats response = (scpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static base_response update(nitro_service client, nd6ravariables resource) throws Exception {\n\t\tnd6ravariables updateresource = new nd6ravariables();\n\t\tupdateresource.vlan = resource.vlan;\n\t\tupdateresource.ceaserouteradv = resource.ceaserouteradv;\n\t\tupdateresource.sendrouteradv = resource.sendrouteradv;\n\t\tupdateresource.srclinklayeraddroption = resource.srclinklayeraddroption;\n\t\tupdateresource.onlyunicastrtadvresponse = resource.onlyunicastrtadvresponse;\n\t\tupdateresource.managedaddrconfig = resource.managedaddrconfig;\n\t\tupdateresource.otheraddrconfig = resource.otheraddrconfig;\n\t\tupdateresource.currhoplimit = resource.currhoplimit;\n\t\tupdateresource.maxrtadvinterval = resource.maxrtadvinterval;\n\t\tupdateresource.minrtadvinterval = resource.minrtadvinterval;\n\t\tupdateresource.linkmtu = resource.linkmtu;\n\t\tupdateresource.reachabletime = resource.reachabletime;\n\t\tupdateresource.retranstime = resource.retranstime;\n\t\tupdateresource.defaultlifetime = resource.defaultlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static boolean isSymmetric( DMatrixSparseCSC A , double tol ) {\n if( A.numRows != A.numCols )\n return false;\n\n int N = A.numCols;\n\n for (int i = 0; i < N; i++) {\n int idx0 = A.col_idx[i];\n int idx1 = A.col_idx[i+1];\n\n for (int index = idx0; index < idx1; index++) {\n int j = A.nz_rows[index];\n double value_ji = A.nz_values[index];\n double value_ij = A.get(i,j);\n\n if( Math.abs(value_ij-value_ji) > tol )\n return false;\n }\n }\n\n return true;\n }",
"public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }",
"public List<ServerRedirect> deleteServerMapping(int serverMappingId) {\n ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();\n try {\n JSONArray serverArray = new JSONArray(doDelete(BASE_SERVER + \"/\" + serverMappingId, null));\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServer = serverArray.getJSONObject(i);\n ServerRedirect server = getServerRedirectFromJSON(jsonServer);\n if (server != null) {\n servers.add(server);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n\n return servers;\n }",
"static Parameter createParameter(final String name, final String value) {\n if (value != null && isQuoted(value)) {\n return new QuotedParameter(name, value);\n }\n return new Parameter(name, value);\n }",
"@Override\r\n public synchronized long skip(final long length) throws IOException {\r\n final long skip = super.skip(length);\r\n this.count += skip;\r\n return skip;\r\n }"
] |
Return the Payload attached to the current active bucket for |test|.
Always returns a payload so the client doesn't crash on a malformed
test definition.
@param testName test name
@return pay load attached to the current active bucket
@deprecated Use {@link #getPayload(String, Bucket)} instead | [
"@Nonnull\n protected Payload getPayload(final String testName) {\n // Get the current bucket.\n final TestBucket testBucket = buckets.get(testName);\n\n // Lookup Payloads for this test\n if (testBucket != null) {\n final Payload payload = testBucket.getPayload();\n if (null != payload) {\n return payload;\n }\n }\n\n return Payload.EMPTY_PAYLOAD;\n }"
] | [
"public Task add()\n {\n Task task = new Task(m_projectFile, (Task) null);\n add(task);\n m_projectFile.getChildTasks().add(task);\n return task;\n }",
"public final void save(final PrintJobStatusExtImpl entry) {\n getSession().merge(entry);\n getSession().flush();\n getSession().evict(entry);\n }",
"private void populateRecurringTask(Record record, RecurringTask task) throws MPXJException\n {\n //System.out.println(record);\n task.setStartDate(record.getDateTime(1));\n task.setFinishDate(record.getDateTime(2));\n task.setDuration(RecurrenceUtility.getDuration(m_projectFile.getProjectProperties(), record.getInteger(3), record.getInteger(4)));\n task.setOccurrences(record.getInteger(5));\n task.setRecurrenceType(RecurrenceUtility.getRecurrenceType(record.getInteger(6)));\n task.setUseEndDate(NumberHelper.getInt(record.getInteger(8)) == 1);\n task.setWorkingDaysOnly(NumberHelper.getInt(record.getInteger(9)) == 1);\n task.setWeeklyDaysFromBitmap(RecurrenceUtility.getDays(record.getString(10)), RecurrenceUtility.RECURRING_TASK_DAY_MASKS);\n\n RecurrenceType type = task.getRecurrenceType();\n if (type != null)\n {\n switch (task.getRecurrenceType())\n {\n case DAILY:\n {\n task.setFrequency(record.getInteger(13));\n break;\n }\n\n case WEEKLY:\n {\n task.setFrequency(record.getInteger(14));\n break;\n }\n\n case MONTHLY:\n {\n task.setRelative(NumberHelper.getInt(record.getInteger(11)) == 1);\n if (task.getRelative())\n {\n task.setFrequency(record.getInteger(17));\n task.setDayNumber(record.getInteger(15));\n task.setDayOfWeek(RecurrenceUtility.getDay(record.getInteger(16)));\n }\n else\n {\n task.setFrequency(record.getInteger(19));\n task.setDayNumber(record.getInteger(18));\n }\n break;\n }\n\n case YEARLY:\n {\n task.setRelative(NumberHelper.getInt(record.getInteger(12)) != 1);\n if (task.getRelative())\n {\n task.setDayNumber(record.getInteger(20));\n task.setDayOfWeek(RecurrenceUtility.getDay(record.getInteger(21)));\n task.setMonthNumber(record.getInteger(22));\n }\n else\n {\n task.setYearlyAbsoluteFromDate(record.getDateTime(23));\n }\n break;\n }\n }\n }\n\n //System.out.println(task);\n }",
"void rejectAttributes(RejectedAttributesLogContext rejectedAttributes, ModelNode attributeValue) {\n for (RejectAttributeChecker checker : checks) {\n rejectedAttributes.checkAttribute(checker, name, attributeValue);\n }\n }",
"public static nsacl6_stats[] get(nitro_service service) throws Exception{\n\t\tnsacl6_stats obj = new nsacl6_stats();\n\t\tnsacl6_stats[] response = (nsacl6_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"private Duration assignmentDuration(Task task, Duration work)\n {\n Duration result = work;\n\n if (result != null)\n {\n if (result.getUnits() == TimeUnit.PERCENT)\n {\n Duration taskWork = task.getWork();\n if (taskWork != null)\n {\n result = Duration.getInstance(taskWork.getDuration() * result.getDuration(), taskWork.getUnits());\n }\n }\n }\n return result;\n }",
"public static base_responses update(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 updateresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new route6();\n\t\t\t\tupdateresources[i].network = resources[i].network;\n\t\t\t\tupdateresources[i].gateway = resources[i].gateway;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].distance = resources[i].distance;\n\t\t\t\tupdateresources[i].cost = resources[i].cost;\n\t\t\t\tupdateresources[i].advertise = resources[i].advertise;\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].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private boolean setNextIterator()\r\n {\r\n boolean retval = false;\r\n // first, check if the activeIterator is null, and set it.\r\n if (m_activeIterator == null)\r\n {\r\n if (m_rsIterators.size() > 0)\r\n {\r\n m_activeIteratorIndex = 0;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n }\r\n }\r\n else if (!m_activeIterator.hasNext())\r\n {\r\n if (m_rsIterators.size() > (m_activeIteratorIndex + 1))\r\n {\r\n // we still have iterators in the collection, move to the\r\n // next one, increment the counter, and set the active\r\n // iterator.\r\n m_activeIteratorIndex++;\r\n m_currentCursorPosition = 0;\r\n m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);\r\n retval = true;\r\n }\r\n }\r\n\r\n return retval;\r\n }",
"private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }"
] |
Generate random time stamps from the current time upto the next one second.
Passed as texture coordinates to the vertex shader; an unused field is present
with every pair passed.
@param totalTime
@return | [
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n\n if ( burstMode ) {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime;\n timeStamps[i + 1] = 0;\n }\n }\n else {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n }\n return timeStamps;\n\n }"
] | [
"public static String regexFindFirst(String pattern, String str) {\n return regexFindFirst(Pattern.compile(pattern), str, 1);\n }",
"public static wisite_binding get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_binding obj = new wisite_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_binding response = (wisite_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"@JmxOperation\n public String stopAsyncOperation(int requestId) {\n try {\n stopOperation(requestId);\n } catch(VoldemortException e) {\n return e.getMessage();\n }\n\n return \"Stopping operation \" + requestId;\n }",
"@Override\n public int read(char[] cbuf, int off, int len) throws IOException {\n int numChars = super.read(cbuf, off, len);\n replaceBadXmlCharactersBySpace(cbuf, off, len);\n return numChars;\n }",
"public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }",
"private static void checkPreconditions(final String dateFormat, final Locale locale) {\n\t\tif( dateFormat == null ) {\n\t\t\tthrow new NullPointerException(\"dateFormat should not be null\");\n\t\t} else if( locale == null ) {\n\t\t\tthrow new NullPointerException(\"locale should not be null\");\n\t\t}\n\t}",
"public synchronized void insert(long data) {\n resetIfNeeded();\n long index = 0;\n if(data >= this.upperBound) {\n index = nBuckets - 1;\n } else if(data < 0) {\n logger.error(data + \" can't be bucketed because it is negative!\");\n return;\n } else {\n index = data / step;\n }\n if(index < 0 || index >= nBuckets) {\n // This should be dead code. Defending against code changes in\n // future.\n logger.error(data + \" can't be bucketed because index is not in range [0,nBuckets).\");\n return;\n }\n buckets[(int) index]++;\n sum += data;\n size++;\n }",
"public static final PatchOperationTarget createLocal(final File jbossHome, List<File> moduleRoots, List<File> bundlesRoots) throws IOException {\n final PatchTool tool = PatchTool.Factory.createLocalTool(jbossHome, moduleRoots, bundlesRoots);\n return new LocalPatchOperationTarget(tool);\n }",
"@SuppressWarnings(\"boxing\")\r\n public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) {\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n\r\n // Flickr seems to return invalid token sometimes so retry a few times.\r\n // See http://www.flickr.com/groups/api/discuss/72157628028927244/\r\n OAuth1Token accessToken = null;\r\n boolean success = false;\r\n for (int i = 0; i < maxGetTokenRetries && !success; i++) {\r\n try {\r\n accessToken = service.getAccessToken(oAuthRequestToken, verifier);\r\n success = true;\r\n } catch (OAuthException | IOException | InterruptedException | ExecutionException e) {\r\n if (i == maxGetTokenRetries - 1) {\r\n logger.error(String.format(\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\", i), e);\r\n throw new FlickrRuntimeException(e);\r\n } else {\r\n logger.warn(String.format(\"OAuthService.getAccessToken failed, try number %d: %s\", i, e.getMessage()));\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n }\r\n\r\n return accessToken;\r\n }"
] |
Perform the merge
@param stereotypeAnnotations The stereotype annotations | [
"protected void merge(Set<Annotation> stereotypeAnnotations) {\n final MetaAnnotationStore store = manager.getServices().get(MetaAnnotationStore.class);\n for (Annotation stereotypeAnnotation : stereotypeAnnotations) {\n // Retrieve and merge all metadata from stereotypes\n StereotypeModel<?> stereotype = store.getStereotype(stereotypeAnnotation.annotationType());\n if (stereotype == null) {\n throw MetadataLogger.LOG.stereotypeNotRegistered(stereotypeAnnotation);\n }\n if (stereotype.isAlternative()) {\n alternative = true;\n }\n if (stereotype.getDefaultScopeType() != null) {\n possibleScopeTypes.add(stereotype.getDefaultScopeType());\n }\n if (stereotype.isBeanNameDefaulted()) {\n beanNameDefaulted = true;\n }\n this.stereotypes.add(stereotypeAnnotation.annotationType());\n // Merge in inherited stereotypes\n merge(stereotype.getInheritedStereotypes());\n }\n }"
] | [
"@Nullable\n\tpublic Import find(@Nonnull final String typeName) {\n\t\tCheck.notEmpty(typeName, \"typeName\");\n\t\tImport ret = null;\n\t\tfinal Type type = new Type(typeName);\n\t\tfor (final Import imp : imports) {\n\t\t\tif (imp.getType().getName().equals(type.getName())) {\n\t\t\t\tret = imp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ret == null) {\n\t\t\tfinal Type javaLangType = Type.evaluateJavaLangType(typeName);\n\t\t\tif (javaLangType != null) {\n\t\t\t\tret = Import.of(javaLangType);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}",
"private double CosineInterpolate(double x1, double x2, double a) {\n double f = (1 - Math.cos(a * Math.PI)) * 0.5;\n\n return x1 * (1 - f) + x2 * f;\n }",
"private void initModeSwitch(final EditMode current) {\n\n FormLayout modes = new FormLayout();\n modes.setHeight(\"100%\");\n modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);\n\n m_modeSelect = new ComboBox();\n m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));\n\n // add Modes\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));\n\n // set current mode as selected\n m_modeSelect.setValue(current);\n\n m_modeSelect.setNewItemsAllowed(false);\n m_modeSelect.setTextInputAllowed(false);\n m_modeSelect.setNullSelectionAllowed(false);\n\n m_modeSelect.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void valueChange(ValueChangeEvent event) {\n\n m_listener.handleModeChange((EditMode)event.getProperty().getValue());\n\n }\n });\n\n modes.addComponent(m_modeSelect);\n m_modeSwitch = modes;\n }",
"public synchronized void unregisterJmxIfRequired() {\n referenceCount--;\n if (isRegistered == true && referenceCount <= 0) {\n JmxUtils.unregisterMbean(this.jmxObjectName);\n isRegistered = false;\n }\n }",
"public static AccessorPrefix determineAccessorPrefix(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn new AccessorPrefix(m.group(1));\n\t}",
"public float getPositionX(int vertex) {\n if (!hasPositions()) {\n throw new IllegalStateException(\"mesh has no positions\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_vertices.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }",
"public void endRecord_() {\n // this is where we actually update the link database. basically,\n // all we need to do is to retract those links which weren't seen\n // this time around, and that can be done via assertLink, since it\n // can override existing links.\n\n // get all the existing links\n Collection<Link> oldlinks = linkdb.getAllLinksFor(getIdentity(current));\n\n // build a hashmap so we can look up corresponding old links from\n // new links\n if (oldlinks != null) {\n Map<String, Link> oldmap = new HashMap(oldlinks.size());\n for (Link l : oldlinks)\n oldmap.put(makeKey(l), l);\n\n // removing all the links we found this time around from the set of\n // old links. any links remaining after this will be stale, and need\n // to be retracted\n for (Link newl : new ArrayList<Link>(curlinks)) {\n String key = makeKey(newl);\n Link oldl = oldmap.get(key);\n if (oldl == null)\n continue;\n\n if (oldl.overrides(newl))\n // previous information overrides this link, so ignore\n curlinks.remove(newl);\n else if (sameAs(oldl, newl)) {\n // there's no new information here, so just ignore this\n curlinks.remove(newl);\n oldmap.remove(key); // we don't want to retract the old one\n } else\n // the link is out of date, but will be overwritten, so remove\n oldmap.remove(key);\n }\n\n // all the inferred links left in oldmap are now old links we\n // didn't find on this pass. there is no longer any evidence\n // supporting them, and so we can retract them.\n for (Link oldl : oldmap.values())\n if (oldl.getStatus() == LinkStatus.INFERRED) {\n oldl.retract(); // changes to retracted, updates timestamp\n curlinks.add(oldl);\n }\n }\n\n // okay, now we write it all to the database\n for (Link l : curlinks)\n linkdb.assertLink(l);\n }",
"private static void checkPreconditions(final long min, final long max) {\n\t\tif( max < min ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"max (%d) should not be < min (%d)\", max, min));\n\t\t}\n\t}",
"@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }"
] |
Filter out interceptors and decorators which are also enabled globally.
@param enabledClasses
@param globallyEnabledClasses
@param logMessageCallback
@param deployment
@return the filtered list | [
"private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback,\n BeanDeployment deployment) {\n for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) {\n Class<?> enabledClass = iterator.next();\n if (globallyEnabledClasses.contains(enabledClass)) {\n logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId());\n iterator.remove();\n }\n }\n return enabledClasses;\n }"
] | [
"public CliCommandBuilder setTimeout(final int timeout) {\n if (timeout > 0) {\n addCliArgument(CliArgument.TIMEOUT, Integer.toString(timeout));\n } else {\n addCliArgument(CliArgument.TIMEOUT, null);\n }\n return this;\n }",
"public int[] getTenors(int moneynessBP, int maturityInMonths) {\r\n\r\n\t\ttry {\r\n\t\t\tList<Integer> ret = new ArrayList<>();\r\n\t\t\tfor(int tenor : getGridNodesPerMoneyness().get(moneynessBP)[1]) {\r\n\t\t\t\tif(containsEntryFor(maturityInMonths, tenor, moneynessBP)) {\r\n\t\t\t\t\tret.add(tenor);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret.stream().mapToInt(Integer::intValue).toArray();\r\n\t\t} catch (NullPointerException e) {\r\n\t\t\treturn new int[0];\r\n\t\t}\r\n\t}",
"public SerialMessage getValueMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_GET };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"private static void addProperties(EndpointReferenceType epr, SLProperties props) {\n MetadataType metadata = WSAEndpointReferenceUtils.getSetMetadata(epr);\n ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter.toServiceLocatorPropertiesType(props);\n\n JAXBElement<ServiceLocatorPropertiesType>\n slp = SL_OBJECT_FACTORY.createServiceLocatorProperties(jaxbProps);\n metadata.getAny().add(slp);\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 }",
"@Override\n public boolean applyLayout(Layout itemLayout) {\n boolean applied = false;\n if (itemLayout != null && mItemLayouts.add(itemLayout)) {\n\n // apply the layout to all visible pages\n List<Widget> views = getAllViews();\n for (Widget view: views) {\n view.applyLayout(itemLayout.clone());\n }\n applied = true;\n }\n return applied;\n }",
"private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }",
"private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }",
"public static base_responses enable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface enableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tenableresources[i] = new Interface();\n\t\t\t\tenableresources[i].id = id[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}"
] |
Removes a value from the list.
@param list the list
@param value value to remove | [
"public static void removeFromList(List<String> list, String value) {\n int foundIndex = -1;\n int i = 0;\n for (String id : list) {\n if (id.equalsIgnoreCase(value)) {\n foundIndex = i;\n break;\n }\n i++;\n }\n if (foundIndex != -1) {\n list.remove(foundIndex);\n }\n }"
] | [
"public static final BigDecimal printCurrency(Number value)\n {\n return (value == null || value.doubleValue() == 0 ? null : new BigDecimal(value.doubleValue() * 100));\n }",
"public void setPerms(String photoId, GeoPermissions perms) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_PERMS);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"is_public\", perms.isPublic() ? \"1\" : \"0\");\r\n parameters.put(\"is_contact\", perms.isContact() ? \"1\" : \"0\");\r\n parameters.put(\"is_friend\", perms.isFriend() ? \"1\" : \"0\");\r\n parameters.put(\"is_family\", perms.isFamily() ? \"1\" : \"0\");\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n // This method has no specific response - It returns an empty sucess response\r\n // if it completes without error.\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public RgbaColor adjustHue(float degrees) {\n float[] HSL = convertToHsl();\n HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360)\n return RgbaColor.fromHsl(HSL);\n }",
"private void processProperties(XMLStreamWriter writer, Set<Method> methodSet, Class<?> aClass) throws IntrospectionException, XMLStreamException\n {\n BeanInfo beanInfo = Introspector.getBeanInfo(aClass, aClass.getSuperclass());\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n\n for (int i = 0; i < propertyDescriptors.length; i++)\n {\n PropertyDescriptor propertyDescriptor = propertyDescriptors[i];\n if (propertyDescriptor.getPropertyType() != null)\n {\n String name = propertyDescriptor.getName();\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n\n String readMethodName = readMethod == null ? null : readMethod.getName();\n String writeMethodName = writeMethod == null ? null : writeMethod.getName();\n addProperty(writer, name, propertyDescriptor.getPropertyType(), readMethodName, writeMethodName);\n\n if (readMethod != null)\n {\n methodSet.add(readMethod);\n }\n\n if (writeMethod != null)\n {\n methodSet.add(writeMethod);\n }\n }\n else\n {\n processAmbiguousProperty(writer, methodSet, aClass, propertyDescriptor);\n }\n }\n }",
"String fetchToken(String tokenType) throws IOException, MediaWikiApiErrorException {\n\t\tMap<String, String> params = new HashMap<>();\n\t\tparams.put(ApiConnection.PARAM_ACTION, \"query\");\n\t\tparams.put(\"meta\", \"tokens\");\n\t\tparams.put(\"type\", tokenType);\n\n\t\ttry {\n\t\t\tJsonNode root = this.sendJsonRequest(\"POST\", params);\n\t\t\treturn root.path(\"query\").path(\"tokens\").path(tokenType + \"token\").textValue();\n\t\t} catch (IOException | MediaWikiApiErrorException e) {\n\t\t\tlogger.error(\"Error when trying to fetch token: \" + e.toString());\n\t\t}\n\t\treturn null;\n\t}",
"private static void updateBaseCalendarNames(List<Pair<ProjectCalendar, BigInteger>> baseCalendars, HashMap<BigInteger, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, BigInteger> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n BigInteger baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n\n }",
"public static base_response clear(nitro_service client) throws Exception {\n\t\tgslbldnsentries clearresource = new gslbldnsentries();\n\t\treturn clearresource.perform_operation(client,\"clear\");\n\t}",
"public static tmglobal_tmsessionpolicy_binding[] get(nitro_service service) throws Exception{\n\t\ttmglobal_tmsessionpolicy_binding obj = new tmglobal_tmsessionpolicy_binding();\n\t\ttmglobal_tmsessionpolicy_binding response[] = (tmglobal_tmsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public MtasCQLParserSentenceCondition createFullSentence()\n throws ParseException {\n if (fullCondition == null) {\n if (secondSentencePart == null) {\n if (firstBasicSentence != null) {\n fullCondition = new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength);\n\n } else {\n fullCondition = firstSentence;\n }\n fullCondition.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n if (firstOptional) {\n fullCondition.setOptional(firstOptional);\n }\n return fullCondition;\n } else {\n if (!orOperator) {\n if (firstBasicSentence != null) {\n firstBasicSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstBasicSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(\n firstBasicSentence, ignoreClause, maximumIgnoreLength);\n } else {\n firstSentence.setOccurence(firstMinimumOccurence,\n firstMaximumOccurence);\n firstSentence.setOptional(firstOptional);\n fullCondition = new MtasCQLParserSentenceCondition(firstSentence,\n ignoreClause, maximumIgnoreLength);\n }\n fullCondition.addSentenceToEndLatestSequence(\n secondSentencePart.createFullSentence());\n } else {\n MtasCQLParserSentenceCondition sentence = secondSentencePart\n .createFullSentence();\n if (firstBasicSentence != null) {\n sentence.addSentenceAsFirstOption(\n new MtasCQLParserSentenceCondition(firstBasicSentence,\n ignoreClause, maximumIgnoreLength));\n } else {\n sentence.addSentenceAsFirstOption(firstSentence);\n }\n fullCondition = sentence;\n }\n return fullCondition;\n }\n } else {\n return fullCondition;\n }\n }"
] |
Write the auxiliary RDF data for encoding the given value.
@param value
the value to write
@param resource
the (subject) URI to use to represent this value in RDF
@throws RDFHandlerException | [
"@Override\n\tpublic void writeValue(TimeValue value, Resource resource)\n\t\t\tthrows RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.WB_TIME_VALUE);\n\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME,\n\t\t\t\tTimeValueConverter.getTimeLiteral(value, this.rdfWriter));\n\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_PRECISION, value.getPrecision());\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_TIMEZONE,\n\t\t\t\tvalue.getTimezoneOffset());\n\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_CALENDAR_MODEL,\n\t\t\t\tvalue.getPreferredCalendarModel());\n\t}"
] | [
"protected int adjustIndex(Widget child, int beforeIndex) {\n\n checkIndexBoundsForInsertion(beforeIndex);\n\n // Check to see if this widget is already a direct child.\n if (child.getParent() == this) {\n // If the Widget's previous position was left of the desired new position\n // shift the desired position left to reflect the removal\n int idx = getWidgetIndex(child);\n if (idx < beforeIndex) {\n beforeIndex--;\n }\n }\n\n return beforeIndex;\n }",
"public void fire(StepFinishedEvent event) {\n Step step = stepStorage.adopt();\n event.process(step);\n\n notifier.fire(event);\n }",
"public void transform(DataPipe cr) {\n Map<String, String> map = cr.getDataMap();\n\n for (String key : map.keySet()) {\n String value = map.get(key);\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n map.put(key, String.valueOf(ran));\n } else if (value.equals(\"#{divideBy2}\")) {\n String i = map.get(\"var_out_V3\");\n String result = String.valueOf(Integer.valueOf(i) / 2);\n map.put(key, result);\n }\n }\n }",
"public static void read(InputStream stream, byte[] buffer) throws IOException {\n int read = 0;\n while(read < buffer.length) {\n int newlyRead = stream.read(buffer, read, buffer.length - read);\n if(newlyRead == -1)\n throw new EOFException(\"Attempt to read \" + buffer.length\n + \" bytes failed due to EOF.\");\n read += newlyRead;\n }\n }",
"private boolean tryCustomErrorPage(CmsObject cms, HttpServletRequest req, HttpServletResponse res, int errorCode) {\n\n String siteRoot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();\n CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);\n if (site != null) {\n // store current site root and URI\n String currentSiteRoot = cms.getRequestContext().getSiteRoot();\n String currentUri = cms.getRequestContext().getUri();\n try {\n if (site.getErrorPage() != null) {\n String rootPath = site.getErrorPage();\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n }\n String rootPath = CmsStringUtil.joinPaths(siteRoot, \"/.errorpages/handle\" + errorCode + \".html\");\n if (loadCustomErrorPage(cms, req, res, rootPath)) {\n return true;\n }\n } finally {\n cms.getRequestContext().setSiteRoot(currentSiteRoot);\n cms.getRequestContext().setUri(currentUri);\n }\n }\n return false;\n }",
"public EventBus emitAsync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }",
"private void processFileType(String token) throws MPXJException\n {\n String version = token.substring(2).split(\" \")[0];\n //System.out.println(version);\n Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version));\n if (fileFormatClass == null)\n {\n throw new MPXJException(\"Unsupported PP file format version \" + version);\n }\n\n try\n {\n AbstractFileFormat format = fileFormatClass.newInstance();\n m_tableDefinitions = format.tableDefinitions();\n m_epochDateFormat = format.epochDateFormat();\n }\n catch (Exception ex)\n {\n throw new MPXJException(\"Failed to configure file format\", ex);\n }\n }",
"public void classifyAndWriteViterbiSearchGraph(String testFile, String searchGraphPrefix, DocumentReaderAndWriter<IN> readerAndWriter) throws IOException {\r\n Timing timer = new Timing();\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(testFile, readerAndWriter);\r\n int numWords = 0;\r\n int numSentences = 0;\r\n\r\n for (List<IN> doc : documents) {\r\n DFSA<String, Integer> tagLattice = getViterbiSearchGraph(doc, AnswerAnnotation.class);\r\n numWords += doc.size();\r\n PrintWriter latticeWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences\r\n + \".wlattice\"));\r\n PrintWriter vsgWriter = new PrintWriter(new FileOutputStream(searchGraphPrefix + '.' + numSentences + \".lattice\"));\r\n if (readerAndWriter instanceof LatticeWriter)\r\n ((LatticeWriter) readerAndWriter).printLattice(tagLattice, doc, latticeWriter);\r\n tagLattice.printAttFsmFormat(vsgWriter);\r\n latticeWriter.close();\r\n vsgWriter.close();\r\n numSentences++;\r\n }\r\n\r\n long millis = timer.stop();\r\n double wordspersec = numWords / (((double) millis) / 1000);\r\n NumberFormat nf = new DecimalFormat(\"0.00\"); // easier way!\r\n System.err.println(this.getClass().getName() + \" tagged \" + numWords + \" words in \" + numSentences\r\n + \" documents at \" + nf.format(wordspersec) + \" words per second.\");\r\n }",
"public Object getFieldByAlias(String alias)\n {\n return getCachedValue(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias));\n }"
] |
Retrieve the number of minutes per week for this calendar.
@return minutes per week | [
"public int getMinutesPerWeek()\n {\n return m_minutesPerWeek == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerWeek()) : m_minutesPerWeek.intValue();\n }"
] | [
"private static OkHttpClient getUnsafeOkHttpClient() {\n try {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] {\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }\n };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new java.security.SecureRandom());\n // Create an ssl socket factory with our all-trusting manager\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n\n OkHttpClient okHttpClient = new OkHttpClient();\n okHttpClient.setSslSocketFactory(sslSocketFactory);\n okHttpClient.setHostnameVerifier(new HostnameVerifier() {\n @Override\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n });\n\n return okHttpClient;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}",
"private void storeToDb(Object obj, ClassDescriptor cld, Identity oid, boolean insert, boolean ignoreReferences)\n {\n // 1. link and store 1:1 references\n storeReferences(obj, cld, insert, ignoreReferences);\n\n Object[] pkValues = oid.getPrimaryKeyValues();\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n // BRJ: fk values may be part of pk, but the are not known during\n // creation of Identity. so we have to get them here\n pkValues = serviceBrokerHelper().getKeyValues(cld, obj);\n if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))\n {\n String append = insert ? \" on insert\" : \" on update\" ;\n throw new PersistenceBrokerException(\"assertValidPkFields failed for Object of type: \" + cld.getClassNameOfObject() + append);\n }\n }\n\n // get super class cld then store it with the object\n /*\n now for multiple table inheritance\n 1. store super classes, topmost parent first\n 2. go down through heirarchy until current class\n 3. todo: store to full extent?\n\n// arminw: TODO: The extend-attribute feature dosn't work, should we remove this stuff?\n This if-clause will go up the inheritance heirarchy to store all the super classes.\n The id for the top most super class will be the id for all the subclasses too\n */\n if(cld.getSuperClass() != null)\n {\n\n ClassDescriptor superCld = getDescriptorRepository().getDescriptorFor(cld.getSuperClass());\n storeToDb(obj, superCld, oid, insert);\n // arminw: why this?? I comment out this section\n // storeCollections(obj, cld.getCollectionDescriptors(), insert);\n }\n\n // 2. store primitive typed attributes (Or is THIS step 3 ?)\n // if obj not present in db use INSERT\n if (insert)\n {\n dbAccess.executeInsert(cld, obj);\n if(oid.isTransient())\n {\n // Create a new Identity based on the current set of primary key values.\n oid = serviceIdentity().buildIdentity(cld, obj);\n }\n }\n // else use UPDATE\n else\n {\n try\n {\n dbAccess.executeUpdate(cld, obj);\n }\n catch(OptimisticLockException e)\n {\n // ensure that the outdated object be removed from cache\n objectCache.remove(oid);\n throw e;\n }\n }\n // cache object for symmetry with getObjectByXXX()\n // Add the object to the cache.\n objectCache.doInternalCache(oid, obj, ObjectCacheInternal.TYPE_WRITE);\n // 3. store 1:n and m:n associations\n if(!ignoreReferences) storeCollections(obj, cld, insert);\n }",
"private List<Row> getTable(String name)\n {\n List<Row> result = m_tables.get(name);\n if (result == null)\n {\n result = Collections.emptyList();\n }\n return result;\n }",
"protected void updateTables()\n {\n byte[] data = m_model.getData();\n int columns = m_model.getColumns();\n int rows = (data.length / columns) + 1;\n int offset = m_model.getOffset();\n\n String[][] hexData = new String[rows][columns];\n String[][] asciiData = new String[rows][columns];\n\n int row = 0;\n int column = 0;\n StringBuilder hexValue = new StringBuilder();\n for (int index = offset; index < data.length; index++)\n {\n int value = data[index];\n hexValue.setLength(0);\n hexValue.append(HEX_DIGITS[(value & 0xF0) >> 4]);\n hexValue.append(HEX_DIGITS[value & 0x0F]);\n\n char c = (char) value;\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n hexData[row][column] = hexValue.toString();\n asciiData[row][column] = Character.toString(c);\n\n ++column;\n if (column == columns)\n {\n column = 0;\n ++row;\n }\n }\n\n String[] columnHeadings = new String[columns];\n TableModel hexTableModel = new DefaultTableModel(hexData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n TableModel asciiTableModel = new DefaultTableModel(asciiData, columnHeadings)\n {\n @Override public boolean isCellEditable(int r, int c)\n {\n return false;\n }\n };\n\n m_model.setSizeValueLabel(Integer.toString(data.length));\n m_model.setHexTableModel(hexTableModel);\n m_model.setAsciiTableModel(asciiTableModel);\n m_model.setCurrentSelectionIndex(0);\n m_model.setPreviousSelectionIndex(0);\n }",
"protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }",
"public static dospolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tdospolicy[] response = (dospolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public String getPermalinkForCurrentPage(CmsObject cms) {\n\n return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId());\n }",
"protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException {\n\t\t// initialize the connections auto-commit flags\n\t\tconn1.setAutoCommit(true);\n\t\tconn2.setAutoCommit(true);\n\t\ttry {\n\t\t\t// change conn1's auto-commit to be false\n\t\t\tconn1.setAutoCommit(false);\n\t\t\tif (conn2.isAutoCommit()) {\n\t\t\t\t// if the 2nd connection's auto-commit is still true then we have multiple connections\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// if the 2nd connection's auto-commit is also false then we have a single connection\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// restore its auto-commit\n\t\t\tconn1.setAutoCommit(true);\n\t\t}\n\t}"
] |
This is a temporary measure until we have a type-safe solution for
retrieving serializers from a SerializerFactory. It avoids warnings all
over the codebase while making it easy to verify who calls it. | [
"@SuppressWarnings(\"unchecked\")\n public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory,\n SerializerDefinition serializerDefinition) {\n return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition);\n }"
] | [
"public Float getFloat(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}",
"public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"private String getSignature(String sharedSecret, Map<String, String> params) {\r\n StringBuffer buffer = new StringBuffer();\r\n buffer.append(sharedSecret);\r\n for (Map.Entry<String, String> entry : params.entrySet()) {\r\n buffer.append(entry.getKey());\r\n buffer.append(entry.getValue());\r\n }\r\n\r\n try {\r\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\r\n return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes(\"UTF-8\")));\r\n } catch (NoSuchAlgorithmException e) {\r\n throw new RuntimeException(e);\r\n } catch (UnsupportedEncodingException u) {\r\n throw new RuntimeException(u);\r\n }\r\n }",
"public static String getModuleVersion(final String moduleId) {\n final int splitter = moduleId.lastIndexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(splitter+1);\n }",
"public static base_responses add(nitro_service client, authenticationradiusaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tauthenticationradiusaction addresources[] = new authenticationradiusaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new authenticationradiusaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].serverip = resources[i].serverip;\n\t\t\t\taddresources[i].serverport = resources[i].serverport;\n\t\t\t\taddresources[i].authtimeout = resources[i].authtimeout;\n\t\t\t\taddresources[i].radkey = resources[i].radkey;\n\t\t\t\taddresources[i].radnasip = resources[i].radnasip;\n\t\t\t\taddresources[i].radnasid = resources[i].radnasid;\n\t\t\t\taddresources[i].radvendorid = resources[i].radvendorid;\n\t\t\t\taddresources[i].radattributetype = resources[i].radattributetype;\n\t\t\t\taddresources[i].radgroupsprefix = resources[i].radgroupsprefix;\n\t\t\t\taddresources[i].radgroupseparator = resources[i].radgroupseparator;\n\t\t\t\taddresources[i].passencoding = resources[i].passencoding;\n\t\t\t\taddresources[i].ipvendorid = resources[i].ipvendorid;\n\t\t\t\taddresources[i].ipattributetype = resources[i].ipattributetype;\n\t\t\t\taddresources[i].accounting = resources[i].accounting;\n\t\t\t\taddresources[i].pwdvendorid = resources[i].pwdvendorid;\n\t\t\t\taddresources[i].pwdattributetype = resources[i].pwdattributetype;\n\t\t\t\taddresources[i].defaultauthenticationgroup = resources[i].defaultauthenticationgroup;\n\t\t\t\taddresources[i].callingstationid = resources[i].callingstationid;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private Integer getKeyPartitionId(byte[] key) {\n Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key);\n\n Utils.notNull(keyPartitionId);\n return keyPartitionId;\n }",
"private boolean isPacketLongEnough(DatagramPacket packet, int expectedLength, String name) {\n final int length = packet.getLength();\n if (length < expectedLength) {\n logger.warn(\"Ignoring too-short \" + name + \" packet; expecting \" + expectedLength + \" bytes and got \" +\n length + \".\");\n return false;\n }\n\n if (length > expectedLength) {\n logger.warn(\"Processing too-long \" + name + \" packet; expecting \" + expectedLength +\n \" bytes and got \" + length + \".\");\n }\n\n return true;\n }",
"protected AbstractColumn buildSimpleColumn() {\n\t\tSimpleColumn column = new SimpleColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumnProperty.getFieldProperties().putAll(fieldProperties);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setFieldDescription(fieldDescription);\n\t\treturn column;\n\t}",
"public GreenMailConfiguration build(Properties properties) {\n GreenMailConfiguration configuration = new GreenMailConfiguration();\n String usersParam = properties.getProperty(GREENMAIL_USERS);\n if (null != usersParam) {\n String[] usersArray = usersParam.split(\",\");\n for (String user : usersArray) {\n extractAndAddUser(configuration, user);\n }\n }\n String disabledAuthentication = properties.getProperty(GREENMAIL_AUTH_DISABLED);\n if (null != disabledAuthentication) {\n configuration.withDisabledAuthentication();\n }\n return configuration;\n }"
] |
Tests whether the given string is the name of a java.lang type. | [
"public static boolean isJavaLangType(String s) {\n\t\treturn getJavaDefaultTypes().contains(s) && Character.isUpperCase(s.charAt(0));\n\t}"
] | [
"public int nextToken() throws IOException\n {\n int c;\n int nextc = -1;\n boolean quoted = false;\n int result = m_next;\n if (m_next != 0)\n {\n m_next = 0;\n }\n\n m_buffer.setLength(0);\n\n while (result == 0)\n {\n if (nextc != -1)\n {\n c = nextc;\n nextc = -1;\n }\n else\n {\n c = read();\n }\n\n switch (c)\n {\n case TT_EOF:\n {\n if (m_buffer.length() != 0)\n {\n result = TT_WORD;\n m_next = TT_EOF;\n }\n else\n {\n result = TT_EOF;\n }\n break;\n }\n\n case TT_EOL:\n {\n int length = m_buffer.length();\n\n if (length != 0 && m_buffer.charAt(length - 1) == '\\r')\n {\n --length;\n m_buffer.setLength(length);\n }\n\n if (length == 0)\n {\n result = TT_EOL;\n }\n else\n {\n result = TT_WORD;\n m_next = TT_EOL;\n }\n\n break;\n }\n\n default:\n {\n if (c == m_quote)\n {\n if (quoted == false && startQuotedIsValid(m_buffer))\n {\n quoted = true;\n }\n else\n {\n if (quoted == false)\n {\n m_buffer.append((char) c);\n }\n else\n {\n nextc = read();\n if (nextc == m_quote)\n {\n m_buffer.append((char) c);\n nextc = -1;\n }\n else\n {\n quoted = false;\n }\n }\n }\n }\n else\n {\n if (c == m_delimiter && quoted == false)\n {\n result = TT_WORD;\n }\n else\n {\n m_buffer.append((char) c);\n }\n }\n }\n }\n }\n\n m_type = result;\n\n return (result);\n }",
"public static boolean hasFacet(GridDialect gridDialect, Class<? extends GridDialect> facetType) {\n\t\tif ( gridDialect instanceof ForwardingGridDialect ) {\n\t\t\treturn hasFacet( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), facetType );\n\t\t}\n\t\telse {\n\t\t\treturn facetType.isAssignableFrom( gridDialect.getClass() );\n\t\t}\n\t}",
"public static<T> Vendor<T> vendor(Func0<T> f) {\n\treturn j.vendor(f);\n }",
"public final static int readXMLUntil(final StringBuilder out, final String in, final int start, final char... end)\n {\n int pos = start;\n boolean inString = false;\n char stringChar = 0;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (inString)\n {\n if (ch == '\\\\')\n {\n out.append(ch);\n pos++;\n if (pos < in.length())\n {\n out.append(ch);\n pos++;\n }\n continue;\n }\n if (ch == stringChar)\n {\n inString = false;\n out.append(ch);\n pos++;\n continue;\n }\n }\n switch (ch)\n {\n case '\"':\n case '\\'':\n inString = true;\n stringChar = ch;\n break;\n }\n if (!inString)\n {\n boolean endReached = false;\n for (int n = 0; n < end.length; n++)\n {\n if (ch == end[n])\n {\n endReached = true;\n break;\n }\n }\n if (endReached)\n {\n break;\n }\n }\n out.append(ch);\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\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 }",
"@Override\n public void close() {\n // unregister MBeans\n if(stats != null) {\n try {\n if(this.jmxEnabled)\n JmxUtils.unregisterMbean(getAggregateMetricName());\n } catch(Exception e) {}\n stats.close();\n }\n factory.close();\n queuedPool.close();\n }",
"private void writeNewLineIndent() throws IOException\n {\n if (m_pretty)\n {\n if (!m_indent.isEmpty())\n {\n m_writer.write('\\n');\n m_writer.write(m_indent);\n }\n }\n }",
"protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }",
"protected void convertToHours(LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Duration totalWork = assignment.getTotalAmount();\n Duration workPerDay = assignment.getAmountPerDay();\n totalWork = Duration.getInstance(totalWork.getDuration() / 60, TimeUnit.HOURS);\n workPerDay = Duration.getInstance(workPerDay.getDuration() / 60, TimeUnit.HOURS);\n assignment.setTotalAmount(totalWork);\n assignment.setAmountPerDay(workPerDay);\n }\n }"
] |
Adapt the size of the tiles so that we have the same amount of tiles as we would have had with maxWidth
and maxHeight, but with the smallest tiles as possible. | [
"private static Dimension adaptTileDimensions(\n final Dimension pixels, final int maxWidth, final int maxHeight) {\n return new Dimension(adaptTileDimension(pixels.width, maxWidth),\n adaptTileDimension(pixels.height, maxHeight));\n }"
] | [
"public GeoPolygon addHoles(List<List<GeoPoint>> holes) {\n\t\tContracts.assertNotNull( holes, \"holes\" );\n\t\tthis.rings.addAll( holes );\n\t\treturn this;\n\t}",
"public boolean checkPrefixes(String uri, String[] patterns) {\n\t\tfor (String pattern : patterns) {\n\t\t\tif (pattern.length() > 0) {\n\t\t\t\tif (uri.startsWith(pattern)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"@SuppressWarnings(\"unchecked\")\n private void addPrivateFieldsAccessors(ClassNode node) {\n Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);\n if (accessedFields==null) return;\n Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);\n if (privateConstantAccessors!=null) {\n // already added\n return;\n }\n int acc = -1;\n privateConstantAccessors = new HashMap<String, MethodNode>();\n final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;\n for (FieldNode fieldNode : node.getFields()) {\n if (accessedFields.contains(fieldNode)) {\n\n acc++;\n Parameter param = new Parameter(node.getPlainNodeReference(), \"$that\");\n Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);\n Statement stmt = new ExpressionStatement(new PropertyExpression(\n receiver,\n fieldNode.getName()\n ));\n MethodNode accessor = node.addMethod(\"pfaccess$\"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);\n privateConstantAccessors.put(fieldNode.getName(), accessor);\n }\n }\n node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);\n }",
"public void fireAssignmentWrittenEvent(ResourceAssignment resourceAssignment)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.assignmentWritten(resourceAssignment);\n }\n }\n }",
"void setLanguage(final Locale locale) {\n\n if (!m_languageSelect.getValue().equals(locale)) {\n m_languageSelect.setValue(locale);\n }\n }",
"public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"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 }",
"public static boolean isAvailable() throws Exception {\n try {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n return true;\n } catch (Exception e) {\n return false;\n }\n }",
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) {\n \tCollection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size());\n \t\n \tMap<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members);\n \tfor(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) {\n \t\tFuture<T> future = futureEntry.getValue();\n \t\tMember member = futureEntry.getKey();\n \t\t\n \t\ttry {\n if(maxWaitTime > 0) {\n \tresult.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit)));\n } else {\n \tresult.add(new MemberResponse<T>(member, future.get()));\n } \n //ignore exceptions... return what you can\n } catch (InterruptedException e) {\n \tThread.currentThread().interrupt(); //restore interrupted status and return what we have\n \treturn result;\n } catch (MemberLeftException e) {\n \tlog.warn(\"Member {} left while trying to get a distributed callable result\", member);\n } catch (ExecutionException e) {\n \tif(e.getCause() instanceof InterruptedException) {\n \t //restore interrupted state and return\n \t Thread.currentThread().interrupt();\n \t return result;\n \t} else {\n \t log.warn(\"Unable to execute callable on \"+member+\". There was an error.\", e);\n \t}\n } catch (TimeoutException e) {\n \tlog.error(\"Unable to execute task on \"+member+\" within 10 seconds.\");\n } catch (RuntimeException e) {\n \tlog.error(\"Unable to execute task on \"+member+\". An unexpected error occurred.\", e);\n }\n \t}\n \n return result;\n }"
] |
Converts a DTO attribute into a generic attribute object.
@param attribute
The DTO attribute.
@return The server side attribute representation. As we don't know at this point what kind of object the
attribute is (that's a problem for the <code>FeatureModel</code>), we return an <code>Object</code>. | [
"public Object toInternal(Attribute<?> attribute) throws GeomajasException {\n\t\tif (attribute instanceof PrimitiveAttribute<?>) {\n\t\t\treturn toPrimitiveObject((PrimitiveAttribute<?>) attribute);\n\t\t} else if (attribute instanceof AssociationAttribute<?>) {\n\t\t\treturn toAssociationObject((AssociationAttribute<?>) attribute);\n\t\t} else {\n\t\t\tthrow new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);\n\t\t}\n\t}"
] | [
"private static XMLStreamException unexpectedElement(final XMLStreamReader reader) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), reader.getLocation());\n }",
"public void applyPattern(String primaryPattern, String[] alternativePatterns, char decimalSeparator, char groupingSeparator)\n {\n m_symbols.setDecimalSeparator(decimalSeparator);\n m_symbols.setGroupingSeparator(groupingSeparator);\n\n setDecimalFormatSymbols(m_symbols);\n applyPattern(primaryPattern);\n\n if (alternativePatterns != null && alternativePatterns.length != 0)\n {\n int loop;\n if (m_alternativeFormats == null || m_alternativeFormats.length != alternativePatterns.length)\n {\n m_alternativeFormats = new DecimalFormat[alternativePatterns.length];\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop] = new DecimalFormat();\n }\n }\n\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop].setDecimalFormatSymbols(m_symbols);\n m_alternativeFormats[loop].applyPattern(alternativePatterns[loop]);\n }\n }\n }",
"private void checkQueryCustomizer(CollectionDescriptorDef collDef, 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 queryCustomizerName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_QUERY_CUSTOMIZER);\r\n\r\n if (queryCustomizerName == 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(queryCustomizerName, QUERY_CUSTOMIZER_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+queryCustomizerName+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" does not implement the interface \"+QUERY_CUSTOMIZER_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+ex.getMessage()+\" specified as query-customizer of collection \"+collDef.getName()+\" in class \"+collDef.getOwner().getName()+\" was not found on the classpath\");\r\n }\r\n }",
"boolean isUserPasswordReset(CmsUser user) {\n\n if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before\n if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map\n return false;\n }\n if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load.\n return true; //Set gets flushed on reloading table\n }\n }\n CmsUser currentUser = user;\n if (user.getAdditionalInfo().size() < 3) {\n\n try {\n currentUser = m_cms.readUser(user.getId());\n } catch (CmsException e) {\n LOG.error(\"Can not read user\", e);\n }\n }\n if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) {\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true));\n m_checkedUserPasswordReset.add(currentUser.getId());\n return true;\n }\n USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false));\n return false;\n }",
"public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"public static String decodeUrlIso(String stringToDecode) {\n try {\n return URLDecoder.decode(stringToDecode, \"ISO-8859-1\");\n } catch (UnsupportedEncodingException e1) {\n throw new RuntimeException(e1);\n }\n }",
"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 ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }",
"public static cmppolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel obj = new cmppolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel response = (cmppolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Creates instance of the entity class. This method is called to create the object
instances when returning query results. | [
"protected T createInstance() {\n try {\n Constructor<T> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n return ctor.newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (SecurityException e) {\n throw new RuntimeException(e);\n } catch (NoSuchMethodException e) {\n throw new RuntimeException(e);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }"
] | [
"public void copyTo(int start, int end, byte[] dest, int destPos) {\n // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object\n arraycopy(start, dest, destPos, end - start);\n }",
"public synchronized Message menuRequestTyped(Message.KnownType requestType, Message.MenuIdentifier targetMenu,\n CdjStatus.TrackSourceSlot slot, CdjStatus.TrackType trackType, Field... arguments)\n throws IOException {\n\n if (!menuLock.isHeldByCurrentThread()) {\n throw new IllegalStateException(\"renderMenuItems() cannot be called without first successfully calling tryLockingForMenuOperation()\");\n }\n\n Field[] combinedArguments = new Field[arguments.length + 1];\n combinedArguments[0] = buildRMST(targetMenu, slot, trackType);\n System.arraycopy(arguments, 0, combinedArguments, 1, arguments.length);\n final Message response = simpleRequest(requestType, Message.KnownType.MENU_AVAILABLE, combinedArguments);\n final NumberField reportedRequestType = (NumberField)response.arguments.get(0);\n if (reportedRequestType.getValue() != requestType.protocolValue) {\n throw new IOException(\"Menu request did not return result for same type as request; sent type: \" +\n requestType.protocolValue + \", received type: \" + reportedRequestType.getValue() +\n \", response: \" + response);\n }\n return response;\n }",
"private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) {\n if (numberClass == Integer.class) {\n buffer.addInt((Integer) value);\n } else if (numberClass == Long.class) {\n buffer.addLong((Long) value);\n } else if (numberClass == BigInteger.class) {\n buffer.addBigInteger((BigInteger) value);\n } else if (numberClass == BigDecimal.class) {\n buffer.addBigDecimal((BigDecimal) value);\n } else if (numberClass == Double.class) {\n Double doubleValue = (Double) value;\n if (doubleValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (doubleValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addDouble(doubleValue);\n } else if (numberClass == Float.class) {\n Float floatValue = (Float) value;\n if (floatValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (floatValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addFloat(floatValue);\n } else if (numberClass == Byte.class) {\n buffer.addByte((Byte) value);\n } else if (numberClass == Short.class) {\n buffer.addShort((Short) value);\n } else { // Handle other Number implementations\n buffer.addString(value.toString());\n }\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 }",
"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 }",
"@Override\n protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)\n throws JsonMappingException\n {\n SerializerProvider prov = visitor.getProvider();\n if ((prov != null) && useNanoseconds(prov)) {\n JsonNumberFormatVisitor v2 = visitor.expectNumberFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.BIG_DECIMAL);\n }\n } else {\n JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.LONG);\n }\n }\n }",
"private static String convertPathToResource(String path) {\n File file = new File(path);\n List<String> parts = new ArrayList<String>();\n do {\n parts.add(file.getName());\n file = file.getParentFile();\n }\n while (file != null);\n\n StringBuffer sb = new StringBuffer();\n int size = parts.size();\n for (int a = size - 1; a >= 0; a--) {\n if (sb.length() > 0) {\n sb.append(\"_\");\n }\n sb.append(parts.get(a));\n }\n\n // TODO: Better regex replacement\n return sb.toString().replace('-', '_').replace(\"+\", \"plus\").toLowerCase(Locale.US);\n }",
"private static String normalizeDirName(String name)\n {\n if(name == null)\n return null;\n return name.toLowerCase().replaceAll(\"[^a-zA-Z0-9]\", \"-\");\n }",
"private static List<Class<?>> getClassHierarchy(Class<?> clazz) {\n\t\tList<Class<?>> hierarchy = new ArrayList<Class<?>>( 4 );\n\n\t\tfor ( Class<?> current = clazz; current != null; current = current.getSuperclass() ) {\n\t\t\thierarchy.add( current );\n\t\t}\n\n\t\treturn hierarchy;\n\t}"
] |
Obtains a string from a PDF value
@param value the PDF value of the String, Integer or Float type
@return the corresponging string value | [
"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 String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }",
"@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }",
"public static Command newQuery(String identifier,\n String name) {\n return getCommandFactoryProvider().newQuery( identifier,\n name );\n\n }",
"public static auditnslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_systemglobal_binding obj = new auditnslogpolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_systemglobal_binding response[] = (auditnslogpolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"static String findNonProgressingOp(Resource resource, boolean forServer, long timeout) throws OperationFailedException {\n\n Resource.ResourceEntry nonProgressing = null;\n for (Resource.ResourceEntry child : resource.getChildren(ACTIVE_OPERATION)) {\n ModelNode model = child.getModel();\n if (model.get(EXCLUSIVE_RUNNING_TIME).asLong() > timeout) {\n nonProgressing = child;\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"non-progressing op: %s\", nonProgressing.getModel());\n break;\n }\n }\n if (nonProgressing != null && !forServer) {\n // WFCORE-263\n // See if the op is non-progressing because it's the HC op waiting for commit\n // from the DC while other ops (i.e. ops proxied to our servers) associated\n // with the same domain-uuid are not completing\n ModelNode model = nonProgressing.getModel();\n if (model.get(DOMAIN_ROLLOUT).asBoolean()\n && OperationContext.ExecutionStatus.COMPLETING.toString().equals(model.get(EXECUTION_STATUS).asString())\n && model.hasDefined(DOMAIN_UUID)) {\n ControllerLogger.MGMT_OP_LOGGER.trace(\"Potential domain rollout issue\");\n String domainUUID = model.get(DOMAIN_UUID).asString();\n\n Set<String> relatedIds = null;\n List<Resource.ResourceEntry> relatedExecutingOps = null;\n for (Resource.ResourceEntry activeOp : resource.getChildren(ACTIVE_OPERATION)) {\n if (nonProgressing.getName().equals(activeOp.getName())) {\n continue; // ignore self\n }\n ModelNode opModel = activeOp.getModel();\n if (opModel.hasDefined(DOMAIN_UUID) && domainUUID.equals(opModel.get(DOMAIN_UUID).asString())\n && opModel.get(RUNNING_TIME).asLong() > timeout) {\n if (relatedIds == null) {\n relatedIds = new TreeSet<String>(); // order these as an aid to unit testing\n }\n relatedIds.add(activeOp.getName());\n\n // If the op is ExecutionStatus.EXECUTING that means it's still EXECUTING on the\n // server or a prepare message got lost. It would be COMPLETING if the server\n // had sent a prepare message, as that would result in ProxyStepHandler calling completeStep\n if (OperationContext.ExecutionStatus.EXECUTING.toString().equals(opModel.get(EXECUTION_STATUS).asString())) {\n if (relatedExecutingOps == null) {\n relatedExecutingOps = new ArrayList<Resource.ResourceEntry>();\n }\n relatedExecutingOps.add(activeOp);\n ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"Related non-executing: %s\", opModel);\n } else ControllerLogger.MGMT_OP_LOGGER.tracef(\"unrelated: %s\", opModel);\n }\n\n if (relatedIds != null) {\n // There are other ops associated with this domain-uuid that are also not completing\n // in the desired time, so we can't treat the one holding the lock as the problem.\n if (relatedExecutingOps != null && relatedExecutingOps.size() == 1) {\n // There's a single related op that's executing for too long. So we can report that one.\n // Note that it's possible that the same problem exists on other hosts as well\n // and that this cancellation will not resolve the overall problem. But, we only\n // get here on a slave HC and if the user is invoking this on a slave and not the\n // master, we'll assume they have a reason for doing that and want us to treat this\n // as a problem on this particular host.\n nonProgressing = relatedExecutingOps.get(0);\n } else {\n // Fail and provide a useful failure message.\n throw DomainManagementLogger.ROOT_LOGGER.domainRolloutNotProgressing(nonProgressing.getName(),\n timeout, domainUUID, relatedIds);\n }\n }\n }\n }\n\n return nonProgressing == null ? null : nonProgressing.getName();\n }",
"public DescriptorRepository readDescriptorRepository(InputStream inst)\r\n {\r\n try\r\n {\r\n RepositoryPersistor persistor = new RepositoryPersistor();\r\n return persistor.readDescriptorRepository(inst);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\"Can not read repository \" + inst, e);\r\n }\r\n }",
"public byte byteAt(int i) {\n\n if (i < 0) {\n throw new IndexOutOfBoundsException(\"i < 0, \" + i);\n }\n\n if (i >= length) {\n throw new IndexOutOfBoundsException(\"i >= length, \" + i + \" >= \" + length);\n }\n\n return data[offset + i];\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 printRelations(ClassDoc c) {\n\tOptions opt = optionProvider.getOptionsFor(c);\n\tif (hidden(c) || c.name().equals(\"\")) // avoid phantom classes, they may pop up when the source uses annotations\n\t return;\n\t// Print generalization (through the Java superclass)\n\tType s = c.superclassType();\n\tClassDoc sc = s != null && !s.qualifiedTypeName().equals(Object.class.getName()) ? s.asClassDoc() : null;\n\tif (sc != null && !c.isEnum() && !hidden(sc))\n\t relation(opt, RelationType.EXTENDS, c, sc, null, null, null);\n\t// Print generalizations (through @extends tags)\n\tfor (Tag tag : c.tags(\"extends\"))\n\t if (!hidden(tag.text()))\n\t\trelation(opt, RelationType.EXTENDS, c, c.findClass(tag.text()), null, null, null);\n\t// Print realizations (Java interfaces)\n\tfor (Type iface : c.interfaceTypes()) {\n\t ClassDoc ic = iface.asClassDoc();\n\t if (!hidden(ic))\n\t\trelation(opt, RelationType.IMPLEMENTS, c, ic, null, null, null);\n\t}\n\t// Print other associations\n\tallRelation(opt, RelationType.COMPOSED, c);\n\tallRelation(opt, RelationType.NAVCOMPOSED, c);\n\tallRelation(opt, RelationType.HAS, c);\n\tallRelation(opt, RelationType.NAVHAS, c);\n\tallRelation(opt, RelationType.ASSOC, c);\n\tallRelation(opt, RelationType.NAVASSOC, c);\n\tallRelation(opt, RelationType.DEPEND, c);\n }"
] |
Returns the red color component of a color from a vertex color set.
@param vertex the vertex index
@param colorset the color set
@return the red color component | [
"public float getColorR(int vertex, int colorset) {\n if (!hasColors(colorset)) {\n throw new IllegalStateException(\"mesh has no colorset \" + colorset);\n }\n \n checkVertexIndexBounds(vertex);\n /* bound checks for colorset are done by java for us */\n \n return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT);\n }"
] | [
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n for ( int i = 0; i < mEmitRate * 2; i +=2 )\n {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n return timeStamps;\n }",
"protected boolean isPrefixBlock(long divisionValue, long upperValue, int divisionPrefixLen) {\n\t\tif(divisionPrefixLen == 0) {\n\t\t\treturn divisionValue == 0 && upperValue == getMaxValue();\n\t\t}\n\t\tlong ones = ~0L;\n\t\tlong divisionBitMask = ~(ones << getBitCount());\n\t\tlong divisionPrefixMask = ones << (getBitCount() - divisionPrefixLen);\n\t\tlong divisionNonPrefixMask = ~divisionPrefixMask;\n\t\treturn testRange(divisionValue,\n\t\t\t\tupperValue,\n\t\t\t\tupperValue,\n\t\t\t\tdivisionPrefixMask & divisionBitMask,\n\t\t\t\tdivisionNonPrefixMask);\n\t}",
"public ArrayList getPrimaryKeys()\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n result.add(fieldDef);\r\n }\r\n }\r\n return result;\r\n }",
"public static void initialize(final Context context) {\n if (!initialized.compareAndSet(false, true)) {\n return;\n }\n\n applicationContext = context.getApplicationContext();\n\n final String packageName = applicationContext.getPackageName();\n localAppName = packageName;\n\n final PackageManager manager = applicationContext.getPackageManager();\n try {\n final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);\n localAppVersion = pkgInfo.versionName;\n } catch (final NameNotFoundException e) {\n Log.d(TAG, \"Failed to get version of application, will not send in device info.\");\n }\n\n Log.d(TAG, \"Initialized android SDK\");\n }",
"public double[] getMaturities(double moneyness) {\r\n\t\tint[] maturitiesInMonths\t= getMaturities(convertMoneyness(moneyness));\r\n\t\tdouble[] maturities\t\t\t= new double[maturitiesInMonths.length];\r\n\r\n\t\tfor(int index = 0; index < maturities.length; index++) {\r\n\t\t\tmaturities[index] = convertMaturity(maturitiesInMonths[index]);\r\n\t\t}\r\n\t\treturn maturities;\r\n\t}",
"public final void unregisterView(final View view) {\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (null != mRenderableViewGroup && view.getParent() == mRenderableViewGroup) {\n mRenderableViewGroup.removeView(view);\n }\n }\n });\n }",
"public static String getEncoding(CmsObject cms, CmsResource file) {\n\n CmsProperty encodingProperty = CmsProperty.getNullProperty();\n try {\n encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);\n } catch (CmsException e) {\n LOG.debug(e.getLocalizedMessage(), e);\n }\n return CmsEncoder.lookupEncoding(encodingProperty.getValue(\"\"), OpenCms.getSystemInfo().getDefaultEncoding());\n }",
"public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {\r\n\t\tlogger.debug(\"Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}\", this.getNode().getNodeId(), endpoint.getEndpointId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, 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) MULTI_CHANNEL_CAPABILITY_GET,\r\n\t\t\t\t\t\t\t\t(byte) endpoint.getEndpointId() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\r\n\t}",
"public static boolean isListLiteralWithOnlyConstantValues(Expression expression) {\r\n if (expression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) expression).getExpressions();\r\n for (Expression e : expressions) {\r\n if (!isConstantOrConstantLiteral(e)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }"
] |
Get the type created by selecting only a subset of properties from this
type. The type must be a map for this to work
@param properties The properties to select
@return The new type definition | [
"public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }"
] | [
"public Photoset getInfo(String photosetId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photosetElement.getAttribute(\"owner\"));\r\n photoset.setOwner(owner);\r\n\r\n Photo primaryPhoto = new Photo();\r\n primaryPhoto.setId(photosetElement.getAttribute(\"primary\"));\r\n primaryPhoto.setSecret(photosetElement.getAttribute(\"secret\")); // TODO verify that this is the secret for the photo\r\n primaryPhoto.setServer(photosetElement.getAttribute(\"server\")); // TODO verify that this is the server for the photo\r\n primaryPhoto.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n // TODO remove secret/server/farm from photoset?\r\n // It's rather related to the primaryPhoto, then to the photoset itself.\r\n photoset.setSecret(photosetElement.getAttribute(\"secret\"));\r\n photoset.setServer(photosetElement.getAttribute(\"server\"));\r\n photoset.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPhotoCount(photosetElement.getAttribute(\"count_photos\"));\r\n photoset.setVideoCount(Integer.parseInt(photosetElement.getAttribute(\"count_videos\")));\r\n photoset.setViewCount(Integer.parseInt(photosetElement.getAttribute(\"count_views\")));\r\n photoset.setCommentCount(Integer.parseInt(photosetElement.getAttribute(\"count_comments\")));\r\n photoset.setDateCreate(photosetElement.getAttribute(\"date_create\"));\r\n photoset.setDateUpdate(photosetElement.getAttribute(\"date_update\"));\r\n\r\n photoset.setIsCanComment(\"1\".equals(photosetElement.getAttribute(\"can_comment\")));\r\n\r\n photoset.setTitle(XMLUtilities.getChildValue(photosetElement, \"title\"));\r\n photoset.setDescription(XMLUtilities.getChildValue(photosetElement, \"description\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n return photoset;\r\n }",
"public Date getStart()\n {\n Date result = null;\n for (ResourceAssignment assignment : m_assignments)\n {\n if (result == null || DateHelper.compare(result, assignment.getStart()) > 0)\n {\n result = assignment.getStart();\n }\n }\n return (result);\n }",
"public SimplifySpanBuild appendMultiClickable(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) {\n processMultiClickableSpecialUnit(false, specialClickableUnit, specialUnitOrStrings);\n return this;\n }",
"public static boolean uniform(Color color, Pixel[] pixels) {\n return Arrays.stream(pixels).allMatch(p -> p.toInt() == color.toRGB().toInt());\n }",
"public CollectionRequest<Task> subtasks(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public synchronized void cleanWaitTaskQueue() {\n\n for (ParallelTask task : waitQ) {\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.USER_CANCELED, \"NA\"));\n logger.info(\n \"task {} removed from wait q. This task has been marked as USER CANCELED.\",\n task.getTaskId());\n\n }\n\n waitQ.clear();\n }",
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"private void checkOrderby(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String orderbySpec = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ORDERBY);\r\n\r\n if ((orderbySpec == null) || (orderbySpec.length() == 0))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner();\r\n String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.');\r\n ClassDescriptorDef elementClass = ((ModelDef)ownerClass.getOwner()).getClass(elementClassName);\r\n FieldDescriptorDef fieldDef;\r\n String token;\r\n String fieldName;\r\n String ordering;\r\n int pos;\r\n\r\n for (CommaListIterator it = new CommaListIterator(orderbySpec); it.hasNext();)\r\n {\r\n token = it.getNext();\r\n pos = token.indexOf('=');\r\n if (pos == -1)\r\n {\r\n fieldName = token;\r\n ordering = null;\r\n }\r\n else\r\n {\r\n fieldName = token.substring(0, pos);\r\n ordering = token.substring(pos + 1);\r\n }\r\n fieldDef = elementClass.getField(fieldName);\r\n if (fieldDef == null)\r\n {\r\n throw new ConstraintException(\"The field \"+fieldName+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" hasn't been found in the element class \"+elementClass.getName());\r\n }\r\n if ((ordering != null) && (ordering.length() > 0) &&\r\n !\"ASC\".equals(ordering) && !\"DESC\".equals(ordering))\r\n {\r\n throw new ConstraintException(\"The ordering \"+ordering+\" specified in the orderby attribute of the collection \"+collDef.getName()+\" in class \"+ownerClass.getName()+\" is invalid\");\r\n }\r\n }\r\n }",
"public static String removeOpenCmsContext(final String path) {\n\n String context = OpenCms.getSystemInfo().getOpenCmsContext();\n if (path.startsWith(context + \"/\")) {\n return path.substring(context.length());\n }\n String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix();\n if (path.startsWith(renderPrefix + \"/\")) {\n return path.substring(renderPrefix.length());\n }\n return path;\n }"
] |
Check if this path matches the address path.
An address matches this address if its path elements match or are valid
multi targets for this path elements. Addresses that are equal are matching.
@param address The path to check against this path. If null, this method
returns false.
@return true if the provided path matches, false otherwise. | [
"public boolean matches(PathAddress address) {\n if (address == null) {\n return false;\n }\n if (equals(address)) {\n return true;\n }\n if (size() != address.size()) {\n return false;\n }\n for (int i = 0; i < size(); i++) {\n PathElement pe = getElement(i);\n PathElement other = address.getElement(i);\n if (!pe.matches(other)) {\n // Could be a multiTarget with segments\n if (pe.isMultiTarget() && !pe.isWildcard()) {\n boolean matched = false;\n for (String segment : pe.getSegments()) {\n if (segment.equals(other.getValue())) {\n matched = true;\n break;\n }\n }\n if (!matched) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }"
] | [
"public static <T> JacksonParser<T> json(Class<T> contentType) {\n return new JacksonParser<>(null, contentType);\n }",
"public static void setFieldValue(Object object, String fieldName, Object value) {\n try {\n getDeclaredFieldInHierarchy(object.getClass(), fieldName).set(object, value);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }",
"public static void shutdownDomain(final ModelControllerClient client, final int timeout) throws IOException, OperationExecutionException {\n // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation.\n // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client\n // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to\n // have this issue.\n\n // First shutdown the servers\n final ModelNode stopServersOp = Operations.createOperation(\"stop-servers\");\n stopServersOp.get(\"blocking\").set(true);\n stopServersOp.get(\"timeout\").set(timeout);\n ModelNode response = client.execute(stopServersOp);\n if (!Operations.isSuccessfulOutcome(response)) {\n throw new OperationExecutionException(\"Failed to stop servers.\", stopServersOp, response);\n }\n\n // Now shutdown the host\n final ModelNode address = determineHostAddress(client);\n final ModelNode shutdownOp = Operations.createOperation(\"shutdown\", address);\n response = client.execute(shutdownOp);\n if (Operations.isSuccessfulOutcome(response)) {\n // Wait until the process has died\n while (true) {\n if (isDomainRunning(client, true)) {\n try {\n TimeUnit.MILLISECONDS.sleep(20L);\n } catch (InterruptedException e) {\n LOGGER.trace(\"Interrupted during sleep\", e);\n }\n } else {\n break;\n }\n }\n } else {\n throw new OperationExecutionException(\"Failed to shutdown host.\", shutdownOp, response);\n }\n }",
"@Deprecated\n\tpublic static ScheduleInterface createScheduleFromConventions(\n\t\t\tLocalDate referenceDate,\n\t\t\tLocalDate startDate,\n\t\t\tString frequency,\n\t\t\tdouble maturity,\n\t\t\tString daycountConvention,\n\t\t\tString shortPeriodConvention\n\t\t\t)\n\t{\n\t\treturn createScheduleFromConventions(\n\t\t\t\treferenceDate,\n\t\t\t\tstartDate,\n\t\t\t\tfrequency,\n\t\t\t\tmaturity,\n\t\t\t\tdaycountConvention,\n\t\t\t\tshortPeriodConvention,\n\t\t\t\t\"UNADJUSTED\",\n\t\t\t\tnew BusinessdayCalendarAny(),\n\t\t\t\t0, 0);\n\t}",
"public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }",
"private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,\n\t\t\tList<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails)\n\t\t\tthrows SQLException {\n\t\tStringBuilder sb = new StringBuilder(256);\n\t\tif (logDetails) {\n\t\t\tlogger.info(\"creating table '{}'\", tableInfo.getTableName());\n\t\t}\n\t\tsb.append(\"CREATE TABLE \");\n\t\tif (ifNotExists && databaseType.isCreateIfNotExistsSupported()) {\n\t\t\tsb.append(\"IF NOT EXISTS \");\n\t\t}\n\t\tdatabaseType.appendEscapedEntityName(sb, tableInfo.getTableName());\n\t\tsb.append(\" (\");\n\t\tList<String> additionalArgs = new ArrayList<String>();\n\t\tList<String> statementsBefore = new ArrayList<String>();\n\t\tList<String> statementsAfter = new ArrayList<String>();\n\t\t// our statement will be set here later\n\t\tboolean first = true;\n\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t// skip foreign collections\n\t\t\tif (fieldType.isForeignCollection()) {\n\t\t\t\tcontinue;\n\t\t\t} else if (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t\tString columnDefinition = fieldType.getColumnDefinition();\n\t\t\tif (columnDefinition == null) {\n\t\t\t\t// we have to call back to the database type for the specific create syntax\n\t\t\t\tdatabaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore,\n\t\t\t\t\t\tstatementsAfter, queriesAfter);\n\t\t\t} else {\n\t\t\t\t// hand defined field\n\t\t\t\tdatabaseType.appendEscapedEntityName(sb, fieldType.getColumnName());\n\t\t\t\tsb.append(' ').append(columnDefinition).append(' ');\n\t\t\t}\n\t\t}\n\t\t// add any sql that sets any primary key fields\n\t\tdatabaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\t// add any sql that sets any unique fields\n\t\tdatabaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,\n\t\t\t\tqueriesAfter);\n\t\tfor (String arg : additionalArgs) {\n\t\t\t// we will have spat out one argument already so we don't have to do the first dance\n\t\t\tsb.append(\", \").append(arg);\n\t\t}\n\t\tsb.append(\") \");\n\t\tdatabaseType.appendCreateTableSuffix(sb);\n\t\tstatements.addAll(statementsBefore);\n\t\tstatements.add(sb.toString());\n\t\tstatements.addAll(statementsAfter);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails);\n\t\taddCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails);\n\t}",
"public <T> T handleResponse(Response response, Type returnType) throws ApiException {\n if (response.isSuccessful()) {\n if (returnType == null || response.code() == 204) {\n // returning null if the returnType is not defined,\n // or the status code is 204 (No Content)\n return null;\n } else {\n return deserialize(response, returnType);\n }\n } else {\n String respBody = null;\n if (response.body() != null) {\n try {\n respBody = response.body().string();\n } catch (IOException e) {\n throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());\n }\n }\n throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);\n }\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 }",
"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}"
] |
Converts assignment duration values from minutes to hours.
@param list assignment data | [
"protected void convertToHours(LinkedList<TimephasedWork> list)\n {\n for (TimephasedWork assignment : list)\n {\n Duration totalWork = assignment.getTotalAmount();\n Duration workPerDay = assignment.getAmountPerDay();\n totalWork = Duration.getInstance(totalWork.getDuration() / 60, TimeUnit.HOURS);\n workPerDay = Duration.getInstance(workPerDay.getDuration() / 60, TimeUnit.HOURS);\n assignment.setTotalAmount(totalWork);\n assignment.setAmountPerDay(workPerDay);\n }\n }"
] | [
"public static byte[] encode(byte[] ba, int offset, long v) {\n ba[offset + 0] = (byte) (v >>> 56);\n ba[offset + 1] = (byte) (v >>> 48);\n ba[offset + 2] = (byte) (v >>> 40);\n ba[offset + 3] = (byte) (v >>> 32);\n ba[offset + 4] = (byte) (v >>> 24);\n ba[offset + 5] = (byte) (v >>> 16);\n ba[offset + 6] = (byte) (v >>> 8);\n ba[offset + 7] = (byte) (v >>> 0);\n return ba;\n }",
"public Membership getMembership() {\n URI uri = new URIBase(getBaseUri()).path(\"_membership\").build();\n Membership membership = couchDbClient.get(uri,\n Membership.class);\n return membership;\n }",
"public boolean isIdProperty(OgmEntityPersister persister, List<String> namesWithoutAlias) {\n\t\tString join = StringHelper.join( namesWithoutAlias, \".\" );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tString[] identifierColumnNames = persister.getIdentifierColumnNames();\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\tString[] embeddedColumnNames = persister.getPropertyColumnNames( join );\n\t\t\tfor ( String embeddedColumn : embeddedColumnNames ) {\n\t\t\t\tif ( !ArrayHelper.contains( identifierColumnNames, embeddedColumn ) ) {\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 ArrayHelper.contains( identifierColumnNames, join );\n\t}",
"public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n // Calculate summaries.\n summaryListener.suiteSummary(e);\n\n Description suiteDescription = e.getDescription();\n String displayName = suiteDescription.getDisplayName();\n if (displayName.trim().isEmpty()) {\n junit4.log(\"Could not emit XML report for suite (null description).\", \n Project.MSG_WARN);\n return;\n }\n\n if (!suiteCounts.containsKey(displayName)) {\n suiteCounts.put(displayName, 1);\n } else {\n int newCount = suiteCounts.get(displayName) + 1;\n suiteCounts.put(displayName, newCount);\n if (!ignoreDuplicateSuites && newCount == 2) {\n junit4.log(\"Duplicate suite name used with XML reports: \"\n + displayName + \". This may confuse tools that process XML reports. \"\n + \"Set 'ignoreDuplicateSuites' to true to skip this message.\", Project.MSG_WARN);\n }\n displayName = displayName + \"-\" + newCount;\n }\n \n try {\n File reportFile = new File(dir, \"TEST-\" + displayName + \".xml\");\n RegistryMatcher rm = new RegistryMatcher();\n rm.bind(String.class, new XmlStringTransformer());\n Persister persister = new Persister(rm);\n persister.write(buildModel(e), reportFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize report for suite \"\n + displayName + \": \" + x.toString(), x, Project.MSG_WARN);\n }\n }",
"public void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"private String convertOutputToHtml(String content) {\n\n if (content.length() == 0) {\n return \"\";\n }\n StringBuilder buffer = new StringBuilder();\n for (String line : content.split(\"\\n\")) {\n buffer.append(CmsEncoder.escapeXml(line) + \"<br>\");\n }\n return buffer.toString();\n }",
"private void setCrosstabOptions() {\n\t\tif (djcross.isUseFullWidth()){\n\t\t\tjrcross.setWidth(layoutManager.getReport().getOptions().getPrintableWidth());\n\t\t} else {\n\t\t\tjrcross.setWidth(djcross.getWidth());\n\t\t}\n\t\tjrcross.setHeight(djcross.getHeight());\n\n\t\tjrcross.setColumnBreakOffset(djcross.getColumnBreakOffset());\n\n jrcross.setIgnoreWidth(djcross.isIgnoreWidth());\n\t}",
"public void create(final DbProduct dbProduct) {\n if(repositoryHandler.getProduct(dbProduct.getName()) != null){\n throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity(\"Product already exist!\").build());\n }\n\n repositoryHandler.store(dbProduct);\n }"
] |
Creates an immutable map. A copy of the given map is used. As a result, it is safe to modify the source map afterwards.
@param map the given map
@return an immutable map | [
"public static <K, V> Map<K, V> copyOf(Map<K, V> map) {\n Preconditions.checkNotNull(map);\n return ImmutableMap.<K, V> builder().putAll(map).build();\n }"
] | [
"public void setLinearLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setLinearLowerLimits(getNative(), limitX, limitY, limitZ);\n }",
"public static Boolean assertTrue(Boolean value, String message) {\n if (!Boolean.valueOf(value))\n throw new IllegalStateException(message);\n\n return value;\n }",
"public static <T> NewManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {\n return new NewManagedBean<T>(attributes, clazz, new StringBeanIdentifier(BeanIdentifiers.forNewManagedBean(clazz)), beanManager);\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 void recordSyncOpTimeNs(SocketDestination dest, long opTimeNs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordSyncOpTimeNs(null, opTimeNs);\n recordSyncOpTimeNs(null, opTimeNs);\n } else {\n this.syncOpTimeRequestCounter.addRequest(opTimeNs);\n }\n }",
"public List<Message> requestFolderMenuFrom(final SlotReference slotReference, final int sortOrder, final int folderId)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Key menu.\");\n Message response = client.menuRequestTyped(Message.KnownType.FOLDER_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n CdjStatus.TrackType.UNANALYZED, new NumberField(sortOrder), new NumberField(folderId), new NumberField(0xffffff));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.UNANALYZED, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting folder menu\");\n }",
"@Deprecated\n public FluoConfiguration addObservers(Iterable<ObserverSpecification> observers) {\n int next = getNextObserverId();\n for (ObserverSpecification oconf : observers) {\n addObserver(oconf, next++);\n }\n return this;\n }",
"public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }",
"public static double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }"
] |
Gets a byte within this sequence of bytes
@param i index into sequence
@return byte
@throws IllegalArgumentException if i is out of range | [
"public byte byteAt(int i) {\n\n if (i < 0) {\n throw new IndexOutOfBoundsException(\"i < 0, \" + i);\n }\n\n if (i >= length) {\n throw new IndexOutOfBoundsException(\"i >= length, \" + i + \" >= \" + length);\n }\n\n return data[offset + i];\n }"
] | [
"protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) {\n Object returnObject = invokeJavascript(function);\n if (returnObject instanceof JSObject) {\n try {\n Constructor<T> constructor = returnType.getConstructor(JSObject.class);\n return constructor.newInstance((JSObject) returnObject);\n } catch (Exception ex) {\n throw new IllegalStateException(ex);\n }\n } else {\n return (T) returnObject;\n }\n }",
"public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}",
"public static base_responses enable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface enableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tenableresources[i] = new Interface();\n\t\t\t\tenableresources[i].id = id[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}",
"public SerialMessage getValueMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command BASIC_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) BASIC_GET };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public static<T> SessionVar<T> vendSessionVar(T defValue) {\n\treturn (new VarsJBridge()).vendSessionVar(defValue, new Exception());\n }",
"public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {\r\n for (String name : names) {\r\n if (hasAnnotation(node, name)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"@Override\n public com.flickr4java.flickr.Response get(String path, Map<String, Object> parameters, String apiKey, String sharedSecret) throws FlickrException {\n\n OAuthRequest request = new OAuthRequest(Verb.GET, buildUrl(path));\n for (Map.Entry<String, Object> entry : parameters.entrySet()) {\n request.addQuerystringParameter(entry.getKey(), String.valueOf(entry.getValue()));\n }\n\n if (proxyAuth) {\n request.addHeader(\"Proxy-Authorization\", \"Basic \" + getProxyCredentials());\n }\n\n RequestContext requestContext = RequestContext.getRequestContext();\n Auth auth = requestContext.getAuth();\n OAuth10aService service = createOAuthService(apiKey, sharedSecret);\n if (auth != null) {\n OAuth1AccessToken requestToken = new OAuth1AccessToken(auth.getToken(), auth.getTokenSecret());\n service.signRequest(requestToken, request);\n } else {\n // For calls that do not require authorization e.g. flickr.people.findByUsername which could be the\n // first call if the user did not supply the user-id (i.e. nsid).\n if (!parameters.containsKey(Flickr.API_KEY)) {\n request.addQuerystringParameter(Flickr.API_KEY, apiKey);\n }\n }\n\n if (Flickr.debugRequest) {\n logger.debug(\"GET: \" + request.getCompleteUrl());\n }\n\n try {\n return handleResponse(request, service);\n } catch (IllegalAccessException | InstantiationException | SAXException | IOException | InterruptedException | ExecutionException | ParserConfigurationException e) {\n throw new FlickrRuntimeException(e);\n }\n }",
"public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}",
"private static void parseDockers(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"dockers\")) {\n ArrayList<Point> dockers = new ArrayList<Point>();\n\n JSONArray dockersObject = modelJSON.getJSONArray(\"dockers\");\n for (int i = 0; i < dockersObject.length(); i++) {\n Double x = dockersObject.getJSONObject(i).getDouble(\"x\");\n Double y = dockersObject.getJSONObject(i).getDouble(\"y\");\n dockers.add(new Point(x,\n y));\n }\n if (dockers.size() > 0) {\n current.setDockers(dockers);\n }\n }\n }"
] |
Check if this applies to the provided authorization scope and return the credentials for that scope or
null if it doesn't apply to the scope.
@param authscope the scope to test against. | [
"@Nullable\n public final Credentials toCredentials(final AuthScope authscope) {\n try {\n\n if (!matches(MatchInfo.fromAuthScope(authscope))) {\n return null;\n }\n } catch (UnknownHostException | MalformedURLException | SocketException e) {\n throw new RuntimeException(e);\n }\n if (this.username == null) {\n return null;\n }\n\n final String passwordString;\n if (this.password != null) {\n passwordString = new String(this.password);\n } else {\n passwordString = null;\n }\n return new UsernamePasswordCredentials(this.username, passwordString);\n }"
] | [
"public static double computeRowMax( ZMatrixRMaj A ,\n int row , int col0 , int col1 ) {\n double max = 0;\n\n int indexA = A.getIndex(row,col0);\n double h[] = A.data;\n\n for (int i = col0; i < col1; i++) {\n double realVal = h[indexA++];\n double imagVal = h[indexA++];\n\n double magVal = realVal*realVal + imagVal*imagVal;\n if( max < magVal ) {\n max = magVal;\n }\n }\n return Math.sqrt(max);\n }",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> addProfile(Model model, String name) throws Exception {\n logger.info(\"Should be adding the profile name when I hit the enter button={}\", name);\n return Utils.getJQGridJSON(profileService.add(name), \"profile\");\n }",
"public static int byteSizeOf(Bitmap bitmap) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n return bitmap.getAllocationByteCount();\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {\n return bitmap.getByteCount();\n } else {\n return bitmap.getRowBytes() * bitmap.getHeight();\n }\n }",
"public String translatePath(String path) {\n String translated;\n // special character: ~ maps to the user's home directory\n if (path.startsWith(\"~\" + File.separator)) {\n translated = System.getProperty(\"user.home\") + path.substring(1);\n } else if (path.startsWith(\"~\")) {\n String userName = path.substring(1);\n translated = new File(new File(System.getProperty(\"user.home\")).getParent(),\n userName).getAbsolutePath();\n // Keep the path separator in translated or add one if no user home specified\n translated = userName.isEmpty() || path.endsWith(File.separator) ? translated + File.separator : translated;\n } else if (!new File(path).isAbsolute()) {\n translated = ctx.getCurrentDir().getAbsolutePath() + File.separator + path;\n } else {\n translated = path;\n }\n return translated;\n }",
"public boolean overrides(Link other) {\n if (other.getStatus() == LinkStatus.ASSERTED &&\n status != LinkStatus.ASSERTED)\n return false;\n else if (status == LinkStatus.ASSERTED &&\n other.getStatus() != LinkStatus.ASSERTED)\n return true;\n\n // the two links are from equivalent sources of information, so we\n // believe the most recent\n\n return timestamp > other.getTimestamp();\n }",
"public static byte[] synchronizeSlaveHostController(ModelNode operation, final PathAddress address, HostFileRepository fileRepository, ContentRepository contentRepository, boolean backup, byte[] oldHash) {\n ModelNode operationContentItem = operation.get(DeploymentAttributes.CONTENT_RESOURCE_ALL.getName()).get(0);\n byte[] newHash = operationContentItem.require(CONTENT_HASH.getName()).asBytes();\n if (needRemoteContent(fileRepository, contentRepository, backup, oldHash)) { // backup DC needs to pull the content\n fileRepository.getDeploymentFiles(ModelContentReference.fromModelAddress(address, newHash));\n }\n return newHash;\n }",
"public Widget addControl(String name, int resId, String label, Widget.OnTouchListener listener) {\n return addControl(name, resId, label, listener, -1);\n }",
"public static Object lookup(String jndiName)\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"lookup(\"+jndiName+\") was called\");\r\n try\r\n {\r\n return getContext().lookup(jndiName);\r\n }\r\n catch (NamingException e)\r\n {\r\n throw new OJBRuntimeException(\"Lookup failed for: \" + jndiName, e);\r\n }\r\n catch(OJBRuntimeException e)\r\n {\r\n throw e;\r\n }\r\n }",
"public void collectVariables(EnvVars env, Run build, TaskListener listener) {\n EnvVars buildParameters = Utils.extractBuildParameters(build, listener);\n if (buildParameters != null) {\n env.putAll(buildParameters);\n }\n addAllWithFilter(envVars, env, filter.getPatternFilter());\n Map<String, String> sysEnv = new HashMap<>();\n Properties systemProperties = System.getProperties();\n Enumeration<?> enumeration = systemProperties.propertyNames();\n while (enumeration.hasMoreElements()) {\n String propertyKey = (String) enumeration.nextElement();\n sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));\n }\n addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());\n }"
] |
Extracts the zip file to the output folder
@param zipFile ZIP File to extract
@param outputFolder Output Folder
@return A Collection with the extracted files
@throws IOException I/O Error | [
"public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\n }"
] | [
"public static GridLabelFormat fromConfig(final GridParam param) {\n if (param.labelFormat != null) {\n return new GridLabelFormat.Simple(param.labelFormat);\n } else if (param.valueFormat != null) {\n return new GridLabelFormat.Detailed(\n param.valueFormat, param.unitFormat,\n param.formatDecimalSeparator, param.formatGroupingSeparator);\n }\n return null;\n }",
"@Override\n public final boolean getBool(final String key) {\n Boolean result = optBool(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"@JmxGetter(name = \"avgFetchEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgFetchEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }",
"protected int complete(CommandContext ctx, ParsedCommandLine parsedCmd, OperationCandidatesProvider candidatesProvider, final String buffer, int cursor, List<String> candidates) {\n\n if(parsedCmd.isRequestComplete()) {\n return -1;\n }\n\n // Headers completion\n if(parsedCmd.endsOnHeaderListStart() || parsedCmd.hasHeaders()) {\n return completeHeaders(ctx, parsedCmd, candidatesProvider, buffer, cursor, candidates);\n }\n\n // Completed.\n if(parsedCmd.endsOnPropertyListEnd()) {\n return buffer.length();\n }\n\n // Complete properties\n if (parsedCmd.hasProperties() || parsedCmd.endsOnPropertyListStart()\n || parsedCmd.endsOnNotOperator()) {\n return completeProperties(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }\n\n // Complete Operation name\n if (parsedCmd.hasOperationName() || parsedCmd.endsOnAddressOperationNameSeparator()) {\n return completeOperationName(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }\n\n // Finally Complete address\n return completeAddress(ctx, parsedCmd, candidatesProvider, buffer, candidates);\n }",
"public static Method findDeclaredMethodByName(Class<?> clazz, String methodName) {\n for (Method method : AccessController.doPrivileged(new GetDeclaredMethodsAction(clazz))) {\n if (methodName.equals(method.getName())) {\n return method;\n }\n }\n return null;\n }",
"private void onClickAdd() {\n\n if (m_currentLocation.isPresent()) {\n CmsFavoriteEntry entry = m_currentLocation.get();\n List<CmsFavoriteEntry> entries = getEntries();\n entries.add(entry);\n try {\n m_favDao.saveFavorites(entries);\n } catch (Exception e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n m_context.close();\n }\n }",
"public static final Integer getInteger(Number value)\n {\n Integer result = null;\n if (value != null)\n {\n if (value instanceof Integer)\n {\n result = (Integer) value;\n }\n else\n {\n result = Integer.valueOf((int) Math.round(value.doubleValue()));\n }\n }\n return (result);\n }",
"public static dnstxtrec[] get(nitro_service service) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tdnstxtrec[] response = (dnstxtrec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 }"
] |
Returns an integer array that contains the current values for all the
texture parameters.
@return an integer array that contains the current values for all the
texture parameters. | [
"public int[] getCurrentValuesArray() {\n int[] currentValues = new int[5];\n\n currentValues[0] = getMinFilterType().getFilterValue(); // MIN FILTER\n currentValues[1] = getMagFilterType().getFilterValue(); // MAG FILTER\n currentValues[2] = getAnisotropicValue(); // ANISO FILTER\n currentValues[3] = getWrapSType().getWrapValue(); // WRAP S\n currentValues[4] = getWrapTType().getWrapValue(); // WRAP T\n\n return currentValues;\n }"
] | [
"private void parse(String header)\n {\n ArrayList<String> list = new ArrayList<String>(4);\n StringBuilder sb = new StringBuilder();\n int index = 1;\n while (index < header.length())\n {\n char c = header.charAt(index++);\n if (Character.isDigit(c))\n {\n sb.append(c);\n }\n else\n {\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n sb.setLength(0);\n }\n }\n }\n\n if (sb.length() != 0)\n {\n list.add(sb.toString());\n }\n\n m_id = list.get(0);\n m_sequence = Integer.parseInt(list.get(1));\n m_type = Integer.valueOf(list.get(2));\n if (list.size() > 3)\n {\n m_subtype = Integer.parseInt(list.get(3));\n }\n }",
"private void onRead0() {\n assert inWire.startUse();\n\n ensureCapacity();\n\n try {\n\n while (!inWire.bytes().isEmpty()) {\n\n try (DocumentContext dc = inWire.readingDocument()) {\n if (!dc.isPresent())\n return;\n\n try {\n if (YamlLogging.showServerReads())\n logYaml(dc);\n onRead(dc, outWire);\n onWrite(outWire);\n } catch (Exception e) {\n Jvm.warn().on(getClass(), \"inWire=\" + inWire.getClass() + \",yaml=\" + Wires.fromSizePrefixedBlobs(dc), e);\n }\n }\n }\n\n } finally {\n assert inWire.endUse();\n }\n }",
"public static dnsaaaarec[] get(nitro_service service) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"static <T> StitchEvent<T> fromEvent(final Event event,\n final Decoder<T> decoder) {\n return new StitchEvent<>(event.getEventName(), event.getData(), decoder);\n }",
"public RgbaColor opacify(float amount) {\n return new RgbaColor(r, g, b, alphaCheck(a + amount));\n }",
"@Override\n public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename,\n long startOffsetBytes, long timeoutMillis) {\n Preconditions.checkArgument(startOffsetBytes >= 0, \"%s: offset must be non-negative: %s\", this,\n startOffsetBytes);\n final int n = dst.remaining();\n Preconditions.checkArgument(n > 0, \"%s: dst full: %s\", this, dst);\n final int want = Math.min(READ_LIMIT_BYTES, n);\n\n final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);\n req.setHeader(\n new HTTPHeader(RANGE, \"bytes=\" + startOffsetBytes + \"-\" + (startOffsetBytes + want - 1)));\n final HTTPRequestInfo info = new HTTPRequestInfo(req);\n return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {\n @Override\n protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {\n long totalLength;\n switch (resp.getResponseCode()) {\n case 200:\n totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);\n break;\n case 206:\n totalLength = getLengthFromContentRange(resp);\n break;\n case 404:\n throw new FileNotFoundException(\"Could not find: \" + filename);\n case 416:\n throw new BadRangeException(\"Requested Range not satisfiable; perhaps read past EOF? \"\n + URLFetchUtils.describeRequestAndResponse(info, resp));\n default:\n throw HttpErrorHandler.error(info, resp);\n }\n byte[] content = resp.getContent();\n Preconditions.checkState(content.length <= want, \"%s: got %s > wanted %s\", this,\n content.length, want);\n dst.put(content);\n return getMetadataFromResponse(filename, resp, totalLength);\n }\n\n @Override\n protected Throwable convertException(Throwable e) {\n return OauthRawGcsService.convertException(info, e);\n }\n };\n }",
"protected void checkConsecutiveAlpha() {\n\n Pattern symbolsPatter = Pattern.compile(REGEX_ALPHA_UC + \"+\");\n Matcher matcher = symbolsPatter.matcher(this.password);\n int met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n\n // alpha lower case\n\n symbolsPatter = Pattern.compile(REGEX_ALPHA_LC + \"+\");\n matcher = symbolsPatter.matcher(this.password);\n met = 0;\n while (matcher.find()) {\n int start = matcher.start();\n int end = matcher.end();\n if (start == end) {\n continue;\n }\n int diff = end - start;\n if (diff >= 3) {\n met += diff;\n }\n\n }\n\n this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);\n }",
"private static String wordShapeDan1(String s) {\r\n boolean digit = true;\r\n boolean upper = true;\r\n boolean lower = true;\r\n boolean mixed = true;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!Character.isDigit(c)) {\r\n digit = false;\r\n }\r\n if (!Character.isLowerCase(c)) {\r\n lower = false;\r\n }\r\n if (!Character.isUpperCase(c)) {\r\n upper = false;\r\n }\r\n if ((i == 0 && !Character.isUpperCase(c)) || (i >= 1 && !Character.isLowerCase(c))) {\r\n mixed = false;\r\n }\r\n }\r\n if (digit) {\r\n return \"ALL-DIGITS\";\r\n }\r\n if (upper) {\r\n return \"ALL-UPPER\";\r\n }\r\n if (lower) {\r\n return \"ALL-LOWER\";\r\n }\r\n if (mixed) {\r\n return \"MIXED-CASE\";\r\n }\r\n return \"OTHER\";\r\n }",
"void commitTempFile(File temp) throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n if (!interactionPolicy.isReadOnly()) {\n FilePersistenceUtils.moveTempFileToMain(temp, mainFile);\n } else {\n FilePersistenceUtils.moveTempFileToMain(temp, lastFile);\n }\n }"
] |
Set the model used by the right table.
@param model table model | [
"public void setRightTableModel(TableModel model)\n {\n TableModel old = m_rightTable.getModel();\n m_rightTable.setModel(model);\n firePropertyChange(\"rightTableModel\", old, model);\n }"
] | [
"public void callFunction(String className, String methodName, PluginArguments pluginArgs, Object... args) throws Exception {\n Class<?> cls = getClass(className);\n\n ArrayList<Object> newArgs = new ArrayList<>();\n newArgs.add(pluginArgs);\n com.groupon.odo.proxylib.models.Method m = preparePluginMethod(newArgs, className, methodName, args);\n\n m.getMethod().invoke(cls, newArgs.toArray(new Object[0]));\n }",
"@Override\n protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n // Is the line an empty comment \"#\" ?\n if (line.startsWith(COMMENT_PREFIX) && line.length() == 1) {\n String nextLine = bufferedFileReader.readLine();\n if (nextLine != null) {\n // Is the next line the realm name \"#$REALM_NAME=\" ?\n if (nextLine.startsWith(COMMENT_PREFIX) && nextLine.contains(REALM_COMMENT_PREFIX)) {\n // Realm name block detected!\n // The next line must be and empty comment \"#\"\n bufferedFileReader.readLine();\n // Avoid adding the realm block\n } else {\n // It's a user comment...\n content.add(line);\n content.add(nextLine);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n } else {\n super.addLineContent(bufferedFileReader, content, line);\n }\n }",
"public FinishRequest toFinishRequest(boolean includeHeaders) {\n if (includeHeaders) {\n return new FinishRequest(body, copyHeaders(headers), statusCode);\n } else {\n String mime = null;\n if (body!=null) {\n mime = \"text/plain\";\n if (headers!=null && (headers.containsKey(\"Content-Type\") || headers.containsKey(\"content-type\"))) {\n mime = headers.get(\"Content-Type\");\n if (mime==null) {\n mime = headers.get(\"content-type\");\n }\n }\n }\n\n return new FinishRequest(body, mime, statusCode);\n }\n }",
"public Plugin[] getPlugins(Boolean onlyValid) {\n Configuration[] configurations = ConfigurationService.getInstance().getConfigurations(Constants.DB_TABLE_CONFIGURATION_PLUGIN_PATH);\n\n ArrayList<Plugin> plugins = new ArrayList<Plugin>();\n\n if (configurations == null) {\n return new Plugin[0];\n }\n\n for (Configuration config : configurations) {\n Plugin plugin = new Plugin();\n plugin.setId(config.getId());\n plugin.setPath(config.getValue());\n\n File path = new File(plugin.getPath());\n if (path.isDirectory()) {\n plugin.setStatus(Constants.PLUGIN_STATUS_VALID);\n plugin.setStatusMessage(\"Valid\");\n } else {\n plugin.setStatus(Constants.PLUGIN_STATUS_NOT_DIRECTORY);\n plugin.setStatusMessage(\"Path is not a directory\");\n }\n\n if (!onlyValid || plugin.getStatus() == Constants.PLUGIN_STATUS_VALID) {\n plugins.add(plugin);\n }\n }\n\n return plugins.toArray(new Plugin[0]);\n }",
"public final void notifyContentItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n int newContentItemCount = getContentItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newContentItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \"\n + (positionStart + itemCount - 1) + \"] is not within the position bounds for content items [0 - \"\n + (newContentItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart + newHeaderItemCount, itemCount);\n }",
"private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException {\n\n final PrintWriter pw = res.getWriter();\n final JSONObject response = getJsonFormattedSpellcheckResult(request);\n pw.println(response.toString());\n pw.close();\n }",
"public static CuratorFramework newAppCurator(FluoConfiguration config) {\n return newCurator(config.getAppZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }",
"public static csvserver_spilloverpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_spilloverpolicy_binding obj = new csvserver_spilloverpolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_spilloverpolicy_binding response[] = (csvserver_spilloverpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }"
] |
This method creates the flattened POM what is the main task of this plugin.
@param pomFile is the name of the original POM file to read and transform.
@return the {@link Model} of the flattened POM.
@throws MojoExecutionException if anything goes wrong (e.g. POM can not be processed).
@throws MojoFailureException if anything goes wrong (logical error). | [
"protected Model createFlattenedPom( File pomFile )\n throws MojoExecutionException, MojoFailureException\n {\n\n ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile );\n Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode );\n\n Model flattenedPom = new Model();\n\n // keep original encoding (we could also normalize to UTF-8 here)\n String modelEncoding = effectivePom.getModelEncoding();\n if ( StringUtils.isEmpty( modelEncoding ) )\n {\n modelEncoding = \"UTF-8\";\n }\n flattenedPom.setModelEncoding( modelEncoding );\n\n Model cleanPom = createCleanPom( effectivePom );\n\n FlattenDescriptor descriptor = getFlattenDescriptor();\n Model originalPom = this.project.getOriginalModel();\n Model resolvedPom = this.project.getModel();\n Model interpolatedPom = createResolvedPom( buildingRequest );\n\n // copy the configured additional POM elements...\n\n for ( PomProperty<?> property : PomProperty.getPomProperties() )\n {\n if ( property.isElement() )\n {\n Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom,\n interpolatedPom, cleanPom );\n if ( sourceModel == null )\n {\n if ( property.isRequired() )\n {\n throw new MojoFailureException( \"Property \" + property.getName()\n + \" is required and can not be removed!\" );\n }\n }\n else\n {\n property.copy( sourceModel, flattenedPom );\n }\n }\n }\n\n return flattenedPom;\n }"
] | [
"@Override\n\tpublic void close() {\n\t\tlogger.info(\"Finished processing.\");\n\t\tthis.timer.stop();\n\t\tthis.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\tprintStatus();\n\t}",
"protected void addNeighbor(Queue<ColorPoint> queue, int px, int py, int color, Feature component) {\n if (!inBoundary(px, py, component)) {\n return;\n }\n\n if (!mask.isTouched(px, py)) {\n queue.add(new ColorPoint(px, py, color));\n }\n }",
"public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }",
"public final void notifyContentItemChanged(int position) {\n if (position < 0 || position >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for content items [0 - \" + (contentItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount);\n }",
"public static ModelNode createLocalHostHostInfo(final LocalHostControllerInfo hostInfo, final ProductConfig productConfig,\n final IgnoredDomainResourceRegistry ignoredResourceRegistry, final Resource hostModelResource) {\n final ModelNode info = new ModelNode();\n info.get(NAME).set(hostInfo.getLocalHostName());\n info.get(RELEASE_VERSION).set(Version.AS_VERSION);\n info.get(RELEASE_CODENAME).set(Version.AS_RELEASE_CODENAME);\n info.get(MANAGEMENT_MAJOR_VERSION).set(Version.MANAGEMENT_MAJOR_VERSION);\n info.get(MANAGEMENT_MINOR_VERSION).set(Version.MANAGEMENT_MINOR_VERSION);\n info.get(MANAGEMENT_MICRO_VERSION).set(Version.MANAGEMENT_MICRO_VERSION);\n final String productName = productConfig.getProductName();\n final String productVersion = productConfig.getProductVersion();\n if(productName != null) {\n info.get(PRODUCT_NAME).set(productName);\n }\n if(productVersion != null) {\n info.get(PRODUCT_VERSION).set(productVersion);\n }\n ModelNode ignoredModel = ignoredResourceRegistry.getIgnoredResourcesAsModel();\n if (ignoredModel.hasDefined(IGNORED_RESOURCE_TYPE)) {\n info.get(IGNORED_RESOURCES).set(ignoredModel.require(IGNORED_RESOURCE_TYPE));\n }\n boolean ignoreUnaffectedServerGroups = hostInfo.isRemoteDomainControllerIgnoreUnaffectedConfiguration();\n IgnoredNonAffectedServerGroupsUtil.addCurrentServerGroupsToHostInfoModel(ignoreUnaffectedServerGroups, hostModelResource, info);\n return info;\n }",
"public Query getPKQuery(Identity oid)\r\n {\r\n Object[] values = oid.getPrimaryKeyValues();\r\n ClassDescriptor cld = pb.getClassDescriptor(oid.getObjectsTopLevelClass());\r\n FieldDescriptor[] fields = cld.getPkFields();\r\n Criteria criteria = new Criteria();\r\n\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fld = fields[i];\r\n criteria.addEqualTo(fld.getAttributeName(), values[i]);\r\n }\r\n return QueryFactory.newQuery(cld.getClassOfObject(), criteria);\r\n }",
"public int millisecondsToX(long milliseconds) {\n if (autoScroll.get()) {\n int playHead = (getWidth() / 2) + 2;\n long offset = milliseconds - getFurthestPlaybackPosition();\n return playHead + (Util.timeToHalfFrame(offset) / scale.get());\n }\n return Util.timeToHalfFrame(milliseconds) / scale.get();\n }",
"public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }",
"public void appendImmediate(Object object, String indentation) {\n\t\tfor (int i = segments.size() - 1; i >= 0; i--) {\n\t\t\tString segment = segments.get(i);\n\t\t\tfor (int j = 0; j < segment.length(); j++) {\n\t\t\t\tif (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) {\n\t\t\t\t\tappend(object, indentation, i + 1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tappend(object, indentation, 0);\n\t}"
] |
Removes CRs but returns LFs | [
"final protected char next(final ByteBuffer buffer, boolean allow8859) throws BaseExceptions.BadMessage {\n\n if (!buffer.hasRemaining()) return HttpTokens.EMPTY_BUFF;\n\n if (_segmentByteLimit <= _segmentBytePosition) {\n shutdownParser();\n throw new BaseExceptions.BadMessage(\"Request length limit exceeded: \" + _segmentByteLimit);\n }\n\n final byte b = buffer.get();\n _segmentBytePosition++;\n\n // If we ended on a CR, make sure we are\n if (_cr) {\n if (b != HttpTokens.LF) {\n throw new BadCharacter(\"Invalid sequence: LF didn't follow CR: \" + b);\n }\n _cr = false;\n return (char)b; // must be LF\n }\n\n // Make sure its a valid character\n if (b < HttpTokens.SPACE) {\n if (b == HttpTokens.CR) { // Set the flag to check for _cr and just run again\n _cr = true;\n return next(buffer, allow8859);\n }\n else if (b == HttpTokens.TAB || allow8859 && b < 0) {\n return (char)(b & 0xff);\n }\n else if (b == HttpTokens.LF) {\n return (char)b; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3\n }\n else if (isLenient()) {\n return HttpTokens.REPLACEMENT;\n }\n else {\n shutdownParser();\n throw new BadCharacter(\"Invalid char: '\" + (char)(b & 0xff) + \"', 0x\" + Integer.toHexString(b));\n }\n }\n\n // valid ascii char\n return (char)b;\n }"
] | [
"private boolean processQueue(K key) {\n Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key);\n if(requestQueue.isEmpty()) {\n return false;\n }\n\n // Attempt to get a resource.\n Pool<V> resourcePool = getResourcePoolForKey(key);\n V resource = null;\n Exception ex = null;\n try {\n // Must attempt non-blocking checkout to ensure resources are\n // created for the pool.\n resource = attemptNonBlockingCheckout(key, resourcePool);\n } catch(Exception e) {\n destroyResource(key, resourcePool, resource);\n ex = e;\n resource = null;\n }\n // Neither we got a resource, nor an exception. So no requests can be\n // processed return\n if(resource == null && ex == null) {\n return false;\n }\n\n // With resource in hand, process the resource requests\n AsyncResourceRequest<V> resourceRequest = getNextUnexpiredResourceRequest(requestQueue);\n if(resourceRequest == null) {\n if(resource != null) {\n // Did not use the resource! Directly check in via super to\n // avoid\n // circular call to processQueue().\n try {\n super.checkin(key, resource);\n } catch(Exception e) {\n logger.error(\"Exception checking in resource: \", e);\n }\n } else {\n // Poor exception, no request to tag this exception onto\n // drop it on the floor and continue as usual.\n }\n return false;\n } else {\n // We have a request here.\n if(resource != null) {\n resourceRequest.useResource(resource);\n } else {\n resourceRequest.handleException(ex);\n }\n return true;\n }\n }",
"public static aaauser_auditsyslogpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_auditsyslogpolicy_binding obj = new aaauser_auditsyslogpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_auditsyslogpolicy_binding response[] = (aaauser_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String getTaskField(int key)\n {\n String result = null;\n\n if ((key > 0) && (key < m_taskNames.length))\n {\n result = m_taskNames[key];\n }\n\n return (result);\n }",
"protected Patch createProcessedPatch(final Patch original) {\n\n // Process elements\n final List<PatchElement> elements = new ArrayList<PatchElement>();\n // Process layers\n for (final PatchEntry entry : getLayers()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n // Process add-ons\n for (final PatchEntry entry : getAddOns()) {\n final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);\n elements.add(element);\n }\n\n // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications\n return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);\n }",
"public static rewriteglobal_binding get(nitro_service service) throws Exception{\n\t\trewriteglobal_binding obj = new rewriteglobal_binding();\n\t\trewriteglobal_binding response = (rewriteglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }",
"public static void fillHermitian(ZMatrixRMaj A, double min, double max, Random rand) {\n if( A.numRows != A.numCols )\n throw new IllegalArgumentException(\"A must be a square matrix\");\n\n double range = max-min;\n\n int length = A.numRows;\n\n for( int i = 0; i < length; i++ ) {\n A.set(i,i,rand.nextDouble()*range + min,0);\n\n for( int j = i+1; j < length; j++ ) {\n double real = rand.nextDouble()*range + min;\n double imaginary = rand.nextDouble()*range + min;\n A.set(i,j,real,imaginary);\n A.set(j,i,real,-imaginary);\n }\n }\n }",
"private void bindProcedure(PreparedStatement stmt, ClassDescriptor cld, Object obj, ProcedureDescriptor proc)\r\n throws SQLException\r\n {\r\n int valueSub = 0;\r\n\r\n // Figure out if we are using a callable statement. If we are, then we\r\n // will need to register one or more output parameters.\r\n CallableStatement callable = null;\r\n try\r\n {\r\n callable = (CallableStatement) stmt;\r\n }\r\n catch(Exception e)\r\n {\r\n m_log.error(\"Error while bind values for class '\" + (cld != null ? cld.getClassNameOfObject() : null)\r\n + \"', using stored procedure: \"+ proc, e);\r\n if(e instanceof SQLException)\r\n {\r\n throw (SQLException) e;\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(\"Unexpected error while bind values for class '\"\r\n + (cld != null ? cld.getClassNameOfObject() : null) + \"', using stored procedure: \"+ proc);\r\n }\r\n }\r\n\r\n // If we have a return value, then register it.\r\n if ((proc.hasReturnValue()) && (callable != null))\r\n {\r\n int jdbcType = proc.getReturnValueFieldRef().getJdbcType().getType();\r\n m_platform.setNullForStatement(stmt, valueSub + 1, jdbcType);\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n valueSub++;\r\n }\r\n\r\n // Process all of the arguments.\r\n Iterator iterator = proc.getArguments().iterator();\r\n while (iterator.hasNext())\r\n {\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iterator.next();\r\n Object val = arg.getValue(obj);\r\n int jdbcType = arg.getJdbcType();\r\n setObjectForStatement(stmt, valueSub + 1, val, jdbcType);\r\n if ((arg.getIsReturnedByProcedure()) && (callable != null))\r\n {\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n }\r\n valueSub++;\r\n }\r\n }",
"public static double Bhattacharyya(double[] histogram1, double[] histogram2) {\n int bins = histogram1.length; // histogram bins\n double b = 0; // Bhattacharyya's coefficient\n\n for (int i = 0; i < bins; i++)\n b += Math.sqrt(histogram1[i]) * Math.sqrt(histogram2[i]);\n\n // Bhattacharyya distance between the two distributions\n return Math.sqrt(1.0 - b);\n }"
] |
Adds an additional statement to the constructed document.
@param statement
the additional statement
@return builder object to continue construction | [
"public T withStatement(Statement statement) {\n\t\tPropertyIdValue pid = statement.getMainSnak()\n\t\t\t\t.getPropertyId();\n\t\tArrayList<Statement> pidStatements = this.statements.get(pid);\n\t\tif (pidStatements == null) {\n\t\t\tpidStatements = new ArrayList<Statement>();\n\t\t\tthis.statements.put(pid, pidStatements);\n\t\t}\n\n\t\tpidStatements.add(statement);\n\t\treturn getThis();\n\t}"
] | [
"protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) {\n\t\treturn (CallableStatement) Proxy.newProxyInstance(\n\t\t\t\tCallableStatementProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {CallableStatementProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public static InetAddress getLocalHost() throws UnknownHostException {\n InetAddress addr;\n try {\n addr = InetAddress.getLocalHost();\n } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404\n addr = InetAddress.getByName(null);\n }\n return addr;\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 readProjectHeader()\n {\n Table table = m_tables.get(\"DIR\");\n MapRow row = table.find(\"\");\n if (row != null)\n {\n setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());\n m_wbsFormat = new P3WbsFormat(row);\n }\n }",
"public static Timespan create(Timespan... timespans) {\n if (timespans == null) {\n return null;\n }\n\n if (timespans.length == 0) {\n return ZERO_MILLISECONDS;\n }\n\n Timespan res = timespans[0];\n\n for (int i = 1; i < timespans.length; i++) {\n Timespan timespan = timespans[i];\n res = res.add(timespan);\n }\n\n return res;\n }",
"private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\n }",
"public PhotoList<Photo> getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)\r\n throws FlickrException {\r\n return getContactsPublicPhotos(userId, Extras.MIN_EXTRAS, count, justFriends, singlePhoto, includeSelf);\r\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 base_responses update(nitro_service client, sslocspresponder resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslocspresponder updateresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new sslocspresponder();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].cache = resources[i].cache;\n\t\t\t\tupdateresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\tupdateresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\tupdateresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\tupdateresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\tupdateresources[i].respondercert = resources[i].respondercert;\n\t\t\t\tupdateresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\tupdateresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\tupdateresources[i].signingcert = resources[i].signingcert;\n\t\t\t\tupdateresources[i].usenonce = resources[i].usenonce;\n\t\t\t\tupdateresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Enable a host
@param hostName
@throws Exception | [
"public static void enableHost(String hostName) throws Exception {\n Registry myRegistry = LocateRegistry.getRegistry(\"127.0.0.1\", port);\n com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);\n\n impl.enableHost(hostName);\n }"
] | [
"void updateFromResponseOnPutPatch(Response<ResponseBody> response) throws CloudException, IOException {\n String responseContent = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n\n if (responseContent == null || responseContent.isEmpty()) {\n throw new CloudException(\"polling response does not contain a valid body\", response);\n }\n\n PollingResource resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n final int statusCode = response.code();\n if (resource != null && resource.properties != null && resource.properties.provisioningState != null) {\n this.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n this.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n }\n\n CloudError error = new CloudError();\n this.withErrorBody(error);\n error.withCode(this.status());\n error.withMessage(\"Long running operation failed\");\n this.withResponse(response);\n this.withResource(serializerAdapter.<T>deserialize(responseContent, resourceType));\n }",
"public static base_response unset(nitro_service client, nsdiameter resource, String[] args) throws Exception{\n\t\tnsdiameter unsetresource = new nsdiameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static CmsUUID readId(JSONObject obj, String key) {\n\n String strValue = obj.optString(key);\n if (!CmsUUID.isValidUUID(strValue)) {\n return null;\n }\n return new CmsUUID(strValue);\n }",
"protected synchronized void streamingSlopPut(ByteArray key,\n Versioned<byte[]> value,\n String storeName,\n int failedNodeId) throws IOException {\n\n Slop slop = new Slop(storeName,\n Slop.Operation.PUT,\n key,\n value.getValue(),\n null,\n failedNodeId,\n new Date());\n\n ByteArray slopKey = slop.makeKey();\n Versioned<byte[]> slopValue = new Versioned<byte[]>(slopSerializer.toBytes(slop),\n value.getVersion());\n\n Node failedNode = adminClient.getAdminClientCluster().getNodeById(failedNodeId);\n HandoffToAnyStrategy slopRoutingStrategy = new HandoffToAnyStrategy(adminClient.getAdminClientCluster(),\n true,\n failedNode.getZoneId());\n // node Id which will receive the slop\n int slopDestination = slopRoutingStrategy.routeHint(failedNode).get(0).getId();\n\n VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder()\n .setKey(ProtoUtils.encodeBytes(slopKey))\n .setVersioned(ProtoUtils.encodeVersioned(slopValue))\n .build();\n\n VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder()\n .setStore(SLOP_STORE)\n .setPartitionEntry(partitionEntry);\n\n DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair<String, Integer>(SLOP_STORE,\n slopDestination));\n\n if(nodeIdStoreInitialized.get(new Pair<String, Integer>(SLOP_STORE, slopDestination))) {\n ProtoUtils.writeMessage(outputStream, updateRequest.build());\n } else {\n ProtoUtils.writeMessage(outputStream,\n VAdminProto.VoldemortAdminRequest.newBuilder()\n .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES)\n .setUpdatePartitionEntries(updateRequest)\n .build());\n outputStream.flush();\n nodeIdStoreInitialized.put(new Pair<String, Integer>(SLOP_STORE, slopDestination), true);\n\n }\n\n throttler.maybeThrottle(1);\n\n }",
"@Override\n\tpublic String toNormalizedString() {\n\t\tString result = normalizedString;\n\t\tif(result == null) {\n\t\t\tnormalizedString = result = toNormalizedString(false);\n\t\t}\n\t\treturn result;\n\t}",
"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 }",
"public static <T extends Comparable<T>> int compareLists(List<T> list1, List<T> list2) {\r\n if (list1 == null && list2 == null)\r\n return 0;\r\n if (list1 == null || list2 == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n int size1 = list1.size();\r\n int size2 = list2.size();\r\n int size = Math.min(size1, size2);\r\n for (int i = 0; i < size; i++) {\r\n int c = list1.get(i).compareTo(list2.get(i));\r\n if (c != 0)\r\n return c;\r\n }\r\n if (size1 < size2)\r\n return -1;\r\n if (size1 > size2)\r\n return 1;\r\n return 0;\r\n }",
"public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }",
"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}"
] |
Transits a float property from the start value to the end value.
@param propertyId
@param vals
@return self | [
"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 static boolean changeHost(String hostName,\n boolean enable,\n boolean disable,\n boolean remove,\n boolean isEnabled,\n boolean exists) throws Exception {\n\n // Open the file that is the first\n // command line parameter\n File hostsFile = new File(\"/etc/hosts\");\n FileInputStream fstream = new FileInputStream(\"/etc/hosts\");\n\n File outFile = null;\n BufferedWriter bw = null;\n // only do file output for destructive operations\n if (!exists && !isEnabled) {\n outFile = File.createTempFile(\"HostsEdit\", \".tmp\");\n bw = new BufferedWriter(new FileWriter(outFile));\n System.out.println(\"File name: \" + outFile.getPath());\n }\n\n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n String strLine;\n boolean foundHost = false;\n boolean hostEnabled = false;\n\n\t\t/*\n * Group 1 - possible commented out host entry\n\t\t * Group 2 - destination address\n\t\t * Group 3 - host name\n\t\t * Group 4 - everything else\n\t\t */\n Pattern pattern = Pattern.compile(\"\\\\s*(#?)\\\\s*([^\\\\s]+)\\\\s*([^\\\\s]+)(.*)\");\n while ((strLine = br.readLine()) != null) {\n\n Matcher matcher = pattern.matcher(strLine);\n\n // if there is a match to the pattern and the host name is the same as the one we want to set\n if (matcher.find() &&\n matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {\n foundHost = true;\n if (remove) {\n // skip this line altogether\n continue;\n } else if (enable) {\n // we will disregard group 2 and just set it to 127.0.0.1\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + matcher.group(3) + matcher.group(4));\n } else if (disable) {\n if (!exists && !isEnabled)\n bw.write(\"# \" + matcher.group(2) + \" \" + matcher.group(3) + matcher.group(4));\n } else if (isEnabled && matcher.group(1).compareTo(\"\") == 0) {\n // host exists and there is no # before it\n hostEnabled = true;\n }\n } else {\n // just write the line back out\n if (!exists && !isEnabled)\n bw.write(strLine);\n }\n\n if (!exists && !isEnabled)\n bw.write('\\n');\n }\n\n // if we didn't find the host in the file but need to enable it\n if (!foundHost && enable) {\n // write a new host entry\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + hostName + '\\n');\n }\n // Close the input stream\n in.close();\n\n if (!exists && !isEnabled) {\n bw.close();\n outFile.renameTo(hostsFile);\n }\n\n // return false if the host wasn't found\n if (exists && !foundHost)\n return false;\n\n // return false if the host wasn't enabled\n if (isEnabled && !hostEnabled)\n return false;\n\n return true;\n }",
"public static Class<?> loadClass(String className, ClassLoader cl) {\n try {\n return Class.forName(className, false, cl);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"private String GCMGetFreshToken(final String senderID) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Requesting a GCM token for Sender ID - \" + senderID);\n String token = null;\n try {\n token = InstanceID.getInstance(context)\n .getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);\n getConfigLogger().info(getAccountId(), \"GCM token : \" + token);\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"GcmManager: Error requesting GCM token\", t);\n }\n return token;\n }",
"public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }",
"public ItemRequest<Webhook> deleteById(String webhook) {\n \n String path = String.format(\"/webhooks/%s\", webhook);\n return new ItemRequest<Webhook>(this, Webhook.class, path, \"DELETE\");\n }",
"public Headers toHeaders() {\n Headers headers = new Headers();\n if (!getMatch().isEmpty()) {\n headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch())));\n }\n if (!getNoneMatch().isEmpty()) {\n headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch())));\n }\n if (modifiedSince.isPresent()) {\n headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get()));\n }\n if (unModifiedSince.isPresent()) {\n headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get()));\n }\n\n return headers;\n }",
"void processDumpFile(MwDumpFile dumpFile,\n\t\t\tMwDumpFileProcessor dumpFileProcessor) {\n\t\ttry (InputStream inputStream = dumpFile.getDumpFileStream()) {\n\t\t\tdumpFileProcessor.processDumpFileContents(inputStream, dumpFile);\n\t\t} catch (FileAlreadyExistsException e) {\n\t\t\tlogger.error(\"Dump file \"\n\t\t\t\t\t+ dumpFile.toString()\n\t\t\t\t\t+ \" could not be processed since file \"\n\t\t\t\t\t+ e.getFile()\n\t\t\t\t\t+ \" already exists. Try deleting the file or dumpfile directory to attempt a new download.\");\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"Dump file \" + dumpFile.toString()\n\t\t\t\t\t+ \" could not be processed: \" + e.toString());\n\t\t}\n\t}",
"public static String toSafeFileName(String name) {\n int size = name.length();\n StringBuilder builder = new StringBuilder(size * 2);\n for (int i = 0; i < size; i++) {\n char c = name.charAt(i);\n boolean valid = c >= 'a' && c <= 'z';\n valid = valid || (c >= 'A' && c <= 'Z');\n valid = valid || (c >= '0' && c <= '9');\n valid = valid || (c == '_') || (c == '-') || (c == '.');\n\n if (valid) {\n builder.append(c);\n } else {\n // Encode the character using hex notation\n builder.append('x');\n builder.append(Integer.toHexString(i));\n }\n }\n return builder.toString();\n }",
"private List<TokenStream> collectTokenStreams(TokenStream stream) {\n \n // walk through the token stream and build a collection \n // of sub token streams that represent possible date locations\n List<Token> currentGroup = null;\n List<List<Token>> groups = new ArrayList<List<Token>>();\n Token currentToken;\n int currentTokenType;\n StringBuilder tokenString = new StringBuilder();\n while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) {\n currentTokenType = currentToken.getType();\n tokenString.append(DateParser.tokenNames[currentTokenType]).append(\" \");\n\n // we're currently NOT collecting for a possible date group\n if(currentGroup == null) {\n // skip over white space and known tokens that cannot be the start of a date\n if(currentTokenType != DateLexer.WHITE_SPACE &&\n DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) {\n\n currentGroup = new ArrayList<Token>();\n currentGroup.add(currentToken);\n }\n }\n\n // we're currently collecting\n else {\n // preserve white space\n if(currentTokenType == DateLexer.WHITE_SPACE) {\n currentGroup.add(currentToken);\n }\n\n else {\n // if this is an unknown token, we'll close out the current group\n if(currentTokenType == DateLexer.UNKNOWN) {\n addGroup(currentGroup, groups);\n currentGroup = null;\n }\n // otherwise, the token is known and we're currently collecting for\n // a group, so we'll add it to the current group\n else {\n currentGroup.add(currentToken);\n }\n }\n }\n }\n\n if(currentGroup != null) {\n addGroup(currentGroup, groups);\n }\n \n _logger.info(\"STREAM: \" + tokenString.toString());\n List<TokenStream> streams = new ArrayList<TokenStream>();\n for(List<Token> group:groups) {\n if(!group.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"GROUP: \");\n for (Token token : group) {\n builder.append(DateParser.tokenNames[token.getType()]).append(\" \");\n }\n _logger.info(builder.toString());\n\n streams.add(new CommonTokenStream(new NattyTokenSource(group)));\n }\n }\n\n return streams;\n }"
] |
Determine the color to use to draw a cue list entry. Hot cues are green, ordinary memory points are red,
and loops are orange.
@param entry the entry being drawn
@return the color with which it should be represented. | [
"public static Color cueColor(CueList.Entry entry) {\n if (entry.hotCueNumber > 0) {\n return Color.GREEN;\n }\n if (entry.isLoop) {\n return Color.ORANGE;\n }\n return Color.RED;\n }"
] | [
"public Set<Class> entityClasses() {\n EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id);\n return null == repo ? C.<Class>set() : repo.entityClasses();\n }",
"public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\n }",
"public void setCanvasWidthHeight(int width, int height) {\n hudWidth = width;\n hudHeight = height;\n HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888);\n canvas = new Canvas(HUD);\n texture = null;\n }",
"private void saveToBundleDescriptor() throws CmsException {\n\n if (null != m_descFile) {\n m_removeDescriptorOnCancel = false;\n updateBundleDescriptorContent();\n m_descFile.getFile().setContents(m_descContent.marshal());\n m_cms.writeFile(m_descFile.getFile());\n }\n }",
"public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }",
"public static dnssuffix get(nitro_service service, String Dnssuffix) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tobj.set_Dnssuffix(Dnssuffix);\n\t\tdnssuffix response = (dnssuffix) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public boolean doSyncPass() {\n if (!this.isConfigured || !syncLock.tryLock()) {\n return false;\n }\n try {\n if (logicalT == Long.MAX_VALUE) {\n if (logger.isInfoEnabled()) {\n logger.info(\"reached max logical time; resetting back to 0\");\n }\n logicalT = 0;\n }\n logicalT++;\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass START\",\n logicalT));\n }\n if (networkMonitor == null || !networkMonitor.isConnected()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Network disconnected\",\n logicalT));\n }\n return false;\n }\n if (authMonitor == null || !authMonitor.tryIsLoggedIn()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Logged out\",\n logicalT));\n }\n return false;\n }\n\n syncRemoteToLocal();\n syncLocalToRemote();\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END\",\n logicalT));\n }\n } catch (InterruptedException e) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass INTERRUPTED\",\n logicalT));\n }\n return false;\n } finally {\n syncLock.unlock();\n }\n return true;\n }",
"public void startup() throws InterruptedException {\n final int maxCacheConnectionPerThread = serverConfig.getMaxConnections() / processors.length;\n logger.debug(\"start {} Processor threads\",processors.length);\n for (int i = 0; i < processors.length; i++) {\n processors[i] = new Processor(handlerFactory, stats, maxRequestSize, maxCacheConnectionPerThread);\n Utils.newThread(\"jafka-processor-\" + i, processors[i], false).start();\n }\n Utils.newThread(\"jafka-acceptor\", acceptor, false).start();\n acceptor.awaitStartup();\n }",
"public static appfwpolicy_stats[] get(nitro_service service) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tappfwpolicy_stats[] response = (appfwpolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}"
] |
Generate a sql where-clause matching the contraints defined by the array of fields
@param columns array containing all columns used in WHERE clause | [
"protected void appendWhereClause(StringBuffer stmt, Object[] columns)\r\n {\r\n stmt.append(\" WHERE \");\r\n\r\n for (int i = 0; i < columns.length; i++)\r\n {\r\n if (i > 0)\r\n {\r\n stmt.append(\" AND \");\r\n }\r\n stmt.append(columns[i]);\r\n stmt.append(\"=?\");\r\n }\r\n }"
] | [
"public static void setCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)\r\n throws PBFactoryException\r\n {\r\n HashMap map = (HashMap) currentBrokerMap.get();\r\n WeakHashMap set = null;\r\n if(map == null)\r\n {\r\n map = new HashMap();\r\n currentBrokerMap.set(map);\r\n\r\n synchronized(lock) {\r\n loadedHMs.add(map);\r\n }\r\n }\r\n else\r\n {\r\n set = (WeakHashMap) map.get(key);\r\n }\r\n\r\n if(set == null)\r\n {\r\n // We emulate weak HashSet using WeakHashMap\r\n set = new WeakHashMap();\r\n map.put(key, set);\r\n }\r\n set.put(broker, null);\r\n }",
"protected static void statistics(int from, int to) {\r\n\t// check that primes contain no accidental errors\r\n\tfor (int i=0; i<primeCapacities.length-1; i++) {\r\n\t\tif (primeCapacities[i] >= primeCapacities[i+1]) throw new RuntimeException(\"primes are unsorted or contain duplicates; detected at \"+i+\"@\"+primeCapacities[i]);\r\n\t}\r\n\t\r\n\tdouble accDeviation = 0.0;\r\n\tdouble maxDeviation = - 1.0;\r\n\r\n\tfor (int i=from; i<=to; i++) {\r\n\t\tint primeCapacity = nextPrime(i);\r\n\t\t//System.out.println(primeCapacity);\r\n\t\tdouble deviation = (primeCapacity - i) / (double)i;\r\n\t\t\r\n\t\tif (deviation > maxDeviation) {\r\n\t\t\tmaxDeviation = deviation;\r\n\t\t\tSystem.out.println(\"new maxdev @\"+i+\"@dev=\"+maxDeviation);\r\n\t\t}\r\n\r\n\t\taccDeviation += deviation;\r\n\t}\r\n\tlong width = 1 + (long)to - (long)from;\r\n\t\r\n\tdouble meanDeviation = accDeviation/width;\r\n\tSystem.out.println(\"Statistics for [\"+ from + \",\"+to+\"] are as follows\");\r\n\tSystem.out.println(\"meanDeviation = \"+(float)meanDeviation*100+\" %\");\r\n\tSystem.out.println(\"maxDeviation = \"+(float)maxDeviation*100+\" %\");\r\n}",
"@Inline(value = \"$1.putAll($2)\", statementExpression = true)\n\tpublic static <K, V> void operator_add(Map<K, V> outputMap, Map<? extends K, ? extends V> inputMap) {\n\t\toutputMap.putAll(inputMap);\n\t}",
"public static base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup addresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new clusternodegroup();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void increaseBeliefCount(String bName) {\n Object belief = this.getBelief(bName);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n this.setBelief(bName, count + 1);\n }",
"private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap();\n for(Integer nodeId: cluster.getNodeIds()) {\n nodeIdToZonePrimaryCount.put(nodeId,\n storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size());\n }\n\n return nodeIdToZonePrimaryCount;\n }",
"public static boolean intersectsPointWithRectF(RectF _Rect, float _X, float _Y) {\n return _X > _Rect.left && _X < _Rect.right && _Y > _Rect.top && _Y < _Rect.bottom;\n }",
"public List<TableProperty> getEditableColumns(CmsMessageBundleEditorTypes.EditMode mode) {\n\n return m_editorState.get(mode).getEditableColumns();\n }",
"public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }"
] |
Use this API to add systemuser resources. | [
"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}"
] | [
"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 }",
"protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) {\n Session sess = this.getSession();\n if (sess != null) {\n String json;\n try {\n json = this.mapper.writeValueAsString(objectToSend);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"Failed to serialize object\", e);\n }\n sess.getRemote().sendString(json, cb);\n }\n }",
"protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }",
"@Override\n public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {\n return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);\n }",
"public static base_response disable(nitro_service client, String name) throws Exception {\n\t\tvserver disableresource = new vserver();\n\t\tdisableresource.name = name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"private void internalCleanup()\r\n {\r\n if(hasBroker())\r\n {\r\n PersistenceBroker broker = getBroker();\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Do internal cleanup and close the internal used connection without\" +\r\n \" closing the used broker\");\r\n }\r\n ConnectionManagerIF cm = broker.serviceConnectionManager();\r\n if(cm.isInLocalTransaction())\r\n {\r\n /*\r\n arminw:\r\n in managed environment this call will be ignored because, the JTA transaction\r\n manager control the connection status. But to make connectionManager happy we\r\n have to complete the \"local tx\" of the connectionManager before release the\r\n connection\r\n */\r\n cm.localCommit();\r\n }\r\n cm.releaseConnection();\r\n }\r\n }",
"private Object mapToId(Object tmp) {\n if (tmp instanceof Double) {\n return new Integer(((Double)tmp).intValue());\n } else {\n return Context.toString(tmp);\n }\n }",
"private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)\r\n {\r\n m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);\r\n }",
"public void start() {\n nsLock.writeLock().lock();\n try {\n if (runnerThread != null) {\n return;\n }\n runnerThread =\n new Thread(new NamespaceChangeStreamRunner(\n new WeakReference<>(this), networkMonitor, logger));\n runnerThread.start();\n } finally {\n nsLock.writeLock().unlock();\n }\n }"
] |
Use this API to update cmpparameter. | [
"public static base_response update(nitro_service client, cmpparameter resource) throws Exception {\n\t\tcmpparameter updateresource = new cmpparameter();\n\t\tupdateresource.cmplevel = resource.cmplevel;\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.servercmp = resource.servercmp;\n\t\tupdateresource.heurexpiry = resource.heurexpiry;\n\t\tupdateresource.heurexpirythres = resource.heurexpirythres;\n\t\tupdateresource.heurexpiryhistwt = resource.heurexpiryhistwt;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.cmpbypasspct = resource.cmpbypasspct;\n\t\tupdateresource.cmponpush = resource.cmponpush;\n\t\tupdateresource.policytype = resource.policytype;\n\t\tupdateresource.addvaryheader = resource.addvaryheader;\n\t\tupdateresource.externalcache = resource.externalcache;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"public void setValue(Vector3f pos) {\n mX = pos.x;\n mY = pos.y;\n mZ = pos.z;\n }",
"public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);\n\t\tDatabaseResults results = null;\n\t\ttry {\n\t\t\tresults = compiledStatement.runQuery(null);\n\t\t\tif (results.first()) {\n\t\t\t\treturn results.getLong(0);\n\t\t\t} else {\n\t\t\t\tthrow new SQLException(\"No result found in queryForLong: \" + preparedStmt.getStatement());\n\t\t\t}\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(results, \"results\");\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}",
"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 }",
"@Override\n public final double getDouble(final String key) {\n Double result = optDouble(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public Stream<ChangeEvent<DocumentT>> watch(final BsonValue... ids)\n throws InterruptedException, IOException {\n return operations.watch(\n new HashSet<>(Arrays.asList(ids)),\n false,\n documentClass\n ).execute(service);\n }",
"public BoxGroupMembership.Info addMembership(BoxUser user, Role role) {\n BoxAPIConnection api = this.getAPI();\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"user\", new JsonObject().add(\"id\", user.getID()));\n requestJSON.add(\"group\", new JsonObject().add(\"id\", this.getID()));\n if (role != null) {\n requestJSON.add(\"role\", role.toJSONString());\n }\n\n URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get(\"id\").asString());\n return membership.new Info(responseJSON);\n }",
"private static int nextIndex( String description, int defaultIndex ) {\n\n Pattern startsWithNumber = Pattern.compile( \"(\\\\d+).*\" );\n Matcher matcher = startsWithNumber.matcher( description );\n if( matcher.matches() ) {\n return Integer.parseInt( matcher.group( 1 ) ) - 1;\n }\n\n return defaultIndex;\n }",
"public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }",
"public <T> void cleanNullReferencesAll() {\n\t\tfor (Map<Object, Reference<Object>> objectMap : classMaps.values()) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}"
] |
Prepares transformation interceptors for a client.
@param clientConfig the client configuration
@param newClient indicates if it is a new/updated client | [
"private void addTransformInterceptors(List<Interceptor<?>> inInterceptors,\n List<Interceptor<?>> outInterceptors,\n boolean newClient) {\n \n // The old service expects the Customer data be qualified with\n // the 'http://customer/v1' namespace.\n \n // The new service expects the Customer data be qualified with\n // the 'http://customer/v2' namespace.\n \n // If it is an old client talking to the new service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v1' qualified data be transformed into\n // 'http://customer/v2' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v2' qualified response data be transformed into\n // 'http://customer/v1' qualified data.\n \n // If it is a new client talking to the old service then:\n // - the out transformation interceptor is configured for \n // 'http://customer/v2' qualified data be transformed into\n // 'http://customer/v1' qualified data.\n // - the in transformation interceptor is configured for \n // 'http://customer/v1' qualified response data be transformed into\n // 'http://customer/v2' qualified data.\n // - new Customer type also introduces a briefDescription property\n // which needs to be dropped for the old service validation to succeed\n \n \n // this configuration can be provided externally\n \n Map<String, String> newToOldTransformMap = new HashMap<String, String>();\n newToOldTransformMap.put(\"{http://customer/v2}*\", \"{http://customer/v1}*\");\n Map<String, String> oldToNewTransformMap = \n Collections.singletonMap(\"{http://customer/v1}*\", \"{http://customer/v2}*\");\n \n TransformOutInterceptor outTransform = new TransformOutInterceptor();\n outTransform.setOutTransformElements(newClient ? newToOldTransformMap \n : oldToNewTransformMap);\n \n if (newClient) {\n newToOldTransformMap.put(\"{http://customer/v2}briefDescription\", \"\");\n //outTransform.setOutDropElements(\n // Collections.singletonList(\"{http://customer/v2}briefDescription\")); \n }\n \n TransformInInterceptor inTransform = new TransformInInterceptor();\n inTransform.setInTransformElements(newClient ? oldToNewTransformMap \n : newToOldTransformMap);\n\n inInterceptors.add(inTransform);\n outInterceptors.add(outTransform);\n \n \n }"
] | [
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher addBooleanFilter(String attribute, Boolean value) {\n booleanFilterMap.put(attribute, value);\n rebuildQueryFacetFilters();\n return this;\n }",
"public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }",
"public static appfwhtmlerrorpage get(nitro_service service, options option) throws Exception{\n\t\tappfwhtmlerrorpage obj = new appfwhtmlerrorpage();\n\t\tappfwhtmlerrorpage[] response = (appfwhtmlerrorpage[])obj.get_resources(service,option);\n\t\treturn response[0];\n\t}",
"public static void doEnqueue(final Jedis jedis, final String namespace, final String queue, final String jobJson) {\n jedis.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n jedis.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }",
"public static appfwprofile_cookieconsistency_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_cookieconsistency_binding obj = new appfwprofile_cookieconsistency_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_cookieconsistency_binding response[] = (appfwprofile_cookieconsistency_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static float gain(float a, float b) {\n/*\n\t\tfloat p = (float)Math.log(1.0 - b) / (float)Math.log(0.5);\n\n\t\tif (a < .001)\n\t\t\treturn 0.0f;\n\t\telse if (a > .999)\n\t\t\treturn 1.0f;\n\t\tif (a < 0.5)\n\t\t\treturn (float)Math.pow(2 * a, p) / 2;\n\t\telse\n\t\t\treturn 1.0f - (float)Math.pow(2 * (1. - a), p) / 2;\n*/\n\t\tfloat c = (1.0f/b-2.0f) * (1.0f-2.0f*a);\n\t\tif (a < 0.5)\n\t\t\treturn a/(c+1.0f);\n\t\telse\n\t\t\treturn (c-a)/(c-1.0f);\n\t}",
"public boolean hasMoreElements()\r\n {\r\n try\r\n {\r\n if (!hasCalledCheck)\r\n {\r\n hasCalledCheck = true;\r\n hasNext = resultSetAndStatment.m_rs.next();\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n LoggerFactory.getDefaultLogger().error(e);\r\n //releaseDbResources();\r\n hasNext = false;\r\n }\r\n finally\r\n {\r\n if(!hasNext)\r\n {\r\n releaseDbResources();\r\n }\r\n }\r\n return hasNext;\r\n }",
"public List<TimephasedCost> getTimephasedActualCost()\n {\n if (m_timephasedActualCost == null)\n {\n Resource r = getResource();\n ResourceType type = r != null ? r.getType() : ResourceType.WORK;\n\n //for Work and Material resources, we will calculate in the normal way\n if (type != ResourceType.COST)\n {\n if (m_timephasedActualWork != null && m_timephasedActualWork.hasData())\n {\n if (hasMultipleCostRates())\n {\n m_timephasedActualCost = getTimephasedCostMultipleRates(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n else\n {\n m_timephasedActualCost = getTimephasedCostSingleRate(getTimephasedActualWork(), getTimephasedActualOvertimeWork());\n }\n }\n }\n else\n {\n m_timephasedActualCost = getTimephasedActualCostFixedAmount();\n }\n\n }\n\n return m_timephasedActualCost;\n }",
"@RequestMapping(value = \"api/edit/server\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerRedirect addRedirectToProfile(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier,\n @RequestParam(value = \"srcUrl\", required = true) String srcUrl,\n @RequestParam(value = \"destUrl\", required = true) String destUrl,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"hostHeader\", required = false) String hostHeader) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n int redirectId = ServerRedirectService.getInstance().addServerRedirectToProfile(\"\", srcUrl, destUrl, hostHeader,\n profileId, clientId);\n return ServerRedirectService.getInstance().getRedirect(redirectId);\n }"
] |
Get a reader implementation class to perform API calls with while specifying
an explicit page size for paginated API calls. This gets translated to a per_page=
parameter on API requests. Note that Canvas does not guarantee it will honor this page size request.
There is an explicit maximum page size on the server side which could change. The default page size
is 10 which can be limiting when, for example, trying to get all users in a 800 person course.
@param type Interface type you wish to get an implementation for
@param oauthToken An OAuth token to use for authentication when making API calls
@param paginationPageSize Requested pagination page size
@param <T> The reader type to request an instance of
@return An instance of the requested reader class | [
"public <T extends CanvasReader> T getReader(Class<T> type, OauthToken oauthToken, Integer paginationPageSize) {\n LOG.debug(\"Factory call to instantiate class: \" + type.getName());\n RestClient restClient = new RefreshingRestClient();\n\n @SuppressWarnings(\"unchecked\")\n Class<T> concreteClass = (Class<T>)readerMap.get(type);\n\n if (concreteClass == null) {\n throw new UnsupportedOperationException(\"No implementation for requested interface found: \" + type.getName());\n }\n\n LOG.debug(\"got class: \" + concreteClass);\n try {\n Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class,\n OauthToken.class, RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);\n return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,\n connectTimeout, readTimeout, paginationPageSize, false);\n } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {\n throw new UnsupportedOperationException(\"Unknown error instantiating the concrete API class: \" + type.getName(), e);\n }\n }"
] | [
"private void readAvailabilityTable(Resource resource, AvailabilityPeriods periods)\n {\n if (periods != null)\n {\n AvailabilityTable table = resource.getAvailability();\n List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();\n for (AvailabilityPeriod period : list)\n {\n Date start = period.getAvailableFrom();\n Date end = period.getAvailableTo();\n Number units = DatatypeConverter.parseUnits(period.getAvailableUnits());\n Availability availability = new Availability(start, end, units);\n table.add(availability);\n }\n Collections.sort(table);\n }\n }",
"public void initialize() {\n if (isClosed.get()) {\n logger.info(\"Initialing Parallel Client Resources: actor system, HttpClientStore, Task Manager ....\");\n ActorConfig.createAndGetActorSystem();\n httpClientStore.init();\n tcpSshPingResourceStore.init();\n isClosed.set(false);\n logger.info(\"Parallel Client Resources has been initialized.\");\n } else {\n logger.debug(\"NO OP. Parallel Client Resources has already been initialized.\");\n }\n }",
"public int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\n }",
"public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {\n return getRetentions(api, new QueryFilter(), fields);\n }",
"public void validate(final List<Throwable> validationErrors) {\n if (this.matchers == null) {\n validationErrors.add(new IllegalArgumentException(\n \"Matchers cannot be null. There should be at least a !acceptAll matcher\"));\n }\n if (this.matchers != null && this.matchers.isEmpty()) {\n validationErrors.add(new IllegalArgumentException(\n \"There are no url matchers defined. There should be at least a \" +\n \"!acceptAll matcher\"));\n }\n }",
"protected AbstractBeanDeployer<E> deploySpecialized() {\n // ensure that all decorators are initialized before initializing\n // the rest of the beans\n for (DecoratorImpl<?> bean : getEnvironment().getDecorators()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addDecorator(bean);\n BootstrapLogger.LOG.foundDecorator(bean);\n }\n for (InterceptorImpl<?> bean : getEnvironment().getInterceptors()) {\n bean.initialize(getEnvironment());\n containerLifecycleEvents.fireProcessBean(getManager(), bean);\n manager.addInterceptor(bean);\n BootstrapLogger.LOG.foundInterceptor(bean);\n }\n return this;\n }",
"public void onAttach(GVRSceneObject sceneObj)\n {\n super.onAttach(sceneObj);\n GVRComponent comp = getComponent(GVRRenderData.getComponentType());\n\n if (comp == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n\n GVRMesh mesh = ((GVRRenderData) comp).getMesh();\n if (mesh == null)\n {\n throw new IllegalStateException(\"Cannot attach a morph to a scene object without a base mesh\");\n }\n GVRShaderData mtl = getMaterial();\n\n if ((mtl == null) ||\n !mtl.getTextureDescriptor().contains(\"blendshapeTexture\"))\n {\n throw new IllegalStateException(\"Scene object shader does not support morphing\");\n }\n copyBaseShape(mesh.getVertexBuffer());\n mtl.setInt(\"u_numblendshapes\", mNumBlendShapes);\n mtl.setFloatArray(\"u_blendweights\", mWeights);\n }",
"@Override\n\tpublic List<Object> loadEntitiesFromTuples(SharedSessionContractImplementor session, LockOptions lockOptions, OgmLoadingContext ogmContext) {\n\t\treturn loadEntity( null, null, session, lockOptions, ogmContext );\n\t}",
"public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }"
] |
Removes an accessory from being handled or advertised by this root. Any existing Homekit
connections will be terminated to allow the clients to reconnect and see the updated accessory
list.
@param accessory accessory to cease advertising and handling | [
"public void removeAccessory(HomekitAccessory accessory) {\n this.registry.remove(accessory);\n logger.info(\"Removed accessory \" + accessory.getLabel());\n if (started) {\n registry.reset();\n webHandler.resetConnections();\n }\n }"
] | [
"@Override\n public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {\n super.startScenario( description );\n return this;\n\n }",
"public static DMatrixRBlock initializeQ(DMatrixRBlock Q,\n int numRows , int numCols , int blockLength ,\n boolean compact) {\n int minLength = Math.min(numRows,numCols);\n if( compact ) {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,minLength,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != minLength ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n } else {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,numRows,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != numRows ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n }\n return Q;\n }",
"public static boolean invertSPD(DMatrixRMaj mat, DMatrixRMaj result ) {\n if( mat.numRows != mat.numCols )\n throw new IllegalArgumentException(\"Must be a square matrix\");\n result.reshape(mat.numRows,mat.numRows);\n\n if( mat.numRows <= UnrolledCholesky_DDRM.MAX ) {\n // L*L' = A\n if( !UnrolledCholesky_DDRM.lower(mat,result) )\n return false;\n // L = inv(L)\n TriangularSolver_DDRM.invertLower(result.data,result.numCols);\n // inv(A) = inv(L')*inv(L)\n SpecializedOps_DDRM.multLowerTranA(result);\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.chol(mat.numCols);\n if( solver.modifiesA() )\n mat = mat.copy();\n\n if( !solver.setA(mat))\n return false;\n solver.invert(result);\n }\n\n return true;\n }",
"public void addLicense(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n // Try to find an existing license that match the new one\n final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);\n final DbLicense license = licenseHandler.resolve(licenseId);\n\n // If there is no existing license that match this one let's use the provided value but\n // only if the artifact has no license yet. Otherwise it could mean that users has already\n // identify the license manually.\n if(license == null){\n if(dbArtifact.getLicenses().isEmpty()){\n LOG.warn(\"Add reference to a non existing license called \" + licenseId + \" in artifact \" + dbArtifact.getGavc());\n repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);\n }\n }\n // Add only if the license is not already referenced\n else if(!dbArtifact.getLicenses().contains(license.getName())){\n repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());\n }\n }",
"public void executeDelete(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeDelete: \" + obj);\r\n }\r\n\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getDeleteStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getDeleteStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"JdbcAccessImpl: getDeleteStatement returned a null statement\");\r\n }\r\n\r\n sm.bindDelete(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeDelete: \" + stmt);\r\n\r\n // @todo: clearify semantics\r\n // thma: the following check is not secure. The object could be deleted *or* changed.\r\n // if it was deleted it makes no sense to throw an OL exception.\r\n // does is make sense to throw an OL exception if the object was changed?\r\n if (stmt.executeUpdate() == 0 && cld.isLocking()) //BRJ\r\n {\r\n /**\r\n * Kuali Foundation modification -- 6/19/2009\r\n */\r\n \tString objToString = \"\";\r\n \ttry {\r\n \t\tobjToString = obj.toString();\r\n \t} catch (Exception ex) {}\r\n throw new OptimisticLockException(\"Object has been modified or deleted by someone else: \" + objToString, obj);\r\n /**\r\n * End of Kuali Foundation modification\r\n */\r\n }\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getDeleteProcedure(), obj, stmt);\r\n }\r\n catch (OptimisticLockException e)\r\n {\r\n // Don't log as error\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"OptimisticLockException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of delete: \"\r\n + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedDeleteStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }",
"public static int[] Unique(int[] values) {\r\n HashSet<Integer> lst = new HashSet<Integer>();\r\n for (int i = 0; i < values.length; i++) {\r\n lst.add(values[i]);\r\n }\r\n\r\n int[] v = new int[lst.size()];\r\n Iterator<Integer> it = lst.iterator();\r\n for (int i = 0; i < v.length; i++) {\r\n v[i] = it.next();\r\n }\r\n\r\n return v;\r\n }",
"@Pure\n\tpublic static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function0<RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply() {\n\t\t\t\treturn function.apply(argument);\n\t\t\t}\n\t\t};\n\t}",
"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}",
"public static base_response delete(nitro_service client, nssimpleacl resource) throws Exception {\n\t\tnssimpleacl deleteresource = new nssimpleacl();\n\t\tdeleteresource.aclname = resource.aclname;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] |
This method retrieves a String of the specified type,
belonging to the item with the specified unique ID.
@param id unique ID of entity to which this data belongs
@param type data type identifier
@return string containing required data | [
"public String getUnicodeString(Integer id, Integer type)\n {\n return (getUnicodeString(m_meta.getOffset(id, type)));\n }"
] | [
"private void deleteLinks(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {\n final PersistentEntityId id = entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final LinksTable links = getLinksTable(txn, entityTypeId);\n final IntHashSet deletedLinks = new IntHashSet();\n try (Cursor cursor = links.getFirstIndexCursor(envTxn)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, 0))) != null;\n success; success = cursor.getNext()) {\n final ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final ByteIterable valueEntry = cursor.getValue();\n if (links.delete(envTxn, keyEntry, valueEntry)) {\n int linkId = key.getPropertyId();\n if (getLinkName(txn, linkId) != null) {\n deletedLinks.add(linkId);\n final LinkValue linkValue = LinkValue.entryToLinkValue(valueEntry);\n txn.linkDeleted(entity.getId(), (PersistentEntityId) linkValue.getEntityId(), linkValue.getLinkId());\n }\n }\n }\n }\n for (Integer linkId : deletedLinks) {\n links.deleteAllIndex(envTxn, linkId, entityLocalId);\n }\n }",
"public void delete() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }",
"protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}",
"public static final <T> T getSingle( Iterable<T> it ) {\n if( ! it.iterator().hasNext() )\n return null;\n\n final Iterator<T> iterator = it.iterator();\n T o = iterator.next();\n if(iterator.hasNext())\n throw new IllegalStateException(\"Found multiple items in iterator over \" + o.getClass().getName() );\n\n return o;\n }",
"public static dnstxtrec get(nitro_service service, String domain) throws Exception{\n\t\tdnstxtrec obj = new dnstxtrec();\n\t\tobj.set_domain(domain);\n\t\tdnstxtrec response = (dnstxtrec) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void getSingleValue(Method method, Object object, Map<String, String> map)\n {\n Object value;\n try\n {\n value = filterValue(method.invoke(object));\n }\n catch (Exception ex)\n {\n value = ex.toString();\n }\n\n if (value != null)\n {\n map.put(getPropertyName(method), String.valueOf(value));\n }\n }",
"public static void touch(final File folder , final String fileName) throws IOException {\n if(!folder.exists()){\n folder.mkdirs();\n }\n\n final File touchedFile = new File(folder, fileName);\n\n // The JVM will only 'touch' the file if you instantiate a\n // FileOutputStream instance for the file in question.\n // You don't actually write any data to the file through\n // the FileOutputStream. Just instantiate it and close it.\n\n try (\n FileOutputStream doneFOS = new FileOutputStream(touchedFile);\n ) {\n // Touching the file\n }\n catch (FileNotFoundException e) {\n throw new FileNotFoundException(\"Failed to the find file.\" + e);\n }\n }",
"public final String getPath(final String key) {\n StringBuilder result = new StringBuilder();\n addPathTo(result);\n result.append(\".\");\n result.append(getPathElement(key));\n return result.toString();\n }",
"public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }"
] |
Converts an integer into a time format.
@param format integer format value
@return TimeUnit instance | [
"private TimeUnit getFormat(int format)\n {\n TimeUnit result;\n if (format == 0xFFFF)\n {\n result = TimeUnit.HOURS;\n }\n else\n {\n result = MPPUtility.getWorkTimeUnits(format);\n }\n return result;\n }"
] | [
"public boolean isPrivate() {\n\t\t// refer to RFC 1918\n // 10/8 prefix\n // 172.16/12 prefix (172.16.0.0 – 172.31.255.255)\n // 192.168/16 prefix\n\t\tIPv4AddressSegment seg0 = getSegment(0);\n\t\tIPv4AddressSegment seg1 = getSegment(1);\n\t\treturn seg0.matches(10)\n\t\t\t|| seg0.matches(172) && seg1.matchesWithPrefixMask(16, 4)\n\t\t\t|| seg0.matches(192) && seg1.matches(168);\n\t}",
"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 }",
"private void deliverMasterChangedAnnouncement(final DeviceUpdate update) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.masterChanged(update);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master changed announcement to listener\", t);\n }\n }\n }",
"protected Date parseNonNullDate(String str, ParsePosition pos)\n {\n Date result = null;\n for (int index = 0; index < m_formats.length; index++)\n {\n result = m_formats[index].parse(str, pos);\n if (pos.getIndex() != 0)\n {\n break;\n }\n result = null;\n }\n return result;\n }",
"public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }",
"public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\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 void updateIteratorPosition(int length) {\n if(length > 0) {\n //make sure we dont go OB\n if((length + character) > parsedLine.line().length())\n length = parsedLine.line().length() - character;\n\n //move word counter to the correct word\n while(hasNextWord() &&\n (length + character) >= parsedLine.words().get(word).lineIndex() +\n parsedLine.words().get(word).word().length())\n word++;\n\n character = length + character;\n }\n else\n throw new IllegalArgumentException(\"The length given must be > 0 and not exceed the boundary of the line (including the current position)\");\n }",
"public static dbdbprofile[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tdbdbprofile[] response = (dbdbprofile[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}"
] |
Search down all extent classes and return max of all found
PK values. | [
"public static long getMaxId(PersistenceBroker brokerForClass, Class topLevel, FieldDescriptor original) throws PersistenceBrokerException\r\n {\r\n long max = 0;\r\n long tmp;\r\n ClassDescriptor cld = brokerForClass.getClassDescriptor(topLevel);\r\n\r\n // if class is not an interface / not abstract we have to search its directly mapped table\r\n if (!cld.isInterface() && !cld.isAbstract())\r\n {\r\n tmp = getMaxIdForClass(brokerForClass, cld, original);\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n // if class is an extent we have to search through its subclasses\r\n if (cld.isExtent())\r\n {\r\n Vector extentClasses = cld.getExtentClasses();\r\n for (int i = 0; i < extentClasses.size(); i++)\r\n {\r\n Class extentClass = (Class) extentClasses.get(i);\r\n if (cld.getClassOfObject().equals(extentClass))\r\n {\r\n throw new PersistenceBrokerException(\"Circular extent in \" + extentClass +\r\n \", please check the repository\");\r\n }\r\n else\r\n {\r\n // fix by Mark Rowell\r\n // Call recursive\r\n tmp = getMaxId(brokerForClass, extentClass, original);\r\n }\r\n if (tmp > max)\r\n {\r\n max = tmp;\r\n }\r\n }\r\n }\r\n return max;\r\n }"
] | [
"public Set<CoreDocumentSynchronizationConfig> getSynchronizedDocuments(\n final MongoNamespace namespace\n ) {\n this.waitUntilInitialized();\n try {\n ongoingOperationsGroup.enter();\n return this.syncConfig.getSynchronizedDocuments(namespace);\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"public static nsconfig get(nitro_service service) throws Exception{\n\t\tnsconfig obj = new nsconfig();\n\t\tnsconfig[] response = (nsconfig[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static void handleDomainOperationResponseStreams(final OperationContext context,\n final ModelNode responseNode,\n final List<OperationResponse.StreamEntry> streams) {\n\n if (responseNode.hasDefined(RESPONSE_HEADERS)) {\n ModelNode responseHeaders = responseNode.get(RESPONSE_HEADERS);\n // Strip out any stream header as the header created by this process is what counts\n responseHeaders.remove(ATTACHED_STREAMS);\n if (responseHeaders.asInt() == 0) {\n responseNode.remove(RESPONSE_HEADERS);\n }\n }\n\n for (OperationResponse.StreamEntry streamEntry : streams) {\n context.attachResultStream(streamEntry.getUUID(), streamEntry.getMimeType(), streamEntry.getStream());\n }\n }",
"private int calcItemWidth(RecyclerView rvCategories) {\n if (itemWidth == null || itemWidth == 0) {\n for (int i = 0; i < rvCategories.getChildCount(); i++) {\n itemWidth = rvCategories.getChildAt(i).getWidth();\n if (itemWidth != 0) {\n break;\n }\n }\n }\n // in case of call before view was created\n if (itemWidth == null) {\n itemWidth = 0;\n }\n return itemWidth;\n }",
"private void addStatement(RecordImpl record,\n String subject,\n String property,\n String object) {\n Collection<Column> cols = columns.get(property);\n if (cols == null) {\n if (property.equals(RDF_TYPE) && !types.isEmpty())\n addValue(record, subject, property, object);\n return;\n }\n \n for (Column col : cols) {\n String cleaned = object;\n if (col.getCleaner() != null)\n cleaned = col.getCleaner().clean(object);\n if (cleaned != null && !cleaned.equals(\"\"))\n addValue(record, subject, col.getProperty(), cleaned);\n }\n }",
"public static long randomLongBetween(long min, long max) {\n Random rand = new Random();\n return min + (long) (rand.nextDouble() * (max - min));\n }",
"private File decompileType(final DecompilerSettings settings, final WindupMetadataSystem metadataSystem, final String typeName) throws IOException\n {\n log.fine(\"Decompiling \" + typeName);\n\n final TypeReference type;\n\n // Hack to get around classes whose descriptors clash with primitive types.\n if (typeName.length() == 1)\n {\n final MetadataParser parser = new MetadataParser(IMetadataResolver.EMPTY);\n final TypeReference reference = parser.parseTypeDescriptor(typeName);\n type = metadataSystem.resolve(reference);\n }\n else\n type = metadataSystem.lookupType(typeName);\n\n if (type == null)\n {\n log.severe(\"Failed to load class: \" + typeName);\n return null;\n }\n\n final TypeDefinition resolvedType = type.resolve();\n if (resolvedType == null)\n {\n log.severe(\"Failed to resolve type: \" + typeName);\n return null;\n }\n\n boolean nested = resolvedType.isNested() || resolvedType.isAnonymous() || resolvedType.isSynthetic();\n if (!this.procyonConf.isIncludeNested() && nested)\n return null;\n\n settings.setJavaFormattingOptions(new JavaFormattingOptions());\n\n final FileOutputWriter writer = createFileWriter(resolvedType, settings);\n final PlainTextOutput output;\n\n output = new PlainTextOutput(writer);\n output.setUnicodeOutputEnabled(settings.isUnicodeOutputEnabled());\n if (settings.getLanguage() instanceof BytecodeLanguage)\n output.setIndentToken(\" \");\n\n DecompilationOptions options = new DecompilationOptions();\n options.setSettings(settings); // I'm missing why these two classes are split.\n\n // --------- DECOMPILE ---------\n final TypeDecompilationResults results = settings.getLanguage().decompileType(resolvedType, output, options);\n\n writer.flush();\n writer.close();\n\n // If we're writing to a file and we were asked to include line numbers in any way,\n // then reformat the file to include that line number information.\n final List<LineNumberPosition> lineNumberPositions = results.getLineNumberPositions();\n\n if (!this.procyonConf.getLineNumberOptions().isEmpty())\n {\n\n final LineNumberFormatter lineFormatter = new LineNumberFormatter(writer.getFile(), lineNumberPositions,\n this.procyonConf.getLineNumberOptions());\n\n lineFormatter.reformatFile();\n }\n return writer.getFile();\n }",
"public void close()\t{\n\t\tif (watchdog != null) {\n\t\t\twatchdog.cancel();\n\t\t\twatchdog = null;\n\t\t}\n\t\t\n\t\tdisconnect();\n\t\t\n\t\t// clear nodes collection and send queue\n\t\tfor (Object listener : this.zwaveEventListeners.toArray()) {\n\t\t\tif (!(listener instanceof ZWaveNode))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tthis.zwaveEventListeners.remove(listener);\n\t\t}\n\t\t\n\t\tthis.zwaveNodes.clear();\n\t\tthis.sendQueue.clear();\n\t\t\n\t\tlogger.info(\"Stopped Z-Wave controller\");\n\t}",
"@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\tthis.attributes = (Map) attributes;\n\t}"
] |
Sets divider padding for axis. If axis does not match the orientation, it has no effect.
@param padding
@param axis {@link Axis} | [
"public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }"
] | [
"public static base_responses add(nitro_service client, appfwjsoncontenttype resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwjsoncontenttype addresources[] = new appfwjsoncontenttype[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new appfwjsoncontenttype();\n\t\t\t\taddresources[i].jsoncontenttypevalue = resources[i].jsoncontenttypevalue;\n\t\t\t\taddresources[i].isregex = resources[i].isregex;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void handleApplicationUpdateRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Update Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\t\n\t\tlogger.trace(\"Application Update Request from Node \" + nodeId);\n\t\tUpdateState updateState = UpdateState.getUpdateState(incomingMessage.getMessagePayloadByte(0));\n\t\t\n\t\tswitch (updateState) {\n\t\t\tcase NODE_INFO_RECEIVED:\n\t\t\t\tlogger.debug(\"Application update request, node information received.\");\t\t\t\n\t\t\t\tint length = incomingMessage.getMessagePayloadByte(2);\n\t\t\t\tZWaveNode node = getNode(nodeId);\n\t\t\t\t\n\t\t\t\tnode.resetResendCount();\n\t\t\t\t\n\t\t\t\tfor (int i = 6; i < length + 3; i++) {\n\t\t\t\t\tint data = incomingMessage.getMessagePayloadByte(i);\n\t\t\t\t\tif(data == 0xef ) {\n\t\t\t\t\t\t// TODO: Implement control command classes\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.debug(String.format(\"Adding command class 0x%02X to the list of supported command classes.\", data));\n\t\t\t\t\tZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(data, node, this);\n\t\t\t\t\tif (commandClass != null)\n\t\t\t\t\t\tnode.addCommandClass(commandClass);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// advance node stage.\n\t\t\t\tnode.advanceNodeStage();\n\t\t\t\t\n\t\t\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\t\ttransactionCompleted.release();\n\t\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase NODE_INFO_REQ_FAILED:\n\t\t\t\tlogger.debug(\"Application update request, Node Info Request Failed, re-request node info.\");\n\t\t\t\t\n\t\t\t\tSerialMessage requestInfoMessage = this.lastSentMessage;\n\t\t\t\t\n\t\t\t\tif (requestInfoMessage.getMessageClass() != SerialMessage.SerialMessageClass.RequestNodeInfo) {\n\t\t\t\t\tlogger.warn(\"Got application update request without node info request, ignoring.\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\tif (--requestInfoMessage.attempts >= 0) {\n\t\t\t\t\tlogger.error(\"Got Node Info Request Failed while sending this serial message. Requeueing\");\n\t\t\t\t\tthis.enqueue(requestInfoMessage);\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tlogger.warn(\"Node Info Request Failed 3x. Discarding message: {}\", lastSentMessage.toString());\n\t\t\t\t}\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(String.format(\"TODO: Implement Application Update Request Handling of %s (0x%02X).\", updateState.getLabel(), updateState.getKey()));\n\t\t}\n\t}",
"private int synchroizeTaskIDToHierarchy(Task parentTask, int currentID)\n {\n for (Task task : parentTask.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n return currentID;\n }",
"private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap)\n {\n Project.Resources resources = project.getResources();\n if (resources != null)\n {\n for (Project.Resources.Resource resource : resources.getResource())\n {\n readResource(resource, calendarMap);\n }\n }\n }",
"private TreeMap<Integer, Integer> createTaskMap(FieldMap fieldMap, FixedMeta taskFixedMeta, FixedData taskFixedData, Var2Data taskVarData)\n {\n TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer>();\n int uniqueIdOffset = fieldMap.getFixedDataOffset(TaskField.UNIQUE_ID);\n Integer taskNameKey = fieldMap.getVarDataKey(TaskField.NAME);\n int itemCount = taskFixedMeta.getAdjustedItemCount();\n int uniqueID;\n Integer key;\n\n //\n // First three items are not tasks, so let's skip them\n //\n for (int loop = 3; loop < itemCount; loop++)\n {\n byte[] data = taskFixedData.getByteArrayValue(loop);\n if (data != null)\n {\n byte[] metaData = taskFixedMeta.getByteArrayValue(loop);\n\n //\n // Check for the deleted task flag\n //\n int flags = MPPUtility.getInt(metaData, 0);\n if ((flags & 0x02) != 0)\n {\n // Project stores the deleted tasks unique id's into the fixed data as well\n // and at least in one case the deleted task was listed twice in the list\n // the second time with data with it causing a phantom task to be shown.\n // See CalendarErrorPhantomTasks.mpp\n //\n // So let's add the unique id for the deleted task into the map so we don't\n // accidentally include the task later.\n //\n uniqueID = MPPUtility.getShort(data, TASK_UNIQUE_ID_FIXED_OFFSET); // Only a short stored for deleted tasks?\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, null); // use null so we can easily ignore this later\n }\n }\n else\n {\n //\n // Do we have a null task?\n //\n if (data.length == NULL_TASK_BLOCK_SIZE)\n {\n uniqueID = MPPUtility.getInt(data, TASK_UNIQUE_ID_FIXED_OFFSET);\n key = Integer.valueOf(uniqueID);\n if (taskMap.containsKey(key) == false)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n else\n {\n //\n // We apply a heuristic here - if we have more than 75% of the data, we assume\n // the task is valid.\n //\n int maxSize = fieldMap.getMaxFixedDataSize(0);\n if (maxSize == 0 || ((data.length * 100) / maxSize) > 75)\n {\n uniqueID = MPPUtility.getInt(data, uniqueIdOffset);\n key = Integer.valueOf(uniqueID);\n\n // Accept this task if it does not have a deleted unique ID or it has a deleted unique ID but the name is not null\n if (!taskMap.containsKey(key) || taskVarData.getUnicodeString(key, taskNameKey) != null)\n {\n taskMap.put(key, Integer.valueOf(loop));\n }\n }\n }\n }\n }\n }\n\n return (taskMap);\n }",
"private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }",
"public static Thread addShutdownHook(final Process process) {\n final Thread thread = new Thread(new Runnable() {\n @Override\n public void run() {\n if (process != null) {\n process.destroy();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n });\n thread.setDaemon(true);\n Runtime.getRuntime().addShutdownHook(thread);\n return thread;\n }",
"public ILog getLog(String topic, int partition) {\n TopicNameValidator.validate(topic);\n Pool<Integer, Log> p = getLogPool(topic, partition);\n return p == null ? null : p.get(partition);\n }",
"protected void prepareForwardedResponseHeaders(ResponseData response) {\n HttpHeaders headers = response.getHeaders();\n headers.remove(TRANSFER_ENCODING);\n headers.remove(CONNECTION);\n headers.remove(\"Public-Key-Pins\");\n headers.remove(SERVER);\n headers.remove(\"Strict-Transport-Security\");\n }"
] |
Get a collection of all of the user's groups.
@return A Collection of Group objects
@throws FlickrException | [
"public Collection<Group> getGroups() throws FlickrException {\r\n GroupList<Group> groups = new GroupList<Group>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GROUPS);\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 groupsElement = response.getPayload();\r\n groups.setPage(groupsElement.getAttribute(\"page\"));\r\n groups.setPages(groupsElement.getAttribute(\"pages\"));\r\n groups.setPerPage(groupsElement.getAttribute(\"perpage\"));\r\n groups.setTotal(groupsElement.getAttribute(\"total\"));\r\n NodeList groupNodes = groupsElement.getElementsByTagName(\"group\");\r\n for (int i = 0; i < groupNodes.getLength(); i++) {\r\n Element groupElement = (Element) groupNodes.item(i);\r\n Group group = new Group();\r\n group.setId(groupElement.getAttribute(\"id\"));\r\n group.setName(groupElement.getAttribute(\"name\"));\r\n group.setAdmin(\"1\".equals(groupElement.getAttribute(\"admin\")));\r\n group.setPrivacy(groupElement.getAttribute(\"privacy\"));\r\n group.setIconServer(groupElement.getAttribute(\"iconserver\"));\r\n group.setIconFarm(groupElement.getAttribute(\"iconfarm\"));\r\n group.setPhotoCount(groupElement.getAttribute(\"photos\"));\r\n groups.add(group);\r\n }\r\n return groups;\r\n }"
] | [
"public static boolean isLong(CharSequence self) {\n try {\n Long.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"public void set1Value(int index, String newValue) {\n try {\n value.set( index, newValue );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) exception \" + e);\n }\n }",
"public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}",
"public static String getDumpFileName(DumpContentType dumpContentType,\n\t\t\tString projectName, String dateStamp) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\treturn dateStamp + WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t} else {\n\t\t\treturn projectName + \"-\" + dateStamp\n\t\t\t\t\t+ WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t}\n\t}",
"public CustomHeadersInterceptor replaceHeader(String name, String value) {\n this.headers.put(name, new ArrayList<String>());\n this.headers.get(name).add(value);\n return this;\n }",
"public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {\r\n\t\tRandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);\r\n\t\treturn conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);\r\n\t}",
"@Deprecated\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic void setAttributes(Map<String, PrimitiveAttribute<?>> attributes) {\n\t\tif (!isPrimitiveOnly()) {\n\t\t\tthrow new UnsupportedOperationException(\"Primitive API not supported for nested association values\");\n\t\t}\n\t\tthis.attributes = (Map) attributes;\n\t}",
"public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static ComplexNumber Subtract(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real - scalar, z1.imaginary);\r\n }"
] |
This method determines whether the given date falls in the range of
dates covered by this exception. Note that this method assumes that both
the start and end date of this exception have been set.
@param date Date to be tested
@return Boolean value | [
"public boolean contains(Date date)\n {\n boolean result = false;\n\n if (date != null)\n {\n result = (DateHelper.compare(getFromDate(), getToDate(), date) == 0);\n }\n\n return (result);\n }"
] | [
"private void writeCompressedText(File file, byte[] compressedContent) throws IOException\r\n {\r\n ByteArrayInputStream bais = new ByteArrayInputStream(compressedContent);\r\n GZIPInputStream gis = new GZIPInputStream(bais);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(gis));\r\n BufferedWriter output = new BufferedWriter(new FileWriter(file));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n gis.close();\r\n bais.close();\r\n output.close();\r\n }",
"private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\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 void readRelationships(Project gpProject)\n {\n for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask())\n {\n readRelationships(gpTask);\n }\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}",
"public int length() {\n int length = 1 + 2 + deviceToken.length + 2 + payload.length;\n final int marshalledLength = marshall().length;\n assert marshalledLength == length;\n return length;\n }",
"@Override\n public void preStateCrawling(CrawlerContext context,\n ImmutableList<CandidateElement> candidateElements, StateVertex state) {\n LOG.debug(\"preStateCrawling\");\n List<CandidateElementPosition> newElements = Lists.newLinkedList();\n LOG.info(\"Prestate found new state {} with {} candidates\", state.getName(),\n candidateElements.size());\n for (CandidateElement element : candidateElements) {\n try {\n WebElement webElement = getWebElement(context.getBrowser(), element);\n if (webElement != null) {\n newElements.add(findElement(webElement, element));\n }\n } catch (WebDriverException e) {\n LOG.info(\"Could not get position for {}\", element, e);\n }\n }\n\n StateBuilder stateOut = outModelCache.addStateIfAbsent(state);\n stateOut.addCandidates(newElements);\n LOG.trace(\"preState finished, elements added to state\");\n }",
"public final PJsonObject getJSONObject(final int i) {\n JSONObject val = this.array.optJSONObject(i);\n final String context = \"[\" + i + \"]\";\n if (val == null) {\n throw new ObjectMissingException(this, context);\n }\n return new PJsonObject(this, val, context);\n }",
"public void addAll(Vertex vtx) {\n if (head == null) {\n head = vtx;\n } else {\n tail.next = vtx;\n }\n vtx.prev = tail;\n while (vtx.next != null) {\n vtx = vtx.next;\n }\n tail = vtx;\n }"
] |
Calculate the value of a swaption assuming the Black'76 model.
@param forwardSwaprate The forward (spot)
@param volatility The Black'76 volatility.
@param optionMaturity The option maturity.
@param optionStrike The option strike.
@param swapAnnuity The swap annuity corresponding to the underlying swap.
@return Returns the value of a Swaption under the Black'76 model | [
"public static double blackModelSwaptionValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble swapAnnuity)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);\n\t}"
] | [
"public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase(\n String privKeyRelativePath, String passphrase) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setPrivKeyUsePassphrase(true);\n this.sshMeta.setPassphrase(passphrase);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\n }",
"public void addGroupBy(String[] fieldNames)\r\n {\r\n for (int i = 0; i < fieldNames.length; i++)\r\n {\r\n addGroupBy(fieldNames[i]);\r\n }\r\n }",
"public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }",
"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 void createAssignmentFieldMap(Props props)\n {\n //System.out.println(\"ASSIGN\");\n byte[] fieldMapData = null;\n for (Integer key : ASSIGNMENT_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultAssignmentData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }",
"public static MetadataTemplate createMetadataTemplate(BoxAPIConnection api, String scope, String templateKey,\n String displayName, boolean hidden, List<Field> fields) {\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"scope\", scope);\n jsonObject.add(\"displayName\", displayName);\n jsonObject.add(\"hidden\", hidden);\n\n if (templateKey != null) {\n jsonObject.add(\"templateKey\", templateKey);\n }\n\n JsonArray fieldsArray = new JsonArray();\n if (fields != null && !fields.isEmpty()) {\n for (Field field : fields) {\n JsonObject fieldObj = getFieldJsonObject(field);\n\n fieldsArray.add(fieldObj);\n }\n\n jsonObject.add(\"fields\", fieldsArray);\n }\n\n URL url = METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(jsonObject.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n return new MetadataTemplate(responseJSON);\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}",
"private void initDurationPanel() {\n\n m_durationPrefixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_PREFIX_0));\n m_durationAfterPostfixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_POSTFIX_0));\n m_seriesEndDate.setDateOnly(true);\n m_seriesEndDate.setAllowInvalidValue(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n m_seriesEndDate.getTextField().addFocusHandler(new FocusHandler() {\n\n public void onFocus(FocusEvent event) {\n\n if (handleChange()) {\n onSeriesEndDateFocus(event);\n }\n\n }\n });\n }",
"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}"
] |
Close it and ignore any exceptions. | [
"public static void closeThrowSqlException(Closeable closeable, String label) throws SQLException {\n\t\tif (closeable != null) {\n\t\t\ttry {\n\t\t\t\tcloseable.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"could not close \" + label, e);\n\t\t\t}\n\t\t}\n\t}"
] | [
"public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }",
"public T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}",
"public void initializePersistenceStrategy(CacheMappingType cacheMappingType, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes, Iterable<Namespace> namespaces) {\n\t\tpersistenceStrategy = PersistenceStrategy.getInstance(\n\t\t\t\tcacheMappingType,\n\t\t\t\texternalCacheManager,\n\t\t\t\tconfig.getConfigurationUrl(),\n\t\t\t\tjtaPlatform,\n\t\t\t\tentityTypes,\n\t\t\t\tassociationTypes,\n\t\t\t\tidSourceTypes\n\t\t);\n\n\t\t// creates handler for TableGenerator Id sources\n\t\tboolean requiresCounter = hasIdGeneration( idSourceTypes );\n\t\tif ( requiresCounter ) {\n\t\t\tthis.tableClusterHandler = new TableClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager() );\n\t\t}\n\n\t\t// creates handlers for SequenceGenerator Id sources\n\t\tfor ( Namespace namespace : namespaces ) {\n\t\t\tfor ( Sequence seq : namespace.getSequences() ) {\n\t\t\t\tthis.sequenceCounterHandlers.put( seq.getExportIdentifier(),\n\t\t\t\t\t\tnew SequenceClusteredCounterHandler( persistenceStrategy.getCacheManager().getCacheManager(), seq ) );\n\t\t\t}\n\t\t}\n\n\t\t// clear resources\n\t\tthis.externalCacheManager = null;\n\t\tthis.jtaPlatform = null;\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 static base_response delete(nitro_service client, String jsoncontenttypevalue) throws Exception {\n\t\tappfwjsoncontenttype deleteresource = new appfwjsoncontenttype();\n\t\tdeleteresource.jsoncontenttypevalue = jsoncontenttypevalue;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public String translatePath(String path) {\n String translated;\n // special character: ~ maps to the user's home directory\n if (path.startsWith(\"~\" + File.separator)) {\n translated = System.getProperty(\"user.home\") + path.substring(1);\n } else if (path.startsWith(\"~\")) {\n String userName = path.substring(1);\n translated = new File(new File(System.getProperty(\"user.home\")).getParent(),\n userName).getAbsolutePath();\n // Keep the path separator in translated or add one if no user home specified\n translated = userName.isEmpty() || path.endsWith(File.separator) ? translated + File.separator : translated;\n } else if (!new File(path).isAbsolute()) {\n translated = ctx.getCurrentDir().getAbsolutePath() + File.separator + path;\n } else {\n translated = path;\n }\n return translated;\n }",
"public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {\n final File layersList = new File(repoRoot, LAYERS_CONF);\n if (!layersList.exists()) {\n return new LayersConfig();\n }\n final Properties properties = PatchUtils.loadProperties(layersList);\n return new LayersConfig(properties);\n }",
"public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {\n StringBuilder queryString = new StringBuilder();\n for (Map.Entry<String, String> entry: queryParams.entries()) {\n if (queryString.length() > 0) {\n queryString.append(\"&\");\n }\n queryString.append(entry.getKey()).append(\"=\").append(entry.getValue());\n }\n try {\n if (initialUri.getHost() == null && initialUri.getAuthority() != null) {\n return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),\n queryString.toString(),\n initialUri.getFragment());\n } else {\n return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),\n initialUri.getPort(),\n initialUri.getPath(),\n queryString.toString(), initialUri.getFragment());\n }\n } catch (URISyntaxException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n }",
"public static Info rand( final Variable A , final Variable B , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableInteger && B instanceof VariableInteger ) {\n ret.op = new Operation(\"rand-ii\") {\n @Override\n public void process() {\n int numRows = ((VariableInteger)A).value;\n int numCols = ((VariableInteger)B).value;\n output.matrix.reshape(numRows,numCols);\n RandomMatrices_DDRM.fillUniform(output.matrix, 0,1,manager.getRandom());\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }"
] |
Ensure that the nodeList is either null or empty.
@param nodeList the nodeList to ensure to be either null or empty
@param expression the expression was used to fine the nodeList
@throws SpinXPathException if the nodeList is either null or empty | [
"public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }"
] | [
"@Deprecated\n public FluoConfiguration addObservers(Iterable<ObserverSpecification> observers) {\n int next = getNextObserverId();\n for (ObserverSpecification oconf : observers) {\n addObserver(oconf, next++);\n }\n return this;\n }",
"void reset()\n {\n if (!hasStopped)\n {\n throw new IllegalStateException(\"cannot reset a non stopped queue poller\");\n }\n hasStopped = false;\n run = true;\n lastLoop = null;\n loop = new Semaphore(0);\n }",
"public synchronized GeoInterface getGeoInterface() {\r\n if (geoInterface == null) {\r\n geoInterface = new GeoInterface(apiKey, sharedSecret, transport);\r\n }\r\n return geoInterface;\r\n }",
"private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }",
"public static 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 rnatparam get(nitro_service service) throws Exception{\n\t\trnatparam obj = new rnatparam();\n\t\trnatparam[] response = (rnatparam[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"public static final BigDecimal printUnits(Number value)\n {\n return (value == null ? BIGDECIMAL_ONE : new BigDecimal(value.doubleValue() / 100));\n }",
"private static Bitmap crop(Bitmap srcBmp, View canvasView, int downsampling) {\n float scale = 1f / downsampling;\n return Bitmap.createBitmap(\n srcBmp,\n (int) Math.floor((ViewCompat.getX(canvasView)) * scale),\n (int) Math.floor((ViewCompat.getY(canvasView)) * scale),\n (int) Math.floor((canvasView.getWidth()) * scale),\n (int) Math.floor((canvasView.getHeight()) * scale)\n );\n }",
"private void purgeDeadJobInstances(DbConn cnx, Node node)\n {\n for (JobInstance ji : JobInstance.select(cnx, \"ji_select_by_node\", node.getId()))\n {\n try\n {\n cnx.runSelectSingle(\"history_select_state_by_id\", String.class, ji.getId());\n }\n catch (NoResultException e)\n {\n History.create(cnx, ji, State.CRASHED, Calendar.getInstance());\n Message.create(cnx,\n \"Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash\",\n ji.getId());\n }\n\n cnx.runUpdate(\"ji_delete_by_id\", ji.getId());\n }\n cnx.commit();\n }"
] |
Add a listener to be invoked when the checked button changes in this group.
@param listener
@param <T>
@return | [
"public <T extends Widget & Checkable> boolean addOnCheckChangedListener\n (OnCheckChangedListener listener) {\n final boolean added;\n synchronized (mListeners) {\n added = mListeners.add(listener);\n }\n if (added) {\n List<T> c = getCheckableChildren();\n for (int i = 0; i < c.size(); ++i) {\n listener.onCheckChanged(this, c.get(i), i);\n }\n }\n return added;\n }"
] | [
"public static base_response update(nitro_service client, cmpparameter resource) throws Exception {\n\t\tcmpparameter updateresource = new cmpparameter();\n\t\tupdateresource.cmplevel = resource.cmplevel;\n\t\tupdateresource.quantumsize = resource.quantumsize;\n\t\tupdateresource.servercmp = resource.servercmp;\n\t\tupdateresource.heurexpiry = resource.heurexpiry;\n\t\tupdateresource.heurexpirythres = resource.heurexpirythres;\n\t\tupdateresource.heurexpiryhistwt = resource.heurexpiryhistwt;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.cmpbypasspct = resource.cmpbypasspct;\n\t\tupdateresource.cmponpush = resource.cmponpush;\n\t\tupdateresource.policytype = resource.policytype;\n\t\tupdateresource.addvaryheader = resource.addvaryheader;\n\t\tupdateresource.externalcache = resource.externalcache;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public Map<String, String> decompose(Frontier frontier, String modelText) {\r\n if (!(frontier instanceof SCXMLFrontier)) {\r\n return null;\r\n }\n\r\n TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState;\r\n Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables;\n\r\n Map<String, String> decomposition = new HashMap<String, String>();\r\n decomposition.put(\"target\", target.getId());\n\r\n StringBuilder packedVariables = new StringBuilder();\r\n for (Map.Entry<String, String> variable : variables.entrySet()) {\r\n packedVariables.append(variable.getKey());\r\n packedVariables.append(\"::\");\r\n packedVariables.append(variable.getValue());\r\n packedVariables.append(\";\");\r\n }\n\r\n decomposition.put(\"variables\", packedVariables.toString());\r\n decomposition.put(\"model\", modelText);\n\r\n return decomposition;\r\n }",
"public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }",
"private int getSegmentForX(int x) {\n if (autoScroll.get()) {\n int playHead = (x - (getWidth() / 2));\n int offset = Util.timeToHalfFrame(getFurthestPlaybackPosition()) / scale.get();\n return (playHead + offset) * scale.get();\n }\n return x * scale.get();\n }",
"public void close() {\n logger.info(\"Closing all sync producers\");\n if (sync) {\n for (SyncProducer p : syncProducers.values()) {\n p.close();\n }\n } else {\n for (AsyncProducer<V> p : asyncProducers.values()) {\n p.close();\n }\n }\n\n }",
"public static sslservicegroup_sslcertkey_binding[] get(nitro_service service, String servicegroupname) throws Exception{\n\t\tsslservicegroup_sslcertkey_binding obj = new sslservicegroup_sslcertkey_binding();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tsslservicegroup_sslcertkey_binding response[] = (sslservicegroup_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void useXopAttachmentServiceWithWebClient() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments/xop\";\n \n JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean();\n factoryBean.setAddress(serviceURI);\n factoryBean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, \n (Object)\"true\"));\n WebClient client = factoryBean.createWebClient();\n WebClient.getConfig(client).getRequestContext().put(\"support.type.as.multipart\", \n \"true\"); \n client.type(\"multipart/related\").accept(\"multipart/related\");\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a WebClient\");\n \n XopBean xopResponse = client.post(xop, XopBean.class);\n \n verifyXopResponse(xop, xopResponse);\n }",
"public static String getParentId(String digest, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(digest).exec().getParent();\n } finally {\n closeQuietly(dockerClient);\n }\n }"
] |
Set the visibility of the object.
@see Visibility
@param visibility
The visibility of the object.
@return {@code true} if the visibility was changed, {@code false} if it
wasn't. | [
"public boolean setVisibility(final Visibility visibility) {\n if (visibility != mVisibility) {\n Log.d(Log.SUBSYSTEM.WIDGET, TAG, \"setVisibility(%s) for %s\", visibility, getName());\n updateVisibility(visibility);\n mVisibility = visibility;\n return true;\n }\n return false;\n }"
] | [
"DeleteResult deleteMany(final MongoNamespace namespace,\n final Bson filter) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();\n final DeleteResult result;\n final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n try {\n final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);\n final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);\n final Set<BsonValue> idsToDelete =\n localCollection\n .find(filter)\n .map(new Function<BsonDocument, BsonValue>() {\n @Override\n @NonNull\n public BsonValue apply(@NonNull final BsonDocument bsonDocument) {\n undoCollection.insertOne(bsonDocument);\n return BsonUtils.getDocumentId(bsonDocument);\n }\n }).into(new HashSet<>());\n\n result = localCollection.deleteMany(filter);\n\n for (final BsonValue documentId : idsToDelete) {\n final CoreDocumentSynchronizationConfig config =\n syncConfig.getSynchronizedDocument(namespace, documentId);\n\n if (config == null) {\n continue;\n }\n\n final ChangeEvent<BsonDocument> event =\n ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);\n\n // this block is to trigger coalescence for a delete after insert\n if (config.getLastUncommittedChangeEvent() != null\n && config.getLastUncommittedChangeEvent().getOperationType()\n == OperationType.INSERT) {\n desyncDocumentsFromRemote(nsConfig, config.getDocumentId())\n .commitAndClear();\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n continue;\n }\n\n config.setSomePendingWritesAndSave(logicalT, event);\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n eventsToEmit.add(event);\n }\n checkAndDeleteNamespaceListener(namespace);\n } finally {\n lock.unlock();\n }\n for (final ChangeEvent<BsonDocument> event : eventsToEmit) {\n eventDispatcher.emitEvent(nsConfig, event);\n }\n return result;\n } finally {\n ongoingOperationsGroup.exit();\n }\n }",
"@Override\r\n public V put(K key, V value) {\r\n if (fast) {\r\n synchronized (this) {\r\n Map<K, V> temp = cloneMap(map);\r\n V result = temp.put(key, value);\r\n map = temp;\r\n return (result);\r\n }\r\n } else {\r\n synchronized (map) {\r\n return (map.put(key, value));\r\n }\r\n }\r\n }",
"public static String analyzeInvalidMetadataRate(final Cluster currentCluster,\n List<StoreDefinition> currentStoreDefs,\n final Cluster finalCluster,\n List<StoreDefinition> finalStoreDefs) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Dump of invalid metadata rates per zone\").append(Utils.NEWLINE);\n\n HashMap<StoreDefinition, Integer> uniqueStores = StoreDefinitionUtils.getUniqueStoreDefinitionsWithCounts(currentStoreDefs);\n\n for(StoreDefinition currentStoreDef: uniqueStores.keySet()) {\n sb.append(\"Store exemplar: \" + currentStoreDef.getName())\n .append(Utils.NEWLINE)\n .append(\"\\tThere are \" + uniqueStores.get(currentStoreDef) + \" other similar stores.\")\n .append(Utils.NEWLINE);\n\n StoreRoutingPlan currentSRP = new StoreRoutingPlan(currentCluster, currentStoreDef);\n StoreDefinition finalStoreDef = StoreUtils.getStoreDef(finalStoreDefs,\n currentStoreDef.getName());\n StoreRoutingPlan finalSRP = new StoreRoutingPlan(finalCluster, finalStoreDef);\n\n // Only care about existing zones\n for(int zoneId: currentCluster.getZoneIds()) {\n int zonePrimariesCount = 0;\n int invalidMetadata = 0;\n\n // Examine nodes in current cluster in existing zone.\n for(int nodeId: currentCluster.getNodeIdsInZone(zoneId)) {\n // For every zone-primary in current cluster\n for(int zonePrimaryPartitionId: currentSRP.getZonePrimaryPartitionIds(nodeId)) {\n zonePrimariesCount++;\n // Determine if original zone-primary node is still some\n // form of n-ary in final cluster. If not,\n // InvalidMetadataException will fire.\n if(!finalSRP.getZoneNAryPartitionIds(nodeId)\n .contains(zonePrimaryPartitionId)) {\n invalidMetadata++;\n }\n }\n }\n float rate = invalidMetadata / (float) zonePrimariesCount;\n sb.append(\"\\tZone \" + zoneId)\n .append(\" : total zone primaries \" + zonePrimariesCount)\n .append(\", # that trigger invalid metadata \" + invalidMetadata)\n .append(\" => \" + rate)\n .append(Utils.NEWLINE);\n }\n }\n\n return sb.toString();\n }",
"public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) {\n add(new LuaAstReturnStatement(argument(value)));\n return endPreparedScript(config);\n }",
"public synchronized Widget measureChild(final int dataIndex, boolean calculateOffset) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"measureChild dataIndex = %d\", dataIndex);\n\n Widget widget = mContainer.get(dataIndex);\n if (widget != null) {\n synchronized (mMeasuredChildren) {\n mMeasuredChildren.add(dataIndex);\n }\n }\n return widget;\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 void deleteArtifact(final String gavc, 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.getArtifactPath(gavc));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to DELETE artifact \" + gavc;\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 Record findRecordById(String id) {\n if (directory == null)\n init();\n\n Property idprop = config.getIdentityProperties().iterator().next();\n for (Record r : lookup(idprop, id))\n if (r.getValue(idprop.getName()).equals(id))\n return r;\n\n return null; // not found\n }",
"public static base_response delete(nitro_service client, String network) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = network;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] |
Create a local target.
@param jbossHome the jboss home
@param moduleRoots the module roots
@param bundlesRoots the bundle roots
@return the local target
@throws IOException | [
"public static final PatchOperationTarget createLocal(final File jbossHome, List<File> moduleRoots, List<File> bundlesRoots) throws IOException {\n final PatchTool tool = PatchTool.Factory.createLocalTool(jbossHome, moduleRoots, bundlesRoots);\n return new LocalPatchOperationTarget(tool);\n }"
] | [
"boolean setFrameIndex(int frame) {\n if(frame < INITIAL_FRAME_POINTER || frame >= getFrameCount()) {\n return false;\n }\n framePointer = frame;\n return true;\n }",
"public void setAlias(String alias)\r\n\t{\r\n\t\tm_alias = alias;\r\n\t\tString attributePath = (String)getAttribute();\r\n\t\tboolean allPathsAliased = true;\r\n\t\tm_userAlias = new UserAlias(alias, attributePath, allPathsAliased);\r\n\t\t\r\n\t}",
"protected void registerValueFormatter(DJGroupVariable djVariable, String variableName) {\n\t\tif ( djVariable.getValueFormatter() == null){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tJRDesignParameter dparam = new JRDesignParameter();\n\t\tdparam.setName(variableName + \"_vf\"); //value formater suffix\n\t\tdparam.setValueClassName(DJValueFormatter.class.getName());\n\t\tlog.debug(\"Registering value formatter parameter for property \" + dparam.getName() );\n\t\ttry {\n\t\t\tgetDjd().addParameter(dparam);\n\t\t} catch (JRException e) {\n\t\t\tthrow new EntitiesRegistrationException(e.getMessage(),e);\n\t\t}\n\t\tgetDjd().getParametersWithValues().put(dparam.getName(), djVariable.getValueFormatter());\t\t\n\t\t\n\t}",
"public void printInferredRelations(ClassDoc c) {\n\t// check if the source is excluded from inference\n\tif (hidden(c))\n\t return;\n\n\tOptions opt = optionProvider.getOptionsFor(c);\n\n\tfor (FieldDoc field : c.fields(false)) {\n\t if(hidden(field))\n\t\tcontinue;\n\t // skip statics\n\t if(field.isStatic())\n\t\tcontinue;\n\t // skip primitives\n\t FieldRelationInfo fri = getFieldRelationInfo(field);\n\t if (fri == null)\n\t\tcontinue;\n\t // check if the destination is excluded from inference\n\t if (hidden(fri.cd))\n\t\tcontinue;\n\n\t // if source and dest are not already linked, add a dependency\n\t RelationPattern rp = getClassInfo(c, true).getRelation(fri.cd.toString());\n\t if (rp == null) {\n\t\tString destAdornment = fri.multiple ? \"*\" : \"\";\n\t\trelation(opt, opt.inferRelationshipType, c, fri.cd, \"\", \"\", destAdornment);\n }\n\t}\n }",
"public static String next(CharSequence self) {\n StringBuilder buffer = new StringBuilder(self);\n if (buffer.length() == 0) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char last = buffer.charAt(buffer.length() - 1);\n if (last == Character.MAX_VALUE) {\n buffer.append(Character.MIN_VALUE);\n } else {\n char next = last;\n next++;\n buffer.setCharAt(buffer.length() - 1, next);\n }\n }\n return buffer.toString();\n }",
"private static Interval parseEndDateTime(Instant start, ZoneOffset offset, CharSequence endStr) {\n try {\n TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(endStr, OffsetDateTime::from, LocalDateTime::from);\n if (temporal instanceof OffsetDateTime) {\n OffsetDateTime odt = (OffsetDateTime) temporal;\n return Interval.of(start, odt.toInstant());\n } else {\n // infer offset from start if not specified by end\n LocalDateTime ldt = (LocalDateTime) temporal;\n return Interval.of(start, ldt.toInstant(offset));\n }\n } catch (DateTimeParseException ex) {\n Instant end = Instant.parse(endStr);\n return Interval.of(start, end);\n }\n }",
"public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\n }",
"protected static BigInteger getRadixPower(BigInteger radix, int power) {\n\t\tlong key = (((long) radix.intValue()) << 32) | power;\n\t\tBigInteger result = radixPowerMap.get(key);\n\t\tif(result == null) {\n\t\t\tif(power == 1) {\n\t\t\t\tresult = radix;\n\t\t\t} else if((power & 1) == 0) {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, power >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower);\n\t\t\t} else {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, (power - 1) >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower).multiply(radix);\n\t\t\t}\n\t\t\tradixPowerMap.put(key, result);\n\t\t}\n\t\treturn result;\n\t}",
"protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }"
] |
Removes all documents from the collection that match the given query filter. If no documents
match, the collection is not modified.
@param filter the query filter to apply the the delete operation
@return the result of the remove many operation | [
"DeleteResult deleteMany(final MongoNamespace namespace,\n final Bson filter) {\n this.waitUntilInitialized();\n\n try {\n ongoingOperationsGroup.enter();\n final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();\n final DeleteResult result;\n final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);\n final Lock lock = nsConfig.getLock().writeLock();\n lock.lock();\n try {\n final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);\n final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);\n final Set<BsonValue> idsToDelete =\n localCollection\n .find(filter)\n .map(new Function<BsonDocument, BsonValue>() {\n @Override\n @NonNull\n public BsonValue apply(@NonNull final BsonDocument bsonDocument) {\n undoCollection.insertOne(bsonDocument);\n return BsonUtils.getDocumentId(bsonDocument);\n }\n }).into(new HashSet<>());\n\n result = localCollection.deleteMany(filter);\n\n for (final BsonValue documentId : idsToDelete) {\n final CoreDocumentSynchronizationConfig config =\n syncConfig.getSynchronizedDocument(namespace, documentId);\n\n if (config == null) {\n continue;\n }\n\n final ChangeEvent<BsonDocument> event =\n ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);\n\n // this block is to trigger coalescence for a delete after insert\n if (config.getLastUncommittedChangeEvent() != null\n && config.getLastUncommittedChangeEvent().getOperationType()\n == OperationType.INSERT) {\n desyncDocumentsFromRemote(nsConfig, config.getDocumentId())\n .commitAndClear();\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n continue;\n }\n\n config.setSomePendingWritesAndSave(logicalT, event);\n undoCollection.deleteOne(getDocumentIdFilter(documentId));\n eventsToEmit.add(event);\n }\n checkAndDeleteNamespaceListener(namespace);\n } finally {\n lock.unlock();\n }\n for (final ChangeEvent<BsonDocument> event : eventsToEmit) {\n eventDispatcher.emitEvent(nsConfig, event);\n }\n return result;\n } finally {\n ongoingOperationsGroup.exit();\n }\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 }",
"protected static BigInteger getRadixPower(BigInteger radix, int power) {\n\t\tlong key = (((long) radix.intValue()) << 32) | power;\n\t\tBigInteger result = radixPowerMap.get(key);\n\t\tif(result == null) {\n\t\t\tif(power == 1) {\n\t\t\t\tresult = radix;\n\t\t\t} else if((power & 1) == 0) {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, power >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower);\n\t\t\t} else {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, (power - 1) >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower).multiply(radix);\n\t\t\t}\n\t\t\tradixPowerMap.put(key, result);\n\t\t}\n\t\treturn result;\n\t}",
"private void addIncludes(DBHandling handling, FileSet fileSet) throws BuildException\r\n {\r\n DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject());\r\n String[] files = scanner.getIncludedFiles();\r\n StringBuffer includes = new StringBuffer();\r\n\r\n for (int idx = 0; idx < files.length; idx++)\r\n {\r\n if (idx > 0)\r\n {\r\n includes.append(\",\");\r\n }\r\n includes.append(files[idx]);\r\n }\r\n try\r\n {\r\n handling.addDBDefinitionFiles(fileSet.getDir(getProject()).getAbsolutePath(), includes.toString());\r\n }\r\n catch (IOException ex)\r\n {\r\n throw new BuildException(ex);\r\n }\r\n }",
"public void set( int row , int col , double real , double imaginary ) {\n if( imaginary == 0 ) {\n set(row,col,real);\n } else {\n ops.set(mat,row,col, real, imaginary);\n }\n }",
"private Map<StandardMethod, UnderrideLevel> findUnderriddenMethods(\n Iterable<ExecutableElement> methods) {\n Map<StandardMethod, ExecutableElement> standardMethods = new LinkedHashMap<>();\n for (ExecutableElement method : methods) {\n Optional<StandardMethod> standardMethod = maybeStandardMethod(method);\n if (standardMethod.isPresent() && isUnderride(method)) {\n standardMethods.put(standardMethod.get(), method);\n }\n }\n if (standardMethods.containsKey(StandardMethod.EQUALS)\n != standardMethods.containsKey(StandardMethod.HASH_CODE)) {\n ExecutableElement underriddenMethod = standardMethods.containsKey(StandardMethod.EQUALS)\n ? standardMethods.get(StandardMethod.EQUALS)\n : standardMethods.get(StandardMethod.HASH_CODE);\n messager.printMessage(ERROR,\n \"hashCode and equals must be implemented together on FreeBuilder types\",\n underriddenMethod);\n }\n ImmutableMap.Builder<StandardMethod, UnderrideLevel> result = ImmutableMap.builder();\n for (StandardMethod standardMethod : standardMethods.keySet()) {\n if (standardMethods.get(standardMethod).getModifiers().contains(Modifier.FINAL)) {\n result.put(standardMethod, UnderrideLevel.FINAL);\n } else {\n result.put(standardMethod, UnderrideLevel.OVERRIDEABLE);\n }\n }\n return result.build();\n }",
"@SuppressWarnings(\"unchecked\")\r\n\tpublic <T> T convertElement(ConversionContext context, Object source,\r\n\t\t\tTypeReference<T> destinationType) throws ConverterException {\r\n\t\treturn (T) elementConverter.convert(context, source, destinationType);\r\n\t}",
"public static base_responses renumber(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 renumberresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\trenumberresources[i] = new nspbr6();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, renumberresources,\"renumber\");\n\t\t}\n\t\treturn result;\n\t}",
"public ItemRequest<CustomField> insertEnumOption(String customField) {\n \n String path = String.format(\"/custom_fields/%s/enum_options/insert\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"POST\");\n }",
"public static void sendMessageBody(String to, String from, String subject, Object body, String contentType, ServerSetup serverSetup) {\r\n try {\r\n Session smtpSession = getSession(serverSetup);\r\n MimeMessage mimeMessage = new MimeMessage(smtpSession);\r\n\r\n mimeMessage.setRecipients(Message.RecipientType.TO, to);\r\n mimeMessage.setFrom(from);\r\n mimeMessage.setSubject(subject);\r\n mimeMessage.setContent(body, contentType);\r\n sendMimeMessage(mimeMessage);\r\n } catch (MessagingException e) {\r\n throw new IllegalStateException(\"Can not send message\", e);\r\n }\r\n }"
] |
Sets the submatrix of W up give Y is already configured and if it is being cached or not. | [
"private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }"
] | [
"public BlurBuilder contrast(float contrast) {\n data.preProcessors.add(new ContrastProcessor(data.contextWrapper.getRenderScript(), Math.max(Math.min(1500.f, contrast), -1500.f)));\n return this;\n }",
"public void putInWakeUpQueue(SerialMessage serialMessage) {\r\n\t\tif (this.wakeUpQueue.contains(serialMessage)) {\r\n\t\t\tlogger.debug(\"Message already on the wake-up queue for node {}. Discarding.\", this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\t\r\n\t\tlogger.debug(\"Putting message in wakeup queue for node {}.\", this.getNode().getNodeId());\r\n\t\tthis.wakeUpQueue.add(serialMessage);\r\n\t}",
"public static void createDirectory(Path dir, String dirDesc)\n {\n try\n {\n Files.createDirectories(dir);\n }\n catch (IOException ex)\n {\n throw new WindupException(\"Error creating \" + dirDesc + \" folder: \" + dir.toString() + \" due to: \" + ex.getMessage(), ex);\n }\n }",
"protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }",
"public static int getBytesToken(ParsingContext ctx) {\n String input = ctx.getInput().substring(ctx.getLocation());\n int tokenOffset = 0;\n int i = 0;\n char[] inputChars = input.toCharArray();\n for (; i < input.length(); i += 1) {\n char c = inputChars[i];\n if (c == ' ') {\n continue;\n }\n if (c != BYTES_TOKEN_CHARS[tokenOffset]) {\n return -1;\n } else {\n tokenOffset += 1;\n if (tokenOffset == BYTES_TOKEN_CHARS.length) {\n // Found the token.\n return i;\n }\n }\n }\n return -1;\n }",
"public void setLicense(String photoId, int licenseId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_LICENSE);\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"license_id\", Integer.toString(licenseId));\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // This method has no specific response - It returns an empty sucess response if it completes without error.\r\n\r\n }",
"protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }",
"private <T extends TimephasedItem<?>> int getStartIndex(DateRange range, List<T> assignments, int startIndex)\n {\n int result = -1;\n if (assignments != null)\n {\n long rangeStart = range.getStart().getTime();\n long rangeEnd = range.getEnd().getTime();\n\n for (int loop = startIndex; loop < assignments.size(); loop++)\n {\n T assignment = assignments.get(loop);\n int compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeStart);\n\n //\n // The start of the target range falls after the assignment end -\n // move on to test the next assignment.\n //\n if (compareResult > 0)\n {\n continue;\n }\n\n //\n // The start of the target range falls within the assignment -\n // return the index of this assignment to the caller.\n //\n if (compareResult == 0)\n {\n result = loop;\n break;\n }\n\n //\n // At this point, we know that the start of the target range is before\n // the assignment start. We need to determine if the end of the\n // target range overlaps the assignment.\n //\n compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeEnd);\n if (compareResult >= 0)\n {\n result = loop;\n break;\n }\n }\n }\n return result;\n }",
"public List<CmsUser> getVisibleUser() {\n\n if (!m_fullyLoaded) {\n return m_users;\n }\n if (size() == m_users.size()) {\n return m_users;\n }\n List<CmsUser> directs = new ArrayList<CmsUser>();\n for (CmsUser user : m_users) {\n if (!m_indirects.contains(user)) {\n directs.add(user);\n }\n }\n return directs;\n }"
] |
Marks the given list of statements for deletion. It is verified that the
current document actually contains the statements before doing so. This
check is based on exact statement equality, including qualifier order and
statement id.
@param currentDocument
the document with the current statements
@param deleteStatements
the list of statements to be deleted | [
"protected void markStatementsForDeletion(StatementDocument currentDocument,\n\t\t\tList<Statement> deleteStatements) {\n\t\tfor (Statement statement : deleteStatements) {\n\t\t\tboolean found = false;\n\t\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\t\tif (!sg.getProperty().equals(statement.getMainSnak().getPropertyId())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tStatement changedStatement = null;\n\t\t\t\tfor (Statement existingStatement : sg) {\n\t\t\t\t\tif (existingStatement.equals(statement)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\ttoDelete.add(statement.getStatementId());\n\t\t\t\t\t} else if (existingStatement.getStatementId().equals(\n\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\t// (we assume all existing statement ids to be nonempty\n\t\t\t\t\t\t// here)\n\t\t\t\t\t\tchangedStatement = existingStatement;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!found) {\n\t\t\t\t\tStringBuilder warning = new StringBuilder();\n\t\t\t\t\twarning.append(\"Cannot delete statement (id \")\n\t\t\t\t\t\t\t.append(statement.getStatementId())\n\t\t\t\t\t\t\t.append(\") since it is not present in data. Statement was:\\n\")\n\t\t\t\t\t\t\t.append(statement);\n\n\t\t\t\t\tif (changedStatement != null) {\n\t\t\t\t\t\twarning.append(\n\t\t\t\t\t\t\t\t\"\\nThe data contains another statement with the same id: maybe it has been edited? Other statement was:\\n\")\n\t\t\t\t\t\t\t\t.append(changedStatement);\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(warning.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] | [
"protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n queue.add(event);\n }",
"public String getBaselineDurationText(int baselineNumber)\n {\n Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber));\n if (result == null)\n {\n result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_DURATIONS, baselineNumber));\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"public void setFileFormat(String fileFormat) {\n\n if (fileFormat.toUpperCase().equals(FileFormat.JSON.toString())) {\n m_fileFormat = FileFormat.JSON;\n }\n }",
"public static boolean isInteger(CharSequence self) {\n try {\n Integer.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }",
"public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {\n Map<String, Object> metadata = new HashMap<String, Object>();\n metadata.put(Constants.DEVICE_ID, deviceId);\n metadata.put(Constants.DEVICE_TYPE, deviceType);\n metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);\n metadata.put(\"scope\", \"generic\");\n ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();\n\n importDeclarations.put(deviceId, declaration);\n\n registerImportDeclaration(declaration);\n }",
"public <TYPE> TYPE get(String key, Class<TYPE> type) {\n\t\treturn cache.get(key, type);\n\t}",
"public boolean getFlag(int index)\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(ResourceFieldLists.CUSTOM_FLAG, index)));\n }",
"public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,\n IllegalAccessException, IllegalArgumentException, InvocationTargetException,\n NoSuchMethodException, SecurityException {\n URLClassLoader sysloader = (URLClassLoader) loader;\n Class<?> sysclass = URLClassLoader.class;\n\n Method method =\n sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});\n method.setAccessible(true);\n method.invoke(sysloader, new Object[] {url});\n\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}"
] |
Generate random time stamps from the current time upto the next one second.
Passed as texture coordinates to the vertex shader, an unused field is present
with every pair passed.
@param totalTime
@return | [
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n for ( int i = 0; i < mEmitRate * 2; i +=2 )\n {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n return timeStamps;\n }"
] | [
"public void handleStateEvent(String callbackKey) {\n if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {\n ((StateEventHandler) handlers.get(callbackKey)).handle();\n } else {\n System.err.println(\"Error in handle: \" + callbackKey + \" for state handler \");\n }\n }",
"public IOrientationState getOrientationStateFromParam(int orientation) {\n switch (orientation) {\n case Orientation.ORIENTATION_HORIZONTAL_BOTTOM:\n return new OrientationStateHorizontalBottom();\n case Orientation.ORIENTATION_HORIZONTAL_TOP:\n return new OrientationStateHorizontalTop();\n case Orientation.ORIENTATION_VERTICAL_LEFT:\n return new OrientationStateVerticalLeft();\n case Orientation.ORIENTATION_VERTICAL_RIGHT:\n return new OrientationStateVerticalRight();\n default:\n return new OrientationStateHorizontalBottom();\n }\n }",
"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 static base_responses apply(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 applyresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tapplyresources[i] = new nspbr6();\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, applyresources,\"apply\");\n\t\t}\n\t\treturn result;\n\t}",
"public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()\n {\n if (resourceRequestCriterion == null)\n {\n resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();\n }\n return this.resourceRequestCriterion;\n }",
"public static FullTypeSignature getTypeSignature(String typeSignatureString,\n\t\t\tboolean useInternalFormFullyQualifiedName) {\n\t\tString key;\n\t\tif (!useInternalFormFullyQualifiedName) {\n\t\t\tkey = typeSignatureString.replace('.', '/')\n\t\t\t\t\t.replace('$', '.');\n\t\t} else {\n\t\t\tkey = typeSignatureString;\n\t\t}\n\n\t\t// we always use the internal form as a key for cache\n\t\tFullTypeSignature typeSignature = typeSignatureCache\n\t\t\t\t.get(key);\n\t\tif (typeSignature == null) {\n\t\t\tClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser(\n\t\t\t\t\ttypeSignatureString);\n\t\t\ttypeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);\n\t\t\ttypeSignature = typeSignatureParser.parseTypeSignature();\n\t\t\ttypeSignatureCache.put(typeSignatureString, typeSignature);\n\t\t}\n\t\treturn typeSignature;\n\t}",
"private void addClasses(XMLStreamWriter writer, File jarFile, boolean mapClassMethods) throws IOException, ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();\n\n URLClassLoader loader = new URLClassLoader(new URL[]\n {\n jarFile.toURI().toURL()\n }, currentThreadClassLoader);\n\n JarFile jar = new JarFile(jarFile);\n Enumeration<JarEntry> enumeration = jar.entries();\n while (enumeration.hasMoreElements())\n {\n JarEntry jarEntry = enumeration.nextElement();\n if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(\".class\"))\n {\n addClass(loader, jarEntry, writer, mapClassMethods);\n }\n }\n jar.close();\n }",
"private OAuth1RequestToken constructToken(Response response) {\r\n Element authElement = response.getPayload();\r\n String oauthToken = XMLUtilities.getChildValue(authElement, \"oauth_token\");\r\n String oauthTokenSecret = XMLUtilities.getChildValue(authElement, \"oauth_token_secret\");\r\n\r\n OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret);\r\n return token;\r\n }",
"public 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 }"
] |
Sets the country for which currencies should be requested.
@param countries The ISO countries.
@return the query for chaining. | [
"public CurrencyQueryBuilder setCountries(Locale... countries) {\n return set(CurrencyQuery.KEY_QUERY_COUNTRIES, Arrays.asList(countries));\n }"
] | [
"public Criteria copy(boolean includeGroupBy, boolean includeOrderBy, boolean includePrefetchedRelationships)\r\n {\r\n Criteria copy = new Criteria();\r\n\r\n copy.m_criteria = new Vector(this.m_criteria);\r\n copy.m_negative = this.m_negative;\r\n\r\n if (includeGroupBy)\r\n {\r\n copy.groupby = this.groupby;\r\n }\r\n if (includeOrderBy)\r\n {\r\n copy.orderby = this.orderby;\r\n }\r\n if (includePrefetchedRelationships)\r\n {\r\n copy.prefetchedRelationships = this.prefetchedRelationships;\r\n }\r\n\r\n return copy;\r\n }",
"public synchronized boolean tryDelegateResponseHandling(Response<ByteArray, Object> response) {\n if(responseHandlingCutoff) {\n return false;\n } else {\n responseQueue.offer(response);\n this.notifyAll();\n return true;\n }\n }",
"private void renderBlurLayer(float slideOffset) {\n if (enableBlur) {\n if (slideOffset == 0 || forceRedraw) {\n clearBlurView();\n }\n\n if (slideOffset > 0f && blurView == null) {\n if (drawerLayout.getChildCount() == 2) {\n blurView = new ImageView(drawerLayout.getContext());\n blurView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));\n blurView.setScaleType(ImageView.ScaleType.FIT_CENTER);\n drawerLayout.addView(blurView, 1);\n }\n\n if (BuilderUtil.isOnUiThread()) {\n if (cacheMode.equals(CacheMode.AUTO) || forceRedraw) {\n dali.load(drawerLayout.getChildAt(0)).blurRadius(blurRadius).downScale(downSample).noFade().error(Dali.NO_RESID).concurrent().skipCache().into(blurView);\n forceRedraw = false;\n } else {\n dali.load(drawerLayout.getChildAt(0)).blurRadius(blurRadius).downScale(downSample).noFade().error(Dali.NO_RESID).concurrent().into(blurView);\n }\n }\n }\n\n if (slideOffset > 0f && slideOffset < 1f) {\n int alpha = (int) Math.ceil((double) slideOffset * 255d);\n LegacySDKUtil.setImageAlpha(blurView, alpha);\n }\n }\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 static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) {\n Map<String, List<String>> ret = new HashMap<String, List<String>>();\n for (String topic : topics) {\n List<String> partList = new ArrayList<String>();\n List<String> brokers = getChildrenParentMayNotExist(zkClient, BrokerTopicsPath + \"/\" + topic);\n if (brokers != null) {\n for (String broker : brokers) {\n final String parts = readData(zkClient, BrokerTopicsPath + \"/\" + topic + \"/\" + broker);\n int nParts = Integer.parseInt(parts);\n for (int i = 0; i < nParts; i++) {\n partList.add(broker + \"-\" + i);\n }\n }\n }\n Collections.sort(partList);\n ret.put(topic, partList);\n }\n return ret;\n }",
"public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException {\n FilePath someWorkspace = project.getSomeWorkspace();\n if (someWorkspace == null) {\n throw new IllegalStateException(\"Couldn't find workspace\");\n }\n\n Map<String, String> workspaceEnv = Maps.newHashMap();\n workspaceEnv.put(\"WORKSPACE\", someWorkspace.getRemote());\n\n for (Builder builder : getBuilders()) {\n if (builder instanceof Gradle) {\n Gradle gradleBuilder = (Gradle) builder;\n String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();\n if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) {\n String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv);\n rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv);\n return new FilePath(someWorkspace, rootBuildScriptNormalized);\n } else {\n return someWorkspace;\n }\n }\n }\n\n throw new IllegalArgumentException(\"Couldn't find Gradle builder in the current builders list\");\n }",
"@Override\n public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) {\n return InternationalFixedDate.of(prolepticYear, month, dayOfMonth);\n }",
"public int[] executeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSendBatch = (Method) m_batchStatementsInProgress.remove(stmt);\r\n final boolean statementBatchingSupported = methodSendBatch != null;\r\n\r\n int[] retval = null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // sendBatch() returns total row count as an Integer\r\n methodSendBatch.invoke(stmt, null);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n retval = super.executeBatch(stmt);\r\n }\r\n return retval;\r\n }",
"public static void validate(final Organization organization) {\n if(organization.getName() == null ||\n organization.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Organization name cannot be null or empty!\")\n .build());\n }\n }"
] |
Sets top and bottom padding for all cells in the row.
@param padding new padding for top and bottom, ignored if smaller than 0
@return this to allow chaining | [
"public AT_Row setPaddingTopBottom(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingTopBottom(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}"
] | [
"public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }",
"synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }",
"private void readPredecessor(Task currTask, Project.Tasks.Task.PredecessorLink link)\n {\n BigInteger uid = link.getPredecessorUID();\n if (uid != null)\n {\n Task prevTask = m_projectFile.getTaskByUniqueID(Integer.valueOf(uid.intValue()));\n if (prevTask != null)\n {\n RelationType type;\n if (link.getType() != null)\n {\n type = RelationType.getInstance(link.getType().intValue());\n }\n else\n {\n type = RelationType.FINISH_START;\n }\n\n TimeUnit lagUnits = DatatypeConverter.parseDurationTimeUnits(link.getLagFormat());\n\n Duration lagDuration;\n int lag = NumberHelper.getInt(link.getLinkLag());\n if (lag == 0)\n {\n lagDuration = Duration.getInstance(0, lagUnits);\n }\n else\n {\n if (lagUnits == TimeUnit.PERCENT || lagUnits == TimeUnit.ELAPSED_PERCENT)\n {\n lagDuration = Duration.getInstance(lag, lagUnits);\n }\n else\n {\n lagDuration = Duration.convertUnits(lag / 10.0, TimeUnit.MINUTES, lagUnits, m_projectFile.getProjectProperties());\n }\n }\n\n Relation relation = currTask.addPredecessor(prevTask, type, lagDuration);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }",
"protected List<I_CmsFacetQueryItem> parseFacetQueryItems(JSONObject queryFacetObject) throws JSONException {\n\n JSONArray items = queryFacetObject.getJSONArray(JSON_KEY_QUERY_FACET_QUERY);\n List<I_CmsFacetQueryItem> result = new ArrayList<I_CmsFacetQueryItem>(items.length());\n for (int i = 0; i < items.length(); i++) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(items.getJSONObject(i));\n if (item != null) {\n result.add(item);\n }\n }\n return result;\n }",
"public boolean contains(Date date)\n {\n boolean result = false;\n\n if (date != null)\n {\n result = (DateHelper.compare(getFromDate(), getToDate(), date) == 0);\n }\n\n return (result);\n }",
"public void errorFuture(UUID taskId, Exception e) {\n DistributedFuture<GROUP, Serializable> future = remove(taskId);\n if(future != null) {\n future.setException(e);\n }\n }",
"public static List<ObjectModelResolver> getResolvers() {\n if (resolvers == null) {\n synchronized (serviceLoader) {\n if (resolvers == null) {\n List<ObjectModelResolver> foundResolvers = new ArrayList<ObjectModelResolver>();\n for (ObjectModelResolver resolver : serviceLoader) {\n foundResolvers.add(resolver);\n }\n resolvers = foundResolvers;\n }\n }\n }\n\n return resolvers;\n }",
"public String isChecked(String value1, String value2) {\n\n if ((value1 == null) || (value2 == null)) {\n return \"\";\n }\n\n if (value1.trim().equalsIgnoreCase(value2.trim())) {\n return \"checked\";\n }\n\n return \"\";\n }",
"public static final long parseDuration(String durationStr, long defaultValue) {\n\n durationStr = durationStr.toLowerCase().trim();\n Matcher matcher = DURATION_NUMBER_AND_UNIT_PATTERN.matcher(durationStr);\n long millis = 0;\n boolean matched = false;\n while (matcher.find()) {\n long number = Long.valueOf(matcher.group(1)).longValue();\n String unit = matcher.group(2);\n long multiplier = 0;\n for (int j = 0; j < DURATION_UNTIS.length; j++) {\n if (unit.equals(DURATION_UNTIS[j])) {\n multiplier = DURATION_MULTIPLIERS[j];\n break;\n }\n }\n if (multiplier == 0) {\n LOG.warn(\"parseDuration: Unknown unit \" + unit);\n } else {\n matched = true;\n }\n millis += number * multiplier;\n }\n if (!matched) {\n millis = defaultValue;\n }\n return millis;\n }"
] |
This method extracts candidate elements from the current DOM tree in the browser, based on
the crawl tags defined by the user.
@param currentState the state in which this extract method is requested.
@return a list of candidate elements that are not excluded.
@throws CrawljaxException if the method fails. | [
"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 static sslglobal_sslpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\tsslglobal_sslpolicy_binding response[] = (sslglobal_sslpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void deleteMetadataTemplate(BoxAPIConnection api, String scope, String template) {\n\n URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"DELETE\");\n\n request.send();\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 }",
"protected DateTimeException _peelDTE(DateTimeException e) {\n while (true) {\n Throwable t = e.getCause();\n if (t != null && t instanceof DateTimeException) {\n e = (DateTimeException) t;\n continue;\n }\n break;\n }\n return e;\n }",
"private List<Rule> getStyleRules(final String styleProperty) {\n final List<Rule> styleRules = new ArrayList<>(this.json.size());\n\n for (Iterator<String> iterator = this.json.keys(); iterator.hasNext(); ) {\n String styleKey = iterator.next();\n if (styleKey.equals(JSON_STYLE_PROPERTY) ||\n styleKey.equals(MapfishStyleParserPlugin.JSON_VERSION)) {\n continue;\n }\n PJsonObject styleJson = this.json.getJSONObject(styleKey);\n final List<Rule> currentRules = createStyleRule(styleKey, styleJson, styleProperty);\n for (Rule currentRule: currentRules) {\n if (currentRule != null) {\n styleRules.add(currentRule);\n }\n }\n }\n\n return styleRules;\n }",
"public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}",
"public 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 String retrieveVendorId() {\n if (MapboxTelemetry.applicationContext == null) {\n return updateVendorId();\n }\n\n SharedPreferences sharedPreferences = obtainSharedPreferences(MapboxTelemetry.applicationContext);\n String mapboxVendorId = sharedPreferences.getString(MAPBOX_SHARED_PREFERENCE_KEY_VENDOR_ID, \"\");\n if (TelemetryUtils.isEmpty(mapboxVendorId)) {\n mapboxVendorId = TelemetryUtils.updateVendorId();\n }\n return mapboxVendorId;\n }",
"public boolean isWorkingDay(Day day)\n {\n DayType value = getWorkingDay(day);\n boolean result;\n\n if (value == DayType.DEFAULT)\n {\n ProjectCalendar cal = getParent();\n if (cal != null)\n {\n result = cal.isWorkingDay(day);\n }\n else\n {\n result = (day != Day.SATURDAY && day != Day.SUNDAY);\n }\n }\n else\n {\n result = (value == DayType.WORKING);\n }\n\n return (result);\n }"
] |
In managed environment do internal close the used connection | [
"private void internalCleanup()\r\n {\r\n if(hasBroker())\r\n {\r\n PersistenceBroker broker = getBroker();\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Do internal cleanup and close the internal used connection without\" +\r\n \" closing the used broker\");\r\n }\r\n ConnectionManagerIF cm = broker.serviceConnectionManager();\r\n if(cm.isInLocalTransaction())\r\n {\r\n /*\r\n arminw:\r\n in managed environment this call will be ignored because, the JTA transaction\r\n manager control the connection status. But to make connectionManager happy we\r\n have to complete the \"local tx\" of the connectionManager before release the\r\n connection\r\n */\r\n cm.localCommit();\r\n }\r\n cm.releaseConnection();\r\n }\r\n }"
] | [
"@Override\r\n public String upload(File file, UploadMetaData metaData) throws FlickrException {\r\n Payload payload = new Payload(file);\r\n return sendUploadRequest(metaData, payload);\r\n }",
"public static 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 }",
"public void read(InputStream is) throws IOException\n {\n byte[] headerBlock = new byte[20];\n is.read(headerBlock);\n\n int headerLength = PEPUtility.getShort(headerBlock, 8);\n int recordCount = PEPUtility.getInt(headerBlock, 10);\n int recordLength = PEPUtility.getInt(headerBlock, 16);\n StreamHelper.skip(is, headerLength - headerBlock.length);\n\n byte[] record = new byte[recordLength];\n for (int recordIndex = 1; recordIndex <= recordCount; recordIndex++)\n {\n is.read(record);\n readRow(recordIndex, record);\n }\n }",
"protected void recordPreparedOperation(final ServerIdentity identity, final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> prepared) {\n final ModelNode preparedResult = prepared.getPreparedResult();\n // Hmm do the server results need to get translated as well as the host one?\n // final ModelNode transformedResult = prepared.getOperation().transformResult(preparedResult);\n updatePolicy.recordServerResult(identity, preparedResult);\n executor.recordPreparedOperation(prepared);\n }",
"public static void validateAllAvroSchemas(SerializerDefinition avroSerDef) {\n Map<Integer, String> schemaVersions = avroSerDef.getAllSchemaInfoVersions();\n if(schemaVersions.size() < 1) {\n throw new VoldemortException(\"No schema specified\");\n }\n for(Map.Entry<Integer, String> entry: schemaVersions.entrySet()) {\n Integer schemaVersionNumber = entry.getKey();\n String schemaStr = entry.getValue();\n try {\n Schema.parse(schemaStr);\n } catch(Exception e) {\n throw new VoldemortException(\"Unable to parse Avro schema version :\"\n + schemaVersionNumber + \", schema string :\"\n + schemaStr);\n }\n }\n }",
"public URI withEmptyAuthority(final URI uri) {\n URI _xifexpression = null;\n if ((uri.isFile() && (uri.authority() == null))) {\n _xifexpression = URI.createHierarchicalURI(uri.scheme(), \"\", uri.device(), uri.segments(), uri.query(), uri.fragment());\n } else {\n _xifexpression = uri;\n }\n return _xifexpression;\n }",
"public Collection getReaders(Object obj)\r\n {\r\n \tcheckTimedOutLocks();\r\n Identity oid = new Identity(obj,getBroker());\r\n return getReaders(oid);\r\n }",
"public void postPhoto(Photo photo, String blogId) throws FlickrException {\r\n postPhoto(photo, blogId, null);\r\n }",
"public BoxFile.Info getFileInfo(String fileID, String... fields) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = FILE_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }"
] |
This method is called to alert project listeners to the fact that
a task has been written to a project file.
@param task task instance | [
"public void fireTaskWrittenEvent(Task task)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.taskWritten(task);\n }\n }\n }"
] | [
"public Iterable<BoxLegalHoldAssignment.Info> getAssignments(String ... fields) {\n return this.getAssignments(null, null, DEFAULT_LIMIT, fields);\n }",
"private List<String> generateDateTimePatterns(String datePattern, String[] timePatterns)\n {\n List<String> patterns = new ArrayList<String>();\n for (String timePattern : timePatterns)\n {\n patterns.add(datePattern + \" \" + timePattern);\n }\n\n // Always fall back on the date-only pattern\n patterns.add(datePattern);\n\n return patterns;\n }",
"public FastTrackTable getTable(FastTrackTableType type)\n {\n FastTrackTable result = m_tables.get(type);\n if (result == null)\n {\n result = EMPTY_TABLE;\n }\n return result;\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 }",
"protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }",
"private void stopAllServersAndRemoveCamelContext(CamelContext camelContext) {\n log.debug(\"Stopping all servers associated with {}\", camelContext);\n List<SingleBusLocatorRegistrar> registrars = locatorRegistrar.getAllRegistars(camelContext);\n registrars.forEach(registrar -> registrar.stopAllServersAndRemoveCamelContext());\n }",
"public int getTrailingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong back = network ? 0 : getDivision(0).getMaxValue();\n\t\tint bitLen = 0;\n\t\tfor(int i = count - 1; i >= 0; i--) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != back) {\n\t\t\t\treturn bitLen + seg.getTrailingBitCount(network);\n\t\t\t}\n\t\t\tbitLen += seg.getBitCount();\n\t\t}\n\t\treturn bitLen;\n\t}",
"public static List<String> asListLinesIgnore(String content, Pattern ignorePattern) {\n List<String> retorno = new ArrayList<String>();\n content = content.replace(CARRIAGE_RETURN, RETURN);\n content = content.replace(RETURN, CARRIAGE_RETURN);\n for (String str : content.split(CARRIAGE_RETURN)) {\n if (!ignorePattern.matcher(str).matches()) {\n retorno.add(str);\n }\n }\n return retorno;\n }",
"public static byte[] copy(byte[] array, int from, int to) {\n if(to - from < 0) {\n return new byte[0];\n } else {\n byte[] a = new byte[to - from];\n System.arraycopy(array, from, a, 0, to - from);\n return a;\n }\n }"
] |
Say whether this character is an annotation introducing
character.
@param ch The character to check
@return Whether it is an annotation introducing character | [
"public boolean isLabelAnnotationIntroducingCharacter(char ch) {\r\n char[] cutChars = labelAnnotationIntroducingCharacters();\r\n for (char cutChar : cutChars) {\r\n if (ch == cutChar) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }"
] | [
"public static Priority getInstance(Locale locale, String priority)\n {\n int index = DEFAULT_PRIORITY_INDEX;\n\n if (priority != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(locale, LocaleData.PRIORITY_TYPES);\n for (int loop = 0; loop < priorityTypes.length; loop++)\n {\n if (priorityTypes[loop].equalsIgnoreCase(priority) == true)\n {\n index = loop;\n break;\n }\n }\n }\n\n return (Priority.getInstance((index + 1) * 100));\n }",
"@Api\n\tpublic static void configureNoCaching(HttpServletResponse response) {\n\t\t// HTTP 1.0 header:\n\t\tresponse.setHeader(HTTP_EXPIRES_HEADER, HTTP_EXPIRES_HEADER_NOCACHE_VALUE);\n\t\tresponse.setHeader(HTTP_CACHE_PRAGMA, HTTP_CACHE_PRAGMA_VALUE);\n\n\t\t// HTTP 1.1 header:\n\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, HTTP_CACHE_CONTROL_HEADER_NOCACHE_VALUE);\n\t}",
"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 base_response delete(nitro_service client, String labelname) throws Exception {\n\t\tdnspolicylabel deleteresource = new dnspolicylabel();\n\t\tdeleteresource.labelname = labelname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static boolean inArea(Point point, Rect area, float offsetRatio) {\n int offset = (int) (area.width() * offsetRatio);\n return point.x >= area.left - offset && point.x <= area.right + offset &&\n point.y >= area.top - offset && point.y <= area.bottom + offset;\n }",
"public static boolean bidiagOuterBlocks( final int blockLength ,\n final DSubmatrixD1 A ,\n final double gammasU[],\n final double gammasV[])\n {\n// System.out.println(\"---------- Orig\");\n// A.original.print();\n\n int width = Math.min(blockLength,A.col1-A.col0);\n int height = Math.min(blockLength,A.row1-A.row0);\n\n int min = Math.min(width,height);\n\n for( int i = 0; i < min; i++ ) {\n //--- Apply reflector to the column\n\n // compute the householder vector\n if (!computeHouseHolderCol(blockLength, A, gammasU, i))\n return false;\n\n // apply to rest of the columns in the column block\n rank1UpdateMultR_Col(blockLength,A,i,gammasU[A.col0+i]);\n\n // apply to the top row block\n rank1UpdateMultR_TopRow(blockLength,A,i,gammasU[A.col0+i]);\n\n System.out.println(\"After column stuff\");\n A.original.print();\n\n //-- Apply reflector to the row\n if(!computeHouseHolderRow(blockLength,A,gammasV,i))\n return false;\n \n // apply to rest of the rows in the row block\n rank1UpdateMultL_Row(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After update row\");\n A.original.print();\n\n // apply to the left column block\n // TODO THIS WON'T WORK!!!!!!!!!!!!!\n // Needs the whole matrix to have been updated by the left reflector to compute the correct solution\n// rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]);\n\n System.out.println(\"After row stuff\");\n A.original.print();\n }\n\n return true;\n }",
"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}",
"private static void flushCurrentWord( StringBuilder currentWords, List<Word> formattedWords, boolean cutWhitespace ) {\n if( currentWords.length() > 0 ) {\n if( cutWhitespace && currentWords.charAt( currentWords.length() - 1 ) == ' ' ) {\n currentWords.setLength( currentWords.length() - 1 );\n }\n formattedWords.add( new Word( currentWords.toString() ) );\n currentWords.setLength( 0 );\n }\n }",
"public static <K, V> void operator_remove(Map<K, V> map, Iterable<? super K> keysToRemove) {\n\t\tfor (final Object key : keysToRemove) {\n\t\t\tmap.remove(key);\n\t\t}\n\t}"
] |
Use this API to enable the mode on Netscaler.
@param mode mode to be enabled.
@return status of the operation performed.
@throws Exception Nitro exception. | [
"public base_response enable_modes(String[] modes) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsmode resource = new nsmode();\n\t\tresource.set_mode(modes);\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 TableReader read() throws IOException\n {\n int tableHeader = m_stream.readInt();\n if (tableHeader != 0x39AF547A)\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n int recordCount = m_stream.readInt();\n for (int loop = 0; loop < recordCount; loop++)\n {\n int rowMagicNumber = m_stream.readInt();\n if (rowMagicNumber != rowMagicNumber())\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n // We use a LinkedHashMap to preserve insertion order in iteration\n // Useful when debugging the file format.\n Map<String, Object> map = new LinkedHashMap<String, Object>();\n\n if (hasUUID())\n {\n readUUID(m_stream, map);\n }\n\n readRow(m_stream, map);\n\n SynchroLogger.log(\"READER\", getClass(), map);\n\n m_rows.add(new MapRow(map));\n }\n\n int tableTrailer = m_stream.readInt();\n if (tableTrailer != 0x6F99E416)\n {\n throw new IllegalArgumentException(\"Unexpected file format\");\n }\n\n postTrailer(m_stream);\n\n return this;\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 QueryBuilder useIndex(String designDocument, String indexName) {\n useIndex = new String[]{designDocument, indexName};\n return this;\n }",
"public static CuratorFramework newFluoCurator(FluoConfiguration config) {\n return newCurator(config.getInstanceZookeepers(), config.getZookeeperTimeout(),\n config.getZookeeperSecret());\n }",
"public void setClasspathRef(Reference r)\r\n {\r\n createClasspath().setRefid(r);\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }",
"public static int isValid( DMatrixRMaj cov ) {\n if( !MatrixFeatures_DDRM.isDiagonalPositive(cov) )\n return 1;\n\n if( !MatrixFeatures_DDRM.isSymmetric(cov,TOL) )\n return 2;\n\n if( !MatrixFeatures_DDRM.isPositiveSemidefinite(cov) )\n return 3;\n\n return 0;\n }",
"public static void writeObject(File file, Object object) throws IOException {\n FileOutputStream fileOut = new FileOutputStream(file);\n ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));\n try {\n out.writeObject(object);\n out.flush();\n // Force sync\n fileOut.getFD().sync();\n } finally {\n IoUtils.safeClose(out);\n }\n }",
"public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }",
"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 }"
] |
Use this API to add nspbr6 resources. | [
"public static base_responses add(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 addresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nspbr6();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].action = resources[i].action;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].nexthop = resources[i].nexthop;\n\t\t\t\taddresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\taddresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }",
"@SuppressWarnings(\"unchecked\")\r\n public static boolean addPropertyDefault(PropertiesImpl props, PropertyDefinition<?> propDef) {\r\n\r\n if ((props == null) || (props.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Props must not be null!\");\r\n }\r\n\r\n if (propDef == null) {\r\n return false;\r\n }\r\n\r\n List<?> defaultValue = propDef.getDefaultValue();\r\n if ((defaultValue != null) && (!defaultValue.isEmpty())) {\r\n switch (propDef.getPropertyType()) {\r\n case BOOLEAN:\r\n props.addProperty(new PropertyBooleanImpl(propDef.getId(), (List<Boolean>)defaultValue));\r\n break;\r\n case DATETIME:\r\n props.addProperty(new PropertyDateTimeImpl(propDef.getId(), (List<GregorianCalendar>)defaultValue));\r\n break;\r\n case DECIMAL:\r\n props.addProperty(new PropertyDecimalImpl(propDef.getId(), (List<BigDecimal>)defaultValue));\r\n break;\r\n case HTML:\r\n props.addProperty(new PropertyHtmlImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case ID:\r\n props.addProperty(new PropertyIdImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case INTEGER:\r\n props.addProperty(new PropertyIntegerImpl(propDef.getId(), (List<BigInteger>)defaultValue));\r\n break;\r\n case STRING:\r\n props.addProperty(new PropertyStringImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n case URI:\r\n props.addProperty(new PropertyUriImpl(propDef.getId(), (List<String>)defaultValue));\r\n break;\r\n default:\r\n throw new RuntimeException(\"Unknown datatype! Spec change?\");\r\n }\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"public float[] getFloatArray(String attributeName)\n {\n float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }",
"public Session startSshSessionAndObtainSession() {\n\n Session session = null;\n try {\n\n JSch jsch = new JSch();\n if (sshMeta.getSshLoginType() == SshLoginType.KEY) {\n\n String workingDir = System.getProperty(\"user.dir\");\n String privKeyAbsPath = workingDir + \"/\"\n + sshMeta.getPrivKeyRelativePath();\n logger.debug(\"use privkey: path: \" + privKeyAbsPath);\n\n if (!PcFileNetworkIoUtils.isFileExist(privKeyAbsPath)) {\n throw new RuntimeException(\"file not found at \"\n + privKeyAbsPath);\n }\n\n if (sshMeta.isPrivKeyUsePassphrase()\n && sshMeta.getPassphrase() != null) {\n jsch.addIdentity(privKeyAbsPath, sshMeta.getPassphrase());\n } else {\n jsch.addIdentity(privKeyAbsPath);\n }\n }\n\n session = jsch.getSession(sshMeta.getUserName(), targetHost,\n sshMeta.getSshPort());\n if (sshMeta.getSshLoginType() == SshLoginType.PASSWORD) {\n session.setPassword(sshMeta.getPassword());\n }\n\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n } catch (Exception t) {\n throw new RuntimeException(t);\n }\n return session;\n }",
"private long getWeightedMatchScore(Iterable<String> requestUriParts, Iterable<String> destUriParts) {\n // The score calculated below is a base 5 number\n // The score will have one digit for one part of the URI\n // This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13\n // We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during\n // score calculation\n long score = 0;\n for (Iterator<String> rit = requestUriParts.iterator(), dit = destUriParts.iterator();\n rit.hasNext() && dit.hasNext(); ) {\n String requestPart = rit.next();\n String destPart = dit.next();\n if (requestPart.equals(destPart)) {\n score = (score * 5) + 4;\n } else if (PatternPathRouterWithGroups.GROUP_PATTERN.matcher(destPart).matches()) {\n score = (score * 5) + 3;\n } else {\n score = (score * 5) + 2;\n }\n }\n return score;\n }",
"public Date getStart()\n {\n Date result = null;\n for (ResourceAssignment assignment : m_assignments)\n {\n if (result == null || DateHelper.compare(result, assignment.getStart()) > 0)\n {\n result = assignment.getStart();\n }\n }\n return (result);\n }",
"public ContentAssistEntry createProposal(final String proposal, final String prefix, final ContentAssistContext context, final String kind, final Procedure1<? super ContentAssistEntry> init) {\n boolean _isValidProposal = this.isValidProposal(proposal, prefix, context);\n if (_isValidProposal) {\n final ContentAssistEntry result = new ContentAssistEntry();\n result.setProposal(proposal);\n result.setPrefix(prefix);\n if ((kind != null)) {\n result.setKind(kind);\n }\n if ((init != null)) {\n init.apply(result);\n }\n return result;\n }\n return null;\n }",
"public static route6[] get(nitro_service service) throws Exception{\n\t\troute6 obj = new route6();\n\t\troute6[] response = (route6[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public List<Method> getMethodsFromGroupId(int groupId, String[] filters) throws Exception {\n ArrayList<Method> methods = new ArrayList<Method>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_GROUP_ID + \" = ?\"\n );\n statement.setInt(1, groupId);\n results = statement.executeQuery();\n while (results.next()) {\n Method method = PathOverrideService.getInstance().getMethodForOverrideId(results.getInt(\"id\"));\n if (method == null) {\n continue;\n }\n\n // decide whether or not to add this method based on the filters\n boolean add = true;\n if (filters != null) {\n add = false;\n for (String filter : filters) {\n if (method.getMethodType().endsWith(filter)) {\n add = true;\n break;\n }\n }\n }\n\n if (add && !methods.contains(method)) {\n methods.add(method);\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 (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return methods;\n }"
] |
Calculates a column title using camel humps to separate words.
@param _property the property descriptor.
@return the column title for the given property. | [
"private static String getColumnTitle(final PropertyDescriptor _property) {\n final StringBuilder buffer = new StringBuilder();\n final String name = _property.getName();\n buffer.append(Character.toUpperCase(name.charAt(0)));\n for (int i = 1; i < name.length(); i++) {\n final char c = name.charAt(i);\n if (Character.isUpperCase(c)) {\n buffer.append(' ');\n }\n buffer.append(c);\n }\n return buffer.toString();\n }"
] | [
"public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }",
"public static final BigDecimal printCurrency(Number value)\n {\n return (value == null || value.doubleValue() == 0 ? null : new BigDecimal(value.doubleValue() * 100));\n }",
"public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {\r\n String[] coVariables = action.getCoVariables().split(\",\");\r\n int n = Integer.valueOf(action.getN());\n\r\n List<Map<String, String>> newPossibleStateList = new ArrayList<>();\n\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n Map<String, String[]> variableDomains = new HashMap<>();\r\n Map<String, String> defaultVariableValues = new HashMap<>();\r\n for (String variable : coVariables) {\r\n String variableMetaInfo = possibleState.get(variable);\r\n String[] variableDomain = variableMetaInfo.split(\",\");\r\n variableDomains.put(variable, variableDomain);\r\n defaultVariableValues.put(variable, variableDomain[0]);\r\n }\n\r\n List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);\r\n for (Map<String, String> nWiseCombination : nWiseCombinations) {\r\n Map<String, String> newPossibleState = new HashMap<>(possibleState);\r\n newPossibleState.putAll(defaultVariableValues);\r\n newPossibleState.putAll(nWiseCombination);\r\n newPossibleStateList.add(newPossibleState);\r\n }\r\n }\n\r\n return newPossibleStateList;\r\n }",
"public static JqmClient getClient(String name, Properties p, boolean cached)\n {\n Properties p2 = null;\n if (binder == null)\n {\n bind();\n }\n if (p == null)\n {\n p2 = props;\n }\n else\n {\n p2 = new Properties(props);\n p2.putAll(p);\n }\n return binder.getClientFactory().getClient(name, p2, cached);\n }",
"public static Command newSetGlobal(String identifier,\n Object object) {\n return getCommandFactoryProvider().newSetGlobal( identifier,\n object );\n }",
"private void reconnectFlows() {\n // create the reverse id map:\n for (Entry<Object, List<String>> entry : _outgoingFlows.entrySet()) {\n for (String flowId : entry.getValue()) {\n if (entry.getKey() instanceof SequenceFlow) { // if it is a sequence flow, we can tell its targets\n if (_idMap.get(flowId) instanceof FlowNode) {\n ((SequenceFlow) entry.getKey()).setTargetRef((FlowNode) _idMap.get(flowId));\n }\n if (_idMap.get(flowId) instanceof Association) {\n ((Association) _idMap.get(flowId)).setTargetRef((SequenceFlow) entry.getKey());\n }\n } else if (entry.getKey() instanceof Association) {\n ((Association) entry.getKey()).setTargetRef((BaseElement) _idMap.get(flowId));\n } else { // if it is a node, we can map it to its outgoing sequence flows\n if (_idMap.get(flowId) instanceof SequenceFlow) {\n ((FlowNode) entry.getKey()).getOutgoing().add((SequenceFlow) _idMap.get(flowId));\n } else if (_idMap.get(flowId) instanceof Association) {\n ((Association) _idMap.get(flowId)).setSourceRef((BaseElement) entry.getKey());\n }\n }\n }\n }\n }",
"public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) {\n Class<?> superClass = typeInfo.getSuperClass();\n if (superClass.getName().startsWith(JAVA)) {\n ClassLoader cl = proxyServices.getClassLoader(proxiedType);\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass);\n }",
"public ItemRequest<Tag> update(String tag) {\n \n String path = String.format(\"/tags/%s\", tag);\n return new ItemRequest<Tag>(this, Tag.class, path, \"PUT\");\n }",
"void releaseResources(JobInstance ji)\n {\n this.peremption.remove(ji.getId());\n this.actualNbThread.decrementAndGet();\n\n for (ResourceManagerBase rm : this.resourceManagers)\n {\n rm.releaseResource(ji);\n }\n\n if (!this.strictPollingPeriod)\n {\n // Force a new loop at once. This makes queues more fluid.\n loop.release(1);\n }\n this.engine.signalEndOfRun();\n }"
] |
Reads and returns the mediator URN from the JSON content.
@see #RegistrationConfig(String) | [
"public String getURN() throws InvalidRegistrationContentException {\n if (parsedConfig==null || parsedConfig.urn==null || parsedConfig.urn.trim().isEmpty()) {\n throw new InvalidRegistrationContentException(\"Invalid registration config - failed to read mediator URN\");\n }\n return parsedConfig.urn;\n }"
] | [
"private void computeUnnamedParams() {\n unnamedParams.addAll(rawArgs.stream().filter(arg -> !isNamedParam(arg)).collect(Collectors.toList()));\n }",
"public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }",
"public static int cudnnGetReductionWorkspaceSize(\n cudnnHandle handle, \n cudnnReduceTensorDescriptor reduceTensorDesc, \n cudnnTensorDescriptor aDesc, \n cudnnTensorDescriptor cDesc, \n long[] sizeInBytes)\n {\n return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));\n }",
"public static long count(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"public String format(final LoggingEvent event) {\n\t\tfinal StringBuffer buf = new StringBuffer();\n\t\tfor (PatternConverter c = head; c != null; c = c.next) {\n\t\t\tc.format(buf, event);\n\t\t}\n\t\treturn buf.toString();\n\t}",
"public final void reset()\n {\n for (int i = 0; i < permutationIndices.length; i++)\n {\n permutationIndices[i] = i;\n }\n remainingPermutations = totalPermutations;\n }",
"public static BoxStoragePolicyAssignment.Info getAssignmentForTarget(final BoxAPIConnection api,\n String resolvedForType, String resolvedForID) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"resolved_for_type\", resolvedForType)\n .appendParam(\"resolved_for_id\", resolvedForID);\n URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,\n response.getJsonObject().get(\"entries\").asArray().get(0).asObject().get(\"id\").asString());\n BoxStoragePolicyAssignment.Info info = storagePolicyAssignment.new\n Info(response.getJsonObject().get(\"entries\").asArray().get(0).asObject());\n\n return info;\n }",
"@SuppressWarnings(\"unused\")\n public void setError(CharSequence error, Drawable icon) {\n mPhoneEdit.setError(error, icon);\n }",
"private static Map<String, List<String>> getOrCreateProtocolHeader(\n Message message) {\n Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message\n .get(Message.PROTOCOL_HEADERS));\n if (headers == null) {\n headers = new HashMap<String, List<String>>();\n message.put(Message.PROTOCOL_HEADERS, headers);\n }\n return headers;\n }"
] |
Get the days difference | [
"public static int daysDiff(Date earlierDate, Date laterDate) {\n if (earlierDate == null || laterDate == null) {\n return 0;\n }\n\n return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS));\n }"
] | [
"public void onDrawFrame(float frameTime)\n {\n if (isEnabled() && (mScene != null) && mPickEventLock.tryLock())\n {\n // Don't call if we are in the middle of processing another pick\n try\n {\n doPick();\n }\n finally\n {\n mPickEventLock.unlock();\n }\n }\n }",
"public static snmpalarm[] get(nitro_service service) throws Exception{\n\t\tsnmpalarm obj = new snmpalarm();\n\t\tsnmpalarm[] response = (snmpalarm[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected void deliverLifecycleAnnouncement(final Logger logger, final boolean starting) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n for (final LifecycleListener listener : getLifecycleListeners()) {\n try {\n if (starting) {\n listener.started(LifecycleParticipant.this);\n } else {\n listener.stopped(LifecycleParticipant.this);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering lifecycle announcement to listener\", t);\n }\n }\n }\n }, \"Lifecycle announcement delivery\").start();\n }",
"List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }",
"public static String stripHtml(String html) {\n\n if (html == null) {\n return null;\n }\n Element el = DOM.createDiv();\n el.setInnerHTML(html);\n return el.getInnerText();\n }",
"public static List<Artifact> getAllArtifacts(final Module module){\n final List<Artifact> artifacts = new ArrayList<Artifact>();\n\n for(final Module subModule: module.getSubmodules()){\n artifacts.addAll(getAllArtifacts(subModule));\n }\n\n artifacts.addAll(module.getArtifacts());\n\n return artifacts;\n }",
"protected void _format(EObject obj, IFormattableDocument document) {\n\t\tfor (EObject child : obj.eContents())\n\t\t\tdocument.format(child);\n\t}",
"public static sslvserver_sslcipher_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcipher_binding obj = new sslvserver_sslcipher_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcipher_binding response[] = (sslvserver_sslcipher_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void updateFrontFacingRotation(float rotation) {\n if (!Float.isNaN(rotation) && !equal(rotation, frontFacingRotation)) {\n final float oldRotation = frontFacingRotation;\n frontFacingRotation = rotation % 360;\n for (OnFrontRotationChangedListener listener : mOnFrontRotationChangedListeners) {\n try {\n listener.onFrontRotationChanged(this, frontFacingRotation, oldRotation);\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(TAG, e, \"updateFrontFacingRotation()\");\n }\n }\n }\n }"
] |
Checks whether two internet addresses are on the same subnet.
@param prefixLength the number of bits within an address that identify the network
@param address1 the first address to be compared
@param address2 the second address to be compared
@return true if both addresses share the same network bits | [
"public static boolean sameNetwork(int prefixLength, InetAddress address1, InetAddress address2) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Comparing address \" + address1.getHostAddress() + \" with \" + address2.getHostAddress() + \", prefixLength=\" + prefixLength);\n }\n long prefixMask = 0xffffffffL & (-1 << (32 - prefixLength));\n return (addressToLong(address1) & prefixMask) == (addressToLong(address2) & prefixMask);\n }"
] | [
"public void close()\n {\n if (transac_open)\n {\n try\n {\n this._cnx.rollback();\n }\n catch (Exception e)\n {\n // Ignore.\n }\n }\n\n for (Statement s : toClose)\n {\n closeQuietly(s);\n }\n toClose.clear();\n\n closeQuietly(_cnx);\n _cnx = null;\n }",
"private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }",
"public void createNamespace() {\n Map<String, String> namespaceAnnotations = annotationProvider.create(session.getId(), Constants.RUNNING_STATUS);\n if (namespaceService.exists(session.getNamespace())) {\n //namespace exists\n } else if (configuration.isNamespaceLazyCreateEnabled()) {\n namespaceService.create(session.getNamespace(), namespaceAnnotations);\n } else {\n throw new IllegalStateException(\"Namespace [\" + session.getNamespace() + \"] doesn't exist and lazily creation of namespaces is disabled. \"\n + \"Either use an existing one, or set `namespace.lazy.enabled` to true.\");\n }\n }",
"private static Map<String, Integer> findClasses(Path path)\n {\n List<String> paths = findPaths(path, true);\n Map<String, Integer> results = new HashMap<>();\n for (String subPath : paths)\n {\n if (subPath.endsWith(\".java\") || subPath.endsWith(\".class\"))\n {\n String qualifiedName = PathUtil.classFilePathToClassname(subPath);\n addClassToMap(results, qualifiedName);\n }\n }\n return results;\n }",
"private void readResourceCustomPropertyDefinitions(Resources gpResources)\n {\n CustomField field = m_projectFile.getCustomFields().getCustomField(ResourceField.TEXT1);\n field.setAlias(\"Phone\");\n\n for (CustomPropertyDefinition definition : gpResources.getCustomPropertyDefinition())\n {\n //\n // Find the next available field of the correct type.\n //\n String type = definition.getType();\n FieldType fieldType = RESOURCE_PROPERTY_TYPES.get(type).getField();\n\n //\n // If we have run out of fields of the right type, try using a text field.\n //\n if (fieldType == null)\n {\n fieldType = RESOURCE_PROPERTY_TYPES.get(\"text\").getField();\n }\n\n //\n // If we actually have a field available, set the alias to match\n // the name used in GanttProject.\n //\n if (fieldType != null)\n {\n field = m_projectFile.getCustomFields().getCustomField(fieldType);\n field.setAlias(definition.getName());\n String defaultValue = definition.getDefaultValue();\n if (defaultValue != null && defaultValue.isEmpty())\n {\n defaultValue = null;\n }\n m_resourcePropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue));\n }\n }\n }",
"public Photoset getInfo(String photosetId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photosetElement.getAttribute(\"owner\"));\r\n photoset.setOwner(owner);\r\n\r\n Photo primaryPhoto = new Photo();\r\n primaryPhoto.setId(photosetElement.getAttribute(\"primary\"));\r\n primaryPhoto.setSecret(photosetElement.getAttribute(\"secret\")); // TODO verify that this is the secret for the photo\r\n primaryPhoto.setServer(photosetElement.getAttribute(\"server\")); // TODO verify that this is the server for the photo\r\n primaryPhoto.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n // TODO remove secret/server/farm from photoset?\r\n // It's rather related to the primaryPhoto, then to the photoset itself.\r\n photoset.setSecret(photosetElement.getAttribute(\"secret\"));\r\n photoset.setServer(photosetElement.getAttribute(\"server\"));\r\n photoset.setFarm(photosetElement.getAttribute(\"farm\"));\r\n photoset.setPhotoCount(photosetElement.getAttribute(\"count_photos\"));\r\n photoset.setVideoCount(Integer.parseInt(photosetElement.getAttribute(\"count_videos\")));\r\n photoset.setViewCount(Integer.parseInt(photosetElement.getAttribute(\"count_views\")));\r\n photoset.setCommentCount(Integer.parseInt(photosetElement.getAttribute(\"count_comments\")));\r\n photoset.setDateCreate(photosetElement.getAttribute(\"date_create\"));\r\n photoset.setDateUpdate(photosetElement.getAttribute(\"date_update\"));\r\n\r\n photoset.setIsCanComment(\"1\".equals(photosetElement.getAttribute(\"can_comment\")));\r\n\r\n photoset.setTitle(XMLUtilities.getChildValue(photosetElement, \"title\"));\r\n photoset.setDescription(XMLUtilities.getChildValue(photosetElement, \"description\"));\r\n photoset.setPrimaryPhoto(primaryPhoto);\r\n\r\n return photoset;\r\n }",
"private void writeCompressedText(File file, byte[] compressedContent) throws IOException\r\n {\r\n ByteArrayInputStream bais = new ByteArrayInputStream(compressedContent);\r\n GZIPInputStream gis = new GZIPInputStream(bais);\r\n BufferedReader input = new BufferedReader(new InputStreamReader(gis));\r\n BufferedWriter output = new BufferedWriter(new FileWriter(file));\r\n String line;\r\n\r\n while ((line = input.readLine()) != null)\r\n {\r\n output.write(line);\r\n output.write('\\n');\r\n }\r\n input.close();\r\n gis.close();\r\n bais.close();\r\n output.close();\r\n }",
"public Number getOvertimeCost()\n {\n Number cost = (Number) getCachedValue(AssignmentField.OVERTIME_COST);\n if (cost == null)\n {\n Number actual = getActualOvertimeCost();\n Number remaining = getRemainingOvertimeCost();\n if (actual != null && remaining != null)\n {\n cost = NumberHelper.getDouble(actual.doubleValue() + remaining.doubleValue());\n set(AssignmentField.OVERTIME_COST, cost);\n }\n }\n return (cost);\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry454Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry454Date>) super.zonedDateTime(temporal);\n }"
] |
Reads a single day for a calendar.
@param mpxjCalendar ProjectCalendar instance
@param day ConceptDraw PROJECT week day | [
"private void readWeekDay(ProjectCalendar mpxjCalendar, WeekDay day)\n {\n if (day.isIsDayWorking())\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day.getDay());\n for (Document.Calendars.Calendar.WeekDays.WeekDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n hours.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }"
] | [
"public void ifDoesntHaveMemberTag(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean result = false;\r\n\r\n if (getCurrentField() != null) {\r\n if (!hasTag(attributes, FOR_FIELD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (!hasTag(attributes, FOR_METHOD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n if (!result) {\r\n String error = attributes.getProperty(\"error\");\r\n\r\n if (error != null) {\r\n getEngine().print(error);\r\n }\r\n }\r\n }",
"public static nd6ravariables[] get(nitro_service service, Long vlan[]) throws Exception{\n\t\tif (vlan !=null && vlan.length>0) {\n\t\t\tnd6ravariables response[] = new nd6ravariables[vlan.length];\n\t\t\tnd6ravariables obj[] = new nd6ravariables[vlan.length];\n\t\t\tfor (int i=0;i<vlan.length;i++) {\n\t\t\t\tobj[i] = new nd6ravariables();\n\t\t\t\tobj[i].set_vlan(vlan[i]);\n\t\t\t\tresponse[i] = (nd6ravariables) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void writeDayTypes(Calendars calendars)\n {\n DayTypes dayTypes = m_factory.createDayTypes();\n calendars.setDayTypes(dayTypes);\n List<DayType> typeList = dayTypes.getDayType();\n\n DayType dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"0\");\n dayType.setName(\"Working\");\n dayType.setDescription(\"A default working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"1\");\n dayType.setName(\"Nonworking\");\n dayType.setDescription(\"A default non working day\");\n\n dayType = m_factory.createDayType();\n typeList.add(dayType);\n dayType.setId(\"2\");\n dayType.setName(\"Use base\");\n dayType.setDescription(\"Use day from base calendar\");\n }",
"public long getTimeRemainingInMillis()\n {\n long batchTime = System.currentTimeMillis() - startTime;\n double timePerIteration = (double) batchTime / (double) worked.get();\n return (long) (timePerIteration * (total - worked.get()));\n }",
"private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }",
"public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }",
"protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }",
"public static Interface[] get(nitro_service service) throws Exception{\n\t\tInterface obj = new Interface();\n\t\tInterface[] response = (Interface[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Schedule at most one task.
The scheduled task *must* invoke 'doneTask()' upon
completion/termination.
@param executeService flag to control execution of the service, some tests pass
in value 'false'
@return The task scheduled or null if not possible to schedule a task at
this time. | [
"protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }"
] | [
"private String typeParameters(Options opt, ParameterizedType t) {\n\tif (t == null)\n\t return \"\";\n\tStringBuffer tp = new StringBuffer(1000).append(\"<\");\n\tType args[] = t.typeArguments();\n\tfor (int i = 0; i < args.length; i++) {\n\t tp.append(type(opt, args[i], true));\n\t if (i != args.length - 1)\n\t\ttp.append(\", \");\n\t}\n\treturn tp.append(\">\").toString();\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 static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {\n return Collections.unmodifiableSortedMap(self);\n }",
"public void close() {\n this.waitUntilInitialized();\n\n this.ongoingOperationsGroup.blockAndWait();\n\n syncLock.lock();\n try {\n if (this.networkMonitor != null) {\n this.networkMonitor.removeNetworkStateListener(this);\n }\n this.dispatcher.close();\n stop();\n this.localClient.close();\n } finally {\n syncLock.unlock();\n }\n }",
"private void firstInnerTableStart(Options opt) {\n\tw.print(linePrefix + linePrefix + \"<tr>\" + opt.shape.extraColumn() +\n\t\t\"<td><table border=\\\"0\\\" cellspacing=\\\"0\\\" \" +\n\t\t\"cellpadding=\\\"1\\\">\" + linePostfix);\n }",
"@Override\n public void perform(Rewrite event, EvaluationContext context)\n {\n perform((GraphRewrite) event, context);\n }",
"public synchronized boolean put(byte value) {\n if (available == capacity) {\n return false;\n }\n buffer[idxPut] = value;\n idxPut = (idxPut + 1) % capacity;\n available++;\n return true;\n }",
"public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException {\n\t\tdocument.writeElement(\"vml:shape\", asChild);\n\t\tPoint p = (Point) o;\n\t\tString adj = document.getFormatter().format(p.getX()) + \",\"\n\t\t\t\t+ document.getFormatter().format(p.getY());\n\t\tdocument.writeAttribute(\"adj\", adj);\n\t}",
"public static cachepolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_binding obj = new cachepolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_binding response = (cachepolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.