query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Sorts the specified list itself according to the order induced by applying a key function to each element which
yields a comparable criteria.
@param list
the list to be sorted. May not be <code>null</code>.
@param key
the key function to-be-used. May not be <code>null</code>.
@return the sorted list itself.
@see Collections#sort(List) | [
"public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\tif (key == null)\n\t\t\tthrow new NullPointerException(\"key\");\n\t\tCollections.sort(list, new KeyComparator<T, C>(key));\n\t\treturn list;\n\t}"
] | [
"private void allClustersEqual(final List<String> clusterUrls) {\n Validate.notEmpty(clusterUrls, \"clusterUrls cannot be null\");\n // If only one clusterUrl return immediately\n if (clusterUrls.size() == 1)\n return;\n AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0));\n Cluster clusterLhs = adminClientLhs.getAdminClientCluster();\n for (int index = 1; index < clusterUrls.size(); index++) {\n AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index));\n Cluster clusterRhs = adminClientRhs.getAdminClientCluster();\n if (!areTwoClustersEqual(clusterLhs, clusterRhs))\n throw new VoldemortException(\"Cluster \" + clusterLhs.getName()\n + \" is not the same as \" + clusterRhs.getName());\n }\n }",
"protected static void checkQueues(final Iterable<String> queues) {\n if (queues == null) {\n throw new IllegalArgumentException(\"queues must not be null\");\n }\n for (final String queue : queues) {\n if (queue == null || \"\".equals(queue)) {\n throw new IllegalArgumentException(\"queues' members must not be null: \" + queues);\n }\n }\n }",
"private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }",
"public static ProctorLoadResult verify(\n @Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource,\n @Nonnull final Map<String, TestSpecification> requiredTests,\n @Nonnull final FunctionMapper functionMapper,\n final ProvidedContext providedContext,\n @Nonnull final Set<String> dynamicTests\n ) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());\n for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {\n final Map<Integer, String> bucketValueToName = Maps.newHashMap();\n for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {\n bucketValueToName.put(bucket.getValue(), bucket.getKey());\n }\n allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);\n }\n\n final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();\n final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());\n resultBuilder.recordAllMissing(missingTests);\n for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {\n final String testName = entry.getKey();\n\n final Map<Integer, String> knownBuckets;\n final TestSpecification specification;\n final boolean isRequired;\n if (allTestsKnownBuckets.containsKey(testName)) {\n // required in specification\n isRequired = true;\n knownBuckets = allTestsKnownBuckets.remove(testName);\n specification = requiredTests.get(testName);\n } else if (dynamicTests.contains(testName)) {\n // resolved by dynamic filter\n isRequired = false;\n knownBuckets = Collections.emptyMap();\n specification = new TestSpecification();\n } else {\n // we don't care about this test\n continue;\n }\n\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);\n\n } catch (IncompatibleTestMatrixException e) {\n if (isRequired) {\n LOGGER.error(String.format(\"Unable to load test matrix for a required test %s\", testName), e);\n resultBuilder.recordError(testName, e);\n } else {\n LOGGER.info(String.format(\"Unable to load test matrix for a dynamic test %s\", testName), e);\n resultBuilder.recordIncompatibleDynamicTest(testName, e);\n }\n }\n }\n\n // TODO mjs - is this check additive?\n resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());\n\n resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());\n\n final ProctorLoadResult loadResult = resultBuilder.build();\n\n return loadResult;\n }",
"public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }",
"public static void popShell() {\n\n ArrayList<CmsShell> shells = SHELL_STACK.get();\n if (shells.size() > 0) {\n shells.remove(shells.size() - 1);\n }\n\n }",
"public void run(Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter)\n throws Throwable {\n run(configuration, candidateSteps, story, filter, null);\n }",
"@UiHandler(\"m_everyDay\")\r\n void onEveryDayChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setInterval(m_everyDay.getFormValueAsString());\r\n }\r\n\r\n }",
"public static Cluster\n repeatedlyBalanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster,\n final int maxContiguousPartitionsPerZone) {\n System.out.println(\"Looping to evenly balance partitions across zones while limiting contiguous partitions\");\n // This loop is hard to make definitive. I.e., there are corner cases\n // for small clusters and/or clusters with few partitions for which it\n // may be impossible to achieve tight limits on contiguous run lenghts.\n // Therefore, a constant number of loops are run. Note that once the\n // goal is reached, the loop becomes a no-op.\n int repeatContigBalance = 10;\n Cluster returnCluster = nextCandidateCluster;\n for(int i = 0; i < repeatContigBalance; i++) {\n returnCluster = balanceContiguousPartitionsPerZone(returnCluster,\n maxContiguousPartitionsPerZone);\n\n returnCluster = balancePrimaryPartitions(returnCluster, false);\n System.out.println(\"Completed round of balancing contiguous partitions: round \"\n + (i + 1) + \" of \" + repeatContigBalance);\n }\n\n return returnCluster;\n }"
] |
Use this API to fetch cacheselector resource of given name . | [
"public static cacheselector get(nitro_service service, String selectorname) throws Exception{\n\t\tcacheselector obj = new cacheselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tcacheselector response = (cacheselector) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"private void buildTransformers_4_0(ResourceTransformationDescriptionBuilder builder) {\n\n // We need to do custom transformation of the attribute in the root resource\n // related to endpoint configs, as these were moved to the root from a previous child resource\n EndPointWriteTransformer endPointWriteTransformer = new EndPointWriteTransformer();\n builder.getAttributeBuilder()\n .setDiscard(DiscardAttributeChecker.ALWAYS, endpointAttrArray)\n .end()\n .addOperationTransformationOverride(\"add\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(new EndPointAddTransformer())\n .end()\n .addOperationTransformationOverride(\"write-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end()\n .addOperationTransformationOverride(\"undefine-attribute\")\n //.inheritResourceAttributeDefinitions() // don't inherit as we discard\n .setCustomOperationTransformer(endPointWriteTransformer)\n .end();\n }",
"public String getBaselineDurationText()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof String))\n {\n result = null;\n }\n return (String) result;\n }",
"static EntityIdValue fromId(String id, String siteIri) {\n\t\tswitch (guessEntityTypeFromId(id)) {\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM:\n\t\t\t\treturn new ItemIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY:\n\t\t\t\treturn new PropertyIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_LEXEME:\n\t\t\t\treturn new LexemeIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_FORM:\n\t\t\t\treturn new FormIdValueImpl(id, siteIri);\n\t\t\tcase EntityIdValueImpl.JSON_ENTITY_TYPE_SENSE:\n\t\t\t\treturn new SenseIdValueImpl(id, siteIri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Entity id \\\"\" + id + \"\\\" is not supported.\");\n\t\t}\n\t}",
"private InputStream runSparqlQuery(String query) throws IOException {\n\t\ttry {\n\t\t\tString queryString = \"query=\" + URLEncoder.encode(query, \"UTF-8\")\n\t\t\t\t\t+ \"&format=json\";\n\t\t\tURL url = new URL(\"https://query.wikidata.org/sparql?\"\n\t\t\t\t\t+ queryString);\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url\n\t\t\t\t\t.openConnection();\n\t\t\tconnection.setRequestMethod(\"GET\");\n\n\t\t\treturn connection.getInputStream();\n\t\t} catch (UnsupportedEncodingException | MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}",
"@Override\n protected void addBuildInfoProperties(BuildInfoBuilder builder) {\n if (envVars != null) {\n for (Map.Entry<String, String> entry : envVars.entrySet()) {\n builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + entry.getKey(), entry.getValue());\n }\n }\n\n if (sysVars != null) {\n for (Map.Entry<String, String> entry : sysVars.entrySet()) {\n builder.addProperty(entry.getKey(), entry.getValue());\n }\n }\n }",
"public static StringBuilder leftShift(StringBuilder self, Object value) {\n self.append(value);\n return self;\n }",
"public double getValue(ForwardCurveInterface forwardCurve, double swaprateVolatility) {\n\t\tdouble swaprate = swaprates[0];\n\t\tfor (double swaprate1 : swaprates) {\n\t\t\tif (swaprate1 != swaprate) {\n\t\t\t\tthrow new RuntimeException(\"Uneven swaprates not allows for analytical pricing.\");\n\t\t\t}\n\t\t}\n\n\t\tdouble[] swapTenor = new double[fixingDates.length+1];\n\t\tSystem.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);\n\t\tswapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];\n\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(new TimeDiscretization(swapTenor), new TimeDiscretization(swapTenor), forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretization(swapTenor), forwardCurve);\n\n\t\treturn AnalyticFormulas.blackModelSwaptionValue(forwardSwapRate, swaprateVolatility, exerciseDate, swaprate, swapAnnuity);\n\t}",
"public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {\n File file = new File(fileName);\n MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();\n FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);\n multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n multipartEntityBuilder.addPart(\"fileData\", fileBody);\n multipartEntityBuilder.addTextBody(\"odoImport\", odoImport);\n try {\n JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId, multipartEntityBuilder));\n if (response.length() == 0) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }",
"public static base_response update(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice updateresource = new gslbservice();\n\t\tupdateresource.servicename = resource.servicename;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.publicip = resource.publicip;\n\t\tupdateresource.publicport = resource.publicport;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.sitepersistence = resource.sitepersistence;\n\t\tupdateresource.siteprefix = resource.siteprefix;\n\t\tupdateresource.maxclient = resource.maxclient;\n\t\tupdateresource.healthmonitor = resource.healthmonitor;\n\t\tupdateresource.maxbandwidth = resource.maxbandwidth;\n\t\tupdateresource.downstateflush = resource.downstateflush;\n\t\tupdateresource.maxaaausers = resource.maxaaausers;\n\t\tupdateresource.viewname = resource.viewname;\n\t\tupdateresource.viewip = resource.viewip;\n\t\tupdateresource.monthreshold = resource.monthreshold;\n\t\tupdateresource.weight = resource.weight;\n\t\tupdateresource.monitor_name_svc = resource.monitor_name_svc;\n\t\tupdateresource.hashid = resource.hashid;\n\t\tupdateresource.comment = resource.comment;\n\t\tupdateresource.appflowlog = resource.appflowlog;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Returns the Java command to use.
@param javaHome the Java Home, if {@code null} an attempt to determine the command will be done
@return the Java executable command | [
"public static String getJavaCommand(final Path javaHome) {\n final Path resolvedJavaHome = javaHome == null ? findJavaHome() : javaHome;\n final String exe;\n if (resolvedJavaHome == null) {\n exe = \"java\";\n } else {\n exe = resolvedJavaHome.resolve(\"bin\").resolve(\"java\").toString();\n }\n if (exe.contains(\" \")) {\n return \"\\\"\" + exe + \"\\\"\";\n }\n if (WINDOWS) {\n return exe + \".exe\";\n }\n return exe;\n }"
] | [
"private void populateRelationList(Task task, TaskField field, String data)\n {\n DeferredRelationship dr = new DeferredRelationship();\n dr.setTask(task);\n dr.setField(field);\n dr.setData(data);\n m_deferredRelationships.add(dr);\n }",
"public static base_response update(nitro_service client, vridparam resource) throws Exception {\n\t\tvridparam updateresource = new vridparam();\n\t\tupdateresource.sendtomaster = resource.sendtomaster;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static List<File> listFilesByRegex(String regex, File... directories) {\n return listFiles(directories,\n new RegexFileFilter(regex),\n CanReadFileFilter.CAN_READ);\n }",
"public static Info ones( 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(\"ones-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 CommonOps_DDRM.fill(output.matrix, 1);\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }",
"public static void withInstance(String url, Closure c) throws SQLException {\n Sql sql = null;\n try {\n sql = newInstance(url);\n c.call(sql);\n } finally {\n if (sql != null) sql.close();\n }\n }",
"private static boolean isPredefinedConstant(Expression expression) {\r\n if (expression instanceof PropertyExpression) {\r\n Expression object = ((PropertyExpression) expression).getObjectExpression();\r\n Expression property = ((PropertyExpression) expression).getProperty();\r\n\r\n if (object instanceof VariableExpression) {\r\n List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName());\r\n if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) {\n // for expressions like foo = { ... }\n // we know that the RHS type is a closure\n // but we must check if the binary expression is an assignment\n // because we need to check if a setter uses @DelegatesTo\n VariableExpression ve = new VariableExpression(\"%\", setterInfo.receiverType);\n MethodCallExpression call = new MethodCallExpression(\n ve,\n setterInfo.name,\n rightExpression\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate==null) {\n // this may happen if there's a setter of type boolean/String/Class, and that we are using the property\n // notation AND that the RHS is not a boolean/String/Class\n for (MethodNode setter : setterInfo.setters) {\n ClassNode type = getWrapper(setter.getParameters()[0].getOriginType());\n if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) {\n call = new MethodCallExpression(\n ve,\n setterInfo.name,\n new CastExpression(type,rightExpression)\n );\n call.setImplicitThis(false);\n visitMethodCallExpression(call);\n directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);\n if (directSetterCandidate!=null) {\n break;\n }\n }\n }\n }\n if (directSetterCandidate != null) {\n for (MethodNode setter : setterInfo.setters) {\n if (setter == directSetterCandidate) {\n leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate);\n storeType(leftExpression, getType(rightExpression));\n break;\n }\n }\n } else {\n ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType();\n addAssignmentError(firstSetterType, getType(rightExpression), expression);\n return true;\n }\n return false;\n }",
"public static double Taneja(double[] p, double[] q) {\n double r = 0;\n for (int i = 0; i < p.length; i++) {\n if (p[i] != 0 && q[i] != 0) {\n double pq = p[i] + q[i];\n r += (pq / 2) * Math.log(pq / (2 * Math.sqrt(p[i] * q[i])));\n }\n }\n return r;\n }",
"protected void getBatch(int batchSize){\r\n\r\n// if (numCalls == 0) {\r\n// for (int i = 0; i < 1538*\\15; i++) {\r\n// randGenerator.nextInt(this.dataDimension());\r\n// }\r\n// }\r\n// numCalls++;\r\n\r\n if (thisBatch == null || thisBatch.length != batchSize){\r\n thisBatch = new int[batchSize];\r\n }\r\n\r\n //-----------------------------\r\n //RANDOM WITH REPLACEMENT\r\n //-----------------------------\r\n if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index\r\n// System.err.println(\"numCalls = \"+(numCalls++));\r\n }\r\n //-----------------------------\r\n //ORDERED\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.Ordered)){\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = (curElement + i) % this.dataDimension() ; //Take the next batchSize points in order\r\n }\r\n curElement = (curElement + batchSize) % this.dataDimension(); //watch out for overflow\r\n\r\n //-----------------------------\r\n //RANDOM WITHOUT REPLACEMENT\r\n //-----------------------------\r\n }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){\r\n //Declare the indices array if needed.\r\n if (allIndices == null || allIndices.size()!= this.dataDimension()){\r\n\r\n allIndices = new ArrayList<Integer>();\r\n for(int i=0;i<this.dataDimension();i++){\r\n allIndices.add(i);\r\n }\r\n Collections.shuffle(allIndices,randGenerator);\r\n }\r\n\r\n for(int i = 0; i<batchSize;i++){\r\n thisBatch[i] = allIndices.get((curElement + i) % allIndices.size()); //Grab the next batchSize indices\r\n }\r\n\r\n if (curElement + batchSize > this.dataDimension()){\r\n Collections.shuffle(Arrays.asList(allIndices),randGenerator); //Shuffle if we got to the end of the list\r\n }\r\n\r\n //watch out for overflow\r\n curElement = (curElement + batchSize) % allIndices.size(); //Rollover\r\n\r\n\r\n }else{\r\n System.err.println(\"NO SAMPLING METHOD SELECTED\");\r\n System.exit(1);\r\n }\r\n\r\n\r\n }"
] |
Removes the given value to the set.
@return true if the value was actually removed | [
"public boolean remove(long key) {\n int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;\n Entry previous = null;\n Entry entry = table[index];\n while (entry != null) {\n Entry next = entry.next;\n if (entry.key == key) {\n if (previous == null) {\n table[index] = next;\n } else {\n previous.next = next;\n }\n size--;\n return true;\n }\n previous = entry;\n entry = next;\n }\n return false;\n }"
] | [
"public 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 }",
"public static String encodeQuery(String query, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(query, encoding, HierarchicalUriComponents.Type.QUERY);\n\t}",
"public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) {\n\t\tList<MwDumpFile> dumps = findAllDumps(dumpContentType);\n\n\t\tfor (MwDumpFile dump : dumps) {\n\t\t\tif (dump.isAvailable()) {\n\t\t\t\treturn dump;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public boolean hasNodeWithId(int nodeId) {\n Node node = nodesById.get(nodeId);\n if(node == null) {\n return false;\n }\n return true;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry010Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry010Date>) super.zonedDateTime(temporal);\n }",
"public static dnssuffix[] get(nitro_service service, String Dnssuffix[]) throws Exception{\n\t\tif (Dnssuffix !=null && Dnssuffix.length>0) {\n\t\t\tdnssuffix response[] = new dnssuffix[Dnssuffix.length];\n\t\t\tdnssuffix obj[] = new dnssuffix[Dnssuffix.length];\n\t\t\tfor (int i=0;i<Dnssuffix.length;i++) {\n\t\t\t\tobj[i] = new dnssuffix();\n\t\t\t\tobj[i].set_Dnssuffix(Dnssuffix[i]);\n\t\t\t\tresponse[i] = (dnssuffix) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static dnsview[] get(nitro_service service, String viewname[]) throws Exception{\n\t\tif (viewname !=null && viewname.length>0) {\n\t\t\tdnsview response[] = new dnsview[viewname.length];\n\t\t\tdnsview obj[] = new dnsview[viewname.length];\n\t\t\tfor (int i=0;i<viewname.length;i++) {\n\t\t\t\tobj[i] = new dnsview();\n\t\t\t\tobj[i].set_viewname(viewname[i]);\n\t\t\t\tresponse[i] = (dnsview) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"@Override\n public void populateObject(ProcessedCommand<Command<CI>, CI> processedCommand, InvocationProviders invocationProviders,\n AeshContext aeshContext, CommandLineParser.Mode mode)\n throws CommandLineParserException, OptionValidatorException {\n if(processedCommand.parserExceptions().size() > 0 && mode == CommandLineParser.Mode.VALIDATE)\n throw processedCommand.parserExceptions().get(0);\n for(ProcessedOption option : processedCommand.getOptions()) {\n if(option.getValues() != null && option.getValues().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE );\n else if(option.getDefaultValues().size() > 0) {\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n }\n else if(option.getOptionType().equals(OptionType.GROUP) && option.getProperties().size() > 0)\n option.injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else\n resetField(getObject(), option.getFieldName(), option.hasValue());\n }\n //arguments\n if(processedCommand.getArguments() != null &&\n (processedCommand.getArguments().getValues().size() > 0 || processedCommand.getArguments().getDefaultValues().size() > 0))\n processedCommand.getArguments().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArguments() != null)\n resetField(getObject(), processedCommand.getArguments().getFieldName(), true);\n //argument\n if(processedCommand.getArgument() != null &&\n (processedCommand.getArgument().getValues().size() > 0 || processedCommand.getArgument().getDefaultValues().size() > 0))\n processedCommand.getArgument().injectValueIntoField(getObject(), invocationProviders, aeshContext,\n mode == CommandLineParser.Mode.VALIDATE);\n else if(processedCommand.getArgument() != null)\n resetField(getObject(), processedCommand.getArgument().getFieldName(), true);\n }",
"protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }"
] |
Send a beat announcement to all registered master listeners.
@param beat the beat sent by the tempo master | [
"private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }"
] | [
"private void checkLocking(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);\r\n\r\n if (!\"TIMESTAMP\".equals(jdbcType) && !\"INTEGER\".equals(jdbcType))\r\n {\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_LOCKING, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has locking set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UPDATE_LOCK, false))\r\n {\r\n throw new ConstraintException(\"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has update-lock set to true though it is not of TIMESTAMP or INTEGER type\");\r\n }\r\n }\r\n }",
"public AsciiTable setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static java.sql.Time getTime(Object value) {\n try {\n return toTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }",
"public static <T> T load(String resourcePath, BeanSpec spec) {\n return load(resourcePath, spec, false);\n }",
"public ReportWriter getReportWriter(final JasperPrint _jasperPrint, final String _format, final Map<JRExporterParameter,Object> _parameters) {\n final JRExporter exporter = FormatInfoRegistry.getInstance().getExporter(_format);\n exporter.setParameters(_parameters);\n\n if (_jasperPrint.getPages().size() > PAGES_THRESHHOLD) {\n return new FileReportWriter(_jasperPrint, exporter);\n } else {\n return new MemoryReportWriter(_jasperPrint, exporter);\n }\n }",
"private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }",
"public void recordResourceRequestTimeUs(SocketDestination dest, long resourceRequestTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n recordResourceRequestTimeUs(null, resourceRequestTimeUs);\n } else {\n this.resourceRequestTimeRequestCounter.addRequest(resourceRequestTimeUs\n * Time.NS_PER_US);\n }\n }",
"public WebSocketContext messageReceived(String receivedMessage) {\n this.stringMessage = S.string(receivedMessage).trim();\n isJson = stringMessage.startsWith(\"{\") || stringMessage.startsWith(\"]\");\n tryParseQueryParams();\n return this;\n }",
"public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }"
] |
Returns information about all clients for a profile
@param model
@param profileIdentifier
@return
@throws Exception | [
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getClientList(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier) throws Exception {\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n return Utils.getJQGridJSON(clientService.findAllClients(profileId), \"clients\");\n }"
] | [
"private List<String> getMavenModules(MavenModuleSetBuild mavenBuild) throws IOException, InterruptedException {\n FilePath pathToModuleRoot = mavenBuild.getModuleRoot();\n FilePath pathToPom = new FilePath(pathToModuleRoot, mavenBuild.getProject().getRootPOM(null));\n return pathToPom.act(new MavenModulesExtractor());\n }",
"@Deprecated\n public String get(String path) {\n final JsonValue value = this.values.get(this.pathToProperty(path));\n if (value == null) {\n return null;\n }\n if (!value.isString()) {\n return value.toString();\n }\n return value.asString();\n }",
"public void loadWithTimeout(int timeout) {\n\n for (String stylesheet : m_stylesheets) {\n boolean alreadyLoaded = checkStylesheet(stylesheet);\n if (alreadyLoaded) {\n m_loadCounter += 1;\n } else {\n appendStylesheet(stylesheet, m_jsCallback);\n }\n }\n checkAllLoaded();\n if (timeout > 0) {\n Timer timer = new Timer() {\n\n @SuppressWarnings(\"synthetic-access\")\n @Override\n public void run() {\n\n callCallback();\n }\n };\n\n timer.schedule(timeout);\n }\n }",
"private Number calculatePercentComplete(Row row)\n {\n Number result;\n switch (PercentCompleteType.getInstance(row.getString(\"complete_pct_type\")))\n {\n case UNITS:\n {\n result = calculateUnitsPercentComplete(row);\n break;\n }\n\n case DURATION:\n {\n result = calculateDurationPercentComplete(row);\n break;\n }\n\n default:\n {\n result = calculatePhysicalPercentComplete(row);\n break;\n }\n }\n\n return result;\n }",
"public List<BoxTaskAssignment.Info> getAssignments() {\n URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTaskAssignment.Info> assignments = new ArrayList<BoxTaskAssignment.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject assignmentJSON = value.asObject();\n BoxTaskAssignment assignment = new BoxTaskAssignment(this.getAPI(), assignmentJSON.get(\"id\").asString());\n BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON);\n assignments.add(info);\n }\n\n return assignments;\n }",
"public static netbridge_vlan_binding[] get(nitro_service service, String name) throws Exception{\n\t\tnetbridge_vlan_binding obj = new netbridge_vlan_binding();\n\t\tobj.set_name(name);\n\t\tnetbridge_vlan_binding response[] = (netbridge_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ItemRequest<CustomField> findById(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }",
"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 }",
"private String getQueryParam() {\n\n final String param = parseOptionalStringValue(XML_ELEMENT_QUERYPARAM);\n if (param == null) {\n return DEFAULT_QUERY_PARAM;\n } else {\n return param;\n }\n }"
] |
Writes a buffered some-value restriction.
@param propertyUri
URI of the property to which the restriction applies
@param rangeUri
URI of the class or datatype to which the restriction applies
@param bnode
blank node representing the restriction
@throws RDFHandlerException
if there was a problem writing the RDF triples | [
"void writeSomeValueRestriction(String propertyUri, String rangeUri,\n\t\t\tResource bnode) throws RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(bnode, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}"
] | [
"private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }",
"public static synchronized void resetAndSetNewConfig(Context ctx, Config config) {\n GLOBAL_CONFIG = config;\n\n if (DISK_CACHE_MANAGER != null) {\n DISK_CACHE_MANAGER.clear();\n DISK_CACHE_MANAGER = null;\n createCache(ctx);\n }\n\n if (EXECUTOR_MANAGER != null) {\n EXECUTOR_MANAGER.shutDown();\n EXECUTOR_MANAGER = null;\n }\n Log.i(TAG, \"New config set\");\n }",
"public void removeControl(String name) {\n Widget control = findChildByName(name);\n if (control != null) {\n removeChild(control);\n if (mBgResId != -1) {\n updateMesh();\n }\n }\n }",
"public DesignDocument get(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.find(DesignDocument.class, ensureDesignPrefix(id), rev);\r\n }",
"private static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}",
"@Override\n\tpublic void Invoke(final String method, JSONArray args,\n\t\t\tHubInvokeCallback callback) {\n\n\t\tif (method == null)\n {\n throw new IllegalArgumentException(\"method\");\n }\n\n if (args == null)\n {\n throw new IllegalArgumentException(\"args\");\n }\n\n final String callbackId = mConnection.RegisterCallback(callback);\n\n HubInvocation hubData = new HubInvocation(mHubName, method, args, callbackId);\n\n String value = hubData.Serialize();\n\n mConnection.Send(value, new SendCallback() \n {\n\t\t\t@Override\n\t\t\tpublic void OnSent(CharSequence messageSent) {\n\t\t\t\tLog.v(TAG, \"Invoke of \" + method + \"sent to \" + mHubName);\n\t\t\t\t// callback.OnSent() ??!?!?\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void OnError(Exception ex) {\n\t\t\t\t// TODO Cancel the callback\n\t\t\t\tLog.e(TAG, \"Failed to invoke \" + method + \"on \" + mHubName);\n\t\t\t\tmConnection.RemoveCallback(callbackId);\n\t\t\t\t// callback.OnError() ?!?!?\n\t\t\t}\n });\n }",
"private void updateDefaultTimeAndSizeRollingAppender(final FoundationFileRollingAppender appender) {\n\n\t\tif (appender.getDatePattern().trim().length() == 0) {\n\t\t\tappender.setDatePattern(FoundationLoggerConstants.DEFAULT_DATE_PATTERN.toString());\n\t\t}\n\t\t\n\t\tString maxFileSizeKey = \"log4j.appender.\"+appender.getName()+\".MaxFileSize\";\n\t\tappender.setMaxFileSize(FoundationLogger.log4jConfigProps.getProperty(maxFileSizeKey, FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString()));\n\n//\t\tif (appender.getMaxFileSize() == null || appender.getMaxFileSize().equals(FoundationLoggerConstants.DEFAULT_FILE_SIZE.toString())) {\n//\t\t\tappender.setMaxFileSize(FoundationLoggerConstants.Foundation_MAX_FILE_SIZE.toString());\n//\t\t}\n\n\t\tString maxRollCountKey = \"log4j.appender.\"+appender.getName()+\".MaxRollFileCount\";\n\t\tappender.setMaxRollFileCount(Integer.parseInt(FoundationLogger.log4jConfigProps.getProperty(maxRollCountKey,\"100\")));\n\t}",
"private int calculateRowHeaderMaxWidth(DJCrosstabColumn crosstabColumn) {\n\t\tint auxWidth = 0;\n\t\tboolean firstTime = true;\n\t\tList<DJCrosstabColumn> auxList = new ArrayList<DJCrosstabColumn>(djcross.getColumns());\n\t\tCollections.reverse(auxList);\n\t\tfor (DJCrosstabColumn col : auxList) {\n\t\t\tif (col.equals(crosstabColumn)){\n\t\t\t\tif (auxWidth == 0)\n\t\t\t\t\tauxWidth = col.getWidth();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (firstTime){\n\t\t\t\tauxWidth += col.getWidth();\n\t\t\t\tfirstTime = false;\n\t\t\t}\n\t\t\tif (col.isShowTotals()) {\n\t\t\t\tauxWidth += col.getWidth();\n\t\t\t}\n\t\t}\n\t\treturn auxWidth;\n\t}",
"@SuppressWarnings(\"unchecked\")\n\tstatic void logToFile(String filename) {\n\t\tLogger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);\n\n\t\tFileAppender<ILoggingEvent> fileappender = new FileAppender<>();\n\t\tfileappender.setContext(rootLogger.getLoggerContext());\n\t\tfileappender.setFile(filename);\n\t\tfileappender.setName(\"FILE\");\n\n\t\tConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender(\"STDOUT\");\n\t\tfileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());\n\n\t\tfileappender.start();\n\n\t\trootLogger.addAppender(fileappender);\n\n\t\tconsole.stop();\n\t}"
] |
Interfaces, enums, annotations, and abstract classes cannot be
instantiated.
@param actionClass
class to check
@return returns true if the class cannot be instantiated or should be
ignored | [
"protected boolean cannotInstantiate(Class<?> actionClass) {\n\t\treturn actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum()\n\t\t\t\t|| (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass();\n\t}"
] | [
"private void removeObservation( int index ) {\n final int N = y.numRows-1;\n final double d[] = y.data;\n\n // shift\n for( int i = index; i < N; i++ ) {\n d[i] = d[i+1];\n }\n y.numRows--;\n }",
"public void stop() {\n if (runnerThread == null) {\n return;\n }\n\n runnerThread.interrupt();\n\n nsLock.writeLock().lock();\n try {\n if (runnerThread == null) {\n return;\n }\n\n this.cancel();\n this.close();\n\n while (runnerThread.isAlive()) {\n runnerThread.interrupt();\n try {\n runnerThread.join(1000);\n } catch (final Exception e) {\n e.printStackTrace();\n return;\n }\n }\n runnerThread = null;\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"public void hideKeyboard() {\n InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0);\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 }",
"private void setFieldType(FastTrackTableType tableType)\n {\n switch (tableType)\n {\n case ACTBARS:\n {\n m_type = ActBarField.getInstance(m_header.getColumnType());\n break;\n }\n case ACTIVITIES:\n {\n m_type = ActivityField.getInstance(m_header.getColumnType());\n break;\n }\n case RESOURCES:\n {\n m_type = ResourceField.getInstance(m_header.getColumnType());\n break;\n }\n }\n }",
"@Override\n public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException {\n DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));\n\n try {\n\n byte opCode = inputStream.readByte();\n // Store Name\n inputStream.readUTF();\n // Store routing type\n getRoutingType(inputStream);\n\n switch(opCode) {\n case VoldemortOpCode.GET_VERSION_OP_CODE:\n if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer))\n return false;\n break;\n case VoldemortOpCode.GET_OP_CODE:\n if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n case VoldemortOpCode.GET_ALL_OP_CODE:\n if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n case VoldemortOpCode.PUT_OP_CODE: {\n if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))\n return false;\n break;\n }\n case VoldemortOpCode.DELETE_OP_CODE: {\n if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer))\n return false;\n break;\n }\n default:\n throw new VoldemortException(\" Unrecognized Voldemort OpCode \" + opCode);\n }\n // This should not happen, if we reach here and if buffer has more\n // data, there is something wrong.\n if(buffer.hasRemaining()) {\n logger.info(\"Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode: \"\n + opCode + \", remaining bytes: \" + buffer.remaining());\n }\n return true;\n } catch(IOException e) {\n // This could also occur if the various methods we call into\n // re-throw a corrupted value error as some other type of exception.\n // For example, updating the position on a buffer past its limit\n // throws an InvalidArgumentException.\n if(logger.isDebugEnabled())\n logger.debug(\"Probable partial read occurred causing exception\", e);\n\n return false;\n }\n }",
"public ConfigOptionBuilder setStringConverter( StringConverter converter ) {\n co.setConverter( converter );\n co.setHasArgument( true );\n return this;\n }",
"public static void generateJavaFiles(String requirementsFolder,\n String platformName, String src_test_dir, String tests_package,\n String casemanager_package, String loggingPropFile)\n throws Exception {\n\n File reqFolder = new File(requirementsFolder);\n if (reqFolder.isDirectory()) {\n for (File f : reqFolder.listFiles()) {\n if (f.getName().endsWith(\".story\")) {\n try {\n SystemReader.generateJavaFilesForOneStory(\n f.getCanonicalPath(), platformName,\n src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } catch (IOException e) {\n String message = \"ERROR: \" + e.getMessage();\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n }\n for (File f : reqFolder.listFiles()) {\n if (f.isDirectory()) {\n SystemReader.generateJavaFiles(requirementsFolder\n + File.separator + f.getName(), platformName,\n src_test_dir, tests_package + \".\" + f.getName(),\n casemanager_package, loggingPropFile);\n }\n }\n } else if (reqFolder.getName().endsWith(\".story\")) {\n SystemReader.generateJavaFilesForOneStory(requirementsFolder,\n platformName, src_test_dir, tests_package,\n casemanager_package, loggingPropFile);\n } else {\n String message = \"No story file found in \" + requirementsFolder;\n logger.severe(message);\n throw new BeastException(message);\n }\n\n }",
"private void setMaxMin(IntervalRBTreeNode<T> n) {\n n.min = n.left;\n n.max = n.right;\n if (n.leftChild != null) {\n n.min = Math.min(n.min, n.leftChild.min);\n n.max = Math.max(n.max, n.leftChild.max);\n }\n if (n.rightChild != null) {\n n.min = Math.min(n.min, n.rightChild.min);\n n.max = Math.max(n.max, n.rightChild.max);\n }\n }"
] |
Mark unfinished test cases as interrupted for each unfinished test suite, then write
test suite result
@see #createFakeTestcaseWithWarning(ru.yandex.qatools.allure.model.TestSuiteResult)
@see #markTestcaseAsInterruptedIfNotFinishedYet(ru.yandex.qatools.allure.model.TestCaseResult) | [
"@Override\n public void run() {\n for (Map.Entry<String, TestSuiteResult> entry : testSuites) {\n for (TestCaseResult testCase : entry.getValue().getTestCases()) {\n markTestcaseAsInterruptedIfNotFinishedYet(testCase);\n }\n entry.getValue().getTestCases().add(createFakeTestcaseWithWarning(entry.getValue()));\n\n Allure.LIFECYCLE.fire(new TestSuiteFinishedEvent(entry.getKey()));\n }\n }"
] | [
"public static DMatrixRBlock transpose(DMatrixRBlock A , DMatrixRBlock A_tran )\n {\n if( A_tran != null ) {\n if( A.numRows != A_tran.numCols || A.numCols != A_tran.numRows )\n throw new IllegalArgumentException(\"Incompatible dimensions.\");\n if( A.blockLength != A_tran.blockLength )\n throw new IllegalArgumentException(\"Incompatible block size.\");\n } else {\n A_tran = new DMatrixRBlock(A.numCols,A.numRows,A.blockLength);\n\n }\n\n for( int i = 0; i < A.numRows; i += A.blockLength ) {\n int blockHeight = Math.min( A.blockLength , A.numRows - i);\n\n for( int j = 0; j < A.numCols; j += A.blockLength ) {\n int blockWidth = Math.min( A.blockLength , A.numCols - j);\n\n int indexA = i*A.numCols + blockHeight*j;\n int indexC = j*A_tran.numCols + blockWidth*i;\n\n transposeBlock( A , A_tran , indexA , indexC , blockWidth , blockHeight );\n }\n }\n\n return A_tran;\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 }",
"private Integer getIntegerTimeInMinutes(Date date)\n {\n Integer result = null;\n if (date != null)\n {\n Calendar cal = DateHelper.popCalendar(date);\n int time = cal.get(Calendar.HOUR_OF_DAY) * 60;\n time += cal.get(Calendar.MINUTE);\n DateHelper.pushCalendar(cal);\n result = Integer.valueOf(time); \n }\n return (result);\n }",
"private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = singularValues[i];\n\n if( val < 0 ) {\n singularValues[i] = -val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.data[j] = -Ut.data[j];\n }\n }\n }\n }\n }",
"public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {\r\n\t\treturn new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),\r\n\t\t\t\tgetBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());\r\n\t}",
"public SqlStatement getPreparedInsertStatement(ClassDescriptor cld)\r\n {\r\n SqlStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getInsertSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getInsertProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlInsertStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setInsertSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"public static base_response create(nitro_service client, ssldhparam resource) throws Exception {\n\t\tssldhparam createresource = new ssldhparam();\n\t\tcreateresource.dhfile = resource.dhfile;\n\t\tcreateresource.bits = resource.bits;\n\t\tcreateresource.gen = resource.gen;\n\t\treturn createresource.perform_operation(client,\"create\");\n\t}",
"public static nsspparams get(nitro_service service) throws Exception{\n\t\tnsspparams obj = new nsspparams();\n\t\tnsspparams[] response = (nsspparams[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"private void updateSession(Session newSession) {\n if (this.currentSession == null) {\n this.currentSession = newSession;\n } else {\n synchronized (this.currentSession) {\n this.currentSession = newSession;\n }\n }\n }"
] |
Reply used in error cases. set the response header as null.
@param errorMessage the error message
@param stackTrace the stack trace
@param statusCode the status code
@param statusCodeInt the status code int | [
"private final void replyErrors(final String errorMessage,\n final String stackTrace, final String statusCode,\n final int statusCodeInt) {\n reply(true, errorMessage, stackTrace, statusCode, statusCodeInt,\n PcConstants.NA, null);\n\n }"
] | [
"public static nsacl6[] get(nitro_service service, String acl6name[]) throws Exception{\n\t\tif (acl6name !=null && acl6name.length>0) {\n\t\t\tnsacl6 response[] = new nsacl6[acl6name.length];\n\t\t\tnsacl6 obj[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++) {\n\t\t\t\tobj[i] = new nsacl6();\n\t\t\t\tobj[i].set_acl6name(acl6name[i]);\n\t\t\t\tresponse[i] = (nsacl6) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static void dumpTexCoords(AiMesh mesh, int coords) {\n if (!mesh.hasTexCoords(coords)) {\n System.out.println(\"mesh has no texture coordinate set \" + coords);\n return;\n }\n \n for (int i = 0; i < mesh.getNumVertices(); i++) {\n int numComponents = mesh.getNumUVComponents(coords);\n System.out.print(\"[\" + mesh.getTexCoordU(i, coords));\n \n if (numComponents > 1) {\n System.out.print(\", \" + mesh.getTexCoordV(i, coords));\n }\n \n if (numComponents > 2) {\n System.out.print(\", \" + mesh.getTexCoordW(i, coords));\n }\n \n System.out.println(\"]\");\n }\n }",
"public static base_responses add(nitro_service client, autoscaleaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleaction addresources[] = new autoscaleaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new autoscaleaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t\taddresources[i].profilename = resources[i].profilename;\n\t\t\t\taddresources[i].parameters = resources[i].parameters;\n\t\t\t\taddresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;\n\t\t\t\taddresources[i].quiettime = resources[i].quiettime;\n\t\t\t\taddresources[i].vserver = resources[i].vserver;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public IPAddressSeqRange intersect(IPAddressSeqRange other) {\n\t\tIPAddress otherLower = other.getLower();\n\t\tIPAddress otherUpper = other.getUpper();\n\t\tIPAddress lower = this.getLower();\n\t\tIPAddress upper = this.getUpper();\n\t\tif(compareLowValues(lower, otherLower) <= 0) {\n\t\t\tif(compareLowValues(upper, otherUpper) >= 0) {\n\t\t\t\treturn other;\n\t\t\t} else if(compareLowValues(upper, otherLower) < 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn create(otherLower, upper);\n\t\t} else if(compareLowValues(otherUpper, upper) >= 0) {\n\t\t\treturn this;\n\t\t} else if(compareLowValues(otherUpper, lower) < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn create(lower, otherUpper);\n\t}",
"public void clearHistory() throws Exception {\n String uri;\n try {\n uri = HISTORY + uriEncode(_profileName);\n doDelete(uri, null);\n } catch (Exception e) {\n throw new Exception(\"Could not delete proxy history\");\n }\n }",
"public static base_responses delete(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance deleteresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new clusterinstance();\n\t\t\t\tdeleteresources[i].clid = resources[i].clid;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n\r\n buf.append(join.right.getTableAndAlias());\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n\r\n appendTableWithJoins(join.right, where, buf);\r\n }",
"public ProjectCalendarException addCalendarException(Date fromDate, Date toDate)\n {\n ProjectCalendarException bce = new ProjectCalendarException(fromDate, toDate);\n m_exceptions.add(bce);\n m_expandedExceptions.clear();\n m_exceptionsSorted = false;\n clearWorkingDateCache();\n return bce;\n }",
"public static authenticationvserver_stats get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_stats obj = new authenticationvserver_stats();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_stats response = (authenticationvserver_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Applies this patch to a JSON value.
@param node the value to apply the patch to
@return the patched JSON value
@throws JsonPatchException failed to apply patch
@throws NullPointerException input is null | [
"public JsonNode apply(final JsonNode node) {\n requireNonNull(node, \"node\");\n JsonNode ret = node.deepCopy();\n for (final JsonPatchOperation operation : operations) {\n ret = operation.apply(ret);\n }\n\n return ret;\n }"
] | [
"public LayoutScroller.ScrollableList getPageScrollable() {\n return new LayoutScroller.ScrollableList() {\n\n @Override\n public int getScrollingItemsCount() {\n return MultiPageWidget.super.getScrollingItemsCount();\n }\n\n @Override\n public float getViewPortWidth() {\n return MultiPageWidget.super.getViewPortWidth();\n }\n\n @Override\n public float getViewPortHeight() {\n return MultiPageWidget.super.getViewPortHeight();\n }\n\n @Override\n public float getViewPortDepth() {\n return MultiPageWidget.super.getViewPortDepth();\n }\n\n @Override\n public boolean scrollToPosition(int pos, final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollToPosition(pos, listener);\n }\n\n @Override\n public boolean scrollByOffset(float xOffset, float yOffset, float zOffset,\n final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollByOffset(xOffset, yOffset, zOffset, listener);\n }\n\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.registerDataSetObserver(observer);\n }\n\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.unregisterDataSetObserver(observer);\n }\n\n @Override\n public int getCurrentPosition() {\n return MultiPageWidget.super.getCurrentPosition();\n }\n\n };\n }",
"public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);\n\t}",
"private List<Row> getRows(String sql) throws SQLException\n {\n allocateConnection();\n\n try\n {\n List<Row> result = new LinkedList<Row>();\n\n m_ps = m_connection.prepareStatement(sql);\n m_rs = m_ps.executeQuery();\n populateMetaData();\n while (m_rs.next())\n {\n result.add(new MpdResultSetRow(m_rs, m_meta));\n }\n\n return (result);\n }\n\n finally\n {\n releaseConnection();\n }\n }",
"@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }",
"public static 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 }",
"public PhotoList<Photo> searchInterestingness(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INTERESTINGNESS);\r\n\r\n parameters.putAll(params.getAsParameters());\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n Photo photo = new Photo();\r\n photo.setId(photoElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photoElement.getAttribute(\"owner\"));\r\n photo.setOwner(owner);\r\n\r\n photo.setSecret(photoElement.getAttribute(\"secret\"));\r\n photo.setServer(photoElement.getAttribute(\"server\"));\r\n photo.setFarm(photoElement.getAttribute(\"farm\"));\r\n photo.setTitle(photoElement.getAttribute(\"title\"));\r\n photo.setPublicFlag(\"1\".equals(photoElement.getAttribute(\"ispublic\")));\r\n photo.setFriendFlag(\"1\".equals(photoElement.getAttribute(\"isfriend\")));\r\n photo.setFamilyFlag(\"1\".equals(photoElement.getAttribute(\"isfamily\")));\r\n photos.add(photo);\r\n }\r\n return photos;\r\n }",
"public int getXForBeat(int beat) {\n BeatGrid grid = beatGrid.get();\n if (grid != null) {\n return millisecondsToX(grid.getTimeWithinTrack(beat));\n }\n return 0;\n }",
"@Override protected Class getPrototypeClass(Video content) {\n Class prototypeClass;\n if (content.isFavorite()) {\n prototypeClass = FavoriteVideoRenderer.class;\n } else if (content.isLive()) {\n prototypeClass = LiveVideoRenderer.class;\n } else {\n prototypeClass = LikeVideoRenderer.class;\n }\n return prototypeClass;\n }",
"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 }"
] |
Detach a scope from its parent, this will trigger the garbage collection of this scope and it's
sub-scopes
if they are not referenced outside of Toothpick.
@param name the name of the scope to close. | [
"public static void closeScope(Object name) {\n //we remove the scope first, so that other threads don't see it, and see the next snapshot of the tree\n ScopeNode scope = (ScopeNode) MAP_KEY_TO_SCOPE.remove(name);\n if (scope != null) {\n ScopeNode parentScope = scope.getParentScope();\n if (parentScope != null) {\n parentScope.removeChild(scope);\n } else {\n ConfigurationHolder.configuration.onScopeForestReset();\n }\n removeScopeAndChildrenFromMap(scope);\n }\n }"
] | [
"public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {\n int numSingular = Math.min(W.numRows,W.numCols);\n boolean compact = W.numRows == W.numCols;\n\n if( compact ) {\n if( U != null ) {\n if( tranU && U.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n else if( !tranU && U.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n }\n\n if( V != null ) {\n if( tranV && V.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n else if( !tranV && V.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n }\n } else {\n if( U != null && U.numRows != U.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n if( V != null && V.numRows != V.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n if( U != null && U.numRows != W.numRows )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n if( V != null && V.numRows != W.numCols )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n }\n }",
"private Component createAddKeyButton() {\n\n // the \"+\" button\n Button addKeyButton = new Button();\n addKeyButton.addStyleName(\"icon-only\");\n addKeyButton.addStyleName(\"borderless-colored\");\n addKeyButton.setDescription(m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.setIcon(FontOpenCms.CIRCLE_PLUS, m_messages.key(Messages.GUI_ADD_KEY_0));\n addKeyButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n handleAddKey();\n\n }\n });\n return addKeyButton;\n }",
"public static void getHistory() throws Exception{\n Client client = new Client(\"ProfileName\", false);\n\n // Obtain the 100 history entries starting from offset 0\n History[] history = client.refreshHistory(100, 0);\n\n client.clearHistory();\n }",
"public List<ModelNode> getAllowedValues() {\n if (allowedValues == null) {\n return Collections.emptyList();\n }\n return Arrays.asList(this.allowedValues);\n }",
"protected Container findContainer(ContainerContext ctx, StringBuilder dump) {\n Container container = null;\n // 1. Custom container class\n String containerClassName = ctx.getServletContext().getInitParameter(Container.CONTEXT_PARAM_CONTAINER_CLASS);\n if (containerClassName != null) {\n try {\n Class<Container> containerClass = Reflections.classForName(resourceLoader, containerClassName);\n container = SecurityActions.newInstance(containerClass);\n WeldServletLogger.LOG.containerDetectionSkipped(containerClassName);\n } catch (Exception e) {\n WeldServletLogger.LOG.unableToInstantiateCustomContainerClass(containerClassName);\n WeldServletLogger.LOG.catchingDebug(e);\n }\n }\n if (container == null) {\n // 2. Service providers\n Iterable<Container> extContainers = ServiceLoader.load(Container.class, getClass().getClassLoader());\n container = checkContainers(ctx, dump, extContainers);\n if (container == null) {\n // 3. Built-in containers in predefined order\n container = checkContainers(ctx, dump,\n Arrays.asList(TomcatContainer.INSTANCE, JettyContainer.INSTANCE, UndertowContainer.INSTANCE, GwtDevHostedModeContainer.INSTANCE));\n }\n }\n return container;\n }",
"public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid);\n return resp.getData();\n }",
"public static 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}",
"public void cache(String key, Object obj) {\n H.Session sess = session();\n if (null != sess) {\n sess.cache(key, obj);\n } else {\n app().cache().put(key, obj);\n }\n }",
"public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) {\n dest.clear();\n\n if (key != null) {\n dest.key = new Key(key);\n }\n\n for (int i = 0; i < timeStamps.size(); i++) {\n long time = timeStamps.get(i);\n if (timestampTest.test(time)) {\n dest.add(time, values.get(i));\n }\n }\n }"
] |
1-D Gabor function.
@param x Value.
@param mean Mean.
@param amplitude Amplitude.
@param position Position.
@param width Width.
@param phase Phase.
@param frequency Frequency.
@return Gabor response. | [
"public static double Function1D(double x, double mean, double amplitude, double position, double width, double phase, double frequency) {\n double envelope = mean + amplitude * Math.exp(-Math.pow((x - position), 2) / Math.pow((2 * width), 2));\n double carry = Math.cos(2 * Math.PI * frequency * (x - position) + phase);\n return envelope * carry;\n }"
] | [
"public static <T> T invokeSetters(final T instance, final Map<String,Object> vars) \n throws ReflectiveOperationException {\n if (instance != null && vars != null) {\n final Class<?> clazz = instance.getClass();\n final Method[] methods = clazz.getMethods();\n for (final Entry<String,Object> entry : vars.entrySet()) {\n final String methodName = \"set\" + entry.getKey().substring(0, 1).toUpperCase(Locale.US) \n + entry.getKey().substring(1);\n boolean found = false;\n for (final Method method : methods) {\n if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) {\n method.invoke(instance, entry.getValue());\n found = true;\n break;\n }\n }\n if (!found) {\n throw new NoSuchMethodException(\"Expected setter named '\" + methodName \n + \"' for var '\" + entry.getKey() + \"'\");\n }\n }\n }\n return instance;\n }",
"private static Path resolveDockerDefinition(Path fullpath) {\n final Path ymlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yml\");\n if (Files.exists(ymlPath)) {\n return ymlPath;\n } else {\n final Path yamlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yaml\");\n if (Files.exists(yamlPath)) {\n return yamlPath;\n }\n }\n\n return null;\n }",
"public void transformConfig() throws Exception {\n\n List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, \"transforms.xml\"));\n for (TransformEntry entry : entries) {\n transform(entry.getConfigFile(), entry.getXslt());\n }\n m_isDone = true;\n }",
"private String format(Object o)\n {\n String result;\n\n if (o == null)\n {\n result = \"\";\n }\n else\n {\n if (o instanceof Boolean == true)\n {\n result = LocaleData.getString(m_locale, (((Boolean) o).booleanValue() == true ? LocaleData.YES : LocaleData.NO));\n }\n else\n {\n if (o instanceof Float == true || o instanceof Double == true)\n {\n result = (m_formats.getDecimalFormat().format(((Number) o).doubleValue()));\n }\n else\n {\n if (o instanceof Day)\n {\n result = Integer.toString(((Day) o).getValue());\n }\n else\n {\n result = o.toString();\n }\n }\n }\n\n //\n // At this point there should be no line break characters in\n // the file. If we find any, replace them with spaces\n //\n result = stripLineBreaks(result, MPXConstants.EOL_PLACEHOLDER_STRING);\n\n //\n // Finally we check to ensure that there are no embedded\n // quotes or separator characters in the value. If there are, then\n // we quote the value and escape any existing quote characters.\n //\n if (result.indexOf('\"') != -1)\n {\n result = escapeQuotes(result);\n }\n else\n {\n if (result.indexOf(m_delimiter) != -1)\n {\n result = '\"' + result + '\"';\n }\n }\n }\n\n return (result);\n }",
"private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)\n {\n if (!timeTakenByPhase.containsKey(phase))\n {\n RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class).create();\n model.setRulePhase(phase.toString());\n model.setTimeTaken(timeTaken);\n model.setOrderExecuted(timeTakenByPhase.size());\n timeTakenByPhase.put(phase, model.getElement().id());\n }\n else\n {\n GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class);\n RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n }",
"public ViewPort then(Functions.Func1<ViewPortChange> then, ViewPortFallback fallback) {\n assert then != null : \"'then' callback cannot be null\";\n this.then = then;\n this.fallback = fallback;\n return load();\n }",
"public void 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 Date getStartTime(Date date)\n {\n Date result = m_startTimeCache.get(date);\n if (result == null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultStartTime();\n }\n else\n {\n result = ranges.getRange(0).getStart();\n }\n result = DateHelper.getCanonicalTime(result);\n m_startTimeCache.put(new Date(date.getTime()), result);\n }\n return result;\n }",
"protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}"
] |
Adds an array of groupby fieldNames for ReportQueries.
@param fieldNames The groupby to set
@deprecated use QueryByCriteria#addGroupBy | [
"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 void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException {\n\t\t// Calculate new derivatives. Note that this method is called only with\n\t\t// parameters = parameterCurrent, so we may use valueCurrent.\n\n\t\tVector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length);\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\tfinal double[] parametersNew\t= parameters.clone();\n\t\t\tfinal double[] derivative\t\t= derivatives[parameterIndex];\n\n\t\t\tfinal int workerParameterIndex = parameterIndex;\n\t\t\tCallable<double[]> worker = new Callable<double[]>() {\n\t\t\t\tpublic double[] call() {\n\t\t\t\t\tdouble parameterFiniteDifference;\n\t\t\t\t\tif(parameterSteps != null) {\n\t\t\t\t\t\tparameterFiniteDifference = parameterSteps[workerParameterIndex];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Try to adaptively set a parameter shift. Note that in some\n\t\t\t\t\t\t * applications it may be important to set parameterSteps.\n\t\t\t\t\t\t * appropriately.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tparameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Shift parameter value\n\t\t\t\t\tparametersNew[workerParameterIndex] += parameterFiniteDifference;\n\n\t\t\t\t\t// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsetValues(parametersNew, derivative);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// We signal an exception to calculate the derivative as NaN\n\t\t\t\t\t\tArrays.fill(derivative, Double.NaN);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) {\n\t\t\t\t\t\tderivative[valueIndex] -= valueCurrent[valueIndex];\n\t\t\t\t\t\tderivative[valueIndex] /= parameterFiniteDifference;\n\t\t\t\t\t\tif(Double.isNaN(derivative[valueIndex])) {\n\t\t\t\t\t\t\tderivative[valueIndex] = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn derivative;\n\t\t\t\t}\n\t\t\t};\n\t\t\tif(executor != null) {\n\t\t\t\tFuture<double[]> valueFuture = executor.submit(worker);\n\t\t\t\tvalueFutures.add(parameterIndex, valueFuture);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tFutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker);\n\t\t\t\tvalueFutureTask.run();\n\t\t\t\tvalueFutures.add(parameterIndex, valueFutureTask);\n\t\t\t}\n\t\t}\n\n\t\tfor (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {\n\t\t\ttry {\n\t\t\t\tderivatives[parameterIndex] = valueFutures.get(parameterIndex).get();\n\t\t\t}\n\t\t\tcatch (InterruptedException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\tthrow new SolverException(e);\n\t\t\t}\n\t\t}\n\t}",
"public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static Searcher get(String variant) {\n final Searcher searcher = instances.get(variant);\n if (searcher == null) {\n throw new IllegalStateException(Errors.SEARCHER_GET_BEFORE_CREATE);\n }\n return searcher;\n }",
"public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEntityQuery(), params );\n\t\treturn singleResult( result );\n\t}",
"public void put(final String key, final Object value) {\n if (TASK_DIRECTORY_KEY.equals(key) && this.values.keySet().contains(TASK_DIRECTORY_KEY)) {\n // ensure that no one overwrites the task directory\n throw new IllegalArgumentException(\"Invalid key: \" + key);\n }\n\n if (value == null) {\n throw new IllegalArgumentException(\n \"A null value was attempted to be put into the values object under key: \" + key);\n }\n this.values.put(key, value);\n }",
"public void signOff(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key);\n if (null == connections) {\n return;\n }\n connections.remove(connection);\n }",
"public synchronized void addCertAndPrivateKey(String hostname, final X509Certificate cert, final PrivateKey privKey)\n\tthrows KeyStoreException, CertificateException, NoSuchAlgorithmException\n\t{\n//\t\tString alias = ThumbprintUtil.getThumbprint(cert);\n\n\t\t_ks.deleteEntry(hostname);\n\n _ks.setCertificateEntry(hostname, cert);\n\t\t_ks.setKeyEntry(hostname, privKey, _keypassword, new java.security.cert.Certificate[] {cert});\n\n\t\tif(persistImmediately)\n\t\t{\n\t\t\tpersist();\n\t\t}\n\n\t}",
"public static base_responses update(nitro_service client, nslimitselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnslimitselector updateresources[] = new nslimitselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nslimitselector();\n\t\t\t\tupdateresources[i].selectorname = resources[i].selectorname;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static Bounds getSymmetricBounds(int dim, double l, double u) {\n double [] L = new double[dim];\n double [] U = new double[dim];\n for(int i=0; i<dim; i++) {\n L[i] = l;\n U[i] = u;\n }\n return new Bounds(L, U);\n }"
] |
width of input section | [
"public static int cudnnSetTensor4dDescriptorEx(\n cudnnTensorDescriptor tensorDesc, \n int dataType, /** image data type */\n int n, /** number of inputs (batch size) */\n int c, /** number of input feature maps */\n int h, /** height of input section */\n int w, /** width of input section */\n int nStride, \n int cStride, \n int hStride, \n int wStride)\n {\n return checkResult(cudnnSetTensor4dDescriptorExNative(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride));\n }"
] | [
"public boolean isBitwiseOrCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\treturn super.isBitwiseOrCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}",
"public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {\n return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }",
"public void init(final MultivaluedMap<String, String> queryParameters) {\n final String scopeCompileParam = queryParameters.getFirst(ServerAPI.SCOPE_COMPILE_PARAM);\n if(scopeCompileParam != null){\n this.scopeComp = Boolean.valueOf(scopeCompileParam);\n }\n final String scopeProvidedParam = queryParameters.getFirst(ServerAPI.SCOPE_PROVIDED_PARAM);\n if(scopeProvidedParam != null){\n this.scopePro = Boolean.valueOf(scopeProvidedParam);\n }\n final String scopeRuntimeParam = queryParameters.getFirst(ServerAPI.SCOPE_RUNTIME_PARAM);\n if(scopeRuntimeParam != null){\n this.scopeRun = Boolean.valueOf(scopeRuntimeParam);\n }\n final String scopeTestParam = queryParameters.getFirst(ServerAPI.SCOPE_TEST_PARAM);\n if(scopeTestParam != null){\n this.scopeTest = Boolean.valueOf(scopeTestParam);\n }\n }",
"private String joinElements(int length)\n {\n StringBuilder sb = new StringBuilder();\n for (int index = 0; index < length; index++)\n {\n sb.append(m_elements.get(index));\n }\n return sb.toString();\n }",
"public void detachMetadataCache(SlotReference slot) {\n MetadataCache oldCache = metadataCacheFiles.remove(slot);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing metadata cache\", e);\n }\n deliverCacheUpdate(slot, null);\n }\n }",
"public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n\n for( int i = 0; i < a.numRows; i++ ) {\n\n for( int j = 0; j < b.numCols; j++ ) {\n c.set(i,j,a.get(i,0)*b.get(0,j));\n }\n\n for( int k = 1; k < b.numRows; k++ ) {\n for( int j = 0; j < b.numCols; j++ ) {\n// c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j));\n c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j);\n }\n }\n }\n\n return System.currentTimeMillis() - timeBefore;\n }",
"public void cache(String key, Object obj, int expiration) {\n H.Session session = this.session;\n if (null != session) {\n session.cache(key, obj, expiration);\n } else {\n app().cache().put(key, obj, expiration);\n }\n }",
"public static void parse(Reader src, StatementHandler handler)\n throws IOException {\n new NTriplesParser(src, handler).parse();\n }",
"public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }"
] |
Extract the parameters from a method using the Jmx annotation if present,
or just the raw types otherwise
@param m The method to extract parameters from
@return An array of parameter infos | [
"public static MBeanParameterInfo[] extractParameterInfo(Method m) {\n Class<?>[] types = m.getParameterTypes();\n Annotation[][] annotations = m.getParameterAnnotations();\n MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];\n for(int i = 0; i < params.length; i++) {\n boolean hasAnnotation = false;\n for(int j = 0; j < annotations[i].length; j++) {\n if(annotations[i][j] instanceof JmxParam) {\n JmxParam param = (JmxParam) annotations[i][j];\n params[i] = new MBeanParameterInfo(param.name(),\n types[i].getName(),\n param.description());\n hasAnnotation = true;\n break;\n }\n }\n if(!hasAnnotation) {\n params[i] = new MBeanParameterInfo(\"\", types[i].getName(), \"\");\n }\n }\n\n return params;\n }"
] | [
"public static Collection<ContentStream> toContentStreams(final String str, final String contentType) {\n\n if (str == null) {\n return null;\n }\n\n ArrayList<ContentStream> streams = new ArrayList<>(1);\n ContentStreamBase ccc = new ContentStreamBase.StringStream(str);\n ccc.setContentType(contentType);\n streams.add(ccc);\n return streams;\n }",
"private List<EnrollmentTerm> parseEnrollmentTermList(final List<Response> responses) {\n return responses.stream().\n map(this::parseEnrollmentTermList).\n flatMap(Collection::stream).\n collect(Collectors.toList());\n }",
"private void addPropertyCounters(UsageStatistics usageStatistics,\n\t\t\tPropertyIdValue property) {\n\t\tif (!usageStatistics.propertyCountsMain.containsKey(property)) {\n\t\t\tusageStatistics.propertyCountsMain.put(property, 0);\n\t\t\tusageStatistics.propertyCountsQualifier.put(property, 0);\n\t\t\tusageStatistics.propertyCountsReferences.put(property, 0);\n\t\t}\n\t}",
"private static Map<String, ServerGroupDeploymentPlanResult> buildServerGroupResults(Map<UUID, DeploymentActionResult> deploymentActionResults) {\n Map<String, ServerGroupDeploymentPlanResult> serverGroupResults = new HashMap<String, ServerGroupDeploymentPlanResult>();\n\n for (Map.Entry<UUID, DeploymentActionResult> entry : deploymentActionResults.entrySet()) {\n\n UUID actionId = entry.getKey();\n DeploymentActionResult actionResult = entry.getValue();\n\n Map<String, ServerGroupDeploymentActionResult> actionResultsByServerGroup = actionResult.getResultsByServerGroup();\n for (ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup.values()) {\n String serverGroupName = serverGroupActionResult.getServerGroupName();\n\n ServerGroupDeploymentPlanResultImpl sgdpr = (ServerGroupDeploymentPlanResultImpl) serverGroupResults.get(serverGroupName);\n if (sgdpr == null) {\n sgdpr = new ServerGroupDeploymentPlanResultImpl(serverGroupName);\n serverGroupResults.put(serverGroupName, sgdpr);\n }\n\n for (Map.Entry<String, ServerUpdateResult> serverEntry : serverGroupActionResult.getResultByServer().entrySet()) {\n String serverName = serverEntry.getKey();\n ServerUpdateResult sud = serverEntry.getValue();\n ServerDeploymentPlanResultImpl sdpr = (ServerDeploymentPlanResultImpl) sgdpr.getServerResult(serverName);\n if (sdpr == null) {\n sdpr = new ServerDeploymentPlanResultImpl(serverName);\n sgdpr.storeServerResult(serverName, sdpr);\n }\n sdpr.storeServerUpdateResult(actionId, sud);\n }\n }\n }\n return serverGroupResults;\n }",
"public static BoxCollaborationWhitelist.Info create(final BoxAPIConnection api, String domain,\n WhitelistDirection direction) {\n\n URL url = COLLABORATION_WHITELIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"domain\", domain)\n .add(\"direction\", direction.toString());\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n BoxCollaborationWhitelist domainWhitelist =\n new BoxCollaborationWhitelist(api, responseJSON.get(\"id\").asString());\n\n return domainWhitelist.new Info(responseJSON);\n }",
"private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }",
"@Override\n public void setValue(Boolean value, boolean fireEvents) {\n boolean oldValue = getValue();\n if (value) {\n input.getElement().setAttribute(\"checked\", \"true\");\n } else {\n input.getElement().removeAttribute(\"checked\");\n }\n\n if (fireEvents && oldValue != value) {\n ValueChangeEvent.fire(this, getValue());\n }\n }",
"public static FileOutputStream openResultFileOuputStream(\n\t\t\tPath resultDirectory, String filename) throws IOException {\n\t\tPath filePath = resultDirectory.resolve(filename);\n\t\treturn new FileOutputStream(filePath.toFile());\n\t}",
"public void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n final SortedSet<WeekDay> newWeekDays = null == weekDays ? new TreeSet<WeekDay>() : weekDays;\n SortedSet<WeekDay> currentWeekDays = m_model.getWeekDays();\n if (!currentWeekDays.equals(newWeekDays)) {\n conditionallyRemoveExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekDays(newWeekDays);\n onValueChange();\n }\n }, !newWeekDays.containsAll(m_model.getWeekDays()));\n }\n }"
] |
Use this API to expire cacheobject. | [
"public static base_response expire(nitro_service client, cacheobject resource) throws Exception {\n\t\tcacheobject expireresource = new cacheobject();\n\t\texpireresource.locator = resource.locator;\n\t\texpireresource.url = resource.url;\n\t\texpireresource.host = resource.host;\n\t\texpireresource.port = resource.port;\n\t\texpireresource.groupname = resource.groupname;\n\t\texpireresource.httpmethod = resource.httpmethod;\n\t\treturn expireresource.perform_operation(client,\"expire\");\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 }",
"public static boolean isFolderExist(String directoryPath) {\r\n if (StringUtils.isEmpty(directoryPath)) {\r\n return false;\r\n }\r\n\r\n File dire = new File(directoryPath);\r\n return (dire.exists() && dire.isDirectory());\r\n }",
"public static Class<?> resolveReturnTypeArgument(Method method, Class<?> genericIfc) {\n\t\tAssert.notNull(method, \"method must not be null\");\n\t\tType returnType = method.getReturnType();\n\t\tType genericReturnType = method.getGenericReturnType();\n\t\tif (returnType.equals(genericIfc)) {\n\t\t\tif (genericReturnType instanceof ParameterizedType) {\n\t\t\t\tParameterizedType targetType = (ParameterizedType) genericReturnType;\n\t\t\t\tType[] actualTypeArguments = targetType.getActualTypeArguments();\n\t\t\t\tType typeArg = actualTypeArguments[0];\n\t\t\t\tif (!(typeArg instanceof WildcardType)) {\n\t\t\t\t\treturn (Class<?>) typeArg;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn resolveTypeArgument((Class<?>) returnType, genericIfc);\n\t}",
"private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {\n for (final MasterHandoffListener listener : getMasterHandoffListeners()) {\n try {\n listener.yieldResponse(fromPlayer, yielded);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master yield response to listener\", t);\n }\n }\n }",
"public ServerGroup getServerGroup(int id, int profileId) throws Exception {\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n if (id == 0) {\n return new ServerGroup(0, \"Default\", profileId);\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, id);\n results = queryStatement.executeQuery();\n if (results.next()) {\n ServerGroup curGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.GENERIC_NAME),\n results.getInt(Constants.GENERIC_PROFILE_ID));\n return curGroup;\n }\n logger.info(\"Did not find the ID: {}\", id);\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }",
"public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }",
"public StreamReader getTableData(String name) throws IOException\n {\n InputStream stream = new ByteArrayInputStream(m_tableData.get(name));\n if (m_majorVersion > 5)\n { \n byte[] header = new byte[24];\n stream.read(header);\n SynchroLogger.log(\"TABLE HEADER\", header);\n }\n return new StreamReader(m_majorVersion, stream);\n }",
"public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {\n if (strings == null || strings.size() == 0) {\n return \"\";\n }\n StringBuilder result = null;\n for (String s : strings) {\n if (fixCase) {\n s = fixCase(s);\n }\n if (result == null) {\n result = new StringBuilder(s);\n } else {\n result.append(withChar);\n result.append(s);\n }\n }\n return result.toString();\n }",
"private void processDefaultCurrency(Integer currencyID) throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"currtype where curr_id=?\", currencyID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_reader.processDefaultCurrency(row);\n }\n }"
] |
Returns all the pixels for the image
@return an array of pixels for this image | [
"public Pixel[] pixels() {\n Pixel[] pixels = new Pixel[count()];\n Point[] points = points();\n for (int k = 0; k < points.length; k++) {\n pixels[k] = pixel(points[k]);\n }\n return pixels;\n }"
] | [
"private List<Integer> getPageSizes() {\n\n final String pageSizes = parseOptionalStringValue(XML_ELEMENT_PAGESIZE);\n if (pageSizes != null) {\n String[] pageSizesArray = pageSizes.split(\"-\");\n if (pageSizesArray.length > 0) {\n try {\n List<Integer> result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n return result;\n } catch (NumberFormatException e) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizes), e);\n }\n }\n }\n return null;\n }",
"public static double SquaredEuclidean(double[] x, double[] y) {\n double d = 0.0, u;\n\n for (int i = 0; i < x.length; i++) {\n u = x[i] - y[i];\n d += u * u;\n }\n\n return d;\n }",
"protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) {\n for(MonolingualTextValue val : addAliases) {\n addAlias(val);\n }\n for(MonolingualTextValue val : deleteAliases) {\n deleteAlias(val);\n }\n }",
"public static Info ones( 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(\"ones-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 CommonOps_DDRM.fill(output.matrix, 1);\n }\n };\n } else {\n throw new RuntimeException(\"Expected two integers got \"+A+\" \"+B);\n }\n\n return ret;\n }",
"protected Object checkUndefined(Object val) {\n if (val instanceof String && ((String) val).equals(\"undefined\")) {\n return null;\n }\n return val;\n }",
"public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,\n final int scanInterval, TimeUnit unit, final boolean autoDeployZip,\n final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,\n final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {\n final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,\n autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);\n final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());\n service.scheduledExecutorValue.inject(scheduledExecutorService);\n final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);\n sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.notification-handler-registry\", null),\n NotificationHandlerRegistry.class, service.notificationRegistryValue);\n sb.addDependency(context.getCapabilityServiceName(\"org.wildfly.management.model-controller-client-factory\", null),\n ModelControllerClientFactory.class, service.clientFactoryValue);\n sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);\n sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);\n return sb.install();\n }",
"protected int readShort(InputStream is) throws IOException\n {\n byte[] data = new byte[2];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getShort(data, 0));\n }",
"public void addArtifact(final Artifact artifact) {\n if (!artifacts.contains(artifact)) {\n if (promoted) {\n artifact.setPromoted(promoted);\n }\n\n artifacts.add(artifact);\n }\n }",
"public static sslcertkey_sslvserver_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslvserver_binding obj = new sslcertkey_sslvserver_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslvserver_binding response[] = (sslcertkey_sslvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Get a value from a multiselect metadata field.
@param path the key path in the metadata object. Must be prefixed with a "/".
@return the list of values set in the field. | [
"public List<String> getMultiSelect(String path) {\n List<String> values = new ArrayList<String>();\n for (JsonValue val : this.getValue(path).asArray()) {\n values.add(val.asString());\n }\n\n return values;\n }"
] | [
"private static Pod getRandomPod(KubernetesClient client, String name, String namespace) {\n Endpoints endpoints = client.endpoints().inNamespace(namespace).withName(name).get();\n List<String> pods = new ArrayList<>();\n if (endpoints != null) {\n for (EndpointSubset subset : endpoints.getSubsets()) {\n for (EndpointAddress address : subset.getAddresses()) {\n if (address.getTargetRef() != null && POD.equals(address.getTargetRef().getKind())) {\n String pod = address.getTargetRef().getName();\n if (pod != null && !pod.isEmpty()) {\n pods.add(pod);\n }\n }\n }\n }\n }\n if (pods.isEmpty()) {\n return null;\n } else {\n String chosen = pods.get(RANDOM.nextInt(pods.size()));\n return client.pods().inNamespace(namespace).withName(chosen).get();\n }\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 void map(Story story, MetaFilter metaFilter) {\n if (metaFilter.allow(story.getMeta())) {\n boolean allowed = false;\n for (Scenario scenario : story.getScenarios()) {\n // scenario also inherits meta from story\n Meta inherited = scenario.getMeta().inheritFrom(story.getMeta());\n if (metaFilter.allow(inherited)) {\n allowed = true;\n break;\n }\n }\n if (allowed) {\n add(metaFilter.asString(), story);\n }\n }\n }",
"public static <ResultT> PollingState<ResultT> createFromPollingState(PollingState<?> other, ResultT result) {\n PollingState<ResultT> pollingState = new PollingState<>();\n pollingState.resource = result;\n pollingState.initialHttpMethod = other.initialHttpMethod();\n pollingState.status = other.status();\n pollingState.statusCode = other.statusCode();\n pollingState.azureAsyncOperationHeaderLink = other.azureAsyncOperationHeaderLink();\n pollingState.locationHeaderLink = other.locationHeaderLink();\n pollingState.putOrPatchResourceUri = other.putOrPatchResourceUri();\n pollingState.defaultRetryTimeout = other.defaultRetryTimeout;\n pollingState.retryTimeout = other.retryTimeout;\n pollingState.loggingContext = other.loggingContext;\n pollingState.finalStateVia = other.finalStateVia;\n return pollingState;\n }",
"private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {\n String separator = launcher.isUnix() ? \"/\" : \"\\\\\";\n String java_home = extendedEnv.get(\"JAVA_HOME\");\n if (StringUtils.isNotEmpty(java_home)) {\n if (!StringUtils.endsWith(java_home, separator)) {\n java_home += separator;\n }\n extendedEnv.put(\"PATH+JDK\", java_home + \"bin\");\n }\n }",
"@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}",
"public static File createFolder(String path, String dest_dir)\n throws BeastException {\n File f = new File(dest_dir);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n logger.severe(\"Problem creating directory: \" + path\n + File.separator + dest_dir);\n }\n }\n\n String folderPath = createFolderPath(path);\n\n f = new File(f, folderPath);\n if (!f.isDirectory()) {\n try {\n f.mkdirs();\n } catch (Exception e) {\n String message = \"Problem creating directory: \" + path\n + File.separator + dest_dir;\n logger.severe(message);\n throw new BeastException(message, e);\n }\n }\n\n return f;\n }",
"public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }",
"public static appfwpolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_stats obj = new appfwpolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_stats response = (appfwpolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}"
] |
Checks if a given number is in the range of an integer.
@param number
a number which should be in the range of an integer (positive or negative)
@see java.lang.Integer#MIN_VALUE
@see java.lang.Integer#MAX_VALUE
@return number as an integer (rounding might occur) | [
"@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static int checkInteger(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInIntegerRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), INTEGER_MIN, INTEGER_MAX);\n\t\t}\n\n\t\treturn number.intValue();\n\t}"
] | [
"private static void deleteUserDirectories(final File root,\n final FileFilter filter) {\n final File[] dirs = root.listFiles(filter);\n LOGGER.info(\"Identified (\" + dirs.length + \") directories to delete\");\n for (final File dir : dirs) {\n LOGGER.info(\"Deleting \" + dir);\n if (!FileUtils.deleteQuietly(dir)) {\n LOGGER.info(\"Failed to delete directory \" + dir);\n }\n }\n }",
"public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,\n\t\t\tint resultFlags, ObjectCache objectCache) throws SQLException {\n\t\tprepareQueryForAll();\n\t\treturn buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags);\n\t}",
"private void processCalendarData(List<ProjectCalendar> calendars) throws SQLException\n {\n for (ProjectCalendar calendar : calendars)\n {\n processCalendarData(calendar, getRows(\"SELECT * FROM MSP_CALENDAR_DATA WHERE PROJ_ID=? AND CAL_UID=?\", m_projectID, calendar.getUniqueID()));\n }\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 void applyToOrTransparent(ColorHolder colorHolder, Context ctx, GradientDrawable gradientDrawable) {\n if (colorHolder != null && gradientDrawable != null) {\n colorHolder.applyTo(ctx, gradientDrawable);\n } else if (gradientDrawable != null) {\n gradientDrawable.setColor(Color.TRANSPARENT);\n }\n }",
"private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }",
"public String getHiveExecutionEngine() {\n String executionEngine = hiveConfSystemOverride.get(HiveConf.ConfVars.HIVE_EXECUTION_ENGINE.varname);\n return executionEngine == null ? HiveConf.ConfVars.HIVE_EXECUTION_ENGINE.getDefaultValue() : executionEngine;\n }",
"public static filterglobal_filterpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tfilterglobal_filterpolicy_binding obj = new filterglobal_filterpolicy_binding();\n\t\tfilterglobal_filterpolicy_binding response[] = (filterglobal_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"int acquireTransaction(@NotNull final Thread thread) {\n try (CriticalSection ignored = criticalSection.enter()) {\n final int currentThreadPermits = getThreadPermitsToAcquire(thread);\n waitForPermits(thread, currentThreadPermits > 0 ? nestedQueue : regularQueue, 1, currentThreadPermits);\n }\n return 1;\n }"
] |
Use this API to add sslcipher resources. | [
"public static base_responses add(nitro_service client, sslcipher resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcipher addresources[] = new sslcipher[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslcipher();\n\t\t\t\taddresources[i].ciphergroupname = resources[i].ciphergroupname;\n\t\t\t\taddresources[i].ciphgrpalias = resources[i].ciphgrpalias;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public void addChildTaskBefore(Task child, Task previousSibling)\n {\n int index = m_children.indexOf(previousSibling);\n if (index == -1)\n {\n m_children.add(child);\n }\n else\n {\n m_children.add(index, child);\n }\n\n child.m_parent = this;\n setSummary(true);\n\n if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)\n {\n child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));\n }\n }",
"private void writeAttributeTypes(String name, FieldType[] types) throws IOException\n {\n m_writer.writeStartObject(name);\n for (FieldType field : types)\n {\n m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue());\n }\n m_writer.writeEndObject();\n }",
"public static base_response add(nitro_service client, dnsview resource) throws Exception {\n\t\tdnsview addresource = new dnsview();\n\t\taddresource.viewname = resource.viewname;\n\t\treturn addresource.add_resource(client);\n\t}",
"private JSONValue dateToJson(Date d) {\n\n return null != d ? new JSONString(Long.toString(d.getTime())) : null;\n }",
"public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject,\n\t\t\tObjectCache objectCache) throws SQLException {\n\n\t\tif (logger.isLevelEnabled(Level.TRACE)) {\n\t\t\tlogger.trace(\"assiging from data {}, val {}: {}\", (data == null ? \"null\" : data.getClass()),\n\t\t\t\t\t(val == null ? \"null\" : val.getClass()), val);\n\t\t}\n\t\t// if this is a foreign object then val is the foreign object's id val\n\t\tif (foreignRefField != null && val != null) {\n\t\t\t// get the current field value which is the foreign-id\n\t\t\tObject foreignRef = extractJavaFieldValue(data);\n\t\t\t/*\n\t\t\t * See if we don't need to create a new foreign object. If we are refreshing and the id field has not\n\t\t\t * changed then there is no need to create a new foreign object and maybe lose previously refreshed field\n\t\t\t * information.\n\t\t\t */\n\t\t\tif (foreignRef != null && foreignRef.equals(val)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// awhitlock: raised as OrmLite issue: bug #122\n\t\t\tObject cachedVal;\n\t\t\tObjectCache foreignCache = foreignDao.getObjectCache();\n\t\t\tif (foreignCache == null) {\n\t\t\t\tcachedVal = null;\n\t\t\t} else {\n\t\t\t\tcachedVal = foreignCache.get(getType(), val);\n\t\t\t}\n\t\t\tif (cachedVal != null) {\n\t\t\t\tval = cachedVal;\n\t\t\t} else if (!parentObject) {\n\t\t\t\t// the value we are to assign to our field is now the foreign object itself\n\t\t\t\tval = createForeignObject(connectionSource, val, objectCache);\n\t\t\t}\n\t\t}\n\n\t\tif (fieldSetMethod == null) {\n\t\t\ttry {\n\t\t\t\tfield.set(data, val);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tif (val == null) {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\"Could not assign object '\" + val + \"' to field \" + this, e);\n\t\t\t\t} else {\n\t\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \" to field \" + this, e);\n\t\t\t\t}\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\n\t\t\t\t\t\t\"Could not assign object '\" + val + \"' of type \" + val.getClass() + \"' to field \" + this, e);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tfieldSetMethod.invoke(data, val);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow SqlExceptionUtil\n\t\t\t\t\t\t.create(\"Could not call \" + fieldSetMethod + \" on object with '\" + val + \"' for \" + this, e);\n\t\t\t}\n\t\t}\n\t}",
"public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }",
"public static String getInputValueName(\n @Nullable final String inputPrefix,\n @Nonnull final BiMap<String, String> inputMapper,\n @Nonnull final String field) {\n String name = inputMapper == null ? null : inputMapper.inverse().get(field);\n if (name == null) {\n if (inputMapper != null && inputMapper.containsKey(field)) {\n throw new RuntimeException(\"field in keys\");\n }\n final String[] defaultValues = {\n Values.TASK_DIRECTORY_KEY, Values.CLIENT_HTTP_REQUEST_FACTORY_KEY,\n Values.TEMPLATE_KEY, Values.PDF_CONFIG_KEY, Values.SUBREPORT_DIR_KEY,\n Values.OUTPUT_FORMAT_KEY, Values.JOB_ID_KEY\n };\n if (inputPrefix == null || Arrays.asList(defaultValues).contains(field)) {\n name = field;\n } else {\n name = inputPrefix.trim() +\n Character.toUpperCase(field.charAt(0)) +\n field.substring(1);\n }\n }\n return name;\n }",
"private Object getValue(FieldType field, byte[] block)\n {\n Object result = null;\n\n switch (block[0])\n {\n case 0x07: // Field\n {\n result = getFieldType(block);\n break;\n }\n\n case 0x01: // Constant value\n {\n result = getConstantValue(field, block);\n break;\n }\n\n case 0x00: // Prompt\n {\n result = getPromptValue(field, block);\n break;\n }\n }\n\n return result;\n }",
"public static Cluster\n repeatedlyBalanceContiguousPartitionsPerZone(final Cluster nextCandidateCluster,\n final int maxContiguousPartitionsPerZone) {\n System.out.println(\"Looping to evenly balance partitions across zones while limiting contiguous partitions\");\n // This loop is hard to make definitive. I.e., there are corner cases\n // for small clusters and/or clusters with few partitions for which it\n // may be impossible to achieve tight limits on contiguous run lenghts.\n // Therefore, a constant number of loops are run. Note that once the\n // goal is reached, the loop becomes a no-op.\n int repeatContigBalance = 10;\n Cluster returnCluster = nextCandidateCluster;\n for(int i = 0; i < repeatContigBalance; i++) {\n returnCluster = balanceContiguousPartitionsPerZone(returnCluster,\n maxContiguousPartitionsPerZone);\n\n returnCluster = balancePrimaryPartitions(returnCluster, false);\n System.out.println(\"Completed round of balancing contiguous partitions: round \"\n + (i + 1) + \" of \" + repeatContigBalance);\n }\n\n return returnCluster;\n }"
] |
Check whether the value is matched by a regular expression.
@param value value
@param regex regular expression
@return true when value is matched | [
"protected boolean check(String value, String regex) {\n\t\tPattern pattern = Pattern.compile(regex);\n\t\treturn pattern.matcher(value).matches();\n\t}"
] | [
"private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}",
"public BoxFileUploadSessionPartList listParts(int offset, int limit) {\n URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint();\n URLTemplate template = new URLTemplate(listPartsURL.toString());\n\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(OFFSET_QUERY_STRING, offset);\n String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString();\n\n //Template is initalized with the full URL. So empty string for the path.\n URL url = template.buildWithQuery(\"\", queryString);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n return new BoxFileUploadSessionPartList(jsonObject);\n }",
"public static Predicate anyBitsSet(final String expr, final long bits) {\n return new Predicate() {\n private String param;\n public void init(AbstractSqlCreator creator) {\n param = creator.allocateParameter();\n creator.setParameter(param, bits);\n }\n public String toSql() {\n return String.format(\"(%s & :%s) > 0\", expr, param);\n }\n };\n }",
"public RedwoodConfiguration showOnlyChannels(final Object[] channels){\r\n tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } });\r\n return this;\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 }",
"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 }",
"private static void reverse(int first, int last, Swapper swapper) {\r\n\t// no more needed since manually inlined\r\n\twhile (first < --last) {\r\n\t\tswapper.swap(first++,last);\r\n\t}\r\n}",
"public static void acceptsJson(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_J, OPT_JSON),\n \"fetch key/entry by key value of json type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"protected Query buildPrefetchQuery(Collection ids)\r\n {\r\n CollectionDescriptor cds = getCollectionDescriptor();\r\n QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));\r\n\r\n // check if collection must be ordered\r\n if (!cds.getOrderBy().isEmpty())\r\n {\r\n Iterator iter = cds.getOrderBy().iterator();\r\n while (iter.hasNext())\r\n {\r\n query.addOrderBy((FieldHelper) iter.next());\r\n }\r\n }\r\n\r\n return query;\r\n }"
] |
default visibility for unit test | [
"String decodeCString(ByteBuf buffer) throws IOException {\n int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);\n if (length < 0)\n throw new IOException(\"string termination not found\");\n\n String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);\n buffer.skipBytes(length + 1);\n return result;\n }"
] | [
"public VALUE put(KEY key, VALUE object) {\n CacheEntry<VALUE> entry;\n if (referenceType == ReferenceType.WEAK) {\n entry = new CacheEntry<>(new WeakReference<>(object), null);\n } else if (referenceType == ReferenceType.SOFT) {\n entry = new CacheEntry<>(new SoftReference<>(object), null);\n } else {\n entry = new CacheEntry<>(null, object);\n }\n\n countPutCountSinceEviction++;\n countPut++;\n if (isExpiring && nextCleanUpTimestamp == 0) {\n nextCleanUpTimestamp = System.currentTimeMillis() + expirationMillis + 1;\n }\n\n CacheEntry<VALUE> oldEntry;\n synchronized (this) {\n if (values.size() >= maxSize) {\n evictToTargetSize(maxSize - 1);\n }\n oldEntry = values.put(key, entry);\n }\n return getValueForRemoved(oldEntry);\n }",
"public static void checkOperatorIsValid(int operatorCode) {\n switch (operatorCode) {\n case OPERATOR_LT:\n case OPERATOR_LE:\n case OPERATOR_EQ:\n case OPERATOR_NE:\n case OPERATOR_GE:\n case OPERATOR_GT:\n case OPERATOR_UNKNOWN:\n return;\n default:\n throw new IllegalStateException(String.format(Locale.US, ERROR_INVALID_CODE, operatorCode));\n }\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 }",
"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 }",
"public Map<DeckReference, TrackMetadata> getLoadedTracks() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, TrackMetadata>(hotCache));\n }",
"private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }",
"private void addChildrenForRolesNode(String ouItem) {\n\n try {\n List<CmsRole> roles = OpenCms.getRoleManager().getRoles(m_cms, ouItem.substring(1), false);\n CmsRole.applySystemRoleOrder(roles);\n for (CmsRole role : roles) {\n String roleId = ouItem + \"/\" + role.getId();\n Item roleItem = m_treeContainer.addItem(roleId);\n if (roleItem == null) {\n roleItem = getItem(roleId);\n }\n roleItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(role, CmsOuTreeType.ROLE));\n roleItem.getItemProperty(PROP_TYPE).setValue(CmsOuTreeType.ROLE);\n setChildrenAllowed(roleId, false);\n m_treeContainer.setParent(roleId, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }",
"public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\n }",
"@Beta\n public MSICredentials withObjectId(String objectId) {\n this.objectId = objectId;\n this.clientId = null;\n this.identityId = null;\n return this;\n }"
] |
MOVED INSIDE ExpressionUtils
protected JRDesignExpression getExpressionForConditionalStyle(ConditionalStyle condition, String columExpression) {
String fieldsMap = "(("+DJDefaultScriptlet.class.getName() + ")$P{REPORT_SCRIPTLET}).getCurrentFields()";
String parametersMap = "(("+DJDefaultScriptlet.class.getName() + ")$P{REPORT_SCRIPTLET}).getCurrentParams()";
String variablesMap = "(("+DJDefaultScriptlet.class.getName() + ")$P{REPORT_SCRIPTLET}).getCurrentVariables()";
String evalMethodParams = fieldsMap +", " + variablesMap + ", " + parametersMap + ", " + columExpression;
String text = "(("+ConditionStyleExpression.class.getName()+")$P{" + JRParameter.REPORT_PARAMETERS_MAP + "}.get(\""+condition.getName()+"\"))."+CustomExpression.EVAL_METHOD_NAME+"("+evalMethodParams+")";
JRDesignExpression expression = new JRDesignExpression();
expression.setValueClass(Boolean.class);
expression.setText(text);
return expression;
} | [
"private Style getRowTotalStyle(DJCrosstabRow crosstabRow) {\n\t\treturn crosstabRow.getTotalStyle() == null ? this.djcross.getRowTotalStyle(): crosstabRow.getTotalStyle();\n\t}"
] | [
"public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }",
"@Override\r\n public V get(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V deltaResult = deltaMap.get(key);\r\n if (deltaResult == null) {\r\n return originalMap.get(key);\r\n }\r\n if (deltaResult == nullValue) {\r\n return null;\r\n }\r\n if (deltaResult == removedValue) {\r\n return null;\r\n }\r\n return deltaResult;\r\n }",
"private void computeCosts() {\n cost = Long.MAX_VALUE;\n for (QueueItem item : queueSpans) {\n cost = Math.min(cost, item.sequenceSpans.spans.cost());\n }\n }",
"String getStatusHelp(CmsUser user, boolean disabled, boolean newUser) {\n\n if (disabled) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_HELP_0);\n }\n if (newUser) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_HELP_0);\n }\n if (isUserPasswordReset(user)) {\n return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_HELP_0);\n }\n long lastLogin = user.getLastlogin();\n return CmsVaadinUtils.getMessageText(\n Messages.GUI_USERMANAGEMENT_USER_ACTIVE_HELP_1,\n CmsDateUtil.getDateTime(new Date(lastLogin), DateFormat.SHORT, A_CmsUI.get().getLocale()));\n }",
"public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }",
"static void i(String message){\n if (getStaticDebugLevel() >= CleverTapAPI.LogLevel.INFO.intValue()){\n Log.i(Constants.CLEVERTAP_LOG_TAG,message);\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 }",
"public static nsrollbackcmd[] get(nitro_service service, nsrollbackcmd_args args) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"public static gslbservice get(nitro_service service, String servicename) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tobj.set_servicename(servicename);\n\t\tgslbservice response = (gslbservice) obj.get_resource(service);\n\t\treturn response;\n\t}"
] |
Does not mutate the TestMatrix.
Verifies that the test matrix contains all the required tests and that
each required test is valid.
@param testMatrix the {@link TestMatrixArtifact} to be verified.
@param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
@param requiredTests a {@link Map} of required test. The {@link TestSpecification} would be verified
@param functionMapper a given el {@link FunctionMapper}
@param providedContext a {@link Map} containing variables describing the context in which the request is executing. These will be supplied to verifying all rules.
@param dynamicTests a {@link Set} of dynamic tests determined by filters.
@return a {@link ProctorLoadResult} to describe the result of verification. It contains errors of verification and a list of missing test. | [
"public static ProctorLoadResult verify(\n @Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource,\n @Nonnull final Map<String, TestSpecification> requiredTests,\n @Nonnull final FunctionMapper functionMapper,\n final ProvidedContext providedContext,\n @Nonnull final Set<String> dynamicTests\n ) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());\n for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {\n final Map<Integer, String> bucketValueToName = Maps.newHashMap();\n for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {\n bucketValueToName.put(bucket.getValue(), bucket.getKey());\n }\n allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);\n }\n\n final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();\n final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());\n resultBuilder.recordAllMissing(missingTests);\n for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {\n final String testName = entry.getKey();\n\n final Map<Integer, String> knownBuckets;\n final TestSpecification specification;\n final boolean isRequired;\n if (allTestsKnownBuckets.containsKey(testName)) {\n // required in specification\n isRequired = true;\n knownBuckets = allTestsKnownBuckets.remove(testName);\n specification = requiredTests.get(testName);\n } else if (dynamicTests.contains(testName)) {\n // resolved by dynamic filter\n isRequired = false;\n knownBuckets = Collections.emptyMap();\n specification = new TestSpecification();\n } else {\n // we don't care about this test\n continue;\n }\n\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);\n\n } catch (IncompatibleTestMatrixException e) {\n if (isRequired) {\n LOGGER.error(String.format(\"Unable to load test matrix for a required test %s\", testName), e);\n resultBuilder.recordError(testName, e);\n } else {\n LOGGER.info(String.format(\"Unable to load test matrix for a dynamic test %s\", testName), e);\n resultBuilder.recordIncompatibleDynamicTest(testName, e);\n }\n }\n }\n\n // TODO mjs - is this check additive?\n resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());\n\n resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());\n\n final ProctorLoadResult loadResult = resultBuilder.build();\n\n return loadResult;\n }"
] | [
"public static vpnvserver_authenticationsamlpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationsamlpolicy_binding obj = new vpnvserver_authenticationsamlpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationsamlpolicy_binding response[] = (vpnvserver_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void deliverBeatGridUpdate(int player, BeatGrid beatGrid) {\n if (!getBeatGridListeners().isEmpty()) {\n final BeatGridUpdate update = new BeatGridUpdate(player, beatGrid);\n for (final BeatGridListener listener : getBeatGridListeners()) {\n try {\n listener.beatGridChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering beat grid update to listener\", t);\n }\n }\n }\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 }",
"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 }",
"protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }",
"private static Query buildQuery(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n Criteria crit = new Criteria();\r\n\r\n for(int i = 0; i < pkFields.length; i++)\r\n {\r\n crit.addEqualTo(pkFields[i].getAttributeName(), null);\r\n }\r\n return new QueryByCriteria(cld.getClassOfObject(), crit);\r\n }",
"public double d(double x){\n\t\tint intervalNumber =getIntervalNumber(x);\n\t\tif (intervalNumber==0 || intervalNumber==points.length) {\n\t\t\treturn x;\n\t\t}\n\t\treturn getIntervalReferencePoint(intervalNumber-1);\n\t}",
"private boolean includeDocument(ItemDocument itemDocument) {\n\t\tfor (StatementGroup sg : itemDocument.getStatementGroups()) {\n\t\t\t// \"P19\" is \"place of birth\" on Wikidata\n\t\t\tif (!\"P19\".equals(sg.getProperty().getId())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tif (s.getMainSnak() instanceof ValueSnak) {\n\t\t\t\t\tValue v = s.getValue();\n\t\t\t\t\t// \"Q1731\" is \"Dresden\" on Wikidata\n\t\t\t\t\tif (v instanceof ItemIdValue\n\t\t\t\t\t\t\t&& \"Q1731\".equals(((ItemIdValue) v).getId())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {\n return Collections.unmodifiableSortedMap(self);\n }"
] |
Starts a background thread which calls the controller every
check_interval milliseconds. Returns immediately, leaving the
background thread running. | [
"public void spawnThread(DukeController controller, int check_interval) {\n this.controller = controller;\n timer = mgr.schedule(this, 0, check_interval * 1000); // convert to ms\n }"
] | [
"protected int[] getPatternAsCodewords(int size) {\n if (size >= 10) {\n throw new IllegalArgumentException(\"Pattern groups of 10 or more digits are likely to be too large to parse as integers.\");\n }\n if (pattern == null || pattern.length == 0) {\n return new int[0];\n } else {\n int count = (int) Math.ceil(pattern[0].length() / (double) size);\n int[] codewords = new int[pattern.length * count];\n for (int i = 0; i < pattern.length; i++) {\n String row = pattern[i];\n for (int j = 0; j < count; j++) {\n int substringStart = j * size;\n int substringEnd = Math.min((j + 1) * size, row.length());\n codewords[(i * count) + j] = Integer.parseInt(row.substring(substringStart, substringEnd));\n }\n }\n return codewords;\n }\n }",
"public String addExtent(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n\r\n if (!_model.hasClass(name))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_FIND_TYPE,\r\n new String[]{name}));\r\n }\r\n _curClassDef.addExtentClass(_model.getClass(name));\r\n return \"\";\r\n }",
"public SubReportBuilder setParameterMapPath(String path) {\r\n\t\tsubreport.setParametersExpression(path);\r\n\t\tsubreport.setParametersMapOrigin(DJConstants.SUBREPORT_PARAMETER_MAP_ORIGIN_PARAMETER);\r\n\t\treturn this;\r\n\t}",
"public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }",
"public static base_response update(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder updateresource = new sslocspresponder();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.cache = resource.cache;\n\t\tupdateresource.cachetimeout = resource.cachetimeout;\n\t\tupdateresource.batchingdepth = resource.batchingdepth;\n\t\tupdateresource.batchingdelay = resource.batchingdelay;\n\t\tupdateresource.resptimeout = resource.resptimeout;\n\t\tupdateresource.respondercert = resource.respondercert;\n\t\tupdateresource.trustresponder = resource.trustresponder;\n\t\tupdateresource.producedattimeskew = resource.producedattimeskew;\n\t\tupdateresource.signingcert = resource.signingcert;\n\t\tupdateresource.usenonce = resource.usenonce;\n\t\tupdateresource.insertclientcert = resource.insertclientcert;\n\t\treturn updateresource.update_resource(client);\n\t}",
"final void dispatchToAppender(final LoggingEvent customLoggingEvent) {\n // wrap the LoggingEvent in a FileRollEvent to prevent recursion bug\n final FoundationFileRollingAppender appender = this.getSource();\n if (appender != null) {\n appender.append(new FileRollEvent(customLoggingEvent, this));\n }\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 setRightValue(int index, Object value)\n {\n m_definedRightValues[index] = value;\n\n if (value instanceof FieldType)\n {\n m_symbolicValues = true;\n }\n else\n {\n if (value instanceof Duration)\n {\n if (((Duration) value).getUnits() != TimeUnit.HOURS)\n {\n value = ((Duration) value).convertUnits(TimeUnit.HOURS, m_properties);\n }\n }\n }\n\n m_workingRightValues[index] = value;\n }",
"private <T> InternalProviderImpl installInternalProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider,\n boolean isBound, boolean isTestProvider) {\n if (bindingName == null) {\n if (isBound) {\n return installUnNamedProvider(mapClassesToUnNamedBoundProviders, clazz, internalProvider, isTestProvider);\n } else {\n return installUnNamedProvider(mapClassesToUnNamedUnBoundProviders, clazz, internalProvider, isTestProvider);\n }\n } else {\n return installNamedProvider(mapClassesToNamedBoundProviders, clazz, bindingName, internalProvider, isTestProvider);\n }\n }"
] |
Adds the position range.
@param start the start
@param end the end | [
"final public void addPositionRange(int start, int end) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(start, end);\n } else {\n int[] positions = new int[end - start + 1];\n for (int i = start; i <= end; i++) {\n positions[i - start] = i;\n }\n tokenPosition.add(positions);\n }\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 static String stringMatcherByPattern(String input, String patternStr) {\n\n String output = PcConstants.SYSTEM_FAIL_MATCH_REGEX;\n\n // 20140105: fix the NPE issue\n if (patternStr == null) {\n logger.error(\"patternStr is NULL! (Expected when the aggregation rule is not defined at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n }\n\n if (input == null) {\n logger.error(\"input (Expected when the response is null and now try to match on response) is NULL in stringMatcherByPattern() at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n return output;\n } else {\n input = input.replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n }\n\n logger.debug(\"input: \" + input);\n logger.debug(\"patternStr: \" + patternStr);\n\n Pattern patternMetric = Pattern.compile(patternStr, Pattern.MULTILINE);\n\n final Matcher matcher = patternMetric.matcher(input);\n if (matcher.matches()) {\n output = matcher.group(1);\n }\n return output;\n }",
"protected TypeReference<?> getBeanPropertyType(Class<?> clazz,\r\n\t\t\tString propertyName, TypeReference<?> originalType) {\r\n\t\tTypeReference<?> propertyDestinationType = null;\r\n\t\tif (beanDestinationPropertyTypeProvider != null) {\r\n\t\t\tpropertyDestinationType = beanDestinationPropertyTypeProvider\r\n\t\t\t\t\t.getPropertyType(clazz, propertyName, originalType);\r\n\t\t}\r\n\t\tif (propertyDestinationType == null) {\r\n\t\t\tpropertyDestinationType = originalType;\r\n\t\t}\r\n\t\treturn propertyDestinationType;\r\n\t}",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private void writeCalendars() throws JAXBException\n {\n //\n // Create the new Planner calendar list\n //\n Calendars calendars = m_factory.createCalendars();\n m_plannerProject.setCalendars(calendars);\n writeDayTypes(calendars);\n List<net.sf.mpxj.planner.schema.Calendar> calendar = calendars.getCalendar();\n\n //\n // Process each calendar in turn\n //\n for (ProjectCalendar mpxjCalendar : m_projectFile.getCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerCalendar = m_factory.createCalendar();\n calendar.add(plannerCalendar);\n writeCalendar(mpxjCalendar, plannerCalendar);\n }\n }",
"public BoxRetentionPolicyAssignment.Info assignTo(BoxFolder folder) {\r\n return BoxRetentionPolicyAssignment.createAssignmentToFolder(this.getAPI(), this.getID(), folder.getID());\r\n }",
"public void process(CustomFieldContainer indicators, ProjectProperties properties, Props props)\n {\n m_container = indicators;\n m_properties = properties;\n m_data = props.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n\n if (m_data != null)\n {\n int columnsCount = MPPUtility.getInt(m_data, 4);\n m_headerOffset = 8;\n for (int loop = 0; loop < columnsCount; loop++)\n {\n processColumns();\n }\n }\n }",
"public <T> InternalEjbDescriptor<T> get(String beanName) {\n return cast(ejbByName.get(beanName));\n }",
"private void readResources(Project plannerProject) throws MPXJException\n {\n Resources resources = plannerProject.getResources();\n if (resources != null)\n {\n for (net.sf.mpxj.planner.schema.Resource res : resources.getResource())\n {\n readResource(res);\n }\n }\n }"
] |
Create a RemoteWebDriver backed EmbeddedBrowser.
@param hubUrl Url of the server.
@param filterAttributes the attributes to be filtered from DOM.
@param crawlWaitReload the period to wait after a reload.
@param crawlWaitEvent the period to wait after an event is fired.
@return The EmbeddedBrowser. | [
"public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),\n\t\t\t\tfilterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}"
] | [
"public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }",
"@Override\n public void fire(StepStartedEvent event) {\n for (LifecycleListener listener : listeners) {\n try {\n listener.fire(event);\n } catch (Exception e) {\n logError(listener, e);\n }\n }\n }",
"public double compare(String v1, String v2) {\n // FIXME: it should be possible here to say that, actually, we\n // didn't learn anything from comparing these two values, so that\n // probability is set to 0.5.\n\n if (comparator == null)\n return 0.5; // we ignore properties with no comparator\n\n // first, we call the comparator, to get a measure of how similar\n // these two values are. note that this is not the same as what we\n // are going to return, which is a probability.\n double sim = comparator.compare(v1, v2);\n\n // we have been configured with a high probability (for equal\n // values) and a low probability (for different values). given\n // sim, which is a measure of the similarity somewhere in between\n // equal and different, we now compute our estimate of the\n // probability.\n\n // if sim = 1.0, we return high. if sim = 0.0, we return low. for\n // values in between we need to compute a little. the obvious\n // formula to use would be (sim * (high - low)) + low, which\n // spreads the values out equally spaced between high and low.\n\n // however, if the similarity is higher than 0.5 we don't want to\n // consider this negative evidence, and so there's a threshold\n // there. also, users felt Duke was too eager to merge records,\n // and wanted probabilities to fall off faster with lower\n // probabilities, and so we square sim in order to achieve this.\n\n if (sim >= 0.5)\n return ((high - 0.5) * (sim * sim)) + 0.5;\n else\n return low;\n }",
"public static void addLazyDefinitions(SourceBuilder code) {\n Set<Declaration> defined = new HashSet<>();\n\n // Definitions may lazily declare new names; ensure we add them all\n List<Declaration> declarations =\n code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n while (!defined.containsAll(declarations)) {\n for (Declaration declaration : declarations) {\n if (defined.add(declaration)) {\n code.add(code.scope().get(declaration).definition);\n }\n }\n declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n }\n }",
"protected static int calculateShift(int minimumValue, int maximumValue) {\n\t\tint shift = 0;\n\t\tint value = 1;\n\t\twhile (value < minimumValue && value < maximumValue) {\n\t\t\tvalue <<= 1;\n\t\t\tshift++;\n\t\t}\n\t\treturn shift;\n\t}",
"private static boolean isAssignableFrom(Type from, ParameterizedType to,\n\t\t\tMap<String, Type> typeVarMap) {\n\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// First figure out the class and any type information.\n\t\tClass<?> clazz = getRawType(from);\n\t\tParameterizedType ptype = null;\n\t\tif (from instanceof ParameterizedType) {\n\t\t\tptype = (ParameterizedType) from;\n\t\t}\n\n\t\t// Load up parameterized variable info if it was parameterized.\n\t\tif (ptype != null) {\n\t\t\tType[] tArgs = ptype.getActualTypeArguments();\n\t\t\tTypeVariable<?>[] tParams = clazz.getTypeParameters();\n\t\t\tfor (int i = 0; i < tArgs.length; i++) {\n\t\t\t\tType arg = tArgs[i];\n\t\t\t\tTypeVariable<?> var = tParams[i];\n\t\t\t\twhile (arg instanceof TypeVariable) {\n\t\t\t\t\tTypeVariable<?> v = (TypeVariable<?>) arg;\n\t\t\t\t\targ = typeVarMap.get(v.getName());\n\t\t\t\t}\n\t\t\t\ttypeVarMap.put(var.getName(), arg);\n\t\t\t}\n\n\t\t\t// check if they are equivalent under our current mapping.\n\t\t\tif (typeEquals(ptype, to, typeVarMap)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tfor (Type itype : clazz.getGenericInterfaces()) {\n\t\t\tif (isAssignableFrom(itype, to, new HashMap<String, Type>(\n\t\t\t\t\ttypeVarMap))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// Interfaces didn't work, try the superclass.\n\t\tType sType = clazz.getGenericSuperclass();\n\t\tif (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}",
"public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {\n T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);\n appendErrorHumanMsg(rtn);\n return rtn;\n }",
"public HttpConnection execute(HttpConnection connection) {\n\n //set our HttpUrlFactory on the connection\n connection.connectionFactory = factory;\n\n // all CouchClient requests want to receive application/json responses\n connection.requestProperties.put(\"Accept\", \"application/json\");\n connection.responseInterceptors.addAll(this.responseInterceptors);\n connection.requestInterceptors.addAll(this.requestInterceptors);\n InputStream es = null; // error stream - response from server for a 500 etc\n\n // first try to execute our request and get the input stream with the server's response\n // we want to catch IOException because HttpUrlConnection throws these for non-success\n // responses (eg 404 throws a FileNotFoundException) but we need to map to our own\n // specific exceptions\n try {\n try {\n connection = connection.execute();\n } catch (HttpConnectionInterceptorException e) {\n CouchDbException exception = new CouchDbException(connection.getConnection()\n .getResponseMessage(), connection.getConnection().getResponseCode());\n if (e.deserialize) {\n try {\n JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject\n .class);\n exception.error = getAsString(errorResponse, \"error\");\n exception.reason = getAsString(errorResponse, \"reason\");\n } catch (JsonParseException jpe) {\n exception.error = e.error;\n }\n } else {\n exception.error = e.error;\n exception.reason = e.reason;\n }\n throw exception;\n }\n int code = connection.getConnection().getResponseCode();\n String response = connection.getConnection().getResponseMessage();\n // everything ok? return the stream\n if (code / 100 == 2) { // success [200,299]\n return connection;\n } else {\n final CouchDbException ex;\n switch (code) {\n case HttpURLConnection.HTTP_NOT_FOUND: //404\n ex = new NoDocumentException(response);\n break;\n case HttpURLConnection.HTTP_CONFLICT: //409\n ex = new DocumentConflictException(response);\n break;\n case HttpURLConnection.HTTP_PRECON_FAILED: //412\n ex = new PreconditionFailedException(response);\n break;\n case 429:\n // If a Replay429Interceptor is present it will check for 429 and retry at\n // intervals. If the retries do not succeed or no 429 replay was configured\n // we end up here and throw a TooManyRequestsException.\n ex = new TooManyRequestsException(response);\n break;\n default:\n ex = new CouchDbException(response, code);\n break;\n }\n es = connection.getConnection().getErrorStream();\n //if there is an error stream try to deserialize into the typed exception\n if (es != null) {\n try {\n //read the error stream into memory\n byte[] errorResponse = IOUtils.toByteArray(es);\n\n Class<? extends CouchDbException> exceptionClass = ex.getClass();\n //treat the error as JSON and try to deserialize\n try {\n // Register an InstanceCreator that returns the existing exception so\n // we can just populate the fields, but not ignore the constructor.\n // Uses a new Gson so we don't accidentally recycle an exception.\n Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new\n CouchDbExceptionInstanceCreator(ex)).create();\n // Now populate the exception with the error/reason other info from JSON\n g.fromJson(new InputStreamReader(new ByteArrayInputStream\n (errorResponse),\n \"UTF-8\"), exceptionClass);\n } catch (JsonParseException e) {\n // The error stream was not JSON so just set the string content as the\n // error field on ex before we throw it\n ex.error = new String(errorResponse, \"UTF-8\");\n }\n } finally {\n close(es);\n }\n }\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n } catch (IOException ioe) {\n CouchDbException ex = new CouchDbException(\"Error retrieving server response\", ioe);\n ex.setUrl(connection.url.toString());\n throw ex;\n }\n }",
"private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {\n\t\tif ( configurationResourceUrl != null ) {\n\t\t\ttry ( InputStream openStream = configurationResourceUrl.openStream() ) {\n\t\t\t\thotRodConfiguration.load( openStream );\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow log.failedLoadingHotRodConfigurationProperties( e );\n\t\t\t}\n\t\t}\n\t}"
] |
Use this API to fetch aaapreauthenticationpolicy_binding resource of given name . | [
"public static aaapreauthenticationpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\taaapreauthenticationpolicy_binding obj = new aaapreauthenticationpolicy_binding();\n\t\tobj.set_name(name);\n\t\taaapreauthenticationpolicy_binding response = (aaapreauthenticationpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static String roundCorner(int radiusInner, int radiusOuter, int color) {\n if (radiusInner < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radiusOuter < 0) {\n throw new IllegalArgumentException(\"Outer radius must be greater than or equal to zero.\");\n }\n StringBuilder builder = new StringBuilder(FILTER_ROUND_CORNER).append(\"(\").append(radiusInner);\n if (radiusOuter > 0) {\n builder.append(\"|\").append(radiusOuter);\n }\n final int r = (color & 0xFF0000) >>> 16;\n final int g = (color & 0xFF00) >>> 8;\n final int b = color & 0xFF;\n return builder.append(\",\") //\n .append(r).append(\",\") //\n .append(g).append(\",\") //\n .append(b).append(\")\") //\n .toString();\n }",
"@Override\n public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {\n return delegate.getMatrixHistory(start, limit);\n }",
"public static BuildRetention createBuildRetention(Run build, boolean discardOldArtifacts) {\n BuildRetention buildRetention = new BuildRetention(discardOldArtifacts);\n LogRotator rotator = null;\n BuildDiscarder buildDiscarder = build.getParent().getBuildDiscarder();\n if (buildDiscarder != null && buildDiscarder instanceof LogRotator) {\n rotator = (LogRotator) buildDiscarder;\n }\n if (rotator == null) {\n return buildRetention;\n }\n if (rotator.getNumToKeep() > -1) {\n buildRetention.setCount(rotator.getNumToKeep());\n }\n if (rotator.getDaysToKeep() > -1) {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.DAY_OF_YEAR, -rotator.getDaysToKeep());\n buildRetention.setMinimumBuildDate(new Date(calendar.getTimeInMillis()));\n }\n List<String> notToBeDeleted = ExtractorUtils.getBuildNumbersNotToBeDeleted(build);\n buildRetention.setBuildNumbersNotToBeDiscarded(notToBeDeleted);\n return buildRetention;\n }",
"protected X509Certificate wireUpSslWithCyberVilliansCAOdo(String host, SslListener listener) {\n host = requestOriginalHostName.get();\n\n // Add cybervillians CA(from browsermob)\n try {\n // see https://github.com/webmetrics/browsermob-proxy/issues/105\n String escapedHost = host.replace('*', '_');\n\n KeyStoreManager keyStoreManager = Utils.getKeyStoreManager(escapedHost);\n keyStoreManager.getKeyStore().deleteEntry(KeyStoreManager._caPrivKeyAlias);\n keyStoreManager.persist();\n listener.setKeystore(new File(\"seleniumSslSupport\" + File.separator + escapedHost + File.separator + \"cybervillainsCA.jks\").getAbsolutePath());\n\n return keyStoreManager.getCertificateByAlias(escapedHost);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public static void setFlag(Activity activity, final int bits, boolean on) {\n Window win = activity.getWindow();\n WindowManager.LayoutParams winParams = win.getAttributes();\n if (on) {\n winParams.flags |= bits;\n } else {\n winParams.flags &= ~bits;\n }\n win.setAttributes(winParams);\n }",
"public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {\n final CopyOption[] options;\n if (overwrite) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};\n } else {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.walkFileTree(source, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n Files.copy(dir, target.resolve(source.relativize(dir)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.copy(file, target.resolve(source.relativize(file)), options);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }",
"public static hanode_routemonitor6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor6_binding obj = new hanode_routemonitor6_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor6_binding response[] = (hanode_routemonitor6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String formatAsStackTraceElement(InjectionPoint ij) {\n Member member;\n if (ij.getAnnotated() instanceof AnnotatedField) {\n AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated();\n member = annotatedField.getJavaMember();\n } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) {\n AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();\n member = annotatedParameter.getDeclaringCallable().getJavaMember();\n } else {\n // Not throwing an exception, because this method is invoked when an exception is already being thrown.\n // Throwing an exception here would hide the original exception.\n return \"-\";\n }\n return formatAsStackTraceElement(member);\n }",
"private Object getLiteralValue(Expression expression) {\n\t\tif (!(expression instanceof Literal)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a Literal.\");\n\t\t}\n\t\treturn ((Literal) expression).getValue();\n\t}"
] |
This method must be called on the stop of the component. Stop the directory monitor and unregister all the
declarations. | [
"void stop() {\n try {\n dm.stop(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to stop \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory, e);\n }\n declarationsFiles.clear();\n declarationRegistrationManager.unregisterAll();\n }"
] | [
"public GVRTexture getSplashTexture(GVRContext gvrContext) {\n Bitmap bitmap = BitmapFactory.decodeResource( //\n gvrContext.getContext().getResources(), //\n R.drawable.__default_splash_screen__);\n GVRTexture tex = new GVRTexture(gvrContext);\n tex.setImage(new GVRBitmapImage(gvrContext, bitmap));\n return tex;\n }",
"public ThumborUrlBuilder buildImage(String image) {\n if (image == null || image.length() == 0) {\n throw new IllegalArgumentException(\"Image must not be blank.\");\n }\n return new ThumborUrlBuilder(host, key, image);\n }",
"protected List<String> extractWords() throws IOException\n {\n while( true ) {\n lineNumber++;\n String line = in.readLine();\n if( line == null ) {\n return null;\n }\n\n // skip comment lines\n if( hasComment ) {\n if( line.charAt(0) == comment )\n continue;\n }\n\n // extract the words, which are the variables encoded\n return parseWords(line);\n }\n }",
"@SuppressWarnings({\"OverlyLongMethod\"})\n public void clearProperties(@NotNull final PersistentStoreTransaction txn, @NotNull final Entity entity) {\n final Transaction envTxn = txn.getEnvironmentTransaction();\n final PersistentEntityId id = (PersistentEntityId) entity.getId();\n final int entityTypeId = id.getTypeId();\n final long entityLocalId = id.getLocalId();\n final PropertiesTable properties = getPropertiesTable(txn, entityTypeId);\n final PropertyKey propertyKey = new PropertyKey(entityLocalId, 0);\n try (Cursor cursor = getPrimaryPropertyIndexCursor(txn, properties)) {\n for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(propertyKey)) != null;\n success; success = cursor.getNext()) {\n ByteIterable keyEntry = cursor.getKey();\n final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);\n if (key.getEntityLocalId() != entityLocalId) {\n break;\n }\n final int propertyId = key.getPropertyId();\n final ByteIterable value = cursor.getValue();\n final PropertyValue propValue = propertyTypes.entryToPropertyValue(value);\n txn.propertyChanged(id, propertyId, propValue.getData(), null);\n properties.deleteNoFail(txn, entityLocalId, value, propertyId, propValue.getType());\n }\n }\n }",
"@Nullable public GeoTarget getCanonAncestor(GeoTarget.Type type) {\n for (GeoTarget target = this; target != null; target = target.canonParent()) {\n if (target.key.type == type) {\n return target;\n }\n }\n\n return null;\n }",
"public static Command newStartProcess(String processId,\n Map<String, Object> parameters) {\n return getCommandFactoryProvider().newStartProcess( processId,\n parameters );\n }",
"private synchronized void closeIdleClients() {\n List<Client> candidates = new LinkedList<Client>(openClients.values());\n logger.debug(\"Scanning for idle clients; \" + candidates.size() + \" candidates.\");\n for (Client client : candidates) {\n if ((useCounts.get(client) < 1) &&\n ((timestamps.get(client) + idleLimit.get() * 1000) <= System.currentTimeMillis())) {\n logger.debug(\"Idle time reached for unused client {}\", client);\n closeClient(client);\n }\n }\n }",
"public static List<ContentRepositoryElement> listFiles(final Path rootPath, Path tempDir, final ContentFilter filter) throws IOException {\n List<ContentRepositoryElement> result = new ArrayList<>();\n if (Files.exists(rootPath)) {\n if(isArchive(rootPath)) {\n return listZipContent(rootPath, filter);\n }\n Files.walkFileTree(rootPath, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (filter.acceptFile(rootPath, file)) {\n result.add(ContentRepositoryElement.createFile(formatPath(rootPath.relativize(file)), Files.size(file)));\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n if (filter.acceptDirectory(rootPath, dir)) {\n String directoryPath = formatDirectoryPath(rootPath.relativize(dir));\n if(! \"/\".equals(directoryPath)) {\n result.add(ContentRepositoryElement.createFolder(directoryPath));\n }\n }\n return FileVisitResult.CONTINUE;\n }\n\n private String formatDirectoryPath(Path path) {\n return formatPath(path) + '/';\n }\n\n private String formatPath(Path path) {\n return path.toString().replace(File.separatorChar, '/');\n }\n });\n } else {\n Path file = getFile(rootPath);\n if(isArchive(file)) {\n Path relativePath = file.relativize(rootPath);\n Path target = createTempDirectory(tempDir, \"unarchive\");\n unzip(file, target);\n return listFiles(target.resolve(relativePath), tempDir, filter);\n } else {\n throw new FileNotFoundException(rootPath.toString());\n }\n }\n return result;\n }",
"public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }"
] |
Emit a string event with parameters.
This will invoke all {@link SimpleEventListener} bound to the specified
string value given the listeners has the matching argument list.
For example, suppose we have the following simple event listener methods:
```java
{@literal @}On("USER-LOGIN")
public void logUserLogin(User user, long timestamp) {...}
{@literal @}On("USER-LOGIN")
public void checkDuplicateLoginAttempts(User user, Object... args) {...}
{@literal @}On("USER-LOGIN")
public void foo(User user) {...}
```
The following code will invoke `logUserLogin` and `checkDuplicateLoginAttempts` methods:
```java
User user = ...;
eventBus.emit("USER-LOGIN", user, System.currentTimeMills());
```
The `foo(User)` will not invoked because:
* The parameter list `(User, long)` does not match the declared argument list `(User)`.
Here the `String` in the parameter list is taken out because it is used to indicate
the event, instead of being passing through to the event handler method.
* The method `checkDuplicateLoginAttempts(User, Object ...)` will be invoked because
it declares a varargs typed arguments, meaning it matches any parameters passed in.
@param event
the target event
@param args
the arguments passed in
@see SimpleEventListener | [
"public EventBus emit(String event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\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 static List<Integer> asList(int[] a) {\r\n List<Integer> result = new ArrayList<Integer>(a.length);\r\n for (int i = 0; i < a.length; i++) {\r\n result.add(Integer.valueOf(a[i]));\r\n }\r\n return result;\r\n }",
"public List<List<String>> getAllScopes() {\n this.checkInitialized();\n final ImmutableList.Builder<List<String>> builder = ImmutableList.<List<String>>builder();\n final Consumer<Integer> _function = (Integer it) -> {\n List<String> _get = this.scopes.get(it);\n StringConcatenation _builder = new StringConcatenation();\n _builder.append(\"No scopes are available for index: \");\n _builder.append(it);\n builder.add(Preconditions.<List<String>>checkNotNull(_get, _builder));\n };\n this.scopes.keySet().forEach(_function);\n return builder.build();\n }",
"public InsertBuilder set(String column, String value) {\n columns.add(column);\n values.add(value);\n return this;\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 }",
"String escapeValue(Object value) {\n return HtmlUtils.htmlEscape(value != null ? value.toString() : \"<null>\");\n }",
"public static int randomIntBetween(int min, int max) {\n Random rand = new Random();\n return rand.nextInt((max - min) + 1) + min;\n }",
"public static Date max(Date d1, Date d2)\n {\n Date result;\n if (d1 == null)\n {\n result = d2;\n }\n else\n if (d2 == null)\n {\n result = d1;\n }\n else\n {\n result = (d1.compareTo(d2) > 0) ? d1 : d2;\n }\n return result;\n }",
"public ItemRequest<Project> addCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/addCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }"
] |
Writes the body of this request to an HttpURLConnection.
<p>Subclasses overriding this method must remember to close the connection's OutputStream after writing.</p>
@param connection the connection to which the body should be written.
@param listener an optional listener for monitoring the write progress.
@throws BoxAPIException if an error occurs while writing to the connection. | [
"protected void writeBody(HttpURLConnection connection, ProgressListener listener) {\n if (this.body == null) {\n return;\n }\n\n connection.setDoOutput(true);\n try {\n OutputStream output = connection.getOutputStream();\n if (listener != null) {\n output = new ProgressOutputStream(output, listener, this.bodyLength);\n }\n int b = this.body.read();\n while (b != -1) {\n output.write(b);\n b = this.body.read();\n }\n output.close();\n } catch (IOException e) {\n throw new BoxAPIException(\"Couldn't connect to the Box API due to a network error.\", e);\n }\n }"
] | [
"public static void Forward(double[][] data) {\n double[][] result = new double[data.length][data[0].length];\n\n for (int m = 0; m < data.length; m++) {\n for (int n = 0; n < data[0].length; n++) {\n double sum = 0;\n for (int i = 0; i < result.length; i++) {\n for (int k = 0; k < data.length; k++) {\n sum += data[i][k] * cas(((2.0 * Math.PI) / data.length) * (i * m + k * n));\n }\n result[m][n] = (1.0 / data.length) * sum;\n }\n }\n }\n\n for (int i = 0; i < data.length; i++) {\n for (int j = 0; j < data[0].length; j++) {\n data[i][j] = result[i][j];\n }\n }\n }",
"private void remove() {\n if (removing) {\n return;\n }\n if (deactiveNotifications.size() == 0) {\n return;\n }\n removing = true;\n final NotificationPopupView view = deactiveNotifications.get(0);\n final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) {\n\n @Override\n public void onUpdate(double progress) {\n super.onUpdate(progress);\n for (int i = 0; i < activeNotifications.size(); i++) {\n NotificationPopupView v = activeNotifications.get(i);\n final int left = v.getPopupLeft();\n final int top = (int) (((i + 1) * SPACING) - (progress * SPACING));\n v.setPopupPosition(left,\n top);\n }\n }\n\n @Override\n public void onComplete() {\n super.onComplete();\n view.hide();\n deactiveNotifications.remove(view);\n activeNotifications.remove(view);\n removing = false;\n remove();\n }\n };\n fadeOutAnimation.run(500);\n }",
"@SuppressForbidden(\"legitimate sysstreams.\")\n private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, \n CommandlineJava commandline, \n TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) {\n try {\n String tempDir = commandline.getSystemProperties().getVariablesVector().stream()\n .filter(v -> v.getKey().equals(\"java.io.tmpdir\"))\n .map(v -> v.getValue())\n .findAny()\n .orElse(null);\n\n final LocalSlaveStreamHandler streamHandler = \n new LocalSlaveStreamHandler(\n eventBus, testsClassLoader, System.err, eventStream, \n sysout, syserr, heartbeat, streamsBuffer);\n\n // Add certain properties to allow identification of the forked JVM from within\n // the subprocess. This can be used for policy files etc.\n final Path cwd = getWorkingDirectory(slaveInfo, tempDir);\n\n Variable v = new Variable();\n v.setKey(CHILDVM_SYSPROP_CWD);\n v.setFile(cwd.toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SYSPROP_TEMPDIR);\n v.setFile(getTempDir().toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID);\n v.setValue(Integer.toString(slaveInfo.id));\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT);\n v.setValue(Integer.toString(slaveInfo.slaves));\n commandline.addSysproperty(v);\n\n // Emit command line before -stdin to avoid confusion.\n slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline());\n log(\"Forked child JVM at '\" + cwd.toAbsolutePath().normalize() + \n \"', command (may need escape sequences for your shell):\\n\" + \n slaveInfo.slaveCommandLine, Project.MSG_VERBOSE);\n\n final Execute execute = new Execute();\n execute.setCommandline(commandline.getCommandline());\n execute.setVMLauncher(true);\n execute.setWorkingDirectory(cwd.toFile());\n execute.setStreamHandler(streamHandler);\n execute.setNewenvironment(newEnvironment);\n if (env.getVariables() != null)\n execute.setEnvironment(env.getVariables());\n log(\"Starting JVM J\" + slaveInfo.id, Project.MSG_DEBUG);\n execute.execute();\n return execute;\n } catch (IOException e) {\n throw new BuildException(\"Could not start the child process. Run ant with -verbose to get\" +\n \t\t\" the execution details.\", e);\n }\n }",
"protected void setWhenNoDataBand() {\n log.debug(\"setting up WHEN NO DATA band\");\n String whenNoDataText = getReport().getWhenNoDataText();\n Style style = getReport().getWhenNoDataStyle();\n if (whenNoDataText == null || \"\".equals(whenNoDataText))\n return;\n JRDesignBand band = new JRDesignBand();\n getDesign().setNoData(band);\n\n JRDesignTextField text = new JRDesignTextField();\n JRDesignExpression expression = ExpressionUtils.createStringExpression(\"\\\"\" + whenNoDataText + \"\\\"\");\n text.setExpression(expression);\n\n if (style == null) {\n style = getReport().getOptions().getDefaultDetailStyle();\n }\n\n if (getReport().isWhenNoDataShowTitle()) {\n LayoutUtils.copyBandElements(band, getDesign().getTitle());\n LayoutUtils.copyBandElements(band, getDesign().getPageHeader());\n }\n if (getReport().isWhenNoDataShowColumnHeader())\n LayoutUtils.copyBandElements(band, getDesign().getColumnHeader());\n\n int offset = LayoutUtils.findVerticalOffset(band);\n text.setY(offset);\n applyStyleToElement(style, text);\n text.setWidth(getReport().getOptions().getPrintableWidth());\n text.setHeight(50);\n band.addElement(text);\n log.debug(\"OK setting up WHEN NO DATA band\");\n\n }",
"@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\n }\n }",
"public final double[] getDpiSuggestions() {\n if (this.dpiSuggestions == null) {\n List<Double> list = new ArrayList<>();\n for (double suggestion: DEFAULT_DPI_VALUES) {\n if (suggestion <= this.maxDpi) {\n list.add(suggestion);\n }\n }\n double[] suggestions = new double[list.size()];\n for (int i = 0; i < suggestions.length; i++) {\n suggestions[i] = list.get(i);\n }\n return suggestions;\n }\n return this.dpiSuggestions;\n }",
"public static String getVersionString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.version\");\n\t\t}\n\t\treturn versionString;\n\t}",
"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}",
"protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {\n final String parameterString = servletContext.getInitParameter(parameterName);\n if(parameterString != null && parameterString.trim().length() > 0) {\n try {\n return Integer.parseInt(parameterString);\n }\n catch (NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return defaultValue;\n }"
] |
Read all child tasks for a given parent.
@param parentTask parent task | [
"private void processChildTasks(Task parentTask) throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zparentactivity_=? and z_ent=? order by zorderinparentactivity\", parentTask.getUniqueID(), m_entityMap.get(\"Activity\"));\n for (Row row : rows)\n {\n Task task = parentTask.addTask();\n populateTask(row, task);\n processChildTasks(task);\n }\n }"
] | [
"protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }",
"private void exportModules() {\n\n // avoid to export modules if unnecessary\n if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue())\n || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) {\n m_logStream.println();\n m_logStream.println(\"NOT EXPORTING MODULES - you disabled copy and unzip.\");\n m_logStream.println();\n return;\n }\n CmsModuleManager moduleManager = OpenCms.getModuleManager();\n\n Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty())\n ? m_currentConfiguration.getConfiguredModules()\n : m_modulesToExport;\n\n for (String moduleName : modulesToExport) {\n CmsModule module = moduleManager.getModule(moduleName);\n if (module != null) {\n CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler(\n getCmsObject(),\n module,\n \"Git export handler\");\n try {\n handler.exportData(\n getCmsObject(),\n new CmsPrintStreamReport(\n m_logStream,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()),\n false));\n } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) {\n e.printStackTrace(m_logStream);\n }\n }\n }\n }",
"public void ifHasName(String template, Properties attributes) throws XDocletException\r\n {\r\n String name = getDefForLevel(attributes.getProperty(ATTRIBUTE_LEVEL)).getName();\r\n\r\n if ((name != null) && (name.length() > 0))\r\n {\r\n generate(template);\r\n }\r\n }",
"public void setContentType(String photoId, String contentType) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_CONTENTTYPE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"content_type\", contentType);\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 List<Tag> getRootTags()\n {\n return this.definedTags.values().stream()\n .filter(Tag::isRoot)\n .collect(Collectors.toList());\n }",
"private void processProjectID()\n {\n if (m_projectID == null)\n {\n List<Row> rows = getRows(\"project\", null, null);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n m_projectID = row.getInteger(\"proj_id\");\n }\n }\n }",
"public static sslvserver_sslcertkey_binding[] get(nitro_service service, String vservername) throws Exception{\n\t\tsslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding();\n\t\tobj.set_vservername(vservername);\n\t\tsslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 void initialize() throws SQLException {\n\t\tif (initialized) {\n\t\t\t// just skip it if already initialized\n\t\t\treturn;\n\t\t}\n\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalStateException(\"connectionSource was never set on \" + getClass().getSimpleName());\n\t\t}\n\n\t\tdatabaseType = connectionSource.getDatabaseType();\n\t\tif (databaseType == null) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"connectionSource is getting a null DatabaseType in \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableConfig == null) {\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, dataClass);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\ttableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t}\n\t\tstatementExecutor = new StatementExecutor<T, ID>(databaseType, tableInfo, this);\n\n\t\t/*\n\t\t * This is a bit complex. Initially, when we were configuring the field types, external DAO information would be\n\t\t * configured for auto-refresh, foreign BaseDaoEnabled classes, and foreign-collections. This would cause the\n\t\t * system to go recursive and for class loops, a stack overflow.\n\t\t * \n\t\t * Then we fixed this by putting a level counter in the FieldType constructor that would stop the configurations\n\t\t * when we reach some recursion level. But this created some bad problems because we were using the DaoManager\n\t\t * to cache the created DAOs that had been constructed already limited by the level.\n\t\t * \n\t\t * What we do now is have a 2 phase initialization. The constructor initializes most of the fields but then we\n\t\t * go back and call FieldType.configDaoInformation() after we are done. So for every DAO that is initialized\n\t\t * here, we have to see if it is the top DAO. If not we save it for dao configuration later.\n\t\t */\n\t\tList<BaseDaoImpl<?, ?>> daoConfigList = daoConfigLevelLocal.get();\n\t\tdaoConfigList.add(this);\n\t\tif (daoConfigList.size() > 1) {\n\t\t\t// if we have recursed then just save the dao for later configuration\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t/*\n\t\t\t * WARNING: We do _not_ use an iterator here because we may be adding to the list as we process it and we'll\n\t\t\t * get exceptions otherwise. This is an ArrayList so the get(i) should be efficient.\n\t\t\t * \n\t\t\t * Also, do _not_ get a copy of daoConfigLevel.doArray because that array may be replaced by another, larger\n\t\t\t * one during the recursion.\n\t\t\t */\n\t\t\tfor (int i = 0; i < daoConfigList.size(); i++) {\n\t\t\t\tBaseDaoImpl<?, ?> dao = daoConfigList.get(i);\n\n\t\t\t\t/*\n\t\t\t\t * Here's another complex bit. The first DAO that is being constructed as part of a DAO chain is not yet\n\t\t\t\t * in the DaoManager cache. If we continue onward we might come back around and try to configure this\n\t\t\t\t * DAO again. Forcing it into the cache here makes sure it won't be configured twice. This will cause it\n\t\t\t\t * to be stuck in twice when it returns out to the DaoManager but that's a small price to pay. This also\n\t\t\t\t * applies to self-referencing classes.\n\t\t\t\t */\n\t\t\t\tDaoManager.registerDao(connectionSource, dao);\n\n\t\t\t\ttry {\n\t\t\t\t\t// config our fields which may go recursive\n\t\t\t\t\tfor (FieldType fieldType : dao.getTableInfo().getFieldTypes()) {\n\t\t\t\t\t\tfieldType.configDaoInformation(connectionSource, dao.getDataClass());\n\t\t\t\t\t}\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t// unregister the DAO we just pre-registered\n\t\t\t\t\tDaoManager.unregisterDao(connectionSource, dao);\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\n\t\t\t\t// it's now been fully initialized\n\t\t\t\tdao.initialized = true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// if we throw we want to clear our class hierarchy here\n\t\t\tdaoConfigList.clear();\n\t\t\tdaoConfigLevelLocal.remove();\n\t\t}\n\t}"
] |
Stop finding waveforms for all active players. | [
"@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our waveforms, on the proper thread, outside our lock\n final Set<DeckReference> dyingPreviewCache = new HashSet<DeckReference>(previewHotCache.keySet());\n previewHotCache.clear();\n final Set<DeckReference> dyingDetailCache = new HashSet<DeckReference>(detailHotCache.keySet());\n detailHotCache.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingPreviewCache) { // Report the loss of our previews.\n if (deck.hotCue == 0) {\n deliverWaveformPreviewUpdate(deck.player, null);\n }\n }\n for (DeckReference deck : dyingDetailCache) { // Report the loss of our details.\n if (deck.hotCue == 0) {\n deliverWaveformDetailUpdate(deck.player, null);\n }\n }\n }\n });\n deliverLifecycleAnnouncement(logger, false);\n }\n }"
] | [
"public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }",
"public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }",
"public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(urlPattern, true), actorClass);\n }",
"private void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData)\n {\n String notes = taskExtData.getString(TASK_NOTES);\n if (notes == null && data.length == 366)\n {\n byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362));\n if (offsetData != null && offsetData.length >= 12)\n {\n notes = taskVarData.getString(getOffset(offsetData, 8));\n \n // We do pick up some random stuff with this approach, and \n // we don't know enough about the file format to know when to ignore it\n // so we'll use a heuristic here to ignore anything that\n // doesn't look like RTF.\n if (notes != null && notes.indexOf('{') == -1)\n {\n notes = null;\n }\n }\n }\n \n if (notes != null)\n {\n if (m_reader.getPreserveNoteFormatting() == false)\n {\n notes = RtfHelper.strip(notes);\n }\n\n task.setNotes(notes);\n }\n }",
"public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}",
"public double compare(String v1, String v2) {\n // FIXME: it should be possible here to say that, actually, we\n // didn't learn anything from comparing these two values, so that\n // probability is set to 0.5.\n\n if (comparator == null)\n return 0.5; // we ignore properties with no comparator\n\n // first, we call the comparator, to get a measure of how similar\n // these two values are. note that this is not the same as what we\n // are going to return, which is a probability.\n double sim = comparator.compare(v1, v2);\n\n // we have been configured with a high probability (for equal\n // values) and a low probability (for different values). given\n // sim, which is a measure of the similarity somewhere in between\n // equal and different, we now compute our estimate of the\n // probability.\n\n // if sim = 1.0, we return high. if sim = 0.0, we return low. for\n // values in between we need to compute a little. the obvious\n // formula to use would be (sim * (high - low)) + low, which\n // spreads the values out equally spaced between high and low.\n\n // however, if the similarity is higher than 0.5 we don't want to\n // consider this negative evidence, and so there's a threshold\n // there. also, users felt Duke was too eager to merge records,\n // and wanted probabilities to fall off faster with lower\n // probabilities, and so we square sim in order to achieve this.\n\n if (sim >= 0.5)\n return ((high - 0.5) * (sim * sim)) + 0.5;\n else\n return low;\n }",
"public static int scanright(Color color, int height, int width, int col, PixelsExtractor f, int tolerance) {\n if (col == width || !PixelTools.colorMatches(color, tolerance, f.apply(new Area(col, 0, 1, height))))\n return col;\n else\n return scanright(color, height, width, col + 1, f, tolerance);\n }",
"private static boolean isValidPropertyClass(final PropertyDescriptor _property) {\n final Class type = _property.getPropertyType();\n return Number.class.isAssignableFrom(type) || type == String.class || Date.class.isAssignableFrom(type) || type == Boolean.class;\n }",
"private <Y> void checkObserverMethod(EnhancedAnnotatedMethod<T, Y> annotated) {\n // Make sure exactly one and only one parameter is annotated with Observes or ObservesAsync\n List<EnhancedAnnotatedParameter<?, Y>> eventObjects = annotated.getEnhancedParameters(Observes.class);\n eventObjects.addAll(annotated.getEnhancedParameters(ObservesAsync.class));\n if (this.reception.equals(Reception.IF_EXISTS) && declaringBean.getScope().equals(Dependent.class)) {\n throw EventLogger.LOG.invalidScopedConditionalObserver(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n if (eventObjects.size() > 1) {\n throw EventLogger.LOG.multipleEventParameters(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n EnhancedAnnotatedParameter<?, Y> eventParameter = eventObjects.iterator().next();\n checkRequiredTypeAnnotations(eventParameter);\n // Check for parameters annotated with @Disposes\n List<?> disposeParams = annotated.getEnhancedParameters(Disposes.class);\n if (disposeParams.size() > 0) {\n throw EventLogger.LOG.invalidDisposesParameter(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n // Check annotations on the method to make sure this is not a producer\n // method, initializer method, or destructor method.\n if (this.observerMethod.getAnnotated().isAnnotationPresent(Produces.class)) {\n throw EventLogger.LOG.invalidProducer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n if (this.observerMethod.getAnnotated().isAnnotationPresent(Inject.class)) {\n throw EventLogger.LOG.invalidInitializer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n boolean containerLifecycleObserverMethod = Observers.isContainerLifecycleObserverMethod(this);\n for (EnhancedAnnotatedParameter<?, ?> parameter : annotated.getEnhancedParameters()) {\n // if this is an observer method for container lifecycle event, it must not inject anything besides BeanManager\n if (containerLifecycleObserverMethod && !parameter.isAnnotationPresent(Observes.class) && !parameter.isAnnotationPresent(ObservesAsync.class) && !BeanManager.class.equals(parameter.getBaseType())) {\n throw EventLogger.LOG.invalidInjectionPoint(this, Formats.formatAsStackTraceElement(annotated.getJavaMember()));\n }\n }\n\n }"
] |
Returns the primary message codewords for mode 3.
@param postcode the postal code
@param country the country code
@param service the service code
@return the primary message, as codewords | [
"private static int[] getMode3PrimaryCodewords(String postcode, int country, int service) {\r\n\r\n int[] postcodeNums = new int[postcode.length()];\r\n\r\n postcode = postcode.toUpperCase();\r\n for (int i = 0; i < postcodeNums.length; i++) {\r\n postcodeNums[i] = postcode.charAt(i);\r\n if (postcode.charAt(i) >= 'A' && postcode.charAt(i) <= 'Z') {\r\n // (Capital) letters shifted to Code Set A values\r\n postcodeNums[i] -= 64;\r\n }\r\n if (postcodeNums[i] == 27 || postcodeNums[i] == 31 || postcodeNums[i] == 33 || postcodeNums[i] >= 59) {\r\n // Not a valid postal code character, use space instead\r\n postcodeNums[i] = 32;\r\n }\r\n // Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital\r\n // letters in Code Set A (e.g. LF becomes 'J')\r\n }\r\n\r\n int[] primary = new int[10];\r\n primary[0] = ((postcodeNums[5] & 0x03) << 4) | 3;\r\n primary[1] = ((postcodeNums[4] & 0x03) << 4) | ((postcodeNums[5] & 0x3c) >> 2);\r\n primary[2] = ((postcodeNums[3] & 0x03) << 4) | ((postcodeNums[4] & 0x3c) >> 2);\r\n primary[3] = ((postcodeNums[2] & 0x03) << 4) | ((postcodeNums[3] & 0x3c) >> 2);\r\n primary[4] = ((postcodeNums[1] & 0x03) << 4) | ((postcodeNums[2] & 0x3c) >> 2);\r\n primary[5] = ((postcodeNums[0] & 0x03) << 4) | ((postcodeNums[1] & 0x3c) >> 2);\r\n primary[6] = ((postcodeNums[0] & 0x3c) >> 2) | ((country & 0x3) << 4);\r\n primary[7] = (country & 0xfc) >> 2;\r\n primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);\r\n primary[9] = ((service & 0x3f0) >> 4);\r\n\r\n return primary;\r\n }"
] | [
"protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }",
"public FastReportBuilder addBarcodeColumn(String title, String property,String className, int barcodeType,boolean showText, int width, boolean fixedWidth,ImageScaleMode imageScaleMode, Style style) throws ColumnBuilderException, ClassNotFoundException {\n\t\tAbstractColumn column = ColumnBuilder.getNew()\n\t\t.setColumnProperty(property, className)\n\t\t.setWidth(width)\n\t\t.setTitle(title)\n\t\t.setFixedWidth(fixedWidth)\n\t\t.setColumnType(ColumnBuilder.COLUMN_TYPE_BARCODE)\n\t\t.setStyle(style)\n\t\t.setBarcodeType(barcodeType)\n\t\t.setShowText(showText)\n\t\t.build();\n\n\t\tif (style == null)\n\t\t\tguessStyle(className, column);\n\n\t\taddColumn(column);\n\n\t\treturn this;\n\t}",
"private String visibility(Options opt, ProgramElementDoc e) {\n\treturn opt.showVisibility ? Visibility.get(e).symbol : \" \";\n }",
"public void setCategoryDisplayOptions(\n String displayCategoriesByRepository,\n String displayCategorySelectionCollapsed) {\n\n m_displayCategoriesByRepository = Boolean.parseBoolean(displayCategoriesByRepository);\n m_displayCategorySelectionCollapsed = Boolean.parseBoolean(displayCategorySelectionCollapsed);\n }",
"private boolean skipBar(Row row)\n {\n List<Row> childRows = row.getChildRows();\n return childRows.size() == 1 && childRows.get(0).getChildRows().isEmpty();\n }",
"public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,\n\t\t\t\t\t\t\t\t\t\t\t\tCrawlerContext context) {\n\t\tStateVertex cloneState = this.addStateToCurrentState(newState, event);\n\n\t\trunOnInvariantViolationPlugins(context);\n\n\t\tif (cloneState == null) {\n\t\t\tchangeState(newState);\n\t\t\tplugins.runOnNewStatePlugins(context, newState);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tchangeState(cloneState);\n\t\t\treturn false;\n\t\t}\n\t}",
"public synchronized int getPartitionStoreCount() {\n int count = 0;\n for (String store : storeToPartitionIds.keySet()) {\n count += storeToPartitionIds.get(store).size();\n }\n return count;\n }",
"int cancel(int downloadId) {\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tfor (DownloadRequest request : mCurrentRequests) {\n\t\t\t\tif (request.getDownloadId() == downloadId) {\n\t\t\t\t\trequest.cancel();\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}",
"public static Node updateNode(Node node, List<Integer> partitionsList) {\n return new Node(node.getId(),\n node.getHost(),\n node.getHttpPort(),\n node.getSocketPort(),\n node.getAdminPort(),\n node.getZoneId(),\n partitionsList);\n }"
] |
Print an earned value method.
@param value EarnedValueMethod instance
@return earned value method value | [
"public static final BigInteger printEarnedValueMethod(EarnedValueMethod value)\n {\n return (value == null ? BigInteger.valueOf(EarnedValueMethod.PERCENT_COMPLETE.getValue()) : BigInteger.valueOf(value.getValue()));\n }"
] | [
"private void clearWorkingDateCache()\n {\n m_workingDateCache.clear();\n m_startTimeCache.clear();\n m_getDateLastResult = null;\n for (ProjectCalendar calendar : m_derivedCalendars)\n {\n calendar.clearWorkingDateCache();\n }\n }",
"private Map<String, String> readCustomInfo(long eventId) {\n List<Map<String, Object>> rows = getJdbcTemplate()\n .queryForList(\"select * from EVENTS_CUSTOMINFO where EVENT_ID=\" + eventId);\n Map<String, String> customInfo = new HashMap<String, String>(rows.size());\n for (Map<String, Object> row : rows) {\n customInfo.put((String)row.get(\"CUST_KEY\"), (String)row.get(\"CUST_VALUE\"));\n }\n return customInfo;\n }",
"private void init() {\n validatePreSignedUrls();\n\n try {\n conn = new AWSAuthConnection(access_key, secret_access_key);\n // Determine the bucket name if prefix is set or if pre-signed URLs are being used\n if (prefix != null && prefix.length() > 0) {\n ListAllMyBucketsResponse bucket_list = conn.listAllMyBuckets(null);\n List buckets = bucket_list.entries;\n if (buckets != null) {\n boolean found = false;\n for (Object tmp : buckets) {\n if (tmp instanceof Bucket) {\n Bucket bucket = (Bucket) tmp;\n if (bucket.name.startsWith(prefix)) {\n location = bucket.name;\n found = true;\n }\n }\n }\n if (!found) {\n location = prefix + \"-\" + java.util.UUID.randomUUID().toString();\n }\n }\n }\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n location = parsedPut.getBucket();\n }\n if (!conn.checkBucketExists(location)) {\n conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage();\n }\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3Bucket(location, e.getLocalizedMessage());\n }\n }",
"protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {\n\t\tswitch (httpMethod) {\n\t\t\tcase GET:\n\t\t\t\treturn new HttpGet(uri);\n\t\t\tcase DELETE:\n\t\t\t\treturn new HttpDelete(uri);\n\t\t\tcase HEAD:\n\t\t\t\treturn new HttpHead(uri);\n\t\t\tcase OPTIONS:\n\t\t\t\treturn new HttpOptions(uri);\n\t\t\tcase POST:\n\t\t\t\treturn new HttpPost(uri);\n\t\t\tcase PUT:\n\t\t\t\treturn new HttpPut(uri);\n\t\t\tcase TRACE:\n\t\t\t\treturn new HttpTrace(uri);\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid HTTP method: \" + httpMethod);\n\t\t}\n\t}",
"private void addExceptionRange(ProjectCalendarException exception, Date start, Date finish)\n {\n if (start != null && finish != null)\n {\n exception.addRange(new DateRange(start, finish));\n }\n }",
"private void processResource(MapRow row) throws IOException\n {\n Resource resource = m_project.addResource();\n resource.setName(row.getString(\"NAME\"));\n resource.setGUID(row.getUUID(\"UUID\"));\n resource.setEmailAddress(row.getString(\"EMAIL\"));\n resource.setHyperlink(row.getString(\"URL\"));\n resource.setNotes(getNotes(row.getRows(\"COMMENTARY\")));\n resource.setText(1, row.getString(\"DESCRIPTION\"));\n resource.setText(2, row.getString(\"SUPPLY_REFERENCE\"));\n resource.setActive(true);\n\n List<MapRow> resources = row.getRows(\"RESOURCES\");\n if (resources != null)\n {\n for (MapRow childResource : sort(resources, \"NAME\"))\n {\n processResource(childResource);\n }\n }\n\n m_resourceMap.put(resource.getGUID(), resource);\n }",
"public void add(Vector3d v1) {\n x += v1.x;\n y += v1.y;\n z += v1.z;\n }",
"public void checkAllRequirementsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (Field field: this.dependantsInJson) {\n final Collection<String> requirements = this.dependantToRequirementsMap.get(field);\n if (!requirements.isEmpty()) {\n errors.append(\"\\n\");\n String type = field.getType().getName();\n if (field.getType().isArray()) {\n type = field.getType().getComponentType().getName() + \"[]\";\n }\n errors.append(\"\\t* \").append(type).append(' ').append(field.getName()).append(\" depends on \")\n .append(requirements);\n }\n }\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @Requires dependencies of '\" +\n currentPath + \"': \" + errors);\n }",
"public Credentials toGrgit() {\n if (username != null && password != null) {\n return new Credentials(username, password);\n } else {\n return null;\n }\n }"
] |
Handle changes of the series check box.
@param event the change event. | [
"@UiHandler(\"m_seriesCheckBox\")\n void onSeriesChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setIsSeries(event.getValue());\n }\n }"
] | [
"private String toSQLClause(FieldCriteria c, ClassDescriptor cld)\r\n {\r\n String colName = toSqlClause(c.getAttribute(), cld);\r\n return colName + c.getClause() + c.getValue();\r\n }",
"public static void saveBin(DMatrix A, String fileName)\n throws IOException\n {\n FileOutputStream fileStream = new FileOutputStream(fileName);\n ObjectOutputStream stream = new ObjectOutputStream(fileStream);\n\n try {\n stream.writeObject(A);\n stream.flush();\n } finally {\n // clean up\n try {\n stream.close();\n } finally {\n fileStream.close();\n }\n }\n\n }",
"public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) {\n\t\treturn ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator);\n\t}",
"public static void addLazyDefinitions(SourceBuilder code) {\n Set<Declaration> defined = new HashSet<>();\n\n // Definitions may lazily declare new names; ensure we add them all\n List<Declaration> declarations =\n code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n while (!defined.containsAll(declarations)) {\n for (Declaration declaration : declarations) {\n if (defined.add(declaration)) {\n code.add(code.scope().get(declaration).definition);\n }\n }\n declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList());\n }\n }",
"public List<WebSocketConnection> get(String key) {\n final List<WebSocketConnection> retList = new ArrayList<>();\n accept(key, C.F.addTo(retList));\n return retList;\n }",
"@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 static Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception {\n Integer overrideId = -1;\n\n try {\n // there is an issue with parseInt where it does not parse negative values correctly\n boolean isNegative = false;\n if (overrideIdentifier.startsWith(\"-\")) {\n isNegative = true;\n overrideIdentifier = overrideIdentifier.substring(1);\n }\n overrideId = Integer.parseInt(overrideIdentifier);\n\n if (isNegative) {\n overrideId = 0 - overrideId;\n }\n } catch (NumberFormatException ne) {\n // this is OK.. just means it's not a #\n\n // split into two parts\n String className = null;\n String methodName = null;\n int lastDot = overrideIdentifier.lastIndexOf(\".\");\n className = overrideIdentifier.substring(0, lastDot);\n methodName = overrideIdentifier.substring(lastDot + 1);\n\n overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName);\n }\n\n return overrideId;\n }",
"public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);\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 }"
] |
these are the iterators used by MACAddress | [
"protected Iterator<MACAddress> iterator(MACAddress original) {\r\n\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\tboolean isSingle = !isMultiple();\r\n\t\treturn iterator(\r\n\t\t\t\tisSingle ? original : null, \r\n\t\t\t\tcreator,//using a lambda for this one results in a big performance hit\r\n\t\t\t\tisSingle ? null : segmentsIterator(),\r\n\t\t\t\tgetNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets() ? null : getPrefixLength());\r\n\t}"
] | [
"@Api\n\tpublic void setUseCache(boolean useCache) {\n\t\tif (null == cacheManagerService && useCache) {\n\t\t\tlog.warn(\"The caching plugin needs to be available to cache WMS requests. Not setting useCache.\");\n\t\t} else {\n\t\t\tthis.useCache = useCache;\n\t\t}\n\t}",
"public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\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 synchronized void addCachedDatabaseConfigs(Collection<DatabaseTableConfig<?>> configs) {\n\t\tMap<Class<?>, DatabaseTableConfig<?>> newMap;\n\t\tif (configMap == null) {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>();\n\t\t} else {\n\t\t\tnewMap = new HashMap<Class<?>, DatabaseTableConfig<?>>(configMap);\n\t\t}\n\t\tfor (DatabaseTableConfig<?> config : configs) {\n\t\t\tnewMap.put(config.getDataClass(), config);\n\t\t\tlogger.info(\"Loaded configuration for {}\", config.getDataClass());\n\t\t}\n\t\tconfigMap = newMap;\n\t}",
"@SuppressWarnings(\"unchecked\")\n protected <T extends Indexable> T taskResult(String key) {\n Indexable result = this.taskGroup.taskResult(key);\n if (result == null) {\n return null;\n } else {\n T castedResult = (T) result;\n return castedResult;\n }\n }",
"public void createContainer(String container) {\n\n ContainerController controller = this.platformContainers.get(container);\n if (controller == null) {\n\n // TODO make this configurable\n Profile p = new ProfileImpl();\n p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID);\n p.setParameter(Profile.MAIN_HOST, MAIN_HOST);\n p.setParameter(Profile.MAIN_PORT, MAIN_PORT);\n p.setParameter(Profile.LOCAL_HOST, MAIN_HOST);\n int port = Integer.parseInt(MAIN_PORT);\n port = port + 1 + this.platformContainers.size();\n p.setParameter(Profile.LOCAL_PORT, Integer.toString(port));\n p.setParameter(Profile.CONTAINER_NAME, container);\n logger.fine(\"Creating container \" + container + \"...\");\n ContainerController agentContainer = this.runtime\n .createAgentContainer(p);\n this.platformContainers.put(container, agentContainer);\n logger.fine(\"Container \" + container + \" created successfully.\");\n } else {\n logger.fine(\"Container \" + container + \" is already created.\");\n }\n\n }",
"public static int count(CharSequence self, CharSequence text) {\n int answer = 0;\n for (int idx = 0; true; idx++) {\n idx = self.toString().indexOf(text.toString(), idx);\n // break once idx goes to -1 or for case of empty string once\n // we get to the end to avoid JDK library bug (see GROOVY-5858)\n if (idx < answer) break;\n ++answer;\n }\n return answer;\n }",
"public List<IssueCategory> getIssueCategories()\n {\n return this.issueCategories.values().stream()\n .sorted((category1, category2) -> category1.getPriority() - category2.getPriority())\n .collect(Collectors.toList());\n }",
"private void writeFields(String objectName, FieldContainer container, FieldType[] fields) throws IOException\n {\n m_writer.writeStartObject(objectName);\n for (FieldType field : fields)\n {\n Object value = container.getCurrentValue(field);\n if (value != null)\n {\n writeField(field, value);\n }\n }\n m_writer.writeEndObject();\n }"
] |
Compute eigenvalues. This is a routine not in ATLAS, but in the original
LAPACK. | [
"public static void checkEigenvalues() {\n DoubleMatrix A = new DoubleMatrix(new double[][]{\n {3.0, 2.0, 0.0},\n {2.0, 3.0, 2.0},\n {0.0, 2.0, 3.0}\n });\n\n DoubleMatrix E = new DoubleMatrix(3, 1);\n\n NativeBlas.dsyev('N', 'U', 3, A.data, 0, 3, E.data, 0);\n check(\"checking existence of dsyev...\", true);\n }"
] | [
"private Date readOptionalDate(JSONValue val) {\n\n JSONString str = null == val ? null : val.isString();\n if (str != null) {\n try {\n return new Date(Long.parseLong(str.stringValue()));\n } catch (@SuppressWarnings(\"unused\") NumberFormatException e) {\n // do nothing - return the default value\n }\n }\n return null;\n }",
"public String getOuterMostNullEmbeddableIfAny(String column) {\n\t\tString[] path = column.split( \"\\\\.\" );\n\t\tif ( !isEmbeddableColumn( path ) ) {\n\t\t\treturn null;\n\t\t}\n\t\t// the cached value may be null hence the explicit key lookup\n\t\tif ( columnToOuterMostNullEmbeddableCache.containsKey( column ) ) {\n\t\t\treturn columnToOuterMostNullEmbeddableCache.get( column );\n\t\t}\n\t\treturn determineAndCacheOuterMostNullEmbeddable( column, path );\n\t}",
"Map<Object, Object> getFilters() {\n\n Map<Object, Object> result = new HashMap<Object, Object>(4);\n result.put(TableProperty.KEY, m_table.getFilterFieldValue(TableProperty.KEY));\n result.put(TableProperty.DEFAULT, m_table.getFilterFieldValue(TableProperty.DEFAULT));\n result.put(TableProperty.DESCRIPTION, m_table.getFilterFieldValue(TableProperty.DESCRIPTION));\n result.put(TableProperty.TRANSLATION, m_table.getFilterFieldValue(TableProperty.TRANSLATION));\n return result;\n }",
"public void mark() {\n final long currentTimeMillis = clock.currentTimeMillis();\n\n synchronized (queue) {\n if (queue.size() == capacity) {\n /*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */\n queue.removeFirst();\n }\n queue.addLast(currentTimeMillis);\n }\n }",
"private LoginContext getClientLoginContext() throws LoginException {\n Configuration config = new Configuration() {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name) {\n Map<String, String> options = new HashMap<String, String>();\n options.put(\"multi-threaded\", \"true\");\n options.put(\"restore-login-identity\", \"true\");\n\n AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);\n return new AppConfigurationEntry[] { clmEntry };\n }\n };\n return getLoginContext(config);\n }",
"public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }",
"private void setMasterTempo(double newTempo) {\n double oldTempo = Double.longBitsToDouble(masterTempo.getAndSet(Double.doubleToLongBits(newTempo)));\n if ((getTempoMaster() != null) && (Math.abs(newTempo - oldTempo) > getTempoEpsilon())) {\n // This is a change in tempo, so report it to any registered listeners, and update our metronome if we are synced.\n if (isSynced()) {\n metronome.setTempo(newTempo);\n notifyBeatSenderOfChange();\n }\n deliverTempoChangedAnnouncement(newTempo);\n }\n }",
"void recover() {\n final List<NamespaceSynchronizationConfig> nsConfigs = new ArrayList<>();\n for (final MongoNamespace ns : this.syncConfig.getSynchronizedNamespaces()) {\n nsConfigs.add(this.syncConfig.getNamespaceConfig(ns));\n }\n\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n }\n try {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().lock();\n try {\n recoverNamespace(nsConfig);\n } finally {\n nsConfig.getLock().writeLock().unlock();\n }\n }\n } finally {\n for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) {\n nsConfig.getLock().writeLock().unlock();\n }\n }\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}"
] |
Generic version of getting value by key from the JobContext of current thread
@param key the key
@param clz the val class
@param <T> the val type
@return the value | [
"public static <T> T get(String key, Class<T> clz) {\n return (T)m().get(key);\n }"
] | [
"private <T> void requestAsync(ClientRequest<T> delegate,\n NonblockingStoreCallback callback,\n long timeoutMs,\n String operationName) {\n pool.submitAsync(this.destination, delegate, callback, timeoutMs, operationName);\n }",
"public static base_response update(nitro_service client, autoscaleprofile resource) throws Exception {\n\t\tautoscaleprofile updateresource = new autoscaleprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.apikey = resource.apikey;\n\t\tupdateresource.sharedsecret = resource.sharedsecret;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void close() {\n Iterator<SocketDestination> it = getStatsMap().keySet().iterator();\n while(it.hasNext()) {\n try {\n SocketDestination destination = it.next();\n JmxUtils.unregisterMbean(JmxUtils.createObjectName(JmxUtils.getPackageName(ClientRequestExecutor.class),\n \"stats_\"\n + destination.toString()\n .replace(':',\n '_')\n + identifierString));\n } catch(Exception e) {}\n }\n }",
"@RequestMapping(value = \"/api/scripts\", method = RequestMethod.POST)\n public\n @ResponseBody\n Script addScript(Model model,\n @RequestParam(required = true) String name,\n @RequestParam(required = true) String script) throws Exception {\n\n return ScriptService.getInstance().addScript(name, script);\n }",
"public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {\n\t\treturn HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);\n\t}",
"public static <T extends Comparable<? super T>> List<T> sortInplace(List<T> list) {\n\t\tCollections.sort(list);\n\t\treturn list;\n\t}",
"public ItemRequest<Task> dependents(String task) {\n \n String path = String.format(\"/tasks/%s/dependents\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public static String subscriptionFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).subscriptionId() : null;\n }",
"private void nodeProperties(Options opt) {\n\tOptions def = opt.getGlobalOptions();\n\tif (opt.nodeFontName != def.nodeFontName)\n\t w.print(\",fontname=\\\"\" + opt.nodeFontName + \"\\\"\");\n\tif (opt.nodeFontColor != def.nodeFontColor)\n\t w.print(\",fontcolor=\\\"\" + opt.nodeFontColor + \"\\\"\");\n\tif (opt.nodeFontSize != def.nodeFontSize)\n\t w.print(\",fontsize=\" + fmt(opt.nodeFontSize));\n\tw.print(opt.shape.style);\n\tw.println(\"];\");\n }"
] |
Execute a request
@param httpMethodProxyRequest
@param httpServletRequest
@param httpServletResponse
@param history
@throws Exception | [
"private void executeRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n PluginResponse httpServletResponse,\n History history) throws Exception {\n int intProxyResponseCode = 999;\n // Create a default HttpClient\n HttpClient httpClient = new HttpClient();\n HttpState state = new HttpState();\n\n try {\n httpMethodProxyRequest.setFollowRedirects(false);\n ArrayList<String> headersToRemove = getRemoveHeaders();\n\n httpClient.getParams().setSoTimeout(60000);\n\n httpServletRequest.setAttribute(\"com.groupon.odo.removeHeaders\", headersToRemove);\n\n // exception handling for httpclient\n HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {\n public boolean retryMethod(\n final HttpMethod method,\n final IOException exception,\n int executionCount) {\n return false;\n }\n };\n\n httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);\n\n intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);\n } catch (Exception e) {\n // Return a gateway timeout\n httpServletResponse.setStatus(504);\n httpServletResponse.setHeader(Constants.HEADER_STATUS, \"504\");\n httpServletResponse.flushBuffer();\n return;\n }\n logger.info(\"Response code: {}, {}\", intProxyResponseCode,\n HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n\n // Pass the response code back to the client\n httpServletResponse.setStatus(intProxyResponseCode);\n\n // Pass response headers back to the client\n Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();\n for (Header header : headerArrayResponse) {\n // remove transfer-encoding header. The http libraries will handle this encoding\n if (header.getName().toLowerCase().equals(\"transfer-encoding\")) {\n continue;\n }\n\n httpServletResponse.setHeader(header.getName(), header.getValue());\n }\n\n // there is no data for a HTTP 304 or 204\n if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&\n intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {\n // Send the content to the client\n httpServletResponse.resetBuffer();\n httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());\n }\n\n // copy cookies to servlet response\n for (Cookie cookie : state.getCookies()) {\n javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());\n\n if (cookie.getPath() != null) {\n servletCookie.setPath(cookie.getPath());\n }\n\n if (cookie.getDomain() != null) {\n servletCookie.setDomain(cookie.getDomain());\n }\n\n // convert expiry date to max age\n if (cookie.getExpiryDate() != null) {\n servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));\n }\n\n servletCookie.setSecure(cookie.getSecure());\n\n servletCookie.setVersion(cookie.getVersion());\n\n if (cookie.getComment() != null) {\n servletCookie.setComment(cookie.getComment());\n }\n\n httpServletResponse.addCookie(servletCookie);\n }\n }"
] | [
"private void validateAsMongoDBFieldName(String fieldName) {\n\t\tif ( fieldName.startsWith( \"$\" ) ) {\n\t\t\tthrow log.fieldNameHasInvalidDollarPrefix( fieldName );\n\t\t}\n\t\telse if ( fieldName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.fieldNameContainsNULCharacter( fieldName );\n\t\t}\n\t}",
"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 void linkOneToMany(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkOneToMany(true, obj, cod,referencedObjects, insert);\n }",
"private void parseMetadataItem(Message item) {\n switch (item.getMenuItemType()) {\n case TRACK_TITLE:\n title = ((StringField) item.arguments.get(3)).getValue();\n artworkId = (int) ((NumberField) item.arguments.get(8)).getValue();\n break;\n\n case ARTIST:\n artist = buildSearchableItem(item);\n break;\n\n case ORIGINAL_ARTIST:\n originalArtist = buildSearchableItem(item);\n break;\n\n case REMIXER:\n remixer = buildSearchableItem(item);\n\n case ALBUM_TITLE:\n album = buildSearchableItem(item);\n break;\n\n case LABEL:\n label = buildSearchableItem(item);\n break;\n\n case DURATION:\n duration = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case TEMPO:\n tempo = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case COMMENT:\n comment = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case KEY:\n key = buildSearchableItem(item);\n break;\n\n case RATING:\n rating = (int) ((NumberField)item.arguments.get(1)).getValue();\n break;\n\n case COLOR_NONE:\n case COLOR_AQUA:\n case COLOR_BLUE:\n case COLOR_GREEN:\n case COLOR_ORANGE:\n case COLOR_PINK:\n case COLOR_PURPLE:\n case COLOR_RED:\n case COLOR_YELLOW:\n color = buildColorItem(item);\n break;\n\n case GENRE:\n genre = buildSearchableItem(item);\n break;\n\n case DATE_ADDED:\n dateAdded = ((StringField) item.arguments.get(3)).getValue();\n break;\n\n case YEAR:\n year = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n case BIT_RATE:\n bitRate = (int) ((NumberField) item.arguments.get(1)).getValue();\n break;\n\n default:\n logger.warn(\"Ignoring track metadata item with unknown type: {}\", item);\n }\n }",
"public static void invert( final int blockLength ,\n final boolean upper ,\n final DSubmatrixD1 T ,\n final DSubmatrixD1 T_inv ,\n final double temp[] )\n {\n if( upper )\n throw new IllegalArgumentException(\"Upper triangular matrices not supported yet\");\n\n if( temp.length < blockLength*blockLength )\n throw new IllegalArgumentException(\"Temp must be at least blockLength*blockLength long.\");\n\n if( T.row0 != T_inv.row0 || T.row1 != T_inv.row1 || T.col0 != T_inv.col0 || T.col1 != T_inv.col1)\n throw new IllegalArgumentException(\"T and T_inv must be at the same elements in the matrix\");\n\n final int M = T.row1-T.row0;\n\n final double dataT[] = T.original.data;\n final double dataX[] = T_inv.original.data;\n\n final int offsetT = T.row0*T.original.numCols+M*T.col0;\n\n for( int i = 0; i < M; i += blockLength ) {\n int heightT = Math.min(T.row1-(i+T.row0),blockLength);\n\n int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);\n\n for( int j = 0; j < i; j += blockLength ) {\n int widthX = Math.min(T.col1-(j+T.col0),blockLength);\n\n for( int w = 0; w < temp.length; w++ ) {\n temp[w] = 0;\n }\n\n for( int k = j; k < i; k += blockLength ) {\n int widthT = Math.min(T.col1-(k+T.col0),blockLength);\n\n int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);\n int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);\n\n blockMultMinus(dataT,dataX,temp,indexL,indexX,0,heightT,widthT,widthX);\n }\n\n int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);\n\n InnerTriangularSolver_DDRB.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);\n System.arraycopy(temp,0,dataX,indexX,widthX*heightT);\n }\n InnerTriangularSolver_DDRB.invertLower(dataT,dataX,heightT,indexII,indexII);\n }\n }",
"public static <T> List<T> toList(Iterable<T> items) {\r\n List<T> list = new ArrayList<T>();\r\n addAll(list, items);\r\n return list;\r\n }",
"private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)\n throws IOException\n {\n final String outputDirectory = settings.getOutputDirectory();\n\n final String fileName = type.getName() + settings.getLanguage().getFileExtension();\n final String packageName = type.getPackageName();\n\n // foo.Bar -> foo/Bar.java\n final String subDir = StringUtils.defaultIfEmpty(packageName, \"\").replace('.', File.separatorChar);\n final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName);\n\n final File outputFile = new File(outputPath);\n final File parentDir = outputFile.getParentFile();\n\n if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs())\n {\n throw new IllegalStateException(\"Could not create directory:\" + parentDir);\n }\n\n if (!outputFile.exists() && !outputFile.createNewFile())\n {\n throw new IllegalStateException(\"Could not create output file: \" + outputPath);\n }\n\n return new FileOutputWriter(outputFile, settings);\n }",
"public static List<String> toList(CharSequence self) {\n String s = self.toString();\n int size = s.length();\n List<String> answer = new ArrayList<String>(size);\n for (int i = 0; i < size; i++) {\n answer.add(s.substring(i, i + 1));\n }\n return answer;\n }",
"public void delete(boolean notifyUser, boolean force) {\n String queryString = new QueryStringBuilder()\n .appendParam(\"notify\", String.valueOf(notifyUser))\n .appendParam(\"force\", String.valueOf(force))\n .toString();\n\n URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }"
] |
Use this API to fetch hanode_routemonitor_binding resources of given name . | [
"public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor_binding obj = new hanode_routemonitor_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"@Override\n\tpublic boolean addAll(Collection<? extends T> collection) {\n\t\tboolean changed = false;\n\t\tfor (T data : collection) {\n\t\t\ttry {\n\t\t\t\tif (addElement(data)) {\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not create data elements in dao\", e);\n\t\t\t}\n\t\t}\n\t\treturn changed;\n\t}",
"private String getInitials(String name)\n {\n String result = null;\n\n if (name != null && name.length() != 0)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(name.charAt(0));\n int index = 1;\n while (true)\n {\n index = name.indexOf(' ', index);\n if (index == -1)\n {\n break;\n }\n\n ++index;\n if (index < name.length() && name.charAt(index) != ' ')\n {\n sb.append(name.charAt(index));\n }\n\n ++index;\n }\n\n result = sb.toString();\n }\n\n return result;\n }",
"private void deliverBeatAnnouncement(final Beat beat) {\n for (final MasterListener listener : getMasterListeners()) {\n try {\n listener.newBeat(beat);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering master beat announcement to listener\", t);\n }\n }\n }",
"private static boolean isAssignableFrom(WildcardType type1, Type type2) {\n if (!isAssignableFrom(type1.getUpperBounds()[0], type2)) {\n return false;\n }\n if (type1.getLowerBounds().length > 0 && !isAssignableFrom(type2, type1.getLowerBounds()[0])) {\n return false;\n }\n return true;\n }",
"private void processCalendar(MapRow row)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n\n Map<UUID, List<DateRange>> dayTypeMap = processDayTypes(row.getRows(\"DAY_TYPES\"));\n\n calendar.setName(row.getString(\"NAME\"));\n\n processRanges(dayTypeMap.get(row.getUUID(\"SUNDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.SUNDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"MONDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.MONDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"TUESDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.TUESDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"WEDNESDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.WEDNESDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"THURSDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.THURSDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"FRIDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.FRIDAY));\n processRanges(dayTypeMap.get(row.getUUID(\"SATURDAY_DAY_TYPE\")), calendar.addCalendarHours(Day.SATURDAY));\n\n for (MapRow assignment : row.getRows(\"DAY_TYPE_ASSIGNMENTS\"))\n {\n Date date = assignment.getDate(\"DATE\");\n processRanges(dayTypeMap.get(assignment.getUUID(\"DAY_TYPE_UUID\")), calendar.addCalendarException(date, date));\n }\n\n m_calendarMap.put(row.getUUID(\"UUID\"), calendar);\n }",
"public void setDefaultCalendarName(String calendarName)\n {\n if (calendarName == null || calendarName.length() == 0)\n {\n calendarName = DEFAULT_CALENDAR_NAME;\n }\n\n set(ProjectField.DEFAULT_CALENDAR_NAME, calendarName);\n }",
"public static base_response export(nitro_service client, application resource) throws Exception {\n\t\tapplication exportresource = new application();\n\t\texportresource.appname = resource.appname;\n\t\texportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\texportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn exportresource.perform_operation(client,\"export\");\n\t}",
"private static boolean waitTillNoNotifications(Environment env, TableRange range)\n throws TableNotFoundException {\n boolean sawNotifications = false;\n long retryTime = MIN_SLEEP_MS;\n\n log.debug(\"Scanning tablet {} for notifications\", range);\n\n long start = System.currentTimeMillis();\n while (hasNotifications(env, range)) {\n sawNotifications = true;\n long sleepTime = Math.max(System.currentTimeMillis() - start, retryTime);\n log.debug(\"Tablet {} had notfications, will rescan in {}ms\", range, sleepTime);\n UtilWaitThread.sleep(sleepTime);\n retryTime = Math.min(MAX_SLEEP_MS, (long) (retryTime * 1.5));\n start = System.currentTimeMillis();\n }\n\n return sawNotifications;\n }",
"public static Map<FieldType, String> getDefaultAliases()\n {\n Map<FieldType, String> map = new HashMap<FieldType, String>();\n\n map.put(TaskField.DATE1, \"Suspend Date\");\n map.put(TaskField.DATE2, \"Resume Date\");\n map.put(TaskField.TEXT1, \"Code\");\n map.put(TaskField.TEXT2, \"Activity Type\");\n map.put(TaskField.TEXT3, \"Status\");\n map.put(TaskField.NUMBER1, \"Primary Resource Unique ID\");\n\n return map;\n }"
] |
Cancels all requests still waiting for a response.
@return this {@link Searcher} for chaining. | [
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher cancelPendingRequests() {\n if (pendingRequests.size() != 0) {\n for (int i = 0; i < pendingRequests.size(); i++) {\n int reqId = pendingRequests.keyAt(i);\n Request r = pendingRequests.valueAt(i);\n if (!r.isFinished() && !r.isCancelled()) {\n cancelRequest(r, reqId);\n }\n }\n }\n return this;\n }"
] | [
"public void setValue(Vector3f pos) {\n mX = pos.x;\n mY = pos.y;\n mZ = pos.z;\n }",
"public <T> T find(Class<T> classType, String id) {\n return db.find(classType, id);\n }",
"public static Iterable<BoxGroup.Info> getAllGroupsByName(final BoxAPIConnection api, String name) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (name == null || name.trim().isEmpty()) {\n throw new BoxAPIException(\"Searching groups by name requires a non NULL or non empty name\");\n } else {\n builder.appendParam(\"name\", name);\n }\n\n return new Iterable<BoxGroup.Info>() {\n public Iterator<BoxGroup.Info> iterator() {\n URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n return new BoxGroupIterator(api, url);\n }\n };\n }",
"public static void generateJRXML(DynamicReport dr, LayoutManager layoutManager, Map _parameters, String xmlEncoding, OutputStream outputStream) throws JRException {\n JasperReport jr = generateJasperReport(dr, layoutManager, _parameters);\n if (xmlEncoding == null)\n xmlEncoding = DEFAULT_XML_ENCODING;\n JRXmlWriter.writeReport(jr, outputStream, xmlEncoding);\n }",
"public void fireCalendarReadEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarRead(calendar);\n }\n }\n }",
"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 MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)\n {\n Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);\n if (!mavenProjectModels.iterator().hasNext())\n {\n return null;\n }\n for (MavenProjectModel mavenProjectModel : mavenProjectModels)\n {\n if (mavenProjectModel.getRootFileModel() == null)\n {\n // this is a stub... we can fill it in with details\n return mavenProjectModel;\n }\n }\n return null;\n }",
"@SuppressWarnings({ \"unchecked\" })\n public static <T> T[] readArrayAttributeElement(final XMLExtendedStreamReader reader, final String attributeName,\n final Class<T> type) throws XMLStreamException {\n final List<T> list = readListAttributeElement(reader, attributeName, type);\n return list.toArray((T[]) Array.newInstance(type, list.size()));\n }",
"public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) {\n final String type = jedis.type(key);\n return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type));\n }"
] |
Obtain collection of headers to remove
@return
@throws Exception | [
"private ArrayList<String> getRemoveHeaders() throws Exception {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n\n for (EndpointOverride selectedPath : requestInformation.get().selectedResponsePaths) {\n // check to see if there is custom override data or if we have headers to remove\n List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();\n for (EnabledEndpoint endpoint : points) {\n // skip if repeat count is 0\n if (endpoint.getRepeatNumber() == 0) {\n continue;\n }\n\n if (endpoint.getOverrideId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n // add to remove headers array\n headersToRemove.add(endpoint.getArguments()[0].toString());\n endpoint.decrementRepeatNumber();\n }\n }\n }\n\n return headersToRemove;\n }"
] | [
"public Date getFinishDate()\n {\n Date result = (Date) getCachedValue(ProjectField.FINISH_DATE);\n if (result == null)\n {\n result = getParentFile().getFinishDate();\n }\n return (result);\n }",
"public static void writeFlowId(Message message, String flowId) {\n Map<String, List<String>> headers = getOrCreateProtocolHeader(message);\n headers.put(FLOWID_HTTP_HEADER_NAME, Collections.singletonList(flowId));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"HTTP header '\" + FLOWID_HTTP_HEADER_NAME + \"' set to: \" + flowId);\n }\n }",
"public void check(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureColumn(fieldDef, checkLevel);\r\n ensureJdbcType(fieldDef, checkLevel);\r\n ensureConversion(fieldDef, checkLevel);\r\n ensureLength(fieldDef, checkLevel);\r\n ensurePrecisionAndScale(fieldDef, checkLevel);\r\n checkLocking(fieldDef, checkLevel);\r\n checkSequenceName(fieldDef, checkLevel);\r\n checkId(fieldDef, checkLevel);\r\n if (fieldDef.isAnonymous())\r\n {\r\n checkAnonymous(fieldDef, checkLevel);\r\n }\r\n else\r\n {\r\n checkReadonlyAccessForNativePKs(fieldDef, checkLevel);\r\n }\r\n }",
"public static int getDayAsReadableInt(long time) {\n Calendar cal = calendarThreadLocal.get();\n cal.setTimeInMillis(time);\n return getDayAsReadableInt(cal);\n }",
"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 processClientId(HttpServletRequest httpServletRequest, History history) {\n // get the client id from the request header if applicable.. otherwise set to default\n // also set the client uuid in the history object\n if (httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME) != null &&\n !httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME).equals(\"\")) {\n history.setClientUUID(httpServletRequest.getHeader(Constants.PROFILE_CLIENT_HEADER_NAME));\n } else {\n history.setClientUUID(Constants.PROFILE_CLIENT_DEFAULT_ID);\n }\n logger.info(\"Client UUID is: {}\", history.getClientUUID());\n }",
"public ParallelTaskBuilder prepareSsh() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.SSH);\n return cb;\n }",
"public static ProctorLoadResult verify(\n @Nonnull final TestMatrixArtifact testMatrix,\n final String matrixSource,\n @Nonnull final Map<String, TestSpecification> requiredTests,\n @Nonnull final FunctionMapper functionMapper,\n final ProvidedContext providedContext,\n @Nonnull final Set<String> dynamicTests\n ) {\n final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();\n\n final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());\n for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {\n final Map<Integer, String> bucketValueToName = Maps.newHashMap();\n for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {\n bucketValueToName.put(bucket.getValue(), bucket.getKey());\n }\n allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);\n }\n\n final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();\n final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());\n resultBuilder.recordAllMissing(missingTests);\n for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {\n final String testName = entry.getKey();\n\n final Map<Integer, String> knownBuckets;\n final TestSpecification specification;\n final boolean isRequired;\n if (allTestsKnownBuckets.containsKey(testName)) {\n // required in specification\n isRequired = true;\n knownBuckets = allTestsKnownBuckets.remove(testName);\n specification = requiredTests.get(testName);\n } else if (dynamicTests.contains(testName)) {\n // resolved by dynamic filter\n isRequired = false;\n knownBuckets = Collections.emptyMap();\n specification = new TestSpecification();\n } else {\n // we don't care about this test\n continue;\n }\n\n final ConsumableTestDefinition testDefinition = entry.getValue();\n\n try {\n verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);\n\n } catch (IncompatibleTestMatrixException e) {\n if (isRequired) {\n LOGGER.error(String.format(\"Unable to load test matrix for a required test %s\", testName), e);\n resultBuilder.recordError(testName, e);\n } else {\n LOGGER.info(String.format(\"Unable to load test matrix for a dynamic test %s\", testName), e);\n resultBuilder.recordIncompatibleDynamicTest(testName, e);\n }\n }\n }\n\n // TODO mjs - is this check additive?\n resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());\n\n resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());\n\n final ProctorLoadResult loadResult = resultBuilder.build();\n\n return loadResult;\n }",
"@Override\n public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }"
] |
Add the option specifying if the categories should be displayed collapsed
when the dialog opens.
@see org.opencms.ui.actions.I_CmsADEAction#getParams() | [
"public Map<String, String> getParams() {\n\n Map<String, String> params = new HashMap<>(1);\n params.put(PARAM_COLLAPSED, Boolean.TRUE.toString());\n return params;\n }"
] | [
"private void processSchedulingProjectProperties() throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"projprop where proj_id=? and prop_name='scheduling'\", m_projectID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n Record record = Record.getRecord(row.getString(\"prop_value\"));\n if (record != null)\n {\n String[] keyValues = record.getValue().split(\"\\\\|\");\n for (int i = 0; i < keyValues.length - 1; ++i)\n {\n if (\"sched_calendar_on_relationship_lag\".equals(keyValues[i]))\n {\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", keyValues[i + 1]);\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n break;\n }\n }\n }\n }\n }",
"public static void openLogFile(String logPath) {\n\t\tif (logPath == null) {\n\t\t\tprintStream = System.out;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tprintStream = new PrintStream(new File(logPath));\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Log file \" + logPath + \" was not found\", e);\n\t\t\t}\n\t\t}\n\t}",
"protected boolean hasKey() {\n boolean result = false;\n String requestURI = this.request.getUri();\n parseKeys(requestURI);\n\n if(this.parsedKeys != null) {\n result = true;\n } else {\n logger.error(\"Error when validating request. No key specified.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Error: No key specified !\");\n }\n return result;\n }",
"public static Timer getNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tTimer key = new Timer(timerName, todoFlags, threadId);\n\t\tregisteredTimers.putIfAbsent(key, key);\n\t\treturn registeredTimers.get(key);\n\t}",
"public static int cudnnCreatePersistentRNNPlan(\n cudnnRNNDescriptor rnnDesc, \n int minibatch, \n int dataType, \n cudnnPersistentRNNPlan plan)\n {\n return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan));\n }",
"public Object newInstance(String className) {\n try {\n return classLoader.loadClass(className).newInstance();\n } catch (Exception e) {\n throw new ScalaInstanceNotFound(className);\n }\n }",
"public static void resize(GVRMesh mesh, float size) {\n float dim[] = getBoundingSize(mesh);\n float maxsize = 0.0f;\n\n if (dim[0] > maxsize) maxsize = dim[0];\n if (dim[1] > maxsize) maxsize = dim[1];\n if (dim[2] > maxsize) maxsize = dim[2];\n\n scale(mesh, size / maxsize);\n }",
"public static String wordShape(String inStr, int wordShaper, Collection<String> knownLCWords) {\r\n // this first bit is for backwards compatibility with how things were first\r\n // implemented, where the word shaper name encodes whether to useLC.\r\n // If the shaper is in the old compatibility list, then a specified\r\n // list of knownLCwords is ignored\r\n if (knownLCWords != null && dontUseLC(wordShaper)) {\r\n knownLCWords = null;\r\n }\r\n switch (wordShaper) {\r\n case NOWORDSHAPE:\r\n return inStr;\r\n case WORDSHAPEDAN1:\r\n return wordShapeDan1(inStr);\r\n case WORDSHAPECHRIS1:\r\n return wordShapeChris1(inStr);\r\n case WORDSHAPEDAN2:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2USELC:\r\n return wordShapeDan2(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIO:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEDAN2BIOUSELC:\r\n return wordShapeDan2Bio(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPEJENNY1USELC:\r\n return wordShapeJenny1(inStr, knownLCWords);\r\n case WORDSHAPECHRIS2:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS2USELC:\r\n return wordShapeChris2(inStr, false, knownLCWords);\r\n case WORDSHAPECHRIS3:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS3USELC:\r\n return wordShapeChris2(inStr, true, knownLCWords);\r\n case WORDSHAPECHRIS4:\r\n return wordShapeChris4(inStr, false, knownLCWords);\r\n case WORDSHAPEDIGITS:\r\n return wordShapeDigits(inStr);\r\n default:\r\n throw new IllegalStateException(\"Bad WordShapeClassifier\");\r\n }\r\n }",
"private Iterable<BoxRetentionPolicyAssignment.Info> getAssignments(String type, int limit, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (type != null) {\r\n queryString.appendParam(\"type\", type);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString(), getID());\r\n return new BoxResourceIterable<BoxRetentionPolicyAssignment.Info>(getAPI(), url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicyAssignment assignment\r\n = new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get(\"id\").asString());\r\n return assignment.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }"
] |
Parse the JSON string and return the object. The string is expected to be the JSON print data from the
client.
@param spec the JSON formatted string.
@return The encapsulated JSON object | [
"public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }"
] | [
"public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}",
"public static DMatrixRMaj[] splitIntoVectors(DMatrix1Row A , boolean column )\n {\n int w = column ? A.numCols : A.numRows;\n\n int M = column ? A.numRows : 1;\n int N = column ? 1 : A.numCols;\n\n int o = Math.max(M,N);\n\n DMatrixRMaj[] ret = new DMatrixRMaj[w];\n\n for( int i = 0; i < w; i++ ) {\n DMatrixRMaj a = new DMatrixRMaj(M,N);\n\n if( column )\n subvector(A,0,i,o,false,0,a);\n else\n subvector(A,i,0,o,true,0,a);\n\n ret[i] = a;\n }\n\n return ret;\n }",
"public static appfwglobal_auditsyslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditsyslogpolicy_binding obj = new appfwglobal_auditsyslogpolicy_binding();\n\t\tappfwglobal_auditsyslogpolicy_binding response[] = (appfwglobal_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Duration getWork(Date date, TimeUnit format)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n long time = getTotalTime(ranges);\n return convertFormat(time, format);\n }",
"private IndexedContainer createContainerForBundleWithoutDescriptor() throws IOException, CmsException {\n\n IndexedContainer container = new IndexedContainer();\n\n // create properties\n container.addContainerProperty(TableProperty.KEY, String.class, \"\");\n container.addContainerProperty(TableProperty.TRANSLATION, String.class, \"\");\n\n // add entries\n SortedProperties localization = getLocalization(m_locale);\n Set<Object> keySet = m_keyset.getKeySet();\n for (Object key : keySet) {\n\n Object itemId = container.addItem();\n Item item = container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object translation = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == translation ? \"\" : translation);\n }\n\n return container;\n }",
"public void setReadTimeout(int readTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.readTimeout(readTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}",
"private String getActivityID(Task task)\n {\n String result = null;\n if (m_activityIDField != null)\n {\n Object value = task.getCachedValue(m_activityIDField);\n if (value != null)\n {\n result = value.toString();\n }\n }\n return result;\n }",
"public synchronized void start() throws SocketException {\n if (!isRunning()) {\n DeviceFinder.getInstance().addLifecycleListener(lifecycleListener);\n DeviceFinder.getInstance().addDeviceAnnouncementListener(announcementListener);\n DeviceFinder.getInstance().start();\n for (DeviceAnnouncement device: DeviceFinder.getInstance().getCurrentDevices()) {\n requestPlayerDBServerPort(device);\n }\n\n new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (isRunning()) {\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n logger.warn(\"Interrupted sleeping to close idle dbserver clients\");\n }\n closeIdleClients();\n }\n logger.info(\"Idle dbserver client closer shutting down.\");\n }\n }, \"Idle dbserver client closer\").start();\n\n running.set(true);\n deliverLifecycleAnnouncement(logger, true);\n }\n }",
"public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }"
] |
Extracts a flat set of interception bindings from a given set of interceptor bindings.
@param addTopLevelInterceptorBindings add top level interceptor bindings to the result set.
@param addInheritedInterceptorBindings add inherited level interceptor bindings to the result set.
@return | [
"public static Set<Annotation> flattenInterceptorBindings(EnhancedAnnotatedType<?> clazz, BeanManagerImpl beanManager, Collection<Annotation> annotations, boolean addTopLevelInterceptorBindings,\n boolean addInheritedInterceptorBindings) {\n Set<Annotation> flattenInterceptorBindings = new InterceptorBindingSet(beanManager);\n MetaAnnotationStore metaAnnotationStore = beanManager.getServices().get(MetaAnnotationStore.class);\n\n if (addTopLevelInterceptorBindings) {\n addInterceptorBindings(clazz, annotations, flattenInterceptorBindings, metaAnnotationStore);\n }\n if (addInheritedInterceptorBindings) {\n for (Annotation annotation : annotations) {\n addInheritedInterceptorBindings(clazz, annotation.annotationType(), metaAnnotationStore, flattenInterceptorBindings);\n }\n }\n return flattenInterceptorBindings;\n }"
] | [
"public static URL getKubernetesConfigurationUrl(Map<String, String> map) throws MalformedURLException {\n if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"))) {\n return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, \"\"));\n } else if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\"))) {\n String resourceName = Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, \"\");\n return findConfigResource(resourceName);\n } else if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {\n return new URL(map.get(ENVIRONMENT_CONFIG_URL));\n } else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {\n String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);\n return findConfigResource(resourceName);\n } else {\n // Let the resource locator find the resource\n return null;\n }\n }",
"public CollectionRequest<ProjectMembership> findByProject(String project) {\n \n String path = String.format(\"/projects/%s/project_memberships\", project);\n return new CollectionRequest<ProjectMembership>(this, ProjectMembership.class, path, \"GET\");\n }",
"@Override\n\tpublic boolean isKeyColumn(String columnName) {\n\t\tfor ( String keyColumName : getColumnNames() ) {\n\t\t\tif ( keyColumName.equals( columnName ) ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}",
"public void exceptionShift() {\n numExceptional++;\n double mag = 0.05 * numExceptional;\n if (mag > 1.0) mag = 1.0;\n\n double angle = 2.0 * UtilEjml.PI * (rand.nextDouble() - 0.5) * mag;\n performImplicitSingleStep(0, angle, true);\n\n // allow more convergence time\n nextExceptional = steps + exceptionalThresh; // (numExceptional+1)*\n }",
"protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill)\n {\n float lineWidth = transformWidth(getGraphicsState().getLineWidth());\n \tfloat wcor = stroke ? lineWidth : 0.0f;\n float strokeOffset = wcor == 0 ? 0 : wcor / 2;\n width = width - wcor < 0 ? 1 : width - wcor;\n height = height - wcor < 0 ? 1 : height - wcor;\n\n StringBuilder pstyle = new StringBuilder(50);\n \tpstyle.append(\"left:\").append(style.formatLength(x - strokeOffset)).append(';');\n pstyle.append(\"top:\").append(style.formatLength(y - strokeOffset)).append(';');\n pstyle.append(\"width:\").append(style.formatLength(width)).append(';');\n pstyle.append(\"height:\").append(style.formatLength(height)).append(';');\n \t \n \tif (stroke)\n \t{\n String color = colorString(getGraphicsState().getStrokingColor());\n \tpstyle.append(\"border:\").append(style.formatLength(lineWidth)).append(\" solid \").append(color).append(';');\n \t}\n \t\n \tif (fill)\n \t{\n String fcolor = colorString(getGraphicsState().getNonStrokingColor());\n \t pstyle.append(\"background-color:\").append(fcolor).append(';');\n \t}\n \t\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }",
"private Integer getNullOnValue(Integer value, int nullValue)\n {\n return (NumberHelper.getInt(value) == nullValue ? null : value);\n }",
"public static cmppolicylabel_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tcmppolicylabel_stats[] response = (cmppolicylabel_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal);\n }",
"public static DMatrixRMaj triangularUpper(int dimen , int hessenberg , double min , double max , Random rand )\n {\n if( hessenberg < 0 )\n throw new RuntimeException(\"hessenberg must be more than or equal to 0\");\n\n double range = max-min;\n\n DMatrixRMaj A = new DMatrixRMaj(dimen,dimen);\n\n for( int i = 0; i < dimen; i++ ) {\n int start = i <= hessenberg ? 0 : i-hessenberg;\n\n for( int j = start; j < dimen; j++ ) {\n A.set(i,j, rand.nextDouble()*range+min);\n }\n\n }\n\n return A;\n }"
] |
Resolves the POM for the specified parent.
@param parent the parent coordinates to resolve, must not be {@code null}
@return The source of the requested POM, never {@code null}
@since Apache-Maven-3.2.2 (MNG-5639) | [
"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 static Collection<String> getFormatProviderNames() {\n Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(\n () -> new MonetaryException(\n \"No MonetaryFormatsSingletonSpi loaded, query functionality is not available.\"))\n .getProviderNames();\n if (Objects.isNull(providers)) {\n Logger.getLogger(MonetaryFormats.class.getName()).warning(\n \"No supported rate/conversion providers returned by SPI: \" +\n getMonetaryFormatsSpi().getClass().getName());\n return Collections.emptySet();\n }\n return providers;\n }",
"@SuppressWarnings({\"unchecked\", \"unused\"})\n public static <T> T[] object2Array(final Class<T> clazz, final Object obj) {\n return (T[]) obj;\n }",
"private void retrieveNextPage() {\n if (this.pageSize < Long.MAX_VALUE || this.itemLimit < Long.MAX_VALUE) {\n this.request.query(\"limit\", Math.min(this.pageSize, this.itemLimit - this.count));\n } else {\n this.request.query(\"limit\", null);\n }\n ResultBodyCollection<T> page = null;\n try {\n page = this.getNext();\n } catch (IOException exception) {\n // See comments in hasNext().\n this.ioException = exception;\n }\n if (page != null) {\n this.continuation = this.getContinuation(page);\n if (page.data != null && !page.data.isEmpty()) {\n this.count += page.data.size();\n this.nextData = page.data;\n } else {\n this.nextData = null;\n }\n } else {\n this.continuation = null;\n this.nextData = null;\n }\n }",
"public boolean setUpCameraForVrMode(final int fpsMode) {\n\n cameraSetUpStatus = false;\n this.fpsMode = fpsMode;\n\n if (!isCameraOpen) {\n Log.e(TAG, \"Camera is not open\");\n return false;\n }\n if (fpsMode < 0 || fpsMode > 2) {\n Log.e(TAG,\n \"Invalid fpsMode: %d. It can only take values 0, 1, or 2.\", fpsMode);\n } else {\n Parameters params = camera.getParameters();\n\n // check if the device supports vr mode preview\n if (\"true\".equalsIgnoreCase(params.get(\"vrmode-supported\"))) {\n\n Log.v(TAG, \"VR Mode supported!\");\n\n // set vr mode\n params.set(\"vrmode\", 1);\n\n // true if the apps intend to record videos using\n // MediaRecorder\n params.setRecordingHint(true);\n\n // set preview size\n // params.setPreviewSize(640, 480);\n\n // set fast-fps-mode: 0 for 30fps, 1 for 60 fps,\n // 2 for 120 fps\n params.set(\"fast-fps-mode\", fpsMode);\n\n switch (fpsMode) {\n case 0: // 30 fps\n params.setPreviewFpsRange(30000, 30000);\n break;\n case 1: // 60 fps\n params.setPreviewFpsRange(60000, 60000);\n break;\n case 2: // 120 fps\n params.setPreviewFpsRange(120000, 120000);\n break;\n default:\n }\n\n // for auto focus\n params.set(\"focus-mode\", \"continuous-video\");\n\n params.setVideoStabilization(false);\n if (\"true\".equalsIgnoreCase(params.get(\"ois-supported\"))) {\n params.set(\"ois\", \"center\");\n }\n\n camera.setParameters(params);\n cameraSetUpStatus = true;\n }\n }\n\n return cameraSetUpStatus;\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}",
"private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }",
"public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }",
"private void addGreeting(String guestbookName, String user, String message)\n throws DatastoreException {\n Entity.Builder greeting = Entity.newBuilder();\n greeting.setKey(makeKey(GUESTBOOK_KIND, guestbookName, GREETING_KIND));\n greeting.getMutableProperties().put(USER_PROPERTY, makeValue(user).build());\n greeting.getMutableProperties().put(MESSAGE_PROPERTY, makeValue(message).build());\n greeting.getMutableProperties().put(DATE_PROPERTY, makeValue(new Date()).build());\n Key greetingKey = insert(greeting.build());\n System.out.println(\"greeting key is: \" + greetingKey);\n }",
"private ProjectCalendar getResourceCalendar(Integer calendarID)\n {\n ProjectCalendar result = null;\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_calMap.get(calendarID);\n if (calendar != null)\n {\n //\n // If the resource is linked to a base calendar, derive\n // a default calendar from the base calendar.\n //\n if (!calendar.isDerived())\n {\n ProjectCalendar resourceCalendar = m_project.addCalendar();\n resourceCalendar.setParent(calendar);\n resourceCalendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n result = resourceCalendar;\n }\n else\n {\n //\n // Primavera seems to allow a calendar to be shared between resources\n // whereas in the MS Project model there is a one-to-one\n // relationship. If we find a shared calendar, take a copy of it\n //\n if (calendar.getResource() == null)\n {\n result = calendar;\n }\n else\n {\n ProjectCalendar copy = m_project.addCalendar();\n copy.copy(calendar);\n result = copy;\n }\n }\n }\n }\n\n return result;\n }"
] |
Add or remove the active cursors from the provided scene.
@param scene The GVRScene.
@param add <code>true</code> for add, <code>false</code> to remove | [
"private void updateCursorsInScene(GVRScene scene, boolean add) {\n synchronized (mCursors) {\n for (Cursor cursor : mCursors) {\n if (cursor.isActive()) {\n if (add) {\n addCursorToScene(cursor);\n } else {\n removeCursorFromScene(cursor);\n }\n }\n }\n }\n }"
] | [
"public static appfwglobal_auditsyslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditsyslogpolicy_binding obj = new appfwglobal_auditsyslogpolicy_binding();\n\t\tappfwglobal_auditsyslogpolicy_binding response[] = (appfwglobal_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 Method getSAMMethod(Class<?> c) {\n // SAM = single public abstract method\n // if the class is not abstract there is no abstract method\n if (!Modifier.isAbstract(c.getModifiers())) return null;\n if (c.isInterface()) {\n Method[] methods = c.getMethods();\n // res stores the first found abstract method\n Method res = null;\n for (Method mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (mi.getAnnotation(Traits.Implemented.class)!=null) continue;\n try {\n Object.class.getMethod(mi.getName(), mi.getParameterTypes());\n continue;\n } catch (NoSuchMethodException e) {/*ignore*/}\n\n // we have two methods, so no SAM\n if (res!=null) return null;\n res = mi;\n }\n return res;\n\n } else {\n\n LinkedList<Method> methods = new LinkedList();\n getAbstractMethods(c, methods);\n if (methods.isEmpty()) return null;\n ListIterator<Method> it = methods.listIterator();\n while (it.hasNext()) {\n Method m = it.next();\n if (hasUsableImplementation(c, m)) it.remove();\n }\n return getSingleNonDuplicateMethod(methods);\n }\n }",
"@Api\n\tpublic void setUrl(String url) throws LayerException {\n\t\ttry {\n\t\t\tthis.url = url;\n\t\t\tMap<String, Object> params = new HashMap<String, Object>();\n\t\t\tparams.put(\"url\", url);\n\t\t\tDataStore store = DataStoreFactory.create(params);\n\t\t\tsetDataStore(store);\n\t\t} catch (IOException ioe) {\n\t\t\tthrow new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url);\n\t\t}\n\t}",
"public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public ItemRequest<Project> addMembers(String project) {\n \n String path = String.format(\"/projects/%s/addMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\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 }",
"protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {\n try {\n // Add special methods for interceptors\n for (Method method : LifecycleMixin.class.getMethods()) {\n BeanLogger.LOG.addingMethodToProxy(method);\n MethodInformation methodInfo = new RuntimeMethodInformation(method);\n createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor);\n }\n Method getInstanceMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetInstance\");\n Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod(\"weld_getTargetClass\");\n generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod));\n generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod));\n\n Method setMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_setHandler\", MethodHandler.class);\n generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));\n\n Method getMethodHandlerMethod = ProxyObject.class.getMethod(\"weld_getHandler\");\n generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }",
"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 }"
] |
Creates an Odata filter string that can be used for filtering list results by tags.
@param tagName the name of the tag. If not provided, all resources will be returned.
@param tagValue the value of the tag. If not provided, only tag name will be filtered.
@return the Odata filter to pass into list methods | [
"public static String createOdataFilterForTags(String tagName, String tagValue) {\n if (tagName == null) {\n return null;\n } else if (tagValue == null) {\n return String.format(\"tagname eq '%s'\", tagName);\n } else {\n return String.format(\"tagname eq '%s' and tagvalue eq '%s'\", tagName, tagValue);\n }\n }"
] | [
"public ItemRequest<Task> addSubtask(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"@NonNull\n @Override\n public Loader<SortedList<File>> getLoader() {\n return new AsyncTaskLoader<SortedList<File>>(getActivity()) {\n\n FileObserver fileObserver;\n\n @Override\n public SortedList<File> loadInBackground() {\n File[] listFiles = mCurrentPath.listFiles();\n final int initCap = listFiles == null ? 0 : listFiles.length;\n\n SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {\n @Override\n public int compare(File lhs, File rhs) {\n return compareFiles(lhs, rhs);\n }\n\n @Override\n public boolean areContentsTheSame(File file, File file2) {\n return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());\n }\n\n @Override\n public boolean areItemsTheSame(File file, File file2) {\n return areContentsTheSame(file, file2);\n }\n }, initCap);\n\n\n files.beginBatchedUpdates();\n if (listFiles != null) {\n for (java.io.File f : listFiles) {\n if (isItemVisible(f)) {\n files.add(f);\n }\n }\n }\n files.endBatchedUpdates();\n\n return files;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n // Start watching for changes\n fileObserver = new FileObserver(mCurrentPath.getPath(),\n FileObserver.CREATE |\n FileObserver.DELETE\n | FileObserver.MOVED_FROM | FileObserver.MOVED_TO\n ) {\n\n @Override\n public void onEvent(int event, String path) {\n // Reload\n onContentChanged();\n }\n };\n fileObserver.startWatching();\n\n forceLoad();\n }\n\n /**\n * Handles a request to completely reset the Loader.\n */\n @Override\n protected void onReset() {\n super.onReset();\n\n // Stop watching\n if (fileObserver != null) {\n fileObserver.stopWatching();\n fileObserver = null;\n }\n }\n };\n }",
"public void updateSequenceElement(int[] sequence, int pos, int oldVal) {\r\n if(models != null){\r\n for(int i = 0; i < models.length; i++)\r\n models[i].updateSequenceElement(sequence, pos, oldVal);\r\n return; \r\n }\r\n model1.updateSequenceElement(sequence, pos, 0);\r\n model2.updateSequenceElement(sequence, pos, 0);\r\n }",
"private LinkedList<TimephasedWork> readTimephasedAssignment(ProjectCalendar calendar, Project.Assignments.Assignment assignment, int type)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n for (TimephasedDataType item : assignment.getTimephasedData())\n {\n if (NumberHelper.getInt(item.getType()) != type)\n {\n continue;\n }\n\n Date startDate = item.getStart();\n Date finishDate = item.getFinish();\n\n // Exclude ranges which don't have a start and end date.\n // These seem to be generated by Synchro and have a zero duration.\n if (startDate == null && finishDate == null)\n {\n continue;\n }\n\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.MINUTES, item.getValue());\n if (work == null)\n {\n work = Duration.getInstance(0, TimeUnit.MINUTES);\n }\n else\n {\n work = Duration.getInstance(NumberHelper.round(work.getDuration(), 2), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(startDate);\n tra.setFinish(finishDate);\n tra.setTotalAmount(work);\n\n result.add(tra);\n }\n\n return result;\n }",
"public ProjectCalendar addResourceCalendar() throws MPXJException\n {\n if (getResourceCalendar() != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n ProjectCalendar calendar = new ProjectCalendar(getParentFile());\n setResourceCalendar(calendar);\n return calendar;\n }",
"@Override\n public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n if (this.options.verbose) {\n this.out.println(\n Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));\n//\t\t\tnew Exception(\"TRACE BINARY\").printStackTrace(System.out);\n//\t\t System.out.println();\n }\n LookupEnvironment env = packageBinding.environment;\n env.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);\n }",
"public static snmpmanager[] get(nitro_service service) throws Exception{\n\t\tsnmpmanager obj = new snmpmanager();\n\t\tsnmpmanager[] response = (snmpmanager[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String resourceTypeFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).resourceType() : null;\n }",
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }"
] |
Joins the given iterable objects using the given separator into a single string.
@return the joined string or an empty string if iterable is null | [
"public static String join(Iterable<?> iterable, String separator) {\n if (iterable != null) {\n StringBuilder buf = new StringBuilder();\n Iterator<?> it = iterable.iterator();\n char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;\n while (it.hasNext()) {\n buf.append(it.next());\n if (it.hasNext()) {\n if (singleChar != 0) {\n // More efficient\n buf.append(singleChar);\n } else {\n buf.append(separator);\n }\n }\n }\n return buf.toString();\n } else {\n return \"\";\n }\n }"
] | [
"public void link(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds, Object referencedObject, boolean insert)\n {\n // MBAIRD: we have 'disassociated' this object from the referenced object,\n // the object represented by the reference descriptor is now null, so set\n // the fk in the target object to null.\n // arminw: if an insert was done and ref object was null, we should allow\n // to pass FK fields of main object (maybe only the FK fields are set)\n if (referencedObject == null)\n {\n /*\n arminw:\n if update we set FK fields to 'null', because reference was disassociated\n We do nothing on insert, maybe only the FK fields of main object (without\n materialization of the reference object) are set by the user\n */\n if(!insert)\n {\n unlinkFK(targetObject, cld, rds);\n }\n }\n else\n {\n setFKField(targetObject, cld, rds, referencedObject);\n }\n }",
"public IPv6AddressSegment join(IPv6AddressCreator creator, IPv4AddressSegment low) throws IncompatibleAddressException {\r\n\t\tint shift = IPv4Address.BITS_PER_SEGMENT;\r\n\t\tInteger prefix = getJoinedSegmentPrefixLength(shift, getSegmentPrefixLength(), low.getSegmentPrefixLength());\r\n\t\tif(isMultiple()) {\r\n\t\t\t//if the high segment has a range, the low segment must match the full range, \r\n\t\t\t//otherwise it is not possible to create an equivalent range when joining\r\n\t\t\tif(!low.isFullRange()) {\r\n\t\t\t\tthrow new IncompatibleAddressException(this, low, \"ipaddress.error.invalidMixedRange\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn creator.createSegment(\r\n\t\t\t\t(getSegmentValue() << shift) | low.getSegmentValue(), \r\n\t\t\t\t(getUpperSegmentValue() << shift) | low.getUpperSegmentValue(),\r\n\t\t\t\tprefix);\r\n\t}",
"private void buildJoinTree(Criteria crit)\r\n {\r\n Enumeration e = crit.getElements();\r\n\r\n while (e.hasMoreElements())\r\n {\r\n Object o = e.nextElement();\r\n if (o instanceof Criteria)\r\n {\r\n buildJoinTree((Criteria) o);\r\n }\r\n else\r\n {\r\n SelectionCriteria c = (SelectionCriteria) o;\r\n \r\n // BRJ skip SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n continue;\r\n }\r\n \r\n // BRJ: Outer join for OR\r\n boolean useOuterJoin = (crit.getType() == Criteria.OR);\r\n\r\n // BRJ: do not build join tree for subQuery attribute \r\n if (c.getAttribute() != null && c.getAttribute() instanceof String)\r\n {\r\n\t\t\t\t\t//buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getAlias(), c.getPathClasses());\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n if (c instanceof FieldCriteria)\r\n {\r\n FieldCriteria cc = (FieldCriteria) c;\r\n\t\t\t\t\tbuildJoinTreeForColumn((String) cc.getValue(), useOuterJoin, c.getUserAlias(), c.getPathClasses());\r\n }\r\n }\r\n }\r\n }",
"public static nsacl6 get(nitro_service service, String acl6name) throws Exception{\n\t\tnsacl6 obj = new nsacl6();\n\t\tobj.set_acl6name(acl6name);\n\t\tnsacl6 response = (nsacl6) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static <T extends Comparable<? super T>> List<T> sort(Iterable<T> iterable) {\n\t\tList<T> asList = Lists.newArrayList(iterable);\n\t\tif (iterable instanceof SortedSet<?>) {\n\t\t\tif (((SortedSet<T>) iterable).comparator() == null) {\n\t\t\t\treturn asList;\n\t\t\t}\n\t\t}\n\t\treturn ListExtensions.sortInplace(asList);\n\t}",
"private String getContentFromPath(String sourcePath,\n HostsSourceType sourceType) throws IOException {\n\n String res = \"\";\n\n if (sourceType == HostsSourceType.LOCAL_FILE) {\n res = PcFileNetworkIoUtils.readFileContentToString(sourcePath);\n } else if (sourceType == HostsSourceType.URL) {\n res = PcFileNetworkIoUtils.readStringFromUrlGeneric(sourcePath);\n }\n return res;\n\n }",
"public Object remove(String name) {\n\t\tBean bean = beans.get(name);\n\t\tif (null != bean) {\n\t\t\tbeans.remove(name);\n\t\t\tbean.destructionCallback.run();\n\t\t\treturn bean.object;\n\t\t}\n\t\treturn null;\n\t}",
"public static vpath[] get(nitro_service service) throws Exception{\n\t\tvpath obj = new vpath();\n\t\tvpath[] response = (vpath[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private int slopSize(Versioned<Slop> slopVersioned) {\n int nBytes = 0;\n Slop slop = slopVersioned.getValue();\n nBytes += slop.getKey().length();\n nBytes += ((VectorClock) slopVersioned.getVersion()).sizeInBytes();\n switch(slop.getOperation()) {\n case PUT: {\n nBytes += slop.getValue().length;\n break;\n }\n case DELETE: {\n break;\n }\n default:\n logger.error(\"Unknown slop operation: \" + slop.getOperation());\n }\n return nBytes;\n }"
] |
poll the response queue for response
@param timeout timeout amount
@param timeUnit timeUnit of timeout
@return same result of BlockQueue.poll(long, TimeUnit)
@throws InterruptedException | [
"public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }"
] | [
"public RelatedTagsList getRelated(String tag) throws FlickrException {\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_RELATED);\n\n parameters.put(\"tag\", tag);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element tagsElement = response.getPayload();\n\n RelatedTagsList tags = new RelatedTagsList();\n tags.setSource(tagsElement.getAttribute(\"source\"));\n NodeList tagElements = tagsElement.getElementsByTagName(\"tag\");\n for (int i = 0; i < tagElements.getLength(); i++) {\n Element tagElement = (Element) tagElements.item(i);\n Tag t = new Tag();\n t.setValue(XMLUtilities.getValue(tagElement));\n tags.add(t);\n }\n return tags;\n }",
"public void init(LblTree t1, LblTree t2) {\n\t\tLabelDictionary ld = new LabelDictionary();\n\t\tit1 = new InfoTree(t1, ld);\n\t\tit2 = new InfoTree(t2, ld);\n\t\tsize1 = it1.getSize();\n\t\tsize2 = it2.getSize();\n\t\tIJ = new int[Math.max(size1, size2)][Math.max(size1, size2)];\n\t\tdelta = new double[size1][size2];\n\t\tdeltaBit = new byte[size1][size2];\n\t\tcostV = new long[3][size1][size2];\n\t\tcostW = new long[3][size2];\n\n\t\t// Calculate delta between every leaf in G (empty tree) and all the nodes in F.\n\t\t// Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of\n\t\t// F.\n\t\tint[] labels1 = it1.getInfoArray(POST2_LABEL);\n\t\tint[] labels2 = it2.getInfoArray(POST2_LABEL);\n\t\tint[] sizes1 = it1.getInfoArray(POST2_SIZE);\n\t\tint[] sizes2 = it2.getInfoArray(POST2_SIZE);\n\t\tfor (int x = 0; x < sizes1.length; x++) { // for all nodes of initially left tree\n\t\t\tfor (int y = 0; y < sizes2.length; y++) { // for all nodes of initially right tree\n\n\t\t\t\t// This is an attempt for distances of single-node subtree and anything alse\n\t\t\t\t// The differences between pairs of labels are stored\n\t\t\t\tif (labels1[x] == labels2[y]) {\n\t\t\t\t\tdeltaBit[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tdeltaBit[x][y] =\n\t\t\t\t\t\t\t1; // if this set, the labels differ, cost of relabeling is set\n\t\t\t\t\t// to costMatch\n\t\t\t\t}\n\n\t\t\t\tif (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs\n\t\t\t\t\tdelta[x][y] = 0;\n\t\t\t\t} else {\n\t\t\t\t\tif (sizes1[x] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes2[y] - 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (sizes2[y] == 1) {\n\t\t\t\t\t\tdelta[x][y] = sizes1[x] - 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"private static void handleSignals() {\n if (DaemonStarter.isRunMode()) {\n try {\n // handle SIGHUP to prevent process to get killed when exiting the tty\n Signal.handle(new Signal(\"HUP\"), arg0 -> {\n // Nothing to do here\n System.out.println(\"SIG INT\");\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal HUP not supported\");\n }\n\n try {\n // handle SIGTERM to notify the program to stop\n Signal.handle(new Signal(\"TERM\"), arg0 -> {\n System.out.println(\"SIG TERM\");\n DaemonStarter.stopService();\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal TERM not supported\");\n }\n\n try {\n // handle SIGINT to notify the program to stop\n Signal.handle(new Signal(\"INT\"), arg0 -> {\n System.out.println(\"SIG INT\");\n DaemonStarter.stopService();\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal INT not supported\");\n }\n\n try {\n // handle SIGUSR2 to notify the life-cycle listener\n Signal.handle(new Signal(\"USR2\"), arg0 -> {\n System.out.println(\"SIG USR2\");\n DaemonStarter.getLifecycleListener().signalUSR2();\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal USR2 not supported\");\n }\n }\n }",
"protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage,\n List<Versioned<V>> multiPutValues) {\n List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size());\n // Go over all the values and determine whether the version is\n // acceptable\n for(Versioned<V> value: multiPutValues) {\n Iterator<Versioned<V>> iter = valuesInStorage.iterator();\n boolean obsolete = false;\n // Compare the current version with a set of accepted versions\n while(iter.hasNext()) {\n Versioned<V> curr = iter.next();\n Occurred occurred = value.getVersion().compare(curr.getVersion());\n if(occurred == Occurred.BEFORE) {\n obsolete = true;\n break;\n } else if(occurred == Occurred.AFTER) {\n iter.remove();\n }\n }\n if(obsolete) {\n // add to return value if obsolete\n obsoleteVals.add(value);\n } else {\n // else update the set of accepted versions\n valuesInStorage.add(value);\n }\n }\n\n return obsoleteVals;\n }",
"private PlayState3 findPlayState3() {\n PlayState3 result = PLAY_STATE_3_MAP.get(packetBytes[157]);\n if (result == null) {\n return PlayState3.UNKNOWN;\n }\n return result;\n }",
"static void logConnectionException(URI uri, DiscoveryOption discoveryOption, boolean moreOptions, Exception e) {\n if (uri == null) {\n HostControllerLogger.ROOT_LOGGER.failedDiscoveringMaster(discoveryOption, e);\n } else {\n HostControllerLogger.ROOT_LOGGER.cannotConnect(uri, e);\n }\n if (!moreOptions) {\n // All discovery options have been exhausted\n HostControllerLogger.ROOT_LOGGER.noDiscoveryOptionsLeft();\n }\n }",
"public static appflowpolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tappflowpolicy_binding obj = new appflowpolicy_binding();\n\t\tobj.set_name(name);\n\t\tappflowpolicy_binding response = (appflowpolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static CmsGalleryTabConfiguration resolve(String configStr) {\r\n\r\n CmsGalleryTabConfiguration tabConfig;\r\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(configStr)) {\r\n configStr = \"*sitemap,types,galleries,categories,vfstree,search,results\";\r\n }\r\n if (DEFAULT_CONFIGURATIONS != null) {\r\n tabConfig = DEFAULT_CONFIGURATIONS.get(configStr);\r\n if (tabConfig != null) {\r\n return tabConfig;\r\n }\r\n\r\n }\r\n return parse(configStr);\r\n }",
"private Map<Integer, Integer> getNodeIdToNaryCount(Cluster cluster,\n StoreRoutingPlan storeRoutingPlan) {\n Map<Integer, Integer> nodeIdToNaryCount = Maps.newHashMap();\n\n for(int nodeId: cluster.getNodeIds()) {\n nodeIdToNaryCount.put(nodeId, storeRoutingPlan.getZoneNAryPartitionIds(nodeId).size());\n }\n\n return nodeIdToNaryCount;\n }"
] |
Is alternative.
@param annotated the annotated
@param mergedStereotypes merged stereotypes
@return true if alternative, false otherwise | [
"public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {\n return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();\n }"
] | [
"public ListActiveCoursesInAccountOptions searchTerm(String searchTerm) {\n if(searchTerm == null || searchTerm.length() < 3) {\n throw new IllegalArgumentException(\"Search term must be at least 3 characters\");\n }\n addSingleItem(\"search_term\", searchTerm);\n return this;\n }",
"public static int cudnnGetCTCLossWorkspaceSize(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the\n timing steps, N is the mini batch size, A is the alphabet size) */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the\n dimensions are T,N,A. To compute costs\n only, set it to NULL */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n long[] sizeInBytes)/** pointer to the returned workspace size */\n {\n return checkResult(cudnnGetCTCLossWorkspaceSizeNative(handle, probsDesc, gradientsDesc, labels, labelLengths, inputLengths, algo, ctcLossDesc, sizeInBytes));\n }",
"private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException\r\n {\r\n String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);\r\n ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);\r\n\r\n ensurePKsFromHierarchy(targetClassDef);\r\n }",
"public static base_response unset(nitro_service client, sslservice resource, String[] args) throws Exception{\n\t\tsslservice unsetresource = new sslservice();\n\t\tunsetresource.servicename = resource.servicename;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public Backup getBackupData() throws Exception {\n Backup backupData = new Backup();\n\n backupData.setGroups(getGroups());\n backupData.setProfiles(getProfiles());\n ArrayList<Script> scripts = new ArrayList<Script>();\n Collections.addAll(scripts, ScriptService.getInstance().getScripts());\n backupData.setScripts(scripts);\n\n return backupData;\n }",
"public static CharSequence getAt(CharSequence text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n CharSequence sequence = text.subSequence(info.from, info.to);\n return info.reverse ? reverse(sequence) : sequence;\n }",
"public boolean mapsCell(String cell) {\n return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell));\n }",
"@Override\r\n public V get(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V deltaResult = deltaMap.get(key);\r\n if (deltaResult == null) {\r\n return originalMap.get(key);\r\n }\r\n if (deltaResult == nullValue) {\r\n return null;\r\n }\r\n if (deltaResult == removedValue) {\r\n return null;\r\n }\r\n return deltaResult;\r\n }",
"public Metadata createMetadata(String typeName, Metadata metadata) {\n String scope = Metadata.scopeBasedOnType(typeName);\n return this.createMetadata(typeName, scope, metadata);\n }"
] |
todo remove, here only for binary compatibility of elytron subsystem, drop once it is in. | [
"public static String buildDynamicCapabilityName(String baseName, String dynamicNameElement) {\n return buildDynamicCapabilityName(baseName, new String[]{dynamicNameElement});\n }"
] | [
"public static KieRuntimeLogger newFileLogger(KieRuntimeEventManager session,\n String fileName) {\n return getKnowledgeRuntimeLoggerProvider().newFileLogger( session,\n fileName );\n }",
"public static String getBuildString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.build\");\n\t\t}\n\t\treturn versionString;\n\t}",
"protected void setProperty(String propertyName, JavascriptEnum propertyValue) {\n jsObject.setMember(propertyName, propertyValue.getEnumValue());\n }",
"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 }",
"@PostConstruct\n\tprotected void postConstruct() {\n\t\tif (null == authenticationServices) {\n\t\t\tauthenticationServices = new ArrayList<AuthenticationService>();\n\t\t}\n\t\tif (!excludeDefault) {\n\t\t\tauthenticationServices.add(staticAuthenticationService);\n\t\t}\n\t}",
"public void deleteMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n this.deleteMetadata(templateName, scope);\n }",
"public void addNavigationalInformationForInverseSide() {\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Adding inverse navigational information for entity: \" + MessageHelper.infoString( persister, id, persister.getFactory() ) );\n\t\t}\n\n\t\tfor ( int propertyIndex = 0; propertyIndex < persister.getEntityMetamodel().getPropertySpan(); propertyIndex++ ) {\n\t\t\tif ( persister.isPropertyOfTable( propertyIndex, tableIndex ) ) {\n\t\t\t\tAssociationKeyMetadata associationKeyMetadata = getInverseAssociationKeyMetadata( propertyIndex );\n\n\t\t\t\t// there is no inverse association for the given property\n\t\t\t\tif ( associationKeyMetadata == null ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tObject[] newColumnValues = LogicalPhysicalConverterHelper.getColumnValuesFromResultset(\n\t\t\t\t\t\tresultset,\n\t\t\t\t\t\tpersister.getPropertyColumnNames( propertyIndex )\n\t\t\t\t);\n\n\t\t\t\t//don't index null columns, this means no association\n\t\t\t\tif ( ! CollectionHelper.isEmptyOrContainsOnlyNull( ( newColumnValues ) ) ) {\n\t\t\t\t\taddNavigationalInformationForInverseSide( propertyIndex, associationKeyMetadata, newColumnValues );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static Command newQuery(String identifier,\n String name) {\n return getCommandFactoryProvider().newQuery( identifier,\n name );\n\n }",
"public JSONObject toJson() throws JSONException {\n\n JSONObject result = new JSONObject();\n if (m_detailId != null) {\n result.put(JSON_DETAIL, \"\" + m_detailId);\n }\n if (m_siteRoot != null) {\n result.put(JSON_SITEROOT, m_siteRoot);\n }\n if (m_structureId != null) {\n result.put(JSON_STRUCTUREID, \"\" + m_structureId);\n }\n if (m_projectId != null) {\n result.put(JSON_PROJECT, \"\" + m_projectId);\n }\n if (m_type != null) {\n result.put(JSON_TYPE, \"\" + m_type.getJsonId());\n }\n return result;\n }"
] |
Recursively builds the VFS entry bean for the quick filtering function in the folder tab.<p<
@param resource the resource
@param childMap map from parent to child resources
@param filterMatches the resources matching the filter
@param parentPaths root paths of resources which are not leaves
@param isRoot true if this the root node
@return the VFS entry bean for the client
@throws CmsException if something goes wrong | [
"private CmsVfsEntryBean buildVfsEntryBeanForQuickSearch(\n CmsResource resource,\n Multimap<CmsResource, CmsResource> childMap,\n Set<CmsResource> filterMatches,\n Set<String> parentPaths,\n boolean isRoot)\n throws CmsException {\n\n CmsObject cms = getCmsObject();\n String title = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();\n boolean isMatch = filterMatches.contains(resource);\n List<CmsVfsEntryBean> childBeans = Lists.newArrayList();\n\n Collection<CmsResource> children = childMap.get(resource);\n if (!children.isEmpty()) {\n for (CmsResource child : children) {\n CmsVfsEntryBean childBean = buildVfsEntryBeanForQuickSearch(\n child,\n childMap,\n filterMatches,\n parentPaths,\n false);\n childBeans.add(childBean);\n }\n } else if (filterMatches.contains(resource)) {\n if (parentPaths.contains(resource.getRootPath())) {\n childBeans = null;\n }\n // otherwise childBeans remains an empty list\n }\n\n String rootPath = resource.getRootPath();\n CmsVfsEntryBean result = new CmsVfsEntryBean(\n rootPath,\n resource.getStructureId(),\n title,\n CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), true),\n isRoot,\n isEditable(cms, resource),\n childBeans,\n isMatch);\n String siteRoot = null;\n if (OpenCms.getSiteManager().startsWithShared(rootPath)) {\n siteRoot = OpenCms.getSiteManager().getSharedFolder();\n } else {\n String tempSiteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);\n if (tempSiteRoot != null) {\n siteRoot = tempSiteRoot;\n } else {\n siteRoot = \"\";\n }\n }\n result.setSiteRoot(siteRoot);\n return result;\n }"
] | [
"protected Map<String, OperationTransformer> buildOperationTransformers(AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry) {\n final Map<String, OperationTransformer> operations = new HashMap<String, OperationTransformer>();\n for(final Map.Entry<String, OperationTransformationEntry> entry: operationTransformers.entrySet()) {\n final OperationTransformer transformer = entry.getValue().getOperationTransformer(registry);\n operations.put(entry.getKey(), transformer);\n }\n return operations;\n }",
"@Override\n public void setBody(String body) {\n super.setBody(body);\n this.jsonValue = JsonValue.readFrom(body);\n }",
"public static List<Node> getSiblings(Node parent, Node element) {\n\t\tList<Node> result = new ArrayList<>();\n\t\tNodeList list = parent.getChildNodes();\n\n\t\tfor (int i = 0; i < list.getLength(); i++) {\n\t\t\tNode el = list.item(i);\n\n\t\t\tif (el.getNodeName().equals(element.getNodeName())) {\n\t\t\t\tresult.add(el);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}",
"protected synchronized void quit() {\n log.debug(\"Stopping {}\", getName());\n closeServerSocket();\n\n // Close all handlers. Handler threads terminate if run loop exits\n synchronized (handlers) {\n for (ProtocolHandler handler : handlers) {\n handler.close();\n }\n handlers.clear();\n }\n log.debug(\"Stopped {}\", getName());\n }",
"public static sslglobal_sslpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslglobal_sslpolicy_binding[] response = (sslglobal_sslpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public void setColor(int n, int color) {\n\t\tint firstColor = map[0];\n\t\tint lastColor = map[256-1];\n\t\tif (n > 0)\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)i/n, firstColor, color);\n\t\tif (n < 256-1)\n\t\t\tfor (int i = n; i < 256; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)(i-n)/(256-n), color, lastColor);\n\t}",
"public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\tif (mappedInsert == null) {\n\t\t\tmappedInsert = MappedCreate.build(dao, tableInfo);\n\t\t}\n\t\tint result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);\n\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\tdao.notifyChanges();\n\t\t}\n\t\treturn result;\n\t}",
"public static base_response update(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.expirymonitor = resource.expirymonitor;\n\t\tupdateresource.notificationperiod = resource.notificationperiod;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public PayloadBuilder resizeAlertBody(final int payloadLength, final String postfix) {\n int currLength = length();\n if (currLength <= payloadLength) {\n return this;\n }\n\n // now we are sure that truncation is required\n String body = (String)customAlert.get(\"body\");\n\n final int acceptableSize = Utilities.toUTF8Bytes(body).length\n - (currLength - payloadLength\n + Utilities.toUTF8Bytes(postfix).length);\n body = Utilities.truncateWhenUTF8(body, acceptableSize) + postfix;\n\n // set it back\n customAlert.put(\"body\", body);\n\n // calculate the length again\n currLength = length();\n\n if(currLength > payloadLength) {\n // string is still too long, just remove the body as the body is\n // anyway not the cause OR the postfix might be too long\n customAlert.remove(\"body\");\n }\n\n return this;\n }"
] |
Destroys the current session | [
"private void destroySession() {\n currentSessionId = 0;\n setAppLaunchPushed(false);\n getConfigLogger().verbose(getAccountId(),\"Session destroyed; Session ID is now 0\");\n clearSource();\n clearMedium();\n clearCampaign();\n clearWzrkParams();\n }"
] | [
"public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CRFClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFClassifier<CoreLabel> crf = new CRFClassifier<CoreLabel>(props);\r\n String testFile = crf.flags.testFile;\r\n String textFile = crf.flags.textFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n String loadTextPath = crf.flags.loadTextClassifier;\r\n String serializeTo = crf.flags.serializeTo;\r\n String serializeToText = crf.flags.serializeToText;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (loadTextPath != null) {\r\n System.err.println(\"Warning: this is now only tested for Chinese Segmenter\");\r\n System.err.println(\"(Sun Dec 23 00:59:39 2007) (pichuan)\");\r\n try {\r\n crf.loadTextClassifier(loadTextPath, props);\r\n // System.err.println(\"DEBUG: out from crf.loadTextClassifier\");\r\n } catch (Exception e) {\r\n throw new RuntimeException(\"error loading \" + loadTextPath, e);\r\n }\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else if (crf.flags.trainFile != null || crf.flags.trainFileList != null) {\r\n crf.train();\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n\r\n // System.err.println(\"Using \" + crf.flags.featureFactory);\r\n // System.err.println(\"Using \" +\r\n // StringUtils.getShortClassName(crf.readerAndWriter));\r\n\r\n if (serializeTo != null) {\r\n crf.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (serializeToText != null) {\r\n crf.serializeTextClassifier(serializeToText);\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter<CoreLabel> readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.searchGraphPrefix != null) {\r\n crf.classifyAndWriteViterbiSearchGraph(testFile, crf.flags.searchGraphPrefix, crf.makeReaderAndWriter());\r\n } else if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else if (crf.flags.printLabelValue) {\r\n crf.printLabelInformation(testFile, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n\r\n if (textFile != null) {\r\n crf.classifyAndWriteAnswers(textFile);\r\n }\r\n\r\n if (crf.flags.readStdin) {\r\n crf.classifyStdin();\r\n }\r\n }",
"public static <T, R extends Resource<T>> T getEntity(R resource) {\n return resource.getEntity();\n }",
"protected String getExpectedMessage() {\r\n StringBuilder syntax = new StringBuilder(\"<tag> \");\r\n syntax.append(getName());\r\n\r\n String args = getArgSyntax();\r\n if (args != null && args.length() > 0) {\r\n syntax.append(' ');\r\n syntax.append(args);\r\n }\r\n\r\n return syntax.toString();\r\n }",
"static JobContext copy() {\n JobContext current = current_.get();\n //JobContext ctxt = new JobContext(keepParent ? current : null);\n JobContext ctxt = new JobContext(null);\n if (null != current) {\n ctxt.bag_.putAll(current.bag_);\n }\n return ctxt;\n }",
"public final void setWeekOfMonth(WeekOfMonth weekOfMonth) {\n\n SortedSet<WeekOfMonth> woms = new TreeSet<>();\n if (null != weekOfMonth) {\n woms.add(weekOfMonth);\n }\n setWeeksOfMonth(woms);\n }",
"@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }",
"private String storageOverhead(Map<Integer, Integer> finalNodeToOverhead) {\n double maxOverhead = Double.MIN_VALUE;\n PartitionBalance pb = new PartitionBalance(currentCluster, currentStoreDefs);\n StringBuilder sb = new StringBuilder();\n sb.append(\"Per-node store-overhead:\").append(Utils.NEWLINE);\n DecimalFormat doubleDf = new DecimalFormat(\"####.##\");\n for(int nodeId: finalCluster.getNodeIds()) {\n Node node = finalCluster.getNodeById(nodeId);\n String nodeTag = \"Node \" + String.format(\"%4d\", nodeId) + \" (\" + node.getHost() + \")\";\n int initialLoad = 0;\n if(currentCluster.getNodeIds().contains(nodeId)) {\n initialLoad = pb.getNaryPartitionCount(nodeId);\n }\n int toLoad = 0;\n if(finalNodeToOverhead.containsKey(nodeId)) {\n toLoad = finalNodeToOverhead.get(nodeId);\n }\n double overhead = (initialLoad + toLoad) / (double) initialLoad;\n if(initialLoad > 0 && maxOverhead < overhead) {\n maxOverhead = overhead;\n }\n\n String loadTag = String.format(\"%6d\", initialLoad) + \" + \"\n + String.format(\"%6d\", toLoad) + \" -> \"\n + String.format(\"%6d\", initialLoad + toLoad) + \" (\"\n + doubleDf.format(overhead) + \" X)\";\n sb.append(nodeTag + \" : \" + loadTag).append(Utils.NEWLINE);\n }\n sb.append(Utils.NEWLINE)\n .append(\"**** Max per-node storage overhead: \" + doubleDf.format(maxOverhead) + \" X.\")\n .append(Utils.NEWLINE);\n return (sb.toString());\n }",
"public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) {\n\n int lastDot = path.lastIndexOf('.');\n\n if (lastDot > -1) {\n String parentPath = path.substring(0, lastDot);\n String fieldName = path.substring(lastDot + 1);\n Field parentField = getDeclaredFieldWithPath(clazz, parentPath);\n return getDeclaredFieldInHierarchy(parentField.getType(), fieldName);\n } else {\n return getDeclaredFieldInHierarchy(clazz, path);\n }\n }",
"public T withLabel(String text, String languageCode) {\n\t\twithLabel(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}"
] |
Validates a String to be a valid name to be used in MongoDB for a field name.
@param fieldName | [
"private void validateAsMongoDBFieldName(String fieldName) {\n\t\tif ( fieldName.startsWith( \"$\" ) ) {\n\t\t\tthrow log.fieldNameHasInvalidDollarPrefix( fieldName );\n\t\t}\n\t\telse if ( fieldName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.fieldNameContainsNULCharacter( fieldName );\n\t\t}\n\t}"
] | [
"public static List<String> splitAsList(String text, String delimiter) {\n List<String> answer = new ArrayList<String>();\n if (text != null && text.length() > 0) {\n answer.addAll(Arrays.asList(text.split(delimiter)));\n }\n return answer;\n }",
"@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 }",
"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 Set<Annotation> filterInterceptorBindings(BeanManagerImpl beanManager, Collection<Annotation> annotations) {\n Set<Annotation> interceptorBindings = new InterceptorBindingSet(beanManager);\n for (Annotation annotation : annotations) {\n if (beanManager.isInterceptorBinding(annotation.annotationType())) {\n interceptorBindings.add(annotation);\n }\n }\n return interceptorBindings;\n }",
"public IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }",
"public void setPropertyDestinationType(Class<?> clazz, String propertyName,\r\n\t\t\tTypeReference<?> destinationType) {\r\n\t\tpropertiesDestinationTypes.put(new ClassProperty(clazz, propertyName), destinationType);\r\n\t}",
"public T find(AbstractProject<?, ?> project, Class<T> type) {\n // First check that the Flexible Publish plugin is installed:\n if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) {\n // Iterate all the project's publishers and find the flexible publisher:\n for (Publisher publisher : project.getPublishersList()) {\n // Found the flexible publisher:\n if (publisher instanceof FlexiblePublisher) {\n // See if it wraps a publisher of the specified type and if it does, return it:\n T pub = getWrappedPublisher(publisher, type);\n if (pub != null) {\n return pub;\n }\n }\n }\n }\n\n return null;\n }",
"public void readData(BufferedReader in) throws IOException {\r\n String line, value;\r\n // skip old variables if still present\r\n lexOptions.readData(in);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n try {\r\n tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance();\r\n } catch (Exception e) {\r\n IOException ioe = new IOException(\"Problem instantiating parserParams: \" + line);\r\n ioe.initCause(e);\r\n throw ioe;\r\n }\r\n line = in.readLine();\r\n // ensure backwards compatibility\r\n if (line.matches(\"^forceCNF.*\")) {\r\n value = line.substring(line.indexOf(' ') + 1);\r\n forceCNF = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doPCFG = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doDep = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n freeDependencies = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n directional = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n genStop = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n distance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n coarseDistance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n dcTags = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n if ( ! line.matches(\"^nPrune.*\")) {\r\n throw new RuntimeException(\"Expected nPrune, found: \" + line);\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n nodePrune = Boolean.parseBoolean(value);\r\n line = in.readLine(); // get rid of last line\r\n if (line.length() != 0) {\r\n throw new RuntimeException(\"Expected blank line, found: \" + line);\r\n }\r\n }",
"public List<Throwable> getCauses(Throwable t)\n {\n List<Throwable> causes = new LinkedList<Throwable>();\n Throwable next = t;\n while (next.getCause() != null)\n {\n next = next.getCause();\n causes.add(next);\n }\n return causes;\n }"
] |
Function to update store definitions. Unlike the put method, this
function does not delete any existing state. It only updates the state of
the stores specified in the given stores.xml
@param valueBytes specifies the bytes of the stores.xml containing
updates for the specified stores | [
"@SuppressWarnings(\"unchecked\")\n public void updateStoreDefinitions(Versioned<byte[]> valueBytes) {\n // acquire write lock\n writeLock.lock();\n\n try {\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n Versioned<Object> valueObject = convertStringToObject(STORES_KEY, value);\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) valueObject.getValue();\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n StoreDefinitionUtils.validateNewStoreDefsAreNonBreaking(getStoreDefList(), storeDefinitions);\n\n // Go through each store definition and do a corresponding put\n for(StoreDefinition storeDef: storeDefinitions) {\n if(!this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Cannot update a store which does not exist !\");\n }\n\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n // TODO: Make this more fine grained.. i.e only update listeners for\n // a specific store.\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }"
] | [
"public static sslglobal_sslpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tsslglobal_sslpolicy_binding[] response = (sslglobal_sslpolicy_binding[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public static base_responses add(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 addresources[] = new sslocspresponder[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslocspresponder();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].url = resources[i].url;\n\t\t\t\taddresources[i].cache = resources[i].cache;\n\t\t\t\taddresources[i].cachetimeout = resources[i].cachetimeout;\n\t\t\t\taddresources[i].batchingdepth = resources[i].batchingdepth;\n\t\t\t\taddresources[i].batchingdelay = resources[i].batchingdelay;\n\t\t\t\taddresources[i].resptimeout = resources[i].resptimeout;\n\t\t\t\taddresources[i].respondercert = resources[i].respondercert;\n\t\t\t\taddresources[i].trustresponder = resources[i].trustresponder;\n\t\t\t\taddresources[i].producedattimeskew = resources[i].producedattimeskew;\n\t\t\t\taddresources[i].signingcert = resources[i].signingcert;\n\t\t\t\taddresources[i].usenonce = resources[i].usenonce;\n\t\t\t\taddresources[i].insertclientcert = resources[i].insertclientcert;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private byte[] assembleValues(List<Versioned<byte[]>> values) throws IOException {\n\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n DataOutputStream dataStream = new DataOutputStream(stream);\n\n for(Versioned<byte[]> value: values) {\n byte[] object = value.getValue();\n dataStream.writeInt(object.length);\n dataStream.write(object);\n\n VectorClock clock = (VectorClock) value.getVersion();\n dataStream.writeInt(clock.sizeInBytes());\n dataStream.write(clock.toBytes());\n }\n\n return stream.toByteArray();\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 void digestInteger(MessageDigest digest, int value) {\n byte[] valueBytes = new byte[4];\n Util.numberToBytes(value, valueBytes, 0, 4);\n digest.update(valueBytes);\n }",
"public static <T> PollingState<T> create(Response<ResponseBody> response, LongRunningOperationOptions lroOptions, int defaultRetryTimeout, Type resourceType, SerializerAdapter<?> serializerAdapter) throws IOException {\n PollingState<T> pollingState = new PollingState<>();\n pollingState.initialHttpMethod = response.raw().request().method();\n pollingState.defaultRetryTimeout = defaultRetryTimeout;\n pollingState.withResponse(response);\n pollingState.resourceType = resourceType;\n pollingState.serializerAdapter = serializerAdapter;\n pollingState.loggingContext = response.raw().request().header(LOGGING_HEADER);\n pollingState.finalStateVia = lroOptions.finalStateVia();\n\n String responseContent = null;\n PollingResource resource = null;\n if (response.body() != null) {\n responseContent = response.body().string();\n response.body().close();\n }\n if (responseContent != null && !responseContent.isEmpty()) {\n pollingState.resource = serializerAdapter.deserialize(responseContent, resourceType);\n resource = serializerAdapter.deserialize(responseContent, PollingResource.class);\n }\n final int statusCode = pollingState.response.code();\n if (resource != null && resource.properties != null\n && resource.properties.provisioningState != null) {\n pollingState.withStatus(resource.properties.provisioningState, statusCode);\n } else {\n switch (statusCode) {\n case 202:\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n break;\n case 204:\n case 201:\n case 200:\n pollingState.withStatus(AzureAsyncOperation.SUCCESS_STATUS, statusCode);\n break;\n default:\n pollingState.withStatus(AzureAsyncOperation.FAILED_STATUS, statusCode);\n }\n }\n return pollingState;\n }",
"public static base_response kill(nitro_service client, systemsession resource) throws Exception {\n\t\tsystemsession killresource = new systemsession();\n\t\tkillresource.sid = resource.sid;\n\t\tkillresource.all = resource.all;\n\t\treturn killresource.perform_operation(client,\"kill\");\n\t}",
"public static base_response add(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction addresource = new autoscaleaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.profilename = resource.profilename;\n\t\taddresource.parameters = resource.parameters;\n\t\taddresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\taddresource.quiettime = resource.quiettime;\n\t\taddresource.vserver = resource.vserver;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static Day getDay(Integer day)\n {\n Day result = null;\n if (day != null)\n {\n result = DAY_ARRAY[day.intValue()];\n }\n return (result);\n }"
] |
Injects EJBs and other EE resources.
@param resourceInjectionsHierarchy
@param beanInstance
@param ctx | [
"public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,\n T beanInstance, CreationalContext<T> ctx) {\n for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {\n for (ResourceInjection<?> resourceInjection : resourceInjections) {\n resourceInjection.injectResourceReference(beanInstance, ctx);\n }\n }\n }"
] | [
"public ItemRequest<Task> addProject(String task) {\n \n String path = String.format(\"/tasks/%s/addProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public static dnspolicylabel[] get(nitro_service service) throws Exception{\n\t\tdnspolicylabel obj = new dnspolicylabel();\n\t\tdnspolicylabel[] response = (dnspolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public Jar setJarPrefix(String value) {\n verifyNotSealed();\n if (jos != null)\n throw new IllegalStateException(\"Really executable cannot be set after entries are added.\");\n if (value != null && jarPrefixFile != null)\n throw new IllegalStateException(\"A prefix has already been set (\" + jarPrefixFile + \")\");\n this.jarPrefixStr = value;\n return this;\n }",
"private void readBitmap() {\n // (sub)image position & size.\n header.currentFrame.ix = readShort();\n header.currentFrame.iy = readShort();\n header.currentFrame.iw = readShort();\n header.currentFrame.ih = readShort();\n\n int packed = read();\n // 1 - local color table flag interlace\n boolean lctFlag = (packed & 0x80) != 0;\n int lctSize = (int) Math.pow(2, (packed & 0x07) + 1);\n // 3 - sort flag\n // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color\n // table size\n header.currentFrame.interlace = (packed & 0x40) != 0;\n if (lctFlag) {\n // Read table.\n header.currentFrame.lct = readColorTable(lctSize);\n } else {\n // No local color table.\n header.currentFrame.lct = null;\n }\n\n // Save this as the decoding position pointer.\n header.currentFrame.bufferFrameStart = rawData.position();\n\n // False decode pixel data to advance buffer.\n skipImageData();\n\n if (err()) {\n return;\n }\n\n header.frameCount++;\n // Add image to frame.\n header.frames.add(header.currentFrame);\n }",
"public static Collection<Info> getPendingCollaborations(BoxAPIConnection api) {\n URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL());\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<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get(\"id\").asString());\n BoxCollaboration.Info info = collaboration.new Info(entryObject);\n collaborations.add(info);\n }\n\n return collaborations;\n }",
"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 static BMatrixRMaj elementLessThan(DMatrixRMaj A , double value , BMatrixRMaj output )\n {\n if( output == null ) {\n output = new BMatrixRMaj(A.numRows,A.numCols);\n }\n\n output.reshape(A.numRows, A.numCols);\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n output.data[i] = A.data[i] < value;\n }\n\n return output;\n }",
"public GeoShapeMapper transform(GeoTransformation... transformations) {\n if (this.transformations == null) {\n this.transformations = Arrays.asList(transformations);\n } else {\n this.transformations.addAll(Arrays.asList(transformations));\n }\n return this;\n }",
"public static void setIndex(Matcher matcher, int idx) {\n int count = getCount(matcher);\n if (idx < -count || idx >= count) {\n throw new IndexOutOfBoundsException(\"index is out of range \" + (-count) + \"..\" + (count - 1) + \" (index = \" + idx + \")\");\n }\n if (idx == 0) {\n matcher.reset();\n } else if (idx > 0) {\n matcher.reset();\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n } else if (idx < 0) {\n matcher.reset();\n idx += getCount(matcher);\n for (int i = 0; i < idx; i++) {\n matcher.find();\n }\n }\n }"
] |
Perform the given work with a Jedis connection from the given pool.
Wraps any thrown checked exceptions in a RuntimeException.
@param pool the resource pool
@param work the work to perform
@param <V> the result type
@return the result of the given work | [
"public static <V> V doWorkInPoolNicely(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) {\n final V result;\n try {\n result = doWorkInPool(pool, work);\n } catch (RuntimeException re) {\n throw re;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return result;\n }"
] | [
"public void createAgent(String agent_name, String path) {\n IComponentIdentifier agent = cmsService.createComponent(agent_name,\n path, null, null).get(new ThreadSuspendable());\n createdAgents.put(agent_name, agent);\n }",
"private Collection getOwnerObjects()\r\n {\r\n Collection owners = new Vector();\r\n while (hasNext())\r\n {\r\n owners.add(next());\r\n }\r\n return owners;\r\n }",
"private void addProperty(XMLStreamWriter writer, String name, Class<?> propertyType, String readMethod, String writeMethod) throws XMLStreamException\n {\n if (name.length() != 0)\n {\n writer.writeStartElement(\"property\");\n\n // convert property name to .NET style (i.e. first letter uppercase)\n String propertyName = name.substring(0, 1).toUpperCase() + name.substring(1);\n writer.writeAttribute(\"name\", propertyName);\n\n String type = getTypeString(propertyType);\n\n writer.writeAttribute(\"sig\", \"()\" + type);\n if (readMethod != null)\n {\n writer.writeStartElement(\"getter\");\n writer.writeAttribute(\"name\", readMethod);\n writer.writeAttribute(\"sig\", \"()\" + type);\n writer.writeEndElement();\n }\n if (writeMethod != null)\n {\n writer.writeStartElement(\"setter\");\n writer.writeAttribute(\"name\", writeMethod);\n writer.writeAttribute(\"sig\", \"(\" + type + \")V\");\n writer.writeEndElement();\n }\n\n writer.writeEndElement();\n }\n }",
"public Stats getPhotosetStats(String photosetId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSET_STATS, \"photoset_id\", photosetId, date);\n }",
"public void setNamespace(String prefix, String namespaceURI) {\n ensureNotNull(\"Prefix\", prefix);\n ensureNotNull(\"Namespace URI\", namespaceURI);\n\n namespaces.put(prefix, namespaceURI);\n }",
"public static final Date parseDate(String value)\n {\n Date result = null;\n\n try\n {\n if (value != null && !value.isEmpty())\n {\n result = DATE_FORMAT.get().parse(value);\n }\n }\n catch (ParseException ex)\n {\n // Ignore\n }\n\n return result;\n }",
"public List<CRFCliqueTree> getCliqueTrees(String filename, DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n List<CRFCliqueTree> cts = new ArrayList<CRFCliqueTree>();\r\n ObjectBank<List<IN>> docs = makeObjectBankFromFile(filename, readerAndWriter);\r\n for (List<IN> doc : docs) {\r\n cts.add(getCliqueTree(doc));\r\n }\r\n\r\n return cts;\r\n }",
"protected AbstractColumn buildExpressionColumn() {\n\t\tExpressionColumn column = new ExpressionColumn();\n\t\tpopulateCommonAttributes(column);\n\t\t\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\treturn column;\n\t}",
"public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,\n final Set<String> libraryPaths,\n final Set<String> sourcePaths, Set<Path> sourceFiles)\n {\n\n final String[] encodings = null;\n final String[] bindingKeys = new String[0];\n final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());\n final FileASTRequestor requestor = new FileASTRequestor()\n {\n @Override\n public void acceptAST(String sourcePath, CompilationUnit ast)\n {\n try\n {\n /*\n * This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.\n */\n super.acceptAST(sourcePath, ast);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);\n ast.accept(visitor);\n listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());\n }\n catch (WindupStopException ex)\n {\n throw ex;\n }\n catch (Throwable t)\n {\n listener.failed(Paths.get(sourcePath), t);\n }\n }\n };\n\n List<List<String>> batches = createBatches(sourceFiles);\n\n for (final List<String> batch : batches)\n {\n executor.submit(new Callable<Void>()\n {\n @Override\n public Void call() throws Exception\n {\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map<String, String> options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n // these options seem to slightly reduce the number of times that JDT aborts on compilation errors\n options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, \"warning\");\n options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, \"ignore\");\n options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, \"warning\");\n options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, \"warning\");\n\n parser.setCompilerOptions(options);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),\n sourcePaths.toArray(new String[sourcePaths.size()]),\n null,\n true);\n\n parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);\n return null;\n }\n });\n }\n\n executor.shutdown();\n\n return new BatchASTFuture()\n {\n @Override\n public boolean isDone()\n {\n return executor.isTerminated();\n }\n };\n }"
] |
Used to retrieve all metadata associated with the item.
@param item item to get metadata for.
@param fields the optional fields to retrieve.
@return An iterable of metadata instances associated with the item. | [
"public static Iterable<Metadata> getAllMetadata(BoxItem item, String ... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new BoxResourceIterable<Metadata>(\n item.getAPI(),\n GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery(item.getItemURL().toString(), builder.toString()),\n DEFAULT_LIMIT) {\n\n @Override\n protected Metadata factory(JsonObject jsonObject) {\n return new Metadata(jsonObject);\n }\n\n };\n }"
] | [
"public static Set<String> listLinks(OperationContext context, PathAddress overlayAddress) {\n Resource overlayResource = context.readResourceFromRoot(overlayAddress);\n if (overlayResource.hasChildren(DEPLOYMENT)) {\n return overlayResource.getChildrenNames(DEPLOYMENT);\n }\n return Collections.emptySet();\n }",
"private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {\n Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);\n String concurrentDeployment = getSystemProperty(\"org.jboss.weld.bootstrap.properties.concurrentDeployment\");\n if (concurrentDeployment != null) {\n processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);\n found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));\n }\n String preloaderThreadPoolSize = getSystemProperty(\"org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize\");\n if (preloaderThreadPoolSize != null) {\n found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));\n }\n return found;\n }",
"public static List<String> getStoreNames(List<StoreDefinition> storeDefList) {\n List<String> storeList = new ArrayList<String>();\n for(StoreDefinition def: storeDefList) {\n storeList.add(def.getName());\n }\n return storeList;\n }",
"public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_COORDS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"user_id\", userId);\r\n parameters.put(\"person_x\", bounds.x);\r\n parameters.put(\"person_y\", bounds.y);\r\n parameters.put(\"person_w\", bounds.width);\r\n parameters.put(\"person_h\", bounds.height);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {\n co.setCommandLineOption( commandLineOption );\n co.setValue( value );\n return this;\n }",
"public static service_stats[] get(nitro_service service) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tservice_stats[] response = (service_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"private void updateRoutingStrategies(Cluster cluster, List<StoreDefinition> storeDefs) {\n // acquire write lock\n writeLock.lock();\n try {\n VectorClock clock = new VectorClock();\n if(metadataCache.containsKey(ROUTING_STRATEGY_KEY))\n clock = (VectorClock) metadataCache.get(ROUTING_STRATEGY_KEY).getVersion();\n\n logger.info(\"Updating routing strategy for all stores\");\n HashMap<String, StoreDefinition> storeDefMap = makeStoreDefinitionMap(storeDefs);\n HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster,\n storeDefMap);\n this.metadataCache.put(ROUTING_STRATEGY_KEY,\n new Versioned<Object>(routingStrategyMap,\n clock.incremented(getNodeId(),\n System.currentTimeMillis())));\n\n for(String storeName: storeNameTolisteners.keySet()) {\n RoutingStrategy updatedRoutingStrategy = routingStrategyMap.get(storeName);\n if(updatedRoutingStrategy != null) {\n try {\n for(MetadataStoreListener listener: storeNameTolisteners.get(storeName)) {\n listener.updateRoutingStrategy(updatedRoutingStrategy);\n listener.updateStoreDefinition(storeDefMap.get(storeName));\n }\n } catch(Exception e) {\n if(logger.isEnabledFor(Level.WARN))\n logger.warn(e, e);\n }\n }\n\n }\n } finally {\n writeLock.unlock();\n }\n }",
"private static synchronized StreamHandler getStreamHandler() {\n if (methodHandler == null) {\n methodHandler = new ConsoleHandler();\n methodHandler.setFormatter(new Formatter() {\n @Override\n public String format(LogRecord record) {\n return record.getMessage() + \"\\n\";\n }\n });\n methodHandler.setLevel(Level.FINE);\n }\n return methodHandler;\n }",
"@Deprecated\n public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) {\n return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector);\n }"
] |
Constraint that ensures that the field has precision and scale settings if the jdbc type requires it.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in all levels) | [
"private void ensurePrecisionAndScale(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, null);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, null);\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION))\r\n {\r\n String defaultPrecision = JdbcTypeHelper.getDefaultPrecisionFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultPrecision != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no precision setting though its jdbc type requires it (in most databases); using default precision of \"+defaultPrecision);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, defaultPrecision);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, \"1\");\r\n }\r\n }\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))\r\n {\r\n String defaultScale = JdbcTypeHelper.getDefaultScaleFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultScale != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no scale setting though its jdbc type requires it (in most databases); using default scale of \"+defaultScale);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, defaultScale);\r\n }\r\n else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION) || fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION))\r\n {\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, \"0\");\r\n }\r\n }\r\n }"
] | [
"public static boolean isRowsLinearIndependent( DMatrixRMaj A )\n {\n // LU decomposition\n LUDecomposition<DMatrixRMaj> lu = DecompositionFactory_DDRM.lu(A.numRows,A.numCols);\n if( lu.inputModified() )\n A = A.copy();\n\n if( !lu.decompose(A))\n throw new RuntimeException(\"Decompositon failed?\");\n\n // if they are linearly independent it should not be singular\n return !lu.isSingular();\n }",
"public List<PossibleState> bfs(int min) throws ModelException {\r\n List<PossibleState> bootStrap = new LinkedList<>();\n\r\n TransitionTarget initial = model.getInitialTarget();\r\n PossibleState initialState = new PossibleState(initial, fillInitialVariables());\r\n bootStrap.add(initialState);\n\r\n while (bootStrap.size() < min) {\r\n PossibleState state = bootStrap.remove(0);\r\n TransitionTarget nextState = state.nextState;\n\r\n if (nextState.getId().equalsIgnoreCase(\"end\")) {\r\n throw new ModelException(\"Could not achieve required bootstrap without reaching end state\");\r\n }\n\r\n //run every action in series\r\n List<Map<String, String>> product = new LinkedList<>();\r\n product.add(new HashMap<>(state.variables));\n\r\n OnEntry entry = nextState.getOnEntry();\r\n List<Action> actions = entry.getActions();\n\r\n for (Action action : actions) {\r\n for (CustomTagExtension tagExtension : tagExtensionList) {\r\n if (tagExtension.getTagActionClass().isInstance(action)) {\r\n product = tagExtension.pipelinePossibleStates(action, product);\r\n }\r\n }\r\n }\n\r\n //go through every transition and see which of the products are valid, adding them to the list\r\n List<Transition> transitions = nextState.getTransitionsList();\n\r\n for (Transition transition : transitions) {\r\n String condition = transition.getCond();\r\n TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0);\n\r\n for (Map<String, String> p : product) {\r\n Boolean pass;\n\r\n if (condition == null) {\r\n pass = true;\r\n } else {\r\n //scrub the context clean so we may use it to evaluate transition conditional\r\n Context context = this.getRootContext();\r\n context.reset();\n\r\n //set up new context\r\n for (Map.Entry<String, String> e : p.entrySet()) {\r\n context.set(e.getKey(), e.getValue());\r\n }\n\r\n //evaluate condition\r\n try {\r\n pass = (Boolean) this.getEvaluator().eval(context, condition);\r\n } catch (SCXMLExpressionException ex) {\r\n pass = false;\r\n }\r\n }\n\r\n //transition condition satisfied, add to bootstrap list\r\n if (pass) {\r\n PossibleState result = new PossibleState(target, p);\r\n bootStrap.add(result);\r\n }\r\n }\r\n }\r\n }\n\r\n return bootStrap;\r\n }",
"static void createMessage(String textMessage, JobInstance jobInstance, DbConn cnx)\n {\n cnx.runUpdate(\"message_insert\", jobInstance.getId(), textMessage);\n }",
"protected void mergeSameCost(LinkedList<TimephasedCost> list)\n {\n LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();\n\n TimephasedCost previousAssignment = null;\n for (TimephasedCost assignment : list)\n {\n if (previousAssignment == null)\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n result.add(assignment);\n }\n else\n {\n Number previousAssignmentCost = previousAssignment.getAmountPerDay();\n Number assignmentCost = assignment.getTotalAmount();\n\n if (NumberHelper.equals(previousAssignmentCost.doubleValue(), assignmentCost.doubleValue(), 0.01))\n {\n Date assignmentStart = previousAssignment.getStart();\n Date assignmentFinish = assignment.getFinish();\n double total = previousAssignment.getTotalAmount().doubleValue();\n total += assignmentCost.doubleValue();\n\n TimephasedCost merged = new TimephasedCost();\n merged.setStart(assignmentStart);\n merged.setFinish(assignmentFinish);\n merged.setAmountPerDay(assignmentCost);\n merged.setTotalAmount(Double.valueOf(total));\n\n result.removeLast();\n assignment = merged;\n }\n else\n {\n assignment.setAmountPerDay(assignment.getTotalAmount());\n }\n result.add(assignment);\n }\n\n previousAssignment = assignment;\n }\n\n list.clear();\n list.addAll(result);\n }",
"@Override\n public View getView(int position, View convertView,\n ViewGroup parent) {\n return (wrapped.getView(position, convertView, parent));\n }",
"void registerAlias(FieldType type, String alias)\n {\n m_aliasMap.put(new Pair<FieldTypeClass, String>(type.getFieldTypeClass(), alias), type);\n }",
"@VisibleForTesting\n protected static Dimension getSize(\n final ScalebarAttributeValues scalebarParams,\n final ScaleBarRenderSettings settings, final Dimension maxLabelSize) {\n final float width;\n final float height;\n if (scalebarParams.getOrientation().isHorizontal()) {\n width = 2 * settings.getPadding()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getLeftLabelMargin() + settings.getRightLabelMargin();\n height = 2 * settings.getPadding()\n + settings.getBarSize() + settings.getLabelDistance()\n + Label.getRotatedHeight(maxLabelSize, scalebarParams.getLabelRotation());\n } else {\n width = 2 * settings.getPadding()\n + settings.getLabelDistance() + settings.getBarSize()\n + Label.getRotatedWidth(maxLabelSize, scalebarParams.getLabelRotation());\n height = 2 * settings.getPadding()\n + settings.getTopLabelMargin()\n + settings.getIntervalLengthInPixels() * scalebarParams.intervals\n + settings.getBottomLabelMargin();\n }\n return new Dimension((int) Math.ceil(width), (int) Math.ceil(height));\n }",
"public Set<TupleOperation> getOperations() {\n\t\tif ( currentState == null ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\treturn new SetFromCollection<TupleOperation>( currentState.values() );\n\t\t}\n\t}",
"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 }"
] |
Returns iterable containing assignments for this single legal hold policy.
@param fields the fields to retrieve.
@return an iterable containing assignments for this single legal hold policy. | [
"public Iterable<BoxLegalHoldAssignment.Info> getAssignments(String ... fields) {\n return this.getAssignments(null, null, DEFAULT_LIMIT, fields);\n }"
] | [
"private EndpointOverride getEndpointOverrideFromResultSet(ResultSet results) throws Exception {\n EndpointOverride endpoint = new EndpointOverride();\n endpoint.setPathId(results.getInt(Constants.GENERIC_ID));\n endpoint.setPath(results.getString(Constants.PATH_PROFILE_ACTUAL_PATH));\n endpoint.setBodyFilter(results.getString(Constants.PATH_PROFILE_BODY_FILTER));\n endpoint.setPathName(results.getString(Constants.PATH_PROFILE_PATHNAME));\n endpoint.setContentType(results.getString(Constants.PATH_PROFILE_CONTENT_TYPE));\n endpoint.setRequestType(results.getInt(Constants.PATH_PROFILE_REQUEST_TYPE));\n endpoint.setRepeatNumber(results.getInt(Constants.REQUEST_RESPONSE_REPEAT_NUMBER));\n endpoint.setGroupIds(results.getString(Constants.PATH_PROFILE_GROUP_IDS));\n endpoint.setRequestEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_REQUEST_ENABLED));\n endpoint.setResponseEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_RESPONSE_ENABLED));\n endpoint.setClientUUID(results.getString(Constants.GENERIC_CLIENT_UUID));\n endpoint.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));\n endpoint.setGlobal(results.getBoolean(Constants.PATH_PROFILE_GLOBAL));\n return endpoint;\n }",
"public static base_responses update(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile updateresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleprofile();\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].apikey = resources[i].apikey;\n\t\t\t\tupdateresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public Where<T, ID> not(Where<T, ID> comparison) {\n\t\taddClause(new Not(pop(\"NOT\")));\n\t\treturn this;\n\t}",
"private Date getTimeFromInteger(Integer time)\n {\n Date result = null;\n\n if (time != null)\n {\n int minutes = time.intValue();\n int hours = minutes / 60;\n minutes -= (hours * 60);\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.HOUR_OF_DAY, hours);\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n\n return (result);\n }",
"protected I_CmsSearchConfigurationFacetField parseFieldFacet(final String pathPrefix) {\n\n try {\n final String field = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_FACET_FIELD);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final Integer limit = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_LIMIT);\n final String prefix = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_PREFIX);\n final String sorder = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (@SuppressWarnings(\"unused\") final Exception e) {\n order = null;\n }\n final String filterQueryModifier = parseOptionalStringValue(\n pathPrefix + XML_ELEMENT_FACET_FILTERQUERYMODIFIER);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_FACET_FIELD),\n e);\n return null;\n }\n }",
"public File getStylesheetPath()\n {\n String path = System.getProperty(STYLESHEET_KEY);\n return path == null ? null : new File(path);\n }",
"public void setWholeDay(Boolean isWholeDay) {\r\n\r\n if (m_model.isWholeDay() ^ ((null != isWholeDay) && isWholeDay.booleanValue())) {\r\n m_model.setWholeDay(isWholeDay);\r\n valueChanged();\r\n }\r\n }",
"public static void checkVectorAddition() {\n DoubleMatrix x = new DoubleMatrix(3, 1, 1.0, 2.0, 3.0);\n DoubleMatrix y = new DoubleMatrix(3, 1, 4.0, 5.0, 6.0);\n DoubleMatrix z = new DoubleMatrix(3, 1, 5.0, 7.0, 9.0);\n\n check(\"checking vector addition\", x.add(y).equals(z));\n }",
"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 }"
] |
Applies the given codec registry to be used alongside the default codec registry.
@param codecRegistry the codec registry to merge in.
@return an {@link StitchObjectMapper} with the merged codec registries. | [
"public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {\n // We can't detect if their codecRegistry has any duplicate providers. There's also a chance\n // that putting ours first may prevent decoding of some of their classes if for example they\n // have their own way of decoding an Integer.\n final CodecRegistry newReg =\n CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);\n return new StitchObjectMapper(this, newReg);\n }"
] | [
"public static Collection<CurrencyUnit> getCurrencies(String... providers) {\n return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryCurrenciesSingletonSpi loaded, check your system setup.\"))\n .getCurrencies(providers);\n }",
"public static <T> MetaTinyType<T> metaFor(Class<?> candidate) {\n for (MetaTinyType meta : metas) {\n if (meta.isMetaOf(candidate)) {\n return meta;\n }\n }\n throw new IllegalArgumentException(String.format(\"not a tinytype: %s\", candidate == null ? \"null\" : candidate.getCanonicalName()));\n }",
"public void credentialsMigration(T overrider, Class overriderClass) {\n try {\n deployerMigration(overrider, overriderClass);\n resolverMigration(overrider, overriderClass);\n } catch (NoSuchFieldException | IllegalAccessException | IOException e) {\n converterErrors.add(getConversionErrorMessage(overrider, e));\n }\n }",
"static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }",
"@Override\n public <X> X getScreenshotAs(OutputType<X> target) {\n // Get the screenshot as base64 and convert it to the requested type (i.e. OutputType<T>)\n String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();\n return target.convertFromBase64Png(base64);\n }",
"private Envelope getMaxScreenEnvelope(InternalTile tile, Coordinate panOrigin) {\n\t\tint nrOfTilesX = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenWidth());\n\t\tint nrOfTilesY = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenHeight());\n\n\t\tdouble x1 = panOrigin.x - nrOfTilesX * tile.getTileWidth();\n\t\t// double x2 = x1 + (nrOfTilesX * tileWidth * 2);\n\t\tdouble x2 = panOrigin.x + nrOfTilesX * tile.getTileWidth();\n\t\tdouble y1 = panOrigin.y - nrOfTilesY * tile.getTileHeight();\n\t\t// double y2 = y1 + (nrOfTilesY * tileHeight * 2);\n\t\tdouble y2 = panOrigin.y + nrOfTilesY * tile.getTileHeight();\n\t\treturn new Envelope(x1, x2, y1, y2);\n\t}",
"private void setConstraints(Task task, MapRow row)\n {\n ConstraintType constraintType = null;\n Date constraintDate = null;\n Date lateDate = row.getDate(\"CONSTRAINT_LATE_DATE\");\n Date earlyDate = row.getDate(\"CONSTRAINT_EARLY_DATE\");\n\n switch (row.getInteger(\"CONSTRAINT_TYPE\").intValue())\n {\n case 2: // Cannot Reschedule\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = task.getStart();\n break;\n }\n\n case 12: //Finish Between\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = lateDate;\n break;\n }\n\n case 10: // Finish On or After\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 11: // Finish On or Before\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = lateDate;\n break;\n }\n\n case 13: // Mandatory Start\n case 5: // Start On\n case 9: // Finish On\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 14: // Mandatory Finish\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 4: // Start As Late As Possible\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n break;\n }\n\n case 3: // Start As Soon As Possible\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n break;\n }\n\n case 8: // Start Between\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n constraintDate = earlyDate;\n break;\n }\n\n case 6: // Start On or Before\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 15: // Work Between\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n }\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"public Story storyOfText(Configuration configuration, String storyAsText, String storyId) {\n return configuration.storyParser().parseStory(storyAsText, storyId);\n }",
"public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){\n\t\tfinal Artifact artifact = new Artifact();\n\n\t\tartifact.setGroupId(groupId);\n\t\tartifact.setArtifactId(artifactId);\n\t\tartifact.setVersion(version);\n\n\t\tif(classifier != null){\n\t\t\tartifact.setClassifier(classifier);\n\t\t}\n\n\t\tif(type != null){\n\t\t\tartifact.setType(type);\n\t\t}\n\n\t\tif(extension != null){\n\t\t\tartifact.setExtension(extension);\n\t\t}\n\n\t\tartifact.setOrigin(origin == null ? \"maven\" : origin);\n\n\t\treturn artifact;\n\t}"
] |
Register a data type with the manager. | [
"public static void registerDataPersisters(DataPersister... dataPersisters) {\n\t\t// we build the map and replace it to lower the chance of concurrency issues\n\t\tList<DataPersister> newList = new ArrayList<DataPersister>();\n\t\tif (registeredPersisters != null) {\n\t\t\tnewList.addAll(registeredPersisters);\n\t\t}\n\t\tfor (DataPersister persister : dataPersisters) {\n\t\t\tnewList.add(persister);\n\t\t}\n\t\tregisteredPersisters = newList;\n\t}"
] | [
"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}",
"public static JmsDestinationType getTypeFromClass(String aClass)\n {\n if (StringUtils.equals(aClass, \"javax.jms.Queue\") || StringUtils.equals(aClass, \"javax.jms.QueueConnectionFactory\"))\n {\n return JmsDestinationType.QUEUE;\n }\n else if (StringUtils.equals(aClass, \"javax.jms.Topic\") || StringUtils.equals(aClass, \"javax.jms.TopicConnectionFactory\"))\n {\n return JmsDestinationType.TOPIC;\n }\n else\n {\n return null;\n }\n }",
"public static base_response disable(nitro_service client, nsacl6 resource) throws Exception {\n\t\tnsacl6 disableresource = new nsacl6();\n\t\tdisableresource.acl6name = resource.acl6name;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public static base_responses unset(nitro_service client, Long clid[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (clid != null && clid.length > 0) {\n\t\t\tclusterinstance unsetresources[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++){\n\t\t\t\tunsetresources[i] = new clusterinstance();\n\t\t\t\tunsetresources[i].clid = clid[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public BoxTaskAssignment.Info addAssignment(BoxUser assignTo) {\n JsonObject taskJSON = new JsonObject();\n taskJSON.add(\"type\", \"task\");\n taskJSON.add(\"id\", this.getID());\n\n JsonObject assignToJSON = new JsonObject();\n assignToJSON.add(\"id\", assignTo.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"task\", taskJSON);\n requestJSON.add(\"assign_to\", assignToJSON);\n\n URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTaskAssignment addedAssignment = new BoxTaskAssignment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedAssignment.new Info(responseJSON);\n }",
"@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}",
"public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private Widget setStyle(Widget widget) {\n\n widget.setWidth(m_width);\n widget.getElement().getStyle().setDisplay(Display.INLINE_BLOCK);\n return widget;\n }",
"public static String getFlowContext() {\n TransactionLogger instance = getInstance();\n if (instance == null) {\n return null;\n }\n\n return instance.flowContext;\n }"
] |
return a prepared DELETE Statement fitting for the given ClassDescriptor | [
"public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }"
] | [
"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 }",
"private void readProjectProperties(Project ganttProject)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(ganttProject.getName());\n mpxjProperties.setCompany(ganttProject.getCompany());\n mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS);\n\n String locale = ganttProject.getLocale();\n if (locale == null)\n {\n locale = \"en_US\";\n }\n m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale));\n }",
"public static <T> T get(String key, Class<T> clz) {\n return (T)m().get(key);\n }",
"private String formatAccrueType(AccrueType type)\n {\n return (type == null ? null : LocaleData.getStringArray(m_locale, LocaleData.ACCRUE_TYPES)[type.getValue() - 1]);\n }",
"private org.apache.log4j.Logger getLogger()\r\n\t{\r\n /*\r\n Logger interface extends Serializable, thus Log field is\r\n declared 'transient' and we have to null-check\r\n\t\t*/\r\n\t\tif (logger == null)\r\n\t\t{\r\n\t\t\tlogger = org.apache.log4j.Logger.getLogger(name);\r\n\t\t}\r\n\t\treturn logger;\r\n\t}",
"public static linkset[] get(nitro_service service) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tlinkset[] response = (linkset[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public void restore(String state) {\n JsonObject json = JsonObject.readFrom(state);\n String accessToken = json.get(\"accessToken\").asString();\n String refreshToken = json.get(\"refreshToken\").asString();\n long lastRefresh = json.get(\"lastRefresh\").asLong();\n long expires = json.get(\"expires\").asLong();\n String userAgent = json.get(\"userAgent\").asString();\n String tokenURL = json.get(\"tokenURL\").asString();\n String baseURL = json.get(\"baseURL\").asString();\n String baseUploadURL = json.get(\"baseUploadURL\").asString();\n boolean autoRefresh = json.get(\"autoRefresh\").asBoolean();\n int maxRequestAttempts = json.get(\"maxRequestAttempts\").asInt();\n\n this.accessToken = accessToken;\n this.refreshToken = refreshToken;\n this.lastRefresh = lastRefresh;\n this.expires = expires;\n this.userAgent = userAgent;\n this.tokenURL = tokenURL;\n this.baseURL = baseURL;\n this.baseUploadURL = baseUploadURL;\n this.autoRefresh = autoRefresh;\n this.maxRequestAttempts = maxRequestAttempts;\n }",
"public MediaType copyQualityValue(MediaType mediaType) {\n\t\tif (!mediaType.parameters.containsKey(PARAM_QUALITY_FACTOR)) {\n\t\t\treturn this;\n\t\t}\n\t\tMap<String, String> params = new LinkedHashMap<String, String>(this.parameters);\n\t\tparams.put(PARAM_QUALITY_FACTOR, mediaType.parameters.get(PARAM_QUALITY_FACTOR));\n\t\treturn new MediaType(this, params);\n\t}",
"@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }"
] |
Internal function that uses recursion to create the list | [
"private static void createList( int data[], int k , int level , List<int[]> ret )\n {\n data[k] = level;\n\n if( level < data.length-1 ) {\n for( int i = 0; i < data.length; i++ ) {\n if( data[i] == -1 ) {\n createList(data,i,level+1,ret);\n }\n }\n } else {\n int []copy = new int[data.length];\n System.arraycopy(data,0,copy,0,data.length);\n ret.add(copy);\n }\n data[k] = -1;\n }"
] | [
"public void close() {\n boolean isPreviouslyClosed = isClosed.getAndSet(true);\n if (isPreviouslyClosed) {\n return;\n }\n\n AdminClient client;\n while ((client = clientCache.poll()) != null) {\n client.close();\n }\n }",
"public void visitParameter(String name, int access) {\n if (mv != null) {\n mv.visitParameter(name, access);\n }\n }",
"@Override\r\n\tpublic String toHexString(boolean with0xPrefix) { \r\n\t\tString result;\r\n\t\tif(hasNoStringCache() || (result = (with0xPrefix ? stringCache.hexStringPrefixed : stringCache.hexString)) == null) {\r\n\t\t\tresult = toHexString(with0xPrefix, null);\r\n\t\t\tif(with0xPrefix) {\r\n\t\t\t\tstringCache.hexStringPrefixed = result;\r\n\t\t\t} else {\r\n\t\t\t\tstringCache.hexString = result;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"public BoxFolder.Info restoreFolder(String folderID) {\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"\", \"\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }",
"private void writeResources()\n {\n Resources resources = m_factory.createResources();\n m_plannerProject.setResources(resources);\n List<net.sf.mpxj.planner.schema.Resource> resourceList = resources.getResource();\n for (Resource mpxjResource : m_projectFile.getResources())\n {\n net.sf.mpxj.planner.schema.Resource plannerResource = m_factory.createResource();\n resourceList.add(plannerResource);\n writeResource(mpxjResource, plannerResource);\n }\n }",
"public ActivityCodeValue addValue(Integer uniqueID, String name, String description)\n {\n ActivityCodeValue value = new ActivityCodeValue(this, uniqueID, name, description);\n m_values.add(value);\n return value;\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformDetail> getLoadedDetails() {\n ensureRunning();\n if (!isFindingDetails()) {\n throw new IllegalStateException(\"WaveformFinder is not configured to find waveform details.\");\n }\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformDetail>(detailHotCache));\n }",
"public DbLicense getLicense(final String name) {\n final DbLicense license = repoHandler.getLicense(name);\n\n if (license == null) {\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"License \" + name + \" does not exist.\").build());\n }\n\n return license;\n }",
"public static void isManagementResourceRemoveable(OperationContext context, PathAddress otherManagementEndpoint) throws OperationFailedException {\n ModelNode remotingConnector;\n try {\n remotingConnector = context.readResourceFromRoot(\n PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, \"jmx\"), PathElement.pathElement(\"remoting-connector\", \"jmx\")), false).getModel();\n } catch (Resource.NoSuchResourceException ex) {\n return;\n }\n if (!remotingConnector.hasDefined(USE_MGMT_ENDPOINT) ||\n (remotingConnector.hasDefined(USE_MGMT_ENDPOINT) && context.resolveExpressions(remotingConnector.get(USE_MGMT_ENDPOINT)).asBoolean(true))) {\n try {\n context.readResourceFromRoot(otherManagementEndpoint, false);\n } catch (NoSuchElementException ex) {\n throw RemotingLogger.ROOT_LOGGER.couldNotRemoveResource(context.getCurrentAddress());\n }\n }\n }"
] |
Use this API to fetch lbvserver resource of given name . | [
"public static lbvserver get(nitro_service service, String name) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\tobj.set_name(name);\n\t\tlbvserver response = (lbvserver) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static auditmessages[] get(nitro_service service) throws Exception{\n\t\tauditmessages obj = new auditmessages();\n\t\tauditmessages[] response = (auditmessages[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private OperationResponse executeForResult(final OperationExecutionContext executionContext) throws IOException {\n try {\n return execute(executionContext).get();\n } catch(Exception e) {\n throw new IOException(e);\n }\n }",
"private void readHours(ProjectCalendar calendar, Day day, Integer hours)\n {\n int value = hours.intValue();\n int startHour = 0;\n ProjectCalendarHours calendarHours = null;\n\n Calendar cal = DateHelper.popCalendar();\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n\n calendar.setWorkingDay(day, false);\n\n while (value != 0)\n {\n // Move forward until we find a working hour\n while (startHour < 24 && (value & 0x1) == 0)\n {\n value = value >> 1;\n ++startHour;\n }\n\n // No more working hours, bail out\n if (startHour >= 24)\n {\n break;\n }\n\n // Move forward until we find the end of the working hours\n int endHour = startHour;\n while (endHour < 24 && (value & 0x1) != 0)\n {\n value = value >> 1;\n ++endHour;\n }\n\n cal.set(Calendar.HOUR_OF_DAY, startHour);\n Date startDate = cal.getTime();\n cal.set(Calendar.HOUR_OF_DAY, endHour);\n Date endDate = cal.getTime();\n\n if (calendarHours == null)\n {\n calendarHours = calendar.addCalendarHours(day);\n calendar.setWorkingDay(day, true);\n }\n calendarHours.addRange(new DateRange(startDate, endDate));\n startHour = endHour;\n }\n \n DateHelper.pushCalendar(cal);\n }",
"@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 }",
"protected static int calculateShift(int minimumValue, int maximumValue) {\n\t\tint shift = 0;\n\t\tint value = 1;\n\t\twhile (value < minimumValue && value < maximumValue) {\n\t\t\tvalue <<= 1;\n\t\t\tshift++;\n\t\t}\n\t\treturn shift;\n\t}",
"public AddonChange addAddon(String appName, String addonName) {\n return connection.execute(new AddonInstall(appName, addonName), apiKey);\n }",
"public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }",
"public static int restrictRange(int value, int min, int max)\n {\n return Math.min((Math.max(value, min)), max);\n }",
"public static final void setBounds(UIObject o, Rect bounds) {\n setPosition(o, bounds);\n setSize(o, bounds);\n }"
] |
Set the week of month.
@param weekOfMonthStr the week of month to set. | [
"public void setWeekOfMonth(String weekOfMonthStr) {\n\n final WeekOfMonth weekOfMonth = WeekOfMonth.valueOf(weekOfMonthStr);\n if ((null == m_model.getWeekOfMonth()) || !m_model.getWeekOfMonth().equals(weekOfMonth)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekOfMonth(weekOfMonth);\n onValueChange();\n }\n });\n }\n\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 final Object getRealObject(Object objectOrProxy)\r\n {\r\n if(isNormalOjbProxy(objectOrProxy))\r\n {\r\n String msg;\r\n\r\n try\r\n {\r\n return getIndirectionHandler(objectOrProxy).getRealSubject();\r\n }\r\n catch(ClassCastException e)\r\n {\r\n // shouldn't happen but still ...\r\n msg = \"The InvocationHandler for the provided Proxy was not an instance of \" + IndirectionHandler.class.getName();\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(IllegalArgumentException e)\r\n {\r\n msg = \"Could not retrieve real object for given Proxy: \" + objectOrProxy;\r\n log.error(msg);\r\n throw new PersistenceBrokerException(msg, e);\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for given Proxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else if(isVirtualOjbProxy(objectOrProxy))\r\n {\r\n try\r\n {\r\n return ((VirtualProxy) objectOrProxy).getRealSubject();\r\n }\r\n catch(PersistenceBrokerException e)\r\n {\r\n log.error(\"Could not retrieve real object for VirtualProxy: \" + objectOrProxy);\r\n throw e;\r\n }\r\n }\r\n else\r\n {\r\n return objectOrProxy;\r\n }\r\n }",
"final void waitForSizeQueue(final int queueSize) {\n synchronized (this.queue) {\n while (this.queue.size() > queueSize) {\n try {\n this.queue.wait(250L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n this.queue.notifyAll();\n }\n }",
"public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\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 }",
"public static String generateQuery(final String key, final Object value) {\n\t\tfinal Map<String, Object> params = new HashMap<>();\n\t\tparams.put(key, value);\n\t\treturn generateQuery(params);\n\t}",
"protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}",
"public void setShortAttribute(String name, Short value) {\n\t\tensureValue();\n\t\tAttribute attribute = new ShortAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"private void writeExceptions9(List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n for (ProjectCalendarException exception : exceptions)\n {\n boolean working = exception.getWorking();\n\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BIGINTEGER_ZERO);\n day.setDayWorking(Boolean.valueOf(working));\n\n Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod period = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayTimePeriod();\n day.setTimePeriod(period);\n period.setFromDate(exception.getFromDate());\n period.setToDate(exception.getToDate());\n\n if (working)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes();\n day.setWorkingTimes(times);\n List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();\n\n for (DateRange range : exception)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }"
] |
Adds the basic sentence.
@param s the s
@throws ParseException the parse exception | [
"public void addBasicSentence(MtasCQLParserBasicSentenceCondition s)\n throws ParseException {\n if (!simplified) {\n List<MtasCQLParserBasicSentencePartCondition> newWordList = s\n .getPartList();\n partList.addAll(newWordList);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }"
] | [
"private List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }",
"public String getResourceFilename() {\n switch (resourceType) {\n case ANDROID_ASSETS:\n return assetPath\n .substring(assetPath.lastIndexOf(File.separator) + 1);\n\n case ANDROID_RESOURCE:\n return resourceFilePath.substring(\n resourceFilePath.lastIndexOf(File.separator) + 1);\n\n case LINUX_FILESYSTEM:\n return filePath.substring(filePath.lastIndexOf(File.separator) + 1);\n\n case NETWORK:\n return url.getPath().substring(url.getPath().lastIndexOf(\"/\") + 1);\n\n case INPUT_STREAM:\n return inputStreamName;\n\n default:\n return null;\n }\n }",
"public int getFixedDataOffset(FieldType type)\n {\n int result;\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFixedDataOffset();\n }\n else\n {\n result = -1;\n }\n return result;\n }",
"@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Creatable<? extends Indexable> creatable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) creatable;\n return this.addPostRunDependent(dependency);\n }",
"int cancel(int downloadId) {\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tfor (DownloadRequest request : mCurrentRequests) {\n\t\t\t\tif (request.getDownloadId() == downloadId) {\n\t\t\t\t\trequest.cancel();\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}",
"private void writeWBS(Task mpxj)\n {\n if (mpxj.getUniqueID().intValue() != 0)\n {\n WBSType xml = m_factory.createWBSType();\n m_project.getWBS().add(xml);\n String code = mpxj.getWBS();\n code = code == null || code.length() == 0 ? DEFAULT_WBS_CODE : code;\n\n Task parentTask = mpxj.getParentTask();\n Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();\n\n xml.setCode(code);\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setName(mpxj.getName());\n\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(parentObjectID);\n xml.setProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSequenceNumber(Integer.valueOf(m_wbsSequence++));\n\n xml.setStatus(\"Active\");\n }\n\n writeChildTasks(mpxj);\n }",
"private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) {\n\t\tif (fieldType.isEscapedDefaultValue()) {\n\t\t\tappendEscapedWord(sb, defaultValue.toString());\n\t\t} else {\n\t\t\tsb.append(defaultValue);\n\t\t}\n\t}",
"public static String eachMatch(String self, String regex, @ClosureParams(value=FromString.class, options={\"List<String>\",\"String[]\"}) Closure closure) {\n return eachMatch(self, Pattern.compile(regex), closure);\n }",
"public void copyNodeMetaData(ASTNode other) {\n if (other.metaDataMap == null) {\n return;\n }\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n metaDataMap.putAll(other.metaDataMap);\n }"
] |
Split an artifact gavc to get the groupId
@param gavc
@return String | [
"public static String getGroupId(final String gavc) {\n final int splitter = gavc.indexOf(':');\n if(splitter == -1){\n return gavc;\n }\n return gavc.substring(0, splitter);\n }"
] | [
"public static base_response update(nitro_service client, Interface resource) throws Exception {\n\t\tInterface updateresource = new Interface();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.speed = resource.speed;\n\t\tupdateresource.duplex = resource.duplex;\n\t\tupdateresource.flowctl = resource.flowctl;\n\t\tupdateresource.autoneg = resource.autoneg;\n\t\tupdateresource.hamonitor = resource.hamonitor;\n\t\tupdateresource.tagall = resource.tagall;\n\t\tupdateresource.trunk = resource.trunk;\n\t\tupdateresource.lacpmode = resource.lacpmode;\n\t\tupdateresource.lacpkey = resource.lacpkey;\n\t\tupdateresource.lagtype = resource.lagtype;\n\t\tupdateresource.lacppriority = resource.lacppriority;\n\t\tupdateresource.lacptimeout = resource.lacptimeout;\n\t\tupdateresource.ifalias = resource.ifalias;\n\t\tupdateresource.throughput = resource.throughput;\n\t\tupdateresource.bandwidthhigh = resource.bandwidthhigh;\n\t\tupdateresource.bandwidthnormal = resource.bandwidthnormal;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public void processSplitData(Task task, List<TimephasedWork> timephasedComplete, List<TimephasedWork> timephasedPlanned)\n {\n Date splitsComplete = null;\n TimephasedWork lastComplete = null;\n TimephasedWork firstPlanned = null;\n if (!timephasedComplete.isEmpty())\n {\n lastComplete = timephasedComplete.get(timephasedComplete.size() - 1);\n splitsComplete = lastComplete.getFinish();\n }\n\n if (!timephasedPlanned.isEmpty())\n {\n firstPlanned = timephasedPlanned.get(0);\n }\n\n LinkedList<DateRange> splits = new LinkedList<DateRange>();\n TimephasedWork lastAssignment = null;\n DateRange lastRange = null;\n for (TimephasedWork assignment : timephasedComplete)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n splits.add(lastRange);\n lastAssignment = assignment;\n }\n\n //\n // We may not have a split, we may just have a partially\n // complete split.\n //\n Date splitStart = null;\n if (lastComplete != null && firstPlanned != null && lastComplete.getTotalAmount().getDuration() != 0 && firstPlanned.getTotalAmount().getDuration() != 0)\n {\n lastRange = splits.removeLast();\n splitStart = lastRange.getStart();\n }\n\n lastAssignment = null;\n lastRange = null;\n for (TimephasedWork assignment : timephasedPlanned)\n {\n if (splitStart == null)\n {\n if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)\n {\n splits.removeLast();\n lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());\n }\n else\n {\n lastRange = new DateRange(assignment.getStart(), assignment.getFinish());\n }\n }\n else\n {\n lastRange = new DateRange(splitStart, assignment.getFinish());\n }\n splits.add(lastRange);\n splitStart = null;\n lastAssignment = assignment;\n }\n\n //\n // We must have a minimum of 3 entries for this to be a valid split task\n //\n if (splits.size() > 2)\n {\n task.getSplits().addAll(splits);\n task.setSplitCompleteDuration(splitsComplete);\n }\n else\n {\n task.setSplits(null);\n task.setSplitCompleteDuration(null);\n }\n }",
"public void readTags(InputStream tagsXML)\n {\n SAXParserFactory factory = SAXParserFactory.newInstance();\n try\n {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(tagsXML, new TagsSaxHandler(this));\n }\n catch (ParserConfigurationException | SAXException | IOException ex)\n {\n throw new RuntimeException(\"Failed parsing the tags definition: \" + ex.getMessage(), ex);\n }\n }",
"public PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }",
"private String appendXmlStartTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"<\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }",
"private void countKey(Map<String, Integer> map, String key, int count) {\n\t\tif (map.containsKey(key)) {\n\t\t\tmap.put(key, map.get(key) + count);\n\t\t} else {\n\t\t\tmap.put(key, count);\n\t\t}\n\t}",
"public Where<T, ID> or() {\n\t\tManyClause clause = new ManyClause(pop(\"OR\"), ManyClause.OR_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}",
"public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }",
"public void login(Object userIdentifier) {\n session().put(config().sessionKeyUsername(), userIdentifier);\n app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));\n }"
] |
Get the bar size.
@param settings Parameters for rendering the scalebar. | [
"@VisibleForTesting\n protected static int getBarSize(final ScaleBarRenderSettings settings) {\n if (settings.getParams().barSize != null) {\n return settings.getParams().barSize;\n } else {\n if (settings.getParams().getOrientation().isHorizontal()) {\n return settings.getMaxSize().height / 4;\n } else {\n return settings.getMaxSize().width / 4;\n }\n }\n }"
] | [
"public boolean hasProperties(Set<PropertyKey> keys) {\n for (PropertyKey key : keys) {\n if (null == getProperty(key.m_key)) {\n return false;\n }\n }\n \n return true;\n }",
"private Set<String> findResourceNamesFromFileSystem(String classPathRootOnDisk, String scanRootLocation, File folder) {\n LOGGER.debug(\"Scanning for resources in path: {} ({})\", folder.getPath(), scanRootLocation);\n\n File[] files = folder.listFiles();\n if (files == null) {\n return emptySet();\n }\n\n Set<String> resourceNames = new TreeSet<>();\n\n for (File file : files) {\n if (file.canRead()) {\n if (file.isDirectory()) {\n resourceNames.addAll(findResourceNamesFromFileSystem(classPathRootOnDisk, scanRootLocation, file));\n } else {\n resourceNames.add(toResourceNameOnClasspath(classPathRootOnDisk, file));\n }\n }\n }\n\n return resourceNames;\n }",
"public static float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }",
"protected void postConnection(ConnectionHandle handle, long statsObtainTime){\r\n\r\n\t\thandle.renewConnection(); // mark it as being logically \"open\"\r\n\r\n\t\t// Give an application a chance to do something with it.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onCheckOut(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.closeConnectionWatch){ // a debugging tool\r\n\t\t\tthis.pool.watchConnection(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tthis.pool.statistics.addCumulativeConnectionWaitTime(System.nanoTime()-statsObtainTime);\r\n\t\t}\r\n\t}",
"public static double Cosh(double x, int nTerms) {\r\n if (nTerms < 2) return x;\r\n if (nTerms == 2) {\r\n return 1 + (x * x) / 2D;\r\n } else {\r\n\r\n double mult = x * x;\r\n double fact = 2;\r\n int factS = 4;\r\n double result = 1 + mult / fact;\r\n for (int i = 3; i <= nTerms; i++) {\r\n mult *= x * x;\r\n fact *= factS * (factS - 1);\r\n factS += 2;\r\n result += mult / fact;\r\n }\r\n\r\n return result;\r\n }\r\n }",
"public String getArtifactLastVersion(final String gavc) {\n final List<String> versions = getArtifactVersions(gavc);\n\n final VersionsHandler versionHandler = new VersionsHandler(repositoryHandler);\n final String viaCompare = versionHandler.getLastVersion(versions);\n\n if (viaCompare != null) {\n return viaCompare;\n }\n\n //\n // These versions cannot be compared\n // Let's use the Collection.max() method by default, so goingo for a fallback\n // mechanism.\n //\n LOG.info(\"The versions cannot be compared\");\n return Collections.max(versions);\n\n }",
"public Iterable<BoxItem.Info> getChildren(final String... fields) {\n return new Iterable<BoxItem.Info>() {\n @Override\n public Iterator<BoxItem.Info> iterator() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID());\n return new BoxItemIterator(getAPI(), url);\n }\n };\n }",
"protected String getDBManipulationUrl()\r\n {\r\n JdbcConnectionDescriptor jcd = getConnection();\r\n\r\n return jcd.getProtocol()+\":\"+jcd.getSubProtocol()+\":\"+jcd.getDbAlias();\r\n }",
"private String visibility(Options opt, ProgramElementDoc e) {\n\treturn opt.showVisibility ? Visibility.get(e).symbol : \" \";\n }"
] |
Retrieve row from a nested table.
@param name column name
@return nested table rows | [
"@SuppressWarnings(\"unchecked\") public final List<MapRow> getRows(String name)\n {\n return (List<MapRow>) getObject(name);\n }"
] | [
"public static sslcertkey get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey obj = new sslcertkey();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey response = (sslcertkey) obj.get_resource(service);\n\t\treturn response;\n\t}",
"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 }",
"@SuppressWarnings(\"rawtypes\")\n\tprivate MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) {\n\t\treturn Mail.imapInboundAdapter(urlName.toString())\n\t\t\t\t.shouldMarkMessagesAsRead(this.properties.isMarkAsRead());\n\t}",
"public void setSeed(String randomSeed) {\n if (!Strings.isNullOrEmpty(getProject().getUserProperty(SYSPROP_RANDOM_SEED()))) {\n String userProperty = getProject().getUserProperty(SYSPROP_RANDOM_SEED());\n if (!userProperty.equals(randomSeed)) {\n log(\"Ignoring seed attribute because it is overridden by user properties.\", Project.MSG_WARN);\n }\n } else if (!Strings.isNullOrEmpty(randomSeed)) {\n this.random = randomSeed;\n }\n }",
"public static final Integer parseMinutesFromHours(String value)\n {\n Integer result = null;\n if (value != null)\n {\n result = Integer.valueOf(Integer.parseInt(value) * 60);\n }\n return result;\n }",
"protected void addStatement(Statement statement, boolean isNew) {\n\t\tPropertyIdValue pid = statement.getMainSnak().getPropertyId();\n\n\t\t// This code maintains the following properties:\n\t\t// (1) the toKeep structure does not contain two statements with the\n\t\t// same statement id\n\t\t// (2) the toKeep structure does not contain two statements that can\n\t\t// be merged\n\t\tif (this.toKeep.containsKey(pid)) {\n\t\t\tList<StatementWithUpdate> statements = this.toKeep.get(pid);\n\t\t\tfor (int i = 0; i < statements.size(); i++) {\n\t\t\t\tStatement currentStatement = statements.get(i).statement;\n\t\t\t\tboolean currentIsNew = statements.get(i).write;\n\n\t\t\t\tif (!\"\".equals(currentStatement.getStatementId())\n\t\t\t\t\t\t&& currentStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t// Same, non-empty id: ignore existing statement as if\n\t\t\t\t\t// deleted\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tStatement newStatement = mergeStatements(statement,\n\t\t\t\t\t\tcurrentStatement);\n\t\t\t\tif (newStatement != null) {\n\t\t\t\t\tboolean writeNewStatement = (isNew || !newStatement\n\t\t\t\t\t\t\t.equals(statement))\n\t\t\t\t\t\t\t&& (currentIsNew || !newStatement\n\t\t\t\t\t\t\t\t\t.equals(currentStatement));\n\t\t\t\t\t// noWrite: (newS == statement && !isNew)\n\t\t\t\t\t// || (newS == cur && !curIsNew)\n\t\t\t\t\t// Write: (newS != statement || isNew )\n\t\t\t\t\t// && (newS != cur || curIsNew)\n\n\t\t\t\t\tstatements.set(i, new StatementWithUpdate(newStatement,\n\t\t\t\t\t\t\twriteNewStatement));\n\n\t\t\t\t\t// Impossible with default merge code:\n\t\t\t\t\t// Kept here for future extensions that may choose to not\n\t\t\t\t\t// reuse this id.\n\t\t\t\t\tif (!\"\".equals(statement.getStatementId())\n\t\t\t\t\t\t\t&& !newStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\t\tstatement.getStatementId())) {\n\t\t\t\t\t\tthis.toDelete.add(statement.getStatementId());\n\t\t\t\t\t}\n\t\t\t\t\tif (!\"\".equals(currentStatement.getStatementId())\n\t\t\t\t\t\t\t&& !newStatement.getStatementId().equals(\n\t\t\t\t\t\t\t\t\tcurrentStatement.getStatementId())) {\n\t\t\t\t\t\tthis.toDelete.add(currentStatement.getStatementId());\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatements.add(new StatementWithUpdate(statement, isNew));\n\t\t} else {\n\t\t\tList<StatementWithUpdate> statements = new ArrayList<>();\n\t\t\tstatements.add(new StatementWithUpdate(statement, isNew));\n\t\t\tthis.toKeep.put(pid, statements);\n\t\t}\n\t}",
"private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n config.setAutoWBS(false);\n config.setAutoOutlineNumber(false);\n\n m_project.getProjectProperties().setFileApplication(\"FastTrack\");\n m_project.getProjectProperties().setFileType(\"FTS\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n // processProject();\n // processCalendars();\n processResources();\n processTasks();\n processDependencies();\n processAssignments();\n\n return m_project;\n }",
"private static void setupFlowId(SoapMessage message) {\n String flowId = FlowIdHelper.getFlowId(message);\n\n if (flowId == null) {\n flowId = FlowIdProtocolHeaderCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n flowId = FlowIdSoapCodec.readFlowId(message);\n }\n\n if (flowId == null) {\n Exchange ex = message.getExchange();\n if (null!=ex){\n Message reqMsg = ex.getOutMessage();\n if ( null != reqMsg) {\n flowId = FlowIdHelper.getFlowId(reqMsg);\n }\n }\n }\n\n if (flowId != null && !flowId.isEmpty()) {\n FlowIdHelper.setFlowId(message, flowId);\n }\n }",
"public LatLong getDestinationPoint(double bearing, double distance) {\n\n double brng = Math.toRadians(bearing);\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n\n double lat2 = Math.asin(Math.sin(lat1)\n * Math.cos(distance / EarthRadiusMeters)\n + Math.cos(lat1) * Math.sin(distance / EarthRadiusMeters)\n * Math.cos(brng));\n\n double lon2 = lon1 + Math.atan2(Math.sin(brng)\n * Math.sin(distance / EarthRadiusMeters) * Math.cos(lat1),\n Math.cos(distance / EarthRadiusMeters)\n - Math.sin(lat1) * Math.sin(lat2));\n\n return new LatLong(Math.toDegrees(lat2), Math.toDegrees(lon2));\n\n }"
] |
Set the value for a floating point vector of length 3.
@param key name of uniform to set.
@param x new X value
@param y new Y value
@param z new Z value
@see #getVec3
@see #getFloatVec(String) | [
"public void setVec3(String key, float x, float y, float z)\n {\n checkKeyIsUniform(key);\n NativeLight.setVec3(getNative(), key, x, y, z);\n }"
] | [
"public List<EndpointOverride> getPaths(int profileId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EndpointOverride> properties = new ArrayList<EndpointOverride>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_PROFILE_ID + \"=? \" +\n \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\";\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n statement.setInt(2, profileId);\n\n results = statement.executeQuery();\n while (results.next()) {\n EndpointOverride endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\n properties.add(endpoint);\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 properties;\n }",
"public List<Object> stepsInstances(List<CandidateSteps> candidateSteps) {\n List<Object> instances = new ArrayList<>();\n for (CandidateSteps steps : candidateSteps) {\n if (steps instanceof Steps) {\n instances.add(((Steps) steps).instance());\n }\n }\n return instances;\n }",
"public static<A, Z> Function1<A, Z> lift(Func1<A, Z> f) {\n\treturn bridge.lift(f);\n }",
"@Override\n public PmdRuleSet create() {\n final SAXBuilder parser = new SAXBuilder();\n final Document dom;\n try {\n dom = parser.build(source);\n } catch (JDOMException | IOException e) {\n if (messages != null) {\n messages.addErrorText(INVALID_INPUT + \" : \" + e.getMessage());\n }\n LOG.error(INVALID_INPUT, e);\n return new PmdRuleSet();\n }\n\n final Element eltResultset = dom.getRootElement();\n final Namespace namespace = eltResultset.getNamespace();\n final PmdRuleSet result = new PmdRuleSet();\n\n final String name = eltResultset.getAttributeValue(\"name\");\n final Element descriptionElement = getChild(eltResultset, namespace);\n\n result.setName(name);\n\n if (descriptionElement != null) {\n result.setDescription(descriptionElement.getValue());\n }\n\n for (Element eltRule : getChildren(eltResultset, \"rule\", namespace)) {\n PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue(\"ref\"));\n pmdRule.setClazz(eltRule.getAttributeValue(\"class\"));\n pmdRule.setName(eltRule.getAttributeValue(\"name\"));\n pmdRule.setMessage(eltRule.getAttributeValue(\"message\"));\n parsePmdPriority(eltRule, pmdRule, namespace);\n parsePmdProperties(eltRule, pmdRule, namespace);\n result.addRule(pmdRule);\n }\n return result;\n }",
"public static <T> boolean addAll(Collection<T> self, Iterator<T> items) {\n boolean changed = false;\n while (items.hasNext()) {\n T next = items.next();\n if (self.add(next)) changed = true;\n }\n return changed;\n }",
"public AsciiTable setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public void setModelByText(String model) {\r\n try {\r\n InputStream is = new ByteArrayInputStream(model.getBytes());\r\n this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions());\r\n this.setStateMachine(this.model);\r\n } catch (IOException | SAXException | ModelException e) {\r\n e.printStackTrace();\r\n }\r\n }",
"public ListResponse listTemplates(Map<String, Object> options)\n throws RequestException, LocalOperationException {\n Request request = new Request(this);\n return new ListResponse(request.get(\"/templates\", options));\n }",
"public String processIndexDescriptor(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n IndexDescriptorDef indexDef = _curClassDef.getIndexDescriptor(name);\r\n String attrName;\r\n \r\n if (indexDef == null)\r\n { \r\n indexDef = new IndexDescriptorDef(name);\r\n _curClassDef.addIndexDescriptor(indexDef);\r\n }\r\n\r\n if ((indexDef.getName() == null) || (indexDef.getName().length() == 0))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_NAME_MISSING,\r\n new String[]{_curClassDef.getName()}));\r\n }\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n indexDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }"
] |
Return a public static method of a class.
@param methodName the static method name
@param clazz the class which defines the method
@param args the parameter types to the method
@return the static method, or {@code null} if no static method was found
@throws IllegalArgumentException if the method name is blank or the clazz is null | [
"public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {\n\t\tAssert.notNull(clazz, \"Class must not be null\");\n\t\tAssert.notNull(methodName, \"Method name must not be null\");\n\t\ttry {\n\t\t\tMethod method = clazz.getMethod(methodName, args);\n\t\t\treturn Modifier.isStatic(method.getModifiers()) ? method : null;\n\t\t}\n\t\tcatch (NoSuchMethodException ex) {\n\t\t\treturn null;\n\t\t}\n\t}"
] | [
"public static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\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 }",
"public static <T> Set<T> asSet(T[] o) {\r\n return new HashSet<T>(Arrays.asList(o));\r\n }",
"private void setPlaying(boolean playing) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.playing != playing) {\n setPlaybackState(oldState.player, oldState.position, playing);\n }\n }",
"public String addressPath() {\n if (isLeaf) {\n ManagementModelNode parent = (ManagementModelNode)getParent();\n return parent.addressPath();\n }\n\n StringBuilder builder = new StringBuilder();\n for (Object pathElement : getUserObjectPath()) {\n UserObject userObj = (UserObject)pathElement;\n if (userObj.isRoot()) { // don't want to escape root\n builder.append(userObj.getName());\n continue;\n }\n\n builder.append(userObj.getName());\n builder.append(\"=\");\n builder.append(userObj.getEscapedValue());\n builder.append(\"/\");\n }\n\n return builder.toString();\n }",
"public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }",
"public void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }",
"public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {\n // Evaluate the target filter of the ImporterService on the Declaration\n Filter filter = bindersManager.getTargetFilter(declarationBinderRef);\n return filter.matches(declaration.getMetadata());\n }",
"private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }"
] |
Parses the list of query items for the query facet.
@param queryFacetObject JSON object representing the node with the query facet.
@return list of query options
@throws JSONException if the list cannot be parsed. | [
"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 static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException {\n\n try {\n channel.position(startEndRecord);\n\n final ByteBuffer endDirHeader = getByteBuffer(ENDLEN);\n read(endDirHeader, channel);\n if (endDirHeader.limit() < ENDLEN) {\n // Couldn't read the full end of central directory record header\n return false;\n } else if (getUnsignedInt(endDirHeader, 0) != endSig) {\n return false;\n }\n\n long pos = getUnsignedInt(endDirHeader, END_CENSTART);\n // TODO deal with Zip64\n if (pos == ZIP64_MARKER) {\n return false;\n }\n\n ByteBuffer cdfhBuffer = getByteBuffer(CENLEN);\n read(cdfhBuffer, channel, pos);\n long header = getUnsignedInt(cdfhBuffer, 0);\n if (header == CENSIG) {\n long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET);\n long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ);\n if (firstLoc == 0) {\n // normal case -- first bytes are the first local file\n if (!validateLocalFileRecord(channel, 0, firstSize)) {\n return false;\n }\n } else {\n // confirm that firstLoc is indeed the first local file\n long fileFirstLoc = scanForLocSig(channel);\n if (firstLoc != fileFirstLoc) {\n if (fileFirstLoc == 0) {\n return false;\n } else {\n // scanForLocSig() found a LOCSIG, but not at position zero and not\n // at the expected position.\n // With a file like this, we can't tell if we're in a nested zip\n // or we're in an outer zip and had the bad luck to find random bytes\n // that look like LOCSIG.\n return false;\n }\n }\n }\n\n // At this point, endDirHeader points to the correct end of central dir record.\n // Just need to validate the record is complete, including any comment\n int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN);\n long commentEnd = startEndRecord + ENDLEN + commentLen;\n return commentEnd <= channel.size();\n }\n\n return false;\n } catch (EOFException eof) {\n // pos or firstLoc weren't really positions and moved us to an invalid location\n return false;\n }\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public static synchronized SlotReference getSlotReference(int player, CdjStatus.TrackSourceSlot slot) {\n Map<CdjStatus.TrackSourceSlot, SlotReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<CdjStatus.TrackSourceSlot, SlotReference>();\n instances.put(player, playerMap);\n }\n SlotReference result = playerMap.get(slot);\n if (result == null) {\n result = new SlotReference(player, slot);\n playerMap.put(slot, result);\n }\n return result;\n }",
"protected I_CmsSearchConfigurationFacetField parseFieldFacet(final String pathPrefix) {\n\n try {\n final String field = parseMandatoryStringValue(pathPrefix + XML_ELEMENT_FACET_FIELD);\n final String name = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_NAME);\n final String label = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_LABEL);\n final Integer minCount = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_MINCOUNT);\n final Integer limit = parseOptionalIntValue(pathPrefix + XML_ELEMENT_FACET_LIMIT);\n final String prefix = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_PREFIX);\n final String sorder = parseOptionalStringValue(pathPrefix + XML_ELEMENT_FACET_ORDER);\n I_CmsSearchConfigurationFacet.SortOrder order;\n try {\n order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder);\n } catch (@SuppressWarnings(\"unused\") final Exception e) {\n order = null;\n }\n final String filterQueryModifier = parseOptionalStringValue(\n pathPrefix + XML_ELEMENT_FACET_FILTERQUERYMODIFIER);\n final Boolean isAndFacet = parseOptionalBooleanValue(pathPrefix + XML_ELEMENT_FACET_ISANDFACET);\n final List<String> preselection = parseOptionalStringValues(pathPrefix + XML_ELEMENT_FACET_PRESELECTION);\n final Boolean ignoreAllFacetFilters = parseOptionalBooleanValue(\n pathPrefix + XML_ELEMENT_FACET_IGNOREALLFACETFILTERS);\n return new CmsSearchConfigurationFacetField(\n field,\n name,\n minCount,\n limit,\n prefix,\n label,\n order,\n filterQueryModifier,\n isAndFacet,\n preselection,\n ignoreAllFacetFilters);\n } catch (final Exception e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1,\n XML_ELEMENT_FACET_FIELD),\n e);\n return null;\n }\n }",
"private static ModelNode createOperation(final ModelNode operationToValidate) {\n PathAddress pa = PathAddress.pathAddress(operationToValidate.require(OP_ADDR));\n PathAddress validationAddress = pa.subAddress(0, pa.size() - 1);\n\n return Util.getEmptyOperation(\"validate-cache\", validationAddress.toModelNode());\n }",
"@NonNull\n @Override\n public Loader<SortedList<FtpFile>> getLoader() {\n return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {\n @Override\n public SortedList<FtpFile> loadInBackground() {\n SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {\n @Override\n public int compare(FtpFile lhs, FtpFile rhs) {\n if (lhs.isDirectory() && !rhs.isDirectory()) {\n return -1;\n } else if (rhs.isDirectory() && !lhs.isDirectory()) {\n return 1;\n } else {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n }\n\n @Override\n public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {\n return oldItem.getName().equals(newItem.getName());\n }\n\n @Override\n public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {\n return item1.getName().equals(item2.getName());\n }\n });\n\n\n if (!ftp.isConnected()) {\n // Connect\n try {\n ftp.connect(server, port);\n\n ftp.setFileType(FTP.ASCII_FILE_TYPE);\n ftp.enterLocalPassiveMode();\n ftp.setUseEPSVwithIPv4(false);\n\n if (!(loggedIn = ftp.login(username, password))) {\n ftp.logout();\n Log.e(TAG, \"Login failed\");\n }\n } catch (IOException e) {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException ignored) {\n }\n }\n Log.e(TAG, \"Could not connect to server.\");\n }\n }\n\n if (loggedIn) {\n try {\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n sortedList.beginBatchedUpdates();\n for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {\n FtpFile file;\n if (f.isDirectory()) {\n file = new FtpDir(mCurrentPath, f.getName());\n } else {\n file = new FtpFile(mCurrentPath, f.getName());\n }\n if (isItemVisible(file)) {\n sortedList.add(file);\n }\n }\n sortedList.endBatchedUpdates();\n } catch (IOException e) {\n Log.e(TAG, \"IOException: \" + e.getMessage());\n }\n }\n\n return sortedList;\n }\n\n /**\n * Handles a request to start the Loader.\n */\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n\n // handle if directory does not exist. Fall back to root.\n if (mCurrentPath == null || !mCurrentPath.isDirectory()) {\n mCurrentPath = getRoot();\n }\n\n forceLoad();\n }\n };\n }",
"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 }",
"@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 byte getByte(Integer type)\n {\n byte result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = item[0];\n }\n\n return (result);\n }"
] |
Determines whether or not a given feature matches this pattern.
@param feature
Specified feature to examine.
@return Flag confirming whether or not this feature is inside the filter. | [
"public boolean evaluate(Object feature) {\n\t\t// Checks to ensure that the attribute has been set\n\t\tif (attribute == null) {\n\t\t\treturn false;\n\t\t}\n\t\t// Note that this converts the attribute to a string\n\t\t// for comparison. Unlike the math or geometry filters, which\n\t\t// require specific types to function correctly, this filter\n\t\t// using the mandatory string representation in Java\n\t\t// Of course, this does not guarantee a meaningful result, but it\n\t\t// does guarantee a valid result.\n\t\t// LOGGER.finest(\"pattern: \" + pattern);\n\t\t// LOGGER.finest(\"string: \" + attribute.getValue(feature));\n\t\t// return attribute.getValue(feature).toString().matches(pattern);\n\t\tObject value = attribute.evaluate(feature);\n\n\t\tif (null == value) {\n\t\t\treturn false;\n\t\t}\n\n\t\tMatcher matcher = getMatcher();\n\t\tmatcher.reset(value.toString());\n\n\t\treturn matcher.matches();\n\t}"
] | [
"public B set(String key, int value) {\n this.data.put(key, value);\n return (B) this;\n }",
"public ListenableFuture<Connection> getAsyncConnection(){\r\n\r\n\t\treturn this.asyncExecutor.submit(new Callable<Connection>() {\r\n\r\n\t\t\tpublic Connection call() throws Exception {\r\n\t\t\t\treturn getConnection();\r\n\t\t\t}});\r\n\t}",
"public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_responses update(nitro_service client, ntpserver resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tntpserver updateresources[] = new ntpserver[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new ntpserver();\n\t\t\t\tupdateresources[i].serverip = resources[i].serverip;\n\t\t\t\tupdateresources[i].servername = resources[i].servername;\n\t\t\t\tupdateresources[i].minpoll = resources[i].minpoll;\n\t\t\t\tupdateresources[i].maxpoll = resources[i].maxpoll;\n\t\t\t\tupdateresources[i].preferredntpserver = resources[i].preferredntpserver;\n\t\t\t\tupdateresources[i].autokey = resources[i].autokey;\n\t\t\t\tupdateresources[i].key = resources[i].key;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,\n final Set<String> libraryPaths,\n final Set<String> sourcePaths, Set<Path> sourceFiles)\n {\n\n final String[] encodings = null;\n final String[] bindingKeys = new String[0];\n final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());\n final FileASTRequestor requestor = new FileASTRequestor()\n {\n @Override\n public void acceptAST(String sourcePath, CompilationUnit ast)\n {\n try\n {\n /*\n * This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.\n */\n super.acceptAST(sourcePath, ast);\n ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);\n ast.accept(visitor);\n listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());\n }\n catch (WindupStopException ex)\n {\n throw ex;\n }\n catch (Throwable t)\n {\n listener.failed(Paths.get(sourcePath), t);\n }\n }\n };\n\n List<List<String>> batches = createBatches(sourceFiles);\n\n for (final List<String> batch : batches)\n {\n executor.submit(new Callable<Void>()\n {\n @Override\n public Void call() throws Exception\n {\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n parser.setBindingsRecovery(false);\n parser.setResolveBindings(true);\n Map<String, String> options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n // these options seem to slightly reduce the number of times that JDT aborts on compilation errors\n options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, \"warning\");\n options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, \"warning\");\n options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, \"warning\");\n options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, \"ignore\");\n options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, \"warning\");\n options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, \"warning\");\n options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, \"warning\");\n\n parser.setCompilerOptions(options);\n parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),\n sourcePaths.toArray(new String[sourcePaths.size()]),\n null,\n true);\n\n parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);\n return null;\n }\n });\n }\n\n executor.shutdown();\n\n return new BatchASTFuture()\n {\n @Override\n public boolean isDone()\n {\n return executor.isTerminated();\n }\n };\n }",
"public static String getOperationName(final ModelNode op) {\n if (op.hasDefined(OP)) {\n return op.get(OP).asString();\n }\n throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound();\n }",
"public Version putWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n List<Versioned<V>> versionedValues;\n long startTime = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n logger.debug(\"PUT requested for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + startTime\n + \" . Nested GET and PUT VERSION requests to follow ---\");\n }\n\n // We use the full timeout for doing the Get. In this, we're being\n // optimistic that the subsequent put might be faster such that all the\n // steps might finish within the allotted time\n requestWrapper.setResolveConflicts(true);\n versionedValues = getWithCustomTimeout(requestWrapper);\n Versioned<V> versioned = getItemOrThrow(requestWrapper.getKey(), null, versionedValues);\n\n long endTime = System.currentTimeMillis();\n if(versioned == null)\n versioned = Versioned.value(requestWrapper.getRawValue(), new VectorClock());\n else\n versioned.setObject(requestWrapper.getRawValue());\n\n // This should not happen unless there's a bug in the\n // getWithCustomTimeout\n long timeLeft = requestWrapper.getRoutingTimeoutInMs() - (endTime - startTime);\n if(timeLeft <= 0) {\n throw new StoreTimeoutException(\"PUT request timed out\");\n }\n CompositeVersionedPutVoldemortRequest<K, V> putVersionedRequestObject = new CompositeVersionedPutVoldemortRequest<K, V>(requestWrapper.getKey(),\n versioned,\n timeLeft);\n putVersionedRequestObject.setRequestOriginTimeInMs(requestWrapper.getRequestOriginTimeInMs());\n Version result = putVersionedWithCustomTimeout(putVersionedRequestObject);\n long endTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n logger.debug(\"PUT response received for key: \" + keyHexString + \" , for store: \"\n + this.storeName + \" at time(in ms): \" + endTimeInMs);\n }\n return result;\n }",
"public void bind(T service, Map<String, Object> props) {\n synchronized (serviceMap) {\n serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);\n updateSortedServices();\n }\n }",
"public static base_response unset(nitro_service client, responderparam resource, String[] args) throws Exception{\n\t\tresponderparam unsetresource = new responderparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}"
] |
Returns true if the provided matrix is has a value of 1 along the diagonal
elements and zero along all the other elements.
@param a Matrix being inspected.
@param tol How close to zero or one each element needs to be.
@return If it is within tolerance to an identity matrix. | [
"public static boolean isIdentity(DMatrix a , double tol )\n {\n for( int i = 0; i < a.getNumRows(); i++ ) {\n for( int j = 0; j < a.getNumCols(); j++ ) {\n if( i == j ) {\n if( Math.abs(a.get(i,j)-1.0) > tol )\n return false;\n } else {\n if( Math.abs(a.get(i,j)) > tol )\n return false;\n }\n }\n }\n return true;\n }"
] | [
"final void roll(final long timeForSuffix) {\n\n final File backupFile = this.prepareBackupFile(timeForSuffix);\n\n // close filename\n this.getAppender().closeFile();\n\n // rename filename on disk to filename+suffix(+number)\n this.doFileRoll(this.getAppender().getIoFile(), backupFile);\n\n // setup new file 'filename'\n this.getAppender().openFile();\n\n this.fireFileRollEvent(new FileRollEvent(this, backupFile));\n }",
"private void maybeUpdateScrollbarPositions() {\r\n\r\n if (!isAttached()) {\r\n return;\r\n }\r\n\r\n if (m_scrollbar != null) {\r\n int vPos = getVerticalScrollPosition();\r\n if (m_scrollbar.getVerticalScrollPosition() != vPos) {\r\n m_scrollbar.setVerticalScrollPosition(vPos);\r\n }\r\n }\r\n }",
"protected void processOutlineCodeField(Integer entityID, Row row)\n {\n processField(row, \"OC_FIELD_ID\", entityID, row.getString(\"OC_NAME\"));\n }",
"public static base_responses delete(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 deleteresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new route6();\n\t\t\t\tdeleteresources[i].network = resources[i].network;\n\t\t\t\tdeleteresources[i].gateway = resources[i].gateway;\n\t\t\t\tdeleteresources[i].vlan = resources[i].vlan;\n\t\t\t\tdeleteresources[i].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public void combine(CRFClassifier<IN> crf, double weight) {\r\n Timing timer = new Timing();\r\n\r\n // Check the CRFClassifiers are compatible\r\n if (!this.pad.equals(crf.pad)) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: pad does not match\");\r\n }\r\n if (this.windowSize != crf.windowSize) {\r\n throw new RuntimeException(\"Incompatible CRFClassifier: windowSize does not match\");\r\n }\r\n if (this.labelIndices.length != crf.labelIndices.length) {\r\n // Should match since this should be same as the windowSize\r\n throw new RuntimeException(\"Incompatible CRFClassifier: labelIndices length does not match\");\r\n }\r\n this.classIndex.addAll(crf.classIndex.objectsList());\r\n\r\n // Combine weights of the other classifier with this classifier,\r\n // weighing the other classifier's weights by weight\r\n // First merge the feature indicies\r\n int oldNumFeatures1 = this.featureIndex.size();\r\n int oldNumFeatures2 = crf.featureIndex.size();\r\n int oldNumWeights1 = this.getNumWeights();\r\n int oldNumWeights2 = crf.getNumWeights();\r\n this.featureIndex.addAll(crf.featureIndex.objectsList());\r\n this.knownLCWords.addAll(crf.knownLCWords);\r\n assert (weights.length == oldNumFeatures1);\r\n\r\n // Combine weights of this classifier with other classifier\r\n for (int i = 0; i < labelIndices.length; i++) {\r\n this.labelIndices[i].addAll(crf.labelIndices[i].objectsList());\r\n }\r\n System.err.println(\"Combining weights: will automatically match labelIndices\");\r\n combineWeights(crf, weight);\r\n\r\n int numFeatures = featureIndex.size();\r\n int numWeights = getNumWeights();\r\n long elapsedMs = timer.stop();\r\n System.err.println(\"numFeatures: orig1=\" + oldNumFeatures1 + \", orig2=\" + oldNumFeatures2 + \", combined=\"\r\n + numFeatures);\r\n System.err\r\n .println(\"numWeights: orig1=\" + oldNumWeights1 + \", orig2=\" + oldNumWeights2 + \", combined=\" + numWeights);\r\n System.err.println(\"Time to combine CRFClassifier: \" + Timing.toSecondsString(elapsedMs) + \" seconds\");\r\n }",
"private void createTimephasedData(ProjectFile file, ResourceAssignment assignment, List<TimephasedWork> timephasedPlanned, List<TimephasedWork> timephasedComplete)\n {\n if (timephasedPlanned.isEmpty() && timephasedComplete.isEmpty())\n {\n Duration totalMinutes = assignment.getWork().convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n\n Duration workPerDay;\n\n if (assignment.getResource() == null || assignment.getResource().getType() == ResourceType.WORK)\n {\n workPerDay = totalMinutes.getDuration() == 0 ? totalMinutes : ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n int units = NumberHelper.getInt(assignment.getUnits());\n if (units != 100)\n {\n workPerDay = Duration.getInstance((workPerDay.getDuration() * units) / 100.0, workPerDay.getUnits());\n }\n }\n else\n {\n if (assignment.getVariableRateUnits() == null)\n {\n Duration workingDays = assignment.getCalendar().getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.DAYS);\n double units = NumberHelper.getDouble(assignment.getUnits());\n double unitsPerDayAsMinutes = (units * 60) / (workingDays.getDuration() * 100);\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n else\n {\n double unitsPerHour = NumberHelper.getDouble(assignment.getUnits());\n workPerDay = ResourceAssignmentFactory.DEFAULT_NORMALIZER_WORK_PER_DAY;\n Duration hoursPerDay = workPerDay.convertUnits(TimeUnit.HOURS, file.getProjectProperties());\n double unitsPerDayAsHours = (unitsPerHour * hoursPerDay.getDuration()) / 100;\n double unitsPerDayAsMinutes = unitsPerDayAsHours * 60;\n workPerDay = Duration.getInstance(unitsPerDayAsMinutes, TimeUnit.MINUTES);\n }\n }\n\n Duration overtimeWork = assignment.getOvertimeWork();\n if (overtimeWork != null && overtimeWork.getDuration() != 0)\n {\n Duration totalOvertimeMinutes = overtimeWork.convertUnits(TimeUnit.MINUTES, file.getProjectProperties());\n totalMinutes = Duration.getInstance(totalMinutes.getDuration() - totalOvertimeMinutes.getDuration(), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(assignment.getStart());\n tra.setAmountPerDay(workPerDay);\n tra.setModified(false);\n tra.setFinish(assignment.getFinish());\n tra.setTotalAmount(totalMinutes);\n timephasedPlanned.add(tra);\n }\n }",
"@Subscribe\n public void onSuiteResult(AggregatedSuiteResultEvent e) {\n long millis = e.getExecutionTime();\n String suiteName = e.getDescription().getDisplayName();\n \n List<Long> values = hints.get(suiteName);\n if (values == null) {\n hints.put(suiteName, values = new ArrayList<>());\n }\n values.add(millis);\n while (values.size() > historyLength)\n values.remove(0);\n }",
"public void setBaselineStartText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_STARTS, baselineNumber), value);\n }",
"public String getTextForExpression(DJGroup group, DJGroup childGroup, String type) {\n\t\treturn \"new Double( $V{\" + getReportName() + \"_\" + getGroupVariableName(childGroup) + \"}.doubleValue() / $V{\" + getReportName() + \"_\" + getGroupVariableName(type,group.getColumnToGroupBy().getColumnProperty().getProperty()) + \"}.doubleValue())\";\n\t}"
] |
Send a kill signal to all running instances and return as soon as the signal is sent. | [
"void killAll()\n {\n for (RjiRegistration reg : this.instancesById.values().toArray(new RjiRegistration[] {}))\n {\n reg.rji.handleInstruction(Instruction.KILL);\n }\n }"
] | [
"public final ProcessorDependencyGraph getProcessorGraph() {\n if (this.processorGraph == null) {\n synchronized (this) {\n if (this.processorGraph == null) {\n final Map<String, Class<?>> attcls = new HashMap<>();\n for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {\n attcls.put(attribute.getKey(), attribute.getValue().getValueType());\n }\n this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);\n }\n }\n }\n return this.processorGraph;\n }",
"public static ComplexNumber Tan(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.tan(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n double real2 = 2 * z1.real;\r\n double imag2 = 2 * z1.imaginary;\r\n double denom = Math.cos(real2) + Math.cosh(real2);\r\n\r\n result.real = Math.sin(real2) / denom;\r\n result.imaginary = Math.sinh(imag2) / denom;\r\n }\r\n\r\n return result;\r\n }",
"private Boolean readOptionalBoolean(JSONObject json, String key) {\n\n try {\n return Boolean.valueOf(json.getBoolean(key));\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON boolean failed. Default to provided default value.\", e);\n }\n return null;\n }",
"public String getShortMessage(Locale locale) {\n\t\tString message;\n\t\tmessage = translate(Integer.toString(exceptionCode), locale);\n\t\tif (message != null && msgParameters != null && msgParameters.length > 0) {\n\t\t\tfor (int i = 0; i < msgParameters.length; i++) {\n\t\t\t\tboolean isIncluded = false;\n\t\t\t\tString needTranslationParam = \"$${\" + i + \"}\";\n\t\t\t\tif (message.contains(needTranslationParam)) {\n\t\t\t\t\tString translation = translate(msgParameters[i], locale);\n\t\t\t\t\tif (null == translation && null != msgParameters[i]) {\n\t\t\t\t\t\ttranslation = msgParameters[i].toString();\n\t\t\t\t\t}\n\t\t\t\t\tif (null == translation) {\n\t\t\t\t\t\ttranslation = \"[null]\";\n\t\t\t\t\t}\n\t\t\t\t\tmessage = message.replace(needTranslationParam, translation);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tString verbatimParam = \"${\" + i + \"}\";\n\t\t\t\tString rs = null == msgParameters[i] ? \"[null]\" : msgParameters[i].toString();\n\t\t\t\tif (message.contains(verbatimParam)) {\n\t\t\t\t\tmessage = message.replace(verbatimParam, rs);\n\t\t\t\t\tisIncluded = true;\n\t\t\t\t}\n\t\t\t\tif (!isIncluded) {\n\t\t\t\t\tmessage = message + \" (\" + rs + \")\"; // NOSONAR replace/contains makes StringBuilder use difficult\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn message;\n\t}",
"public ItemRequest<Team> findById(String team) {\n \n String path = String.format(\"/teams/%s\", team);\n return new ItemRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public Jar addPackageOf(Class<?> clazz, Filter filter) throws IOException {\n try {\n final String path = clazz.getPackage().getName().replace('.', '/');\n URL dirURL = clazz.getClassLoader().getResource(path);\n if (dirURL != null && dirURL.getProtocol().equals(\"file\"))\n addDir(Paths.get(path), Paths.get(dirURL.toURI()), filter, false);\n else {\n if (dirURL == null) // In case of a jar file, we can't actually find a directory.\n dirURL = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + \".class\");\n\n if (dirURL.getProtocol().equals(\"jar\")) {\n final URI jarUri = new URI(dirURL.getPath().substring(0, dirURL.getPath().indexOf('!')));\n try (JarInputStream jis1 = newJarInputStream(Files.newInputStream(Paths.get(jarUri)))) {\n for (JarEntry entry; (entry = jis1.getNextJarEntry()) != null;) {\n try {\n if (entry.getName().startsWith(path + '/')) {\n if (filter == null || filter.filter(entry.getName()))\n addEntryNoClose(jos, entry.getName(), jis1);\n }\n } catch (ZipException e) {\n if (!e.getMessage().startsWith(\"duplicate entry\"))\n throw e;\n }\n }\n }\n } else\n throw new AssertionError();\n }\n return this;\n } catch (URISyntaxException e) {\n throw new AssertionError(e);\n }\n }",
"public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {\n try {\n return execute(listener, task.getServerIdentity(), task.getOperation());\n } catch (OperationFailedException e) {\n // Handle failures operation transformation failures\n final ServerIdentity identity = task.getServerIdentity();\n final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));\n return 1; // 1 ms timeout since there is no reason to wait for the locally stored result\n }\n\n }",
"public static base_responses unset(nitro_service client, String selectorname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tnslimitselector unsetresources[] = new nslimitselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tunsetresources[i] = new nslimitselector();\n\t\t\t\tunsetresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"private List<Event> filterEvents(List<Event> events) {\n List<Event> filteredEvents = new ArrayList<Event>();\n for (Event event : events) {\n if (!filter(event)) {\n filteredEvents.add(event);\n }\n }\n return filteredEvents;\n }"
] |
Searches for a sequence of integers
example:
1 2 3 4 6 7 -3 | [
"protected void parseIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) ) {\n start = t;\n state = 1;\n }\n } else if( state == 1 ) {\n // var ?\n if( isVariableInteger(t)) { // see if its explicit number sequence\n state = 2;\n } else { // just scalar integer, skip\n state = 0;\n }\n } else if ( state == 2 ) {\n // var var ....\n if( !isVariableInteger(t) ) {\n // create explicit list sequence\n IntegerSequence sequence = new IntegerSequence.Explicit(start,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }"
] | [
"public void setEndType(final String value) {\r\n\r\n final EndType endType = EndType.valueOf(value);\r\n if (!endType.equals(m_model.getEndType())) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n switch (endType) {\r\n case SINGLE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case TIMES:\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case DATE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(m_model.getStart() == null ? new Date() : m_model.getStart());\r\n break;\r\n default:\r\n break;\r\n }\r\n m_model.setEndType(endType);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }",
"public final void setConfigurationFiles(final Map<String, String> configurationFiles)\n throws URISyntaxException {\n this.configurationFiles.clear();\n this.configurationFileLastModifiedTimes.clear();\n for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {\n if (!entry.getValue().contains(\":/\")) {\n // assume is a file\n this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());\n } else {\n this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));\n }\n }\n\n if (this.configFileLoader != null) {\n this.validateConfigurationFiles();\n }\n }",
"public void releaseAll() {\n synchronized(this) {\n Object[] refSet = allocatedMemoryReferences.values().toArray();\n if(refSet.length != 0) {\n logger.finer(\"Releasing allocated memory regions\");\n }\n for(Object ref : refSet) {\n release((MemoryReference) ref);\n }\n }\n }",
"public static final Bytes of(byte[] data, int offset, int length) {\n Objects.requireNonNull(data);\n if (length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return new Bytes(copy);\n }",
"protected void progressInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n long totalTimeS = (System.currentTimeMillis() - startTimeMs) / Time.MS_PER_SECOND;\n\n logger.info(tag + \" : scanned \" + scanned + \" and fetched \" + fetched + \" for store '\"\n + storageEngine.getName() + \"' partitionIds:\" + partitionIds + \" in \"\n + totalTimeS + \" s\");\n }\n }",
"public ItemRequest<CustomField> findById(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }",
"public base_response clear_config(Boolean force, String level) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsconfig resource = new nsconfig();\n\t\tif (force)\n\t\t\tresource.set_force(force);\n\n\t\tresource.set_level(level);\n\t\toptions option = new options();\n\t\toption.set_action(\"clear\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}",
"public String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }",
"public String checkIn(byte[] data) {\n String id = UUID.randomUUID().toString();\n dataMap.put(id, data);\n return id;\n }"
] |
generate a prepared INSERT-Statement for the Class
described by cld.
@param cld the ClassDescriptor | [
"public SqlStatement getPreparedInsertStatement(ClassDescriptor cld)\r\n {\r\n SqlStatement sql;\r\n SqlForClass sfc = getSqlForClass(cld);\r\n sql = sfc.getInsertSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getInsertProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlInsertStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setInsertSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }"
] | [
"public Method getMethod(Method method) {\n return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());\n }",
"public static String getGetterName(String propertyName, Class type) {\n String prefix = type == boolean.class || type == Boolean.class ? \"is\" : \"get\";\n return prefix + MetaClassHelper.capitalize(propertyName);\n }",
"protected int countedSize() throws PersistenceBrokerException\r\n {\r\n Query countQuery = getBroker().serviceBrokerHelper().getCountQuery(getQueryObject().getQuery());\r\n ResultSetAndStatement rsStmt;\r\n ClassDescriptor cld = getQueryObject().getClassDescriptor();\r\n int count = 0;\r\n\r\n // BRJ: do not use broker.getCount() because it's extent-aware\r\n // the count we need here must not include extents !\r\n if (countQuery instanceof QueryBySQL)\r\n {\r\n String countSql = ((QueryBySQL) countQuery).getSql();\r\n rsStmt = getBroker().serviceJdbcAccess().executeSQL(countSql, cld, Query.NOT_SCROLLABLE);\r\n }\r\n else\r\n {\r\n rsStmt = getBroker().serviceJdbcAccess().executeQuery(countQuery, cld);\r\n }\r\n\r\n try\r\n {\r\n if (rsStmt.m_rs.next())\r\n {\r\n count = rsStmt.m_rs.getInt(1);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n finally\r\n {\r\n rsStmt.close();\r\n }\r\n\r\n return count;\r\n }",
"public String lookupUser(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_USER);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"username\").item(0);\r\n return ((Text) groupnameElement.getFirstChild()).getData();\r\n }",
"public final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public UTMDetail getUTMDetails() {\n UTMDetail ud = new UTMDetail();\n ud.setSource(source);\n ud.setMedium(medium);\n ud.setCampaign(campaign);\n return ud;\n }",
"private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateImagePath = DockerUtils.getImagePath(imageTag);\n String manifestPath;\n\n // Try to get manifest, assuming reverse proxy\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Try to get manifest, assuming proxy-less\n candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf(\"/\") + 1);\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Couldn't find correct manifest\n listener.getLogger().println(\"Could not find corresponding manifest.json file in Artifactory.\");\n return false;\n }",
"public static void resetNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).reset();\n\t}",
"public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeQuery: \" + query);\r\n }\r\n /*\r\n\t\t * MBAIRD: we should create a scrollable resultset if the start at\r\n\t\t * index or end at index is set\r\n\t\t */\r\n boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));\r\n /*\r\n\t\t * OR if the prefetching of relationships is being used.\r\n\t\t */\r\n if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())\r\n {\r\n scrollable = true;\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n final int queryFetchSize = query.getFetchSize();\r\n final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());\r\n stmt = sm.getPreparedStatement(cld, sql.getStatement() ,\r\n scrollable, queryFetchSize, isStoredProcedure);\r\n if (isStoredProcedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindStatement(stmt, query, cld, 2);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindStatement(stmt, query, cld, 1);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n return new ResultSetAndStatement(sm, stmt, rs, sql);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);\r\n }\r\n }"
] |
Are these two numbers effectively equal?
The same logic is applied for each of the 3 vector dimensions: see {@link #equal}
@param v1
@param v2 | [
"public static boolean equal(Vector3f v1, Vector3f v2) {\n return equal(v1.x, v2.x) && equal(v1.y, v2.y) && equal(v1.z, v2.z);\n }"
] | [
"@Deprecated\n public static PersistentResourceXMLBuilder decorator(final String elementName) {\n return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName);\n }",
"public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}",
"public final Iterator<AbstractTraceRegion> leafIterator() {\n\t\tif (nestedRegions == null)\n\t\t\treturn Collections.<AbstractTraceRegion> singleton(this).iterator();\n\t\treturn new LeafIterator(this);\n\t}",
"public static <T extends EObject> IScope scopeFor(Iterable<? extends T> elements,\n\t\t\tfinal Function<T, QualifiedName> nameComputation, IScope outer) {\n\t\treturn new SimpleScope(outer,scopedElementsFor(elements, nameComputation));\n\t}",
"public Object lookup(String name) throws ObjectNameNotFoundException\r\n {\r\n /**\r\n * Is DB open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n if (!this.isOpen())\r\n {\r\n throw new DatabaseClosedException(\"Database is not open. Must have an open DB to call lookup\");\r\n }\r\n /**\r\n * Is Tx open? ODMG 3.0 says it has to be to call bind.\r\n */\r\n TransactionImpl tx = getTransaction();\r\n if (tx == null || !tx.isOpen())\r\n {\r\n throw new TransactionNotInProgressException(\"Tx is not open. Must have an open TX to call lookup.\");\r\n }\r\n\r\n return tx.getNamedRootsMap().lookup(name);\r\n }",
"public byte[] getByteArray(Integer offset)\n {\n byte[] result = null;\n\n if (offset != null)\n {\n result = m_map.get(offset);\n }\n\n return (result);\n }",
"protected void updateLabelActiveStyle() {\n if (this.valueBoxBase.getText() != null && !this.valueBoxBase.getText().isEmpty()) {\n label.addStyleName(CssName.ACTIVE);\n } else {\n label.removeStyleName(CssName.ACTIVE);\n }\n }",
"public T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {\n return modifyFile(name, path, existingHash, newHash, isDirectory, null);\n }",
"public static Envelope getTileBounds(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble[] layerSize = getTileLayerSize(code, maxExtent, scale);\n\t\tif (layerSize[0] == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tdouble cX = maxExtent.getMinX() + code.getX() * layerSize[0];\n\t\tdouble cY = maxExtent.getMinY() + code.getY() * layerSize[1];\n\t\treturn new Envelope(cX, cX + layerSize[0], cY, cY + layerSize[1]);\n\t}"
] |
Promotes this version of the file to be the latest version. | [
"public void promote() {\n URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, \"current\");\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"type\", \"file_version\");\n jsonObject.add(\"id\", this.getID());\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(jsonObject.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n this.parseJSON(JsonObject.readFrom(response.getJSON()));\n }"
] | [
"public static double blackModelCapletValue(\n\t\t\tdouble forward,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike,\n\t\t\tdouble periodLength,\n\t\t\tdouble discountFactor)\n\t{\n\t\t// May be interpreted as a special version of the Black-Scholes Formula\n\t\treturn AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);\n\t}",
"protected int readByte(InputStream is) throws IOException\n {\n byte[] data = new byte[1];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getByte(data, 0));\n }",
"static String encodeUriComponent(String source, String encoding, Type type) throws UnsupportedEncodingException {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\tAssert.hasLength(encoding, \"Encoding must not be empty\");\n\t\tbyte[] bytes = encodeBytes(source.getBytes(encoding), type);\n\t\treturn new String(bytes, \"US-ASCII\");\n\t}",
"public static base_response update(nitro_service client, Interface resource) throws Exception {\n\t\tInterface updateresource = new Interface();\n\t\tupdateresource.id = resource.id;\n\t\tupdateresource.speed = resource.speed;\n\t\tupdateresource.duplex = resource.duplex;\n\t\tupdateresource.flowctl = resource.flowctl;\n\t\tupdateresource.autoneg = resource.autoneg;\n\t\tupdateresource.hamonitor = resource.hamonitor;\n\t\tupdateresource.tagall = resource.tagall;\n\t\tupdateresource.trunk = resource.trunk;\n\t\tupdateresource.lacpmode = resource.lacpmode;\n\t\tupdateresource.lacpkey = resource.lacpkey;\n\t\tupdateresource.lagtype = resource.lagtype;\n\t\tupdateresource.lacppriority = resource.lacppriority;\n\t\tupdateresource.lacptimeout = resource.lacptimeout;\n\t\tupdateresource.ifalias = resource.ifalias;\n\t\tupdateresource.throughput = resource.throughput;\n\t\tupdateresource.bandwidthhigh = resource.bandwidthhigh;\n\t\tupdateresource.bandwidthnormal = resource.bandwidthnormal;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private List<Entity> runQuery(Query query) throws DatastoreException {\n RunQueryRequest.Builder request = RunQueryRequest.newBuilder();\n request.setQuery(query);\n RunQueryResponse response = datastore.runQuery(request.build());\n\n if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.NOT_FINISHED) {\n System.err.println(\"WARNING: partial results\\n\");\n }\n List<EntityResult> results = response.getBatch().getEntityResultsList();\n List<Entity> entities = new ArrayList<Entity>(results.size());\n for (EntityResult result : results) {\n entities.add(result.getEntity());\n }\n return entities;\n }",
"public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }",
"public static ExtensibleConfigurationPersister createTransientDomainXmlConfigurationPersister(ExecutorService executorService, ExtensionRegistry extensionRegistry) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n ExtensibleConfigurationPersister persister = new NullConfigurationPersister(domainXml);\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }",
"public String getPublicConfigValue(String key) throws ConfigurationException {\n if (!allProps.containsKey(key)) {\n throw new UndefinedPropertyException(\"The requested config key does not exist.\");\n }\n if (restrictedConfigs.contains(key)) {\n throw new ConfigurationException(\"The requested config key is not publicly available!\");\n }\n return allProps.get(key);\n }",
"public static <T> ConflictHandler<T> localWins() {\n return new ConflictHandler<T>() {\n @Override\n public T resolveConflict(\n final BsonValue documentId,\n final ChangeEvent<T> localEvent,\n final ChangeEvent<T> remoteEvent\n ) {\n return localEvent.getFullDocument();\n }\n };\n }"
] |
The users element defines users within the domain model, it is a simple authentication for some out of the box users. | [
"private void parseUsersAuthentication(final XMLExtendedStreamReader reader,\n final ModelNode realmAddress, final List<ModelNode> list)\n throws XMLStreamException {\n final ModelNode usersAddress = realmAddress.clone().add(AUTHENTICATION, USERS);\n list.add(Util.getEmptyOperation(ADD, usersAddress));\n\n while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {\n requireNamespace(reader, namespace);\n final Element element = Element.forName(reader.getLocalName());\n switch (element) {\n case USER: {\n parseUser(reader, usersAddress, list);\n break;\n }\n default: {\n throw unexpectedElement(reader);\n }\n }\n }\n }"
] | [
"private static Pod getRandomPod(KubernetesClient client, String name, String namespace) {\n Endpoints endpoints = client.endpoints().inNamespace(namespace).withName(name).get();\n List<String> pods = new ArrayList<>();\n if (endpoints != null) {\n for (EndpointSubset subset : endpoints.getSubsets()) {\n for (EndpointAddress address : subset.getAddresses()) {\n if (address.getTargetRef() != null && POD.equals(address.getTargetRef().getKind())) {\n String pod = address.getTargetRef().getName();\n if (pod != null && !pod.isEmpty()) {\n pods.add(pod);\n }\n }\n }\n }\n }\n if (pods.isEmpty()) {\n return null;\n } else {\n String chosen = pods.get(RANDOM.nextInt(pods.size()));\n return client.pods().inNamespace(namespace).withName(chosen).get();\n }\n }",
"public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }",
"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 remove(int profileId) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //also want to delete what is in the server redirect table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //also want to delete the path_profile table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //and the enabled overrides table\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\n statement.executeUpdate();\n statement.close();\n //and delete all the clients associated with this profile including the default client\n statement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\");\n statement.setInt(1, profileId);\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 int[] getPositions() {\n int[] list;\n if (assumeSinglePosition) {\n list = new int[1];\n list[0] = super.startPosition();\n return list;\n } else {\n try {\n processEncodedPayload();\n list = mtasPosition.getPositions();\n if (list != null) {\n return mtasPosition.getPositions();\n }\n } catch (IOException e) {\n log.debug(e);\n // do nothing\n }\n int start = super.startPosition();\n int end = super.endPosition();\n list = new int[end - start];\n for (int i = start; i < end; i++)\n list[i - start] = i;\n return list;\n }\n }",
"private Date adjustForWholeDay(Date date, boolean isEnd) {\n\n Calendar result = new GregorianCalendar();\n result.setTime(date);\n result.set(Calendar.HOUR_OF_DAY, 0);\n result.set(Calendar.MINUTE, 0);\n result.set(Calendar.SECOND, 0);\n result.set(Calendar.MILLISECOND, 0);\n if (isEnd) {\n result.add(Calendar.DATE, 1);\n }\n\n return result.getTime();\n }",
"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 }",
"public double getRate(AnalyticModel model) {\n\t\tif(model==null) {\n\t\t\tthrow new IllegalArgumentException(\"model==null\");\n\t\t}\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve==null) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve of name '\" + forwardCurveName + \"' found in given model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble fixingDate = schedule.getFixing(0);\n\t\treturn forwardCurve.getForward(model,fixingDate);\n\t}",
"protected int readByte(InputStream is) throws IOException\n {\n byte[] data = new byte[1];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getByte(data, 0));\n }"
] |
Detect and apply waves, now or when the widget is attached.
@param widget target widget to ensure is attached first | [
"public static void detectAndApply(Widget widget) {\n if (!widget.isAttached()) {\n widget.addAttachHandler(event -> {\n if (event.isAttached()) {\n detectAndApply();\n }\n });\n } else {\n detectAndApply();\n }\n }"
] | [
"private void readResourceCustomFields(net.sf.mpxj.ganttproject.schema.Resource gpResource, Resource mpxjResource)\n {\n //\n // Populate custom field default values\n //\n Map<FieldType, Object> customFields = new HashMap<FieldType, Object>();\n for (Pair<FieldType, String> definition : m_resourcePropertyDefinitions.values())\n {\n customFields.put(definition.getFirst(), definition.getSecond());\n }\n\n //\n // Update with custom field actual values\n //\n for (CustomResourceProperty property : gpResource.getCustomProperty())\n {\n Pair<FieldType, String> definition = m_resourcePropertyDefinitions.get(property.getDefinitionId());\n if (definition != null)\n {\n //\n // Retrieve the value. If it is empty, use the default.\n //\n String value = property.getValueAttribute();\n if (value.isEmpty())\n {\n value = null;\n }\n\n //\n // If we have a value,convert it to the correct type\n //\n if (value != null)\n {\n Object result;\n\n switch (definition.getFirst().getDataType())\n {\n case NUMERIC:\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n result = Double.valueOf(value);\n }\n break;\n }\n\n case DATE:\n {\n try\n {\n result = m_localeDateFormat.parse(value);\n }\n catch (ParseException ex)\n {\n result = null;\n }\n break;\n }\n\n case BOOLEAN:\n {\n result = Boolean.valueOf(value.equals(\"true\"));\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n if (result != null)\n {\n customFields.put(definition.getFirst(), result);\n }\n }\n }\n }\n\n for (Map.Entry<FieldType, Object> item : customFields.entrySet())\n {\n if (item.getValue() != null)\n {\n mpxjResource.set(item.getKey(), item.getValue());\n }\n }\n }",
"public Jar setListAttribute(String name, Collection<?> values) {\n return setAttribute(name, join(values));\n }",
"public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception\n {\n System.out.println(\"Reading Primavera database started.\");\n\n Class.forName(driverClass);\n Properties props = new Properties();\n\n //\n // This is not a very robust way to detect that we're working with SQLlite...\n // If you are trying to grab data from\n // a standalone P6 using SQLite, the SQLite JDBC driver needs this property\n // in order to correctly parse timestamps.\n //\n if (driverClass.equals(\"org.sqlite.JDBC\"))\n {\n props.setProperty(\"date_string_format\", \"yyyy-MM-dd HH:mm:ss\");\n }\n\n Connection c = DriverManager.getConnection(connectionString, props);\n PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader();\n reader.setConnection(c);\n\n processProject(reader, Integer.parseInt(projectID), outputFile);\n }",
"public 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 }",
"@Override\n public void writeText(PDDocument doc, Writer outputStream) throws IOException\n {\n try\n {\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation(\"LS\");\n LSSerializer writer = impl.createLSSerializer();\n LSOutput output = impl.createLSOutput();\n writer.getDomConfig().setParameter(\"format-pretty-print\", true);\n output.setCharacterStream(outputStream);\n createDOM(doc);\n writer.write(getDocument(), output);\n } catch (ClassCastException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (ClassNotFoundException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (InstantiationException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (IllegalAccessException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n }\n }",
"public void weeksChange(String week, Boolean value) {\n\n final WeekOfMonth changedWeek = WeekOfMonth.valueOf(week);\n boolean newValue = (null != value) && value.booleanValue();\n boolean currentValue = m_model.getWeeksOfMonth().contains(changedWeek);\n if (newValue != currentValue) {\n if (newValue) {\n setPatternScheme(true, false);\n m_model.addWeekOfMonth(changedWeek);\n onValueChange();\n } else {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.removeWeekOfMonth(changedWeek);\n onValueChange();\n }\n });\n }\n }\n }",
"private String getApiKey(CmsObject cms, String sitePath) throws CmsException {\n\n String res = cms.readPropertyObject(\n sitePath,\n CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,\n true).getValue();\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {\n res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();\n }\n return res;\n\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 }",
"protected void parseOperationsLR(Symbol ops[], TokenList tokens, Sequence sequence) {\n\n if( tokens.size == 0 )\n return;\n\n TokenList.Token token = tokens.first;\n\n if( token.getType() != Type.VARIABLE )\n throw new ParseError(\"The first token in an equation needs to be a variable and not \"+token);\n\n boolean hasLeft = false;\n while( token != null ) {\n if( token.getType() == Type.FUNCTION ) {\n throw new ParseError(\"Function encountered with no parentheses\");\n } else if( token.getType() == Type.VARIABLE ) {\n if( hasLeft ) {\n if( isTargetOp(token.previous,ops)) {\n token = createOp(token.previous.previous,token.previous,token,tokens,sequence);\n }\n } else {\n hasLeft = true;\n }\n } else {\n if( token.previous.getType() == Type.SYMBOL ) {\n throw new ParseError(\"Two symbols next to each other. \"+token.previous+\" and \"+token);\n }\n }\n token = token.next;\n }\n }"
] |
Get the element at the index as a float.
@param i the index of the element to access | [
"@Override\n public final float getFloat(final int i) {\n double val = this.array.optDouble(i, Double.MAX_VALUE);\n if (val == Double.MAX_VALUE) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n return (float) val;\n }"
] | [
"public static final BigInteger printPriority(Priority priority)\n {\n int result = Priority.MEDIUM;\n\n if (priority != null)\n {\n result = priority.getValue();\n }\n\n return (BigInteger.valueOf(result));\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 }",
"@Deprecated\r\n private BufferedImage getImage(String suffix) throws IOException {\r\n StringBuffer buffer = getBaseImageUrl();\r\n buffer.append(suffix);\r\n return _getImage(buffer.toString());\r\n }",
"public static servicegroup_stats get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_stats response = (servicegroup_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public static Integer distance(String h1, String h2) {\n\t\tHammingDistance distance = new HammingDistance();\n\t\treturn distance.apply(h1, h2);\n\t}",
"public Group lookupGroup(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GROUP);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Group group = new Group();\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"groupname\").item(0);\r\n group.setId(payload.getAttribute(\"id\"));\r\n group.setName(((Text) groupnameElement.getFirstChild()).getData());\r\n return group;\r\n }",
"synchronized void bulkRegisterSingleton() {\n for (Map.Entry<Class<? extends AppService>, AppService> entry : registry.entrySet()) {\n if (isSingletonService(entry.getKey())) {\n app.registerSingleton(entry.getKey(), entry.getValue());\n }\n }\n }",
"public static final String getSelectedText(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getItemText(index) : null;\n }",
"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 }"
] |
given the groupId, and 2 string arrays, adds the name-responses pair to the table_override
@param groupId ID of group
@param methodName name of method
@param className name of class
@throws Exception exception | [
"public void createOverride(int groupId, String methodName, String className) throws Exception {\n // first make sure this doesn't already exist\n for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) {\n if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) {\n // don't add if it already exists in the group\n return;\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n PreparedStatement statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_OVERRIDE\n + \"(\" + Constants.OVERRIDE_METHOD_NAME\n + \",\" + Constants.OVERRIDE_CLASS_NAME\n + \",\" + Constants.OVERRIDE_GROUP_ID\n + \")\"\n + \" VALUES (?, ?, ?)\"\n );\n statement.setString(1, methodName);\n statement.setString(2, className);\n statement.setInt(3, groupId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }"
] | [
"private void addToGraph(ClassDoc cd) {\n\t// avoid adding twice the same class, but don't rely on cg.getClassInfo\n\t// since there are other ways to add a classInfor than printing the class\n\tif (visited.contains(cd.toString()))\n\t return;\n\n\tvisited.add(cd.toString());\n\tcg.printClass(cd, false);\n\tcg.printRelations(cd);\n\tif (opt.inferRelationships)\n\t cg.printInferredRelations(cd);\n\tif (opt.inferDependencies)\n\t cg.printInferredDependencies(cd);\n }",
"private static void validateAsMongoDBCollectionName(String collectionName) {\n\t\tContracts.assertStringParameterNotEmpty( collectionName, \"requestedName\" );\n\t\t//Yes it has some strange requirements.\n\t\tif ( collectionName.startsWith( \"system.\" ) ) {\n\t\t\tthrow log.collectionNameHasInvalidSystemPrefix( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.collectionNameContainsNULCharacter( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"$\" ) ) {\n\t\t\tthrow log.collectionNameContainsDollarCharacter( collectionName );\n\t\t}\n\t}",
"public static Observable<Void> mapToVoid(Observable<?> fromObservable) {\n if (fromObservable != null) {\n return fromObservable.subscribeOn(Schedulers.io())\n .map(new RXMapper<Void>());\n } else {\n return Observable.empty();\n }\n }",
"private List<String> parseParams(String param) {\n\t\tAssert.hasText(param, \"param must not be empty nor null\");\n\t\tList<String> paramsToUse = new ArrayList<>();\n\t\tMatcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);\n\t\tint start = 0;\n\t\twhile (regexMatcher.find()) {\n\t\t\tString p = removeQuoting(param.substring(start, regexMatcher.start()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t\tstart = regexMatcher.start();\n\t\t}\n\t\tif (param != null && param.length() > 0) {\n\t\t\tString p = removeQuoting(param.substring(start, param.length()).trim());\n\t\t\tif (StringUtils.hasText(p)) {\n\t\t\t\tparamsToUse.add(p);\n\t\t\t}\n\t\t}\n\t\treturn paramsToUse;\n\t}",
"public Point3d[] getVertices() {\n Point3d[] vtxs = new Point3d[numVertices];\n for (int i = 0; i < numVertices; i++) {\n vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt;\n }\n return vtxs;\n }",
"public static int getProfileIdFromPathID(int path_id) throws Exception {\n return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH);\n }",
"public BoxFile.Info commit(String digest, List<BoxFileUploadSessionPart> parts,\n Map<String, String> attributes, String ifMatch, String ifNoneMatch) {\n\n URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint();\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST);\n request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);\n\n if (ifMatch != null) {\n request.addHeader(HttpHeaders.IF_MATCH, ifMatch);\n }\n\n if (ifNoneMatch != null) {\n request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch);\n }\n\n //Creates the body of the request\n String body = this.getCommitBody(parts, attributes);\n request.setBody(body);\n\n BoxAPIResponse response = request.send();\n //Retry the commit operation after the given number of seconds if the HTTP response code is 202.\n if (response.getResponseCode() == 202) {\n String retryInterval = response.getHeaderField(\"retry-after\");\n if (retryInterval != null) {\n try {\n Thread.sleep(new Integer(retryInterval) * 1000);\n } catch (InterruptedException ie) {\n throw new BoxAPIException(\"Commit retry failed. \", ie);\n }\n\n return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch);\n }\n }\n\n if (response instanceof BoxJSONResponse) {\n //Create the file instance from the response\n return this.getFile((BoxJSONResponse) response);\n } else {\n throw new BoxAPIException(\"Commit response content type is not application/json. The response code : \"\n + response.getResponseCode());\n }\n }",
"public boolean classifySentenceStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n while ((line = is.readLine()) != null) {\r\n \t\r\n if (line.trim().equals(\"\")) {\r\n \t text += sentence + eol;\r\n \t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n classifyAndWriteAnswers(documents, readerWriter);\r\n text = \"\";\r\n } else {\r\n \t text += line + eol;\r\n }\r\n }\r\n if (text.trim().equals(\"\")) {\r\n \treturn false;\r\n }\r\n return true;\r\n }",
"protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) {\n\n if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) {\n return StreamRequestHandlerState.WRITING;\n } else {\n logger.info(\"Finished fetch \" + itemTag + \" for store '\" + storageEngine.getName()\n + \"' with partitions \" + partitionIds);\n progressInfoMessage(\"Fetch \" + itemTag + \" (end of scan)\");\n\n return StreamRequestHandlerState.COMPLETE;\n }\n }"
] |
Given a path to a VFS resource, the method removes the OpenCms context,
in case the path is prefixed by that context.
@param path the path where the OpenCms context should be removed
@return the adjusted path | [
"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 }"
] | [
"public static void requireNamespace(final XMLExtendedStreamReader reader, final Namespace requiredNs) throws XMLStreamException {\n Namespace actualNs = Namespace.forUri(reader.getNamespaceURI());\n if (actualNs != requiredNs) {\n throw unexpectedElement(reader);\n }\n }",
"public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"public PhotoList<Photo> getPhotos(String photosetId, Set<String> extras, int privacy_filter, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n if (privacy_filter > 0) {\r\n parameters.put(\"privacy_filter\", \"\" + privacy_filter);\r\n }\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\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\r\n Element photoset = response.getPayload();\r\n NodeList photoElements = photoset.getElementsByTagName(\"photo\");\r\n photos.setPage(photoset.getAttribute(\"page\"));\r\n photos.setPages(photoset.getAttribute(\"pages\"));\r\n photos.setPerPage(photoset.getAttribute(\"per_page\"));\r\n photos.setTotal(photoset.getAttribute(\"total\"));\r\n\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement, photoset));\r\n }\r\n\r\n return photos;\r\n }",
"public static Attachment writeAttachmentWithErrorMessage(Throwable throwable, String title) {\n String message = throwable.getMessage();\n try {\n return writeAttachment(message.getBytes(CONFIG.getAttachmentsEncoding()), title);\n } catch (Exception e) {\n e.addSuppressed(throwable);\n LOGGER.error(String.format(\"Can't write attachment \\\"%s\\\"\", title), e);\n }\n return new Attachment();\n }",
"public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public static <E> void registerTypeConverter(Class<E> cls, TypeConverter<E> converter) {\n TYPE_CONVERTERS.put(cls, converter);\n }",
"public static vpnvserver_rewritepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_rewritepolicy_binding obj = new vpnvserver_rewritepolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_rewritepolicy_binding response[] = (vpnvserver_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ArrayList<Duration> segmentWork(ProjectCalendar projectCalendar, List<TimephasedWork> work, TimescaleUnits rangeUnits, List<DateRange> dateList)\n {\n ArrayList<Duration> result = new ArrayList<Duration>(dateList.size());\n int lastStartIndex = 0;\n\n //\n // Iterate through the list of dates range we are interested in.\n // Each date range in this list corresponds to a column\n // shown on the \"timescale\" view by MS Project\n //\n for (DateRange range : dateList)\n {\n //\n // If the current date range does not intersect with any of the\n // assignment date ranges in the list, then we show a zero\n // duration for this date range.\n //\n int startIndex = lastStartIndex == -1 ? -1 : getStartIndex(range, work, lastStartIndex);\n if (startIndex == -1)\n {\n result.add(Duration.getInstance(0, TimeUnit.HOURS));\n }\n else\n {\n //\n // We have found an assignment which intersects with the current\n // date range, call the method below to determine how\n // much time from this resource assignment can be allocated\n // to the current date range.\n //\n result.add(getRangeDuration(projectCalendar, rangeUnits, range, work, startIndex));\n lastStartIndex = startIndex;\n }\n }\n\n return result;\n }",
"public CrosstabBuilder setColumnStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setColumnHeaderStyle(headerStyle);\r\n\t\tcrosstab.setColumnTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setColumnTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}"
] |
Returns true if the activity is a start milestone.
@param activity Phoenix activity
@return true if the activity is a milestone | [
"private boolean activityIsStartMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"StartMilestone\") != -1;\n }"
] | [
"public static ObjectName createObjectName(String domain, String type) {\n try {\n return new ObjectName(domain + \":type=\" + type);\n } catch(MalformedObjectNameException e) {\n throw new VoldemortException(e);\n }\n }",
"public ItemRequest<Project> addFollowers(String project) {\n \n String path = String.format(\"/projects/%s/addFollowers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }",
"@Override\n\tpublic ProxyAuthenticationMethod getMethod() {\n\t\tswitch (authenticationMethod) {\n\t\tcase BASIC:\n\t\t\treturn ProxyAuthenticationMethod.BASIC;\n\t\tcase DIGEST:\n\t\t\treturn ProxyAuthenticationMethod.DIGEST;\n\t\tcase URL:\n\t\t\treturn ProxyAuthenticationMethod.URL;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}",
"private ReferenceDescriptorDef cloneReference(ReferenceDescriptorDef refDef, String prefix)\r\n {\r\n ReferenceDescriptorDef copyRefDef = new ReferenceDescriptorDef(refDef, prefix);\r\n\r\n copyRefDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyRefDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n \r\n Properties mod = getModification(copyRefDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyRefDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included reference \"+\r\n copyRefDef.getName()+\" from class \"+refDef.getOwner().getName()); \r\n }\r\n copyRefDef.applyModifications(mod);\r\n }\r\n return copyRefDef;\r\n }",
"static void createMessage(String textMessage, JobInstance jobInstance, DbConn cnx)\n {\n cnx.runUpdate(\"message_insert\", jobInstance.getId(), textMessage);\n }",
"public AnalysisContext copyWithConfiguration(ModelNode configuration) {\n return new AnalysisContext(this.locale, configuration, this.oldApi, this.newApi, this.data);\n }",
"public static Collection<Field> getAllAttributes(final Class<?> classToInspect) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), field -> true);\n return allFields;\n }",
"public static final void parseExtendedAttribute(ProjectFile file, FieldContainer mpx, String value, FieldType mpxFieldID, TimeUnit durationFormat)\n {\n if (mpxFieldID != null)\n {\n switch (mpxFieldID.getDataType())\n {\n case STRING:\n {\n mpx.set(mpxFieldID, value);\n break;\n }\n\n case DATE:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeDate(value));\n break;\n }\n\n case CURRENCY:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeCurrency(value));\n break;\n }\n\n case BOOLEAN:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeBoolean(value));\n break;\n }\n\n case NUMERIC:\n {\n mpx.set(mpxFieldID, parseExtendedAttributeNumber(value));\n break;\n }\n\n case DURATION:\n {\n mpx.set(mpxFieldID, parseDuration(file, durationFormat, value));\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n }",
"@Override\r\n public boolean add(E o) {\r\n Integer index = indexes.get(o);\r\n if (index == null && ! locked) {\r\n index = objects.size();\r\n objects.add(o);\r\n indexes.put(o, index);\r\n return true;\r\n }\r\n return false;\r\n }"
] |
parse the stencil out of a JSONObject and set it to the current shape
@param modelJSON
@param current
@throws org.json.JSONException | [
"private static void parseStencil(JSONObject modelJSON,\n Shape current) throws JSONException {\n // get stencil type\n if (modelJSON.has(\"stencil\")) {\n JSONObject stencil = modelJSON.getJSONObject(\"stencil\");\n // TODO other attributes of stencil\n String stencilString = \"\";\n if (stencil.has(\"id\")) {\n stencilString = stencil.getString(\"id\");\n }\n current.setStencil(new StencilType(stencilString));\n }\n }"
] | [
"public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}",
"private TestSuiteModel buildModel(AggregatedSuiteResultEvent e) throws IOException {\n SimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\", Locale.ROOT);\n TestSuiteModel suite = new TestSuiteModel();\n\n suite.hostname = \"nohost.nodomain\";\n suite.name = e.getDescription().getDisplayName();\n suite.properties = buildModel(e.getSlave().getSystemProperties());\n suite.time = e.getExecutionTime() / 1000.0;\n suite.timestamp = df.format(new Date(e.getStartTimestamp()));\n\n suite.testcases = buildModel(e.getTests());\n suite.tests = suite.testcases.size();\n\n if (mavenExtensions) {\n suite.skipped = 0;\n }\n\n // Suite-level failures and errors are simulated as test cases.\n for (FailureMirror m : e.getFailures()) {\n TestCaseModel model = new TestCaseModel();\n model.classname = \"junit.framework.TestSuite\"; // empirical ANT output.\n model.name = applyFilters(m.getDescription().getClassName());\n model.time = 0;\n if (m.isAssertionViolation()) {\n model.failures.add(buildModel(m));\n } else {\n model.errors.add(buildModel(m));\n }\n suite.testcases.add(model);\n }\n\n // Calculate test numbers that match limited view (no ignored tests, \n // faked suite-level errors).\n for (TestCaseModel tc : suite.testcases) {\n suite.errors += tc.errors.size();\n suite.failures += tc.failures.size();\n if (mavenExtensions && tc.skipped != null) {\n suite.skipped += 1;\n }\n }\n\n StringWriter sysout = new StringWriter();\n StringWriter syserr = new StringWriter();\n if (outputStreams) {\n e.getSlave().decodeStreams(e.getEventStream(), sysout, syserr);\n }\n suite.sysout = sysout.toString();\n suite.syserr = syserr.toString();\n\n return suite;\n }",
"public void setLabel(String label) {\n\n int ix = lstSizes.indexOf(label);\n if (ix != -1) {\n setLabel(ix);\n }\n }",
"public ItemRequest<Task> update(String task) {\n \n String path = String.format(\"/tasks/%s\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"PUT\");\n }",
"public void writeAuxiliaryTriples() throws RDFHandlerException {\n\t\tfor (PropertyRestriction pr : this.someValuesQueue) {\n\t\t\twriteSomeValueRestriction(pr.propertyUri, pr.rangeUri, pr.subject);\n\t\t}\n\t\tthis.someValuesQueue.clear();\n\n\t\tthis.valueRdfConverter.writeAuxiliaryTriples();\n\t}",
"public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig,\n\t\t\tboolean ignoreErrors) throws SQLException {\n\t\tDatabaseType databaseType = connectionSource.getDatabaseType();\n\t\tDao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);\n\t\tif (dao instanceof BaseDaoImpl<?, ?>) {\n\t\t\treturn doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors);\n\t\t} else {\n\t\t\ttableConfig.extractFieldTypes(databaseType);\n\t\t\tTableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);\n\t\t\treturn doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors);\n\t\t}\n\t}",
"@RequestMapping(value=\"/soy/compileJs\", method=GET)\n public ResponseEntity<String> compile(@RequestParam(required = false, value=\"hash\", defaultValue = \"\") final String hash,\n @RequestParam(required = true, value = \"file\") final String[] templateFileNames,\n @RequestParam(required = false, value = \"locale\") String locale,\n @RequestParam(required = false, value = \"disableProcessors\", defaultValue = \"false\") String disableProcessors,\n final HttpServletRequest request) throws IOException {\n return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale);\n }",
"private boolean isWorkingDate(Date date, Day day)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, day);\n return ranges.getRangeCount() != 0;\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 }"
] |
Create the close button UI Component.
@return the close button. | [
"@SuppressWarnings(\"serial\")\n private Component createCloseButton() {\n\n Button closeBtn = CmsToolBar.createButton(\n FontOpenCms.CIRCLE_INV_CANCEL,\n m_messages.key(Messages.GUI_BUTTON_CANCEL_0));\n closeBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n closeAction();\n }\n\n });\n return closeBtn;\n }"
] | [
"public void loadClass(String className) throws Exception {\n ClassInformation classInfo = classInformation.get(className);\n\n logger.info(\"Loading plugin.: {}, {}\", className, classInfo.pluginPath);\n\n // get URL for proxylib\n // need to load this also otherwise the annotations cannot be found later on\n File libFile = new File(proxyLibPath);\n URL libUrl = libFile.toURI().toURL();\n\n // store the last modified time of the plugin\n File pluginDirectoryFile = new File(classInfo.pluginPath);\n classInfo.lastModified = pluginDirectoryFile.lastModified();\n\n // load the plugin directory\n URL classURL = new File(classInfo.pluginPath).toURI().toURL();\n\n URL[] urls = new URL[] {classURL};\n URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());\n\n // load the class\n Class<?> cls = child.loadClass(className);\n\n // put loaded class into classInfo\n classInfo.loadedClass = cls;\n classInfo.loaded = true;\n\n classInformation.put(className, classInfo);\n\n logger.info(\"Loaded plugin: {}, {} method(s)\", cls.toString(), cls.getDeclaredMethods().length);\n }",
"private static String getHostname() {\n if (Hostname == null) {\n try {\n Hostname = InetAddress.getLocalHost().getHostName();\n } catch (Exception e) {\n Hostname = \"default\";\n LOGGER.warn(\"Can not get current hostname\", e);\n }\n }\n return Hostname;\n }",
"public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery)\r\n {\r\n return aQuery;\r\n }",
"public static base_responses unset(nitro_service client, String username[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (username != null && username.length > 0) {\n\t\t\tsystemuser unsetresources[] = new systemuser[username.length];\n\t\t\tfor (int i=0;i<username.length;i++){\n\t\t\t\tunsetresources[i] = new systemuser();\n\t\t\t\tunsetresources[i].username = username[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.fullString) == null) {\n\t\t\tstringCache.fullString = result = toNormalizedString(IPv4StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}",
"public static long decodeLong(byte[] ba, int offset) {\n return ((((long) ba[offset + 0] << 56) + ((long) (ba[offset + 1] & 255) << 48)\n + ((long) (ba[offset + 2] & 255) << 40) + ((long) (ba[offset + 3] & 255) << 32)\n + ((long) (ba[offset + 4] & 255) << 24) + ((ba[offset + 5] & 255) << 16)\n + ((ba[offset + 6] & 255) << 8) + ((ba[offset + 7] & 255) << 0)));\n }",
"public static boolean checkAddProperty(\r\n CmsCmisTypeManager typeManager,\r\n Properties properties,\r\n String typeId,\r\n Set<String> filter,\r\n String id) {\r\n\r\n if ((properties == null) || (properties.getProperties() == null)) {\r\n throw new IllegalArgumentException(\"Properties must not be null!\");\r\n }\r\n\r\n if (id == null) {\r\n throw new IllegalArgumentException(\"Id must not be null!\");\r\n }\r\n\r\n TypeDefinition type = typeManager.getType(typeId);\r\n if (type == null) {\r\n throw new IllegalArgumentException(\"Unknown type: \" + typeId);\r\n }\r\n if (!type.getPropertyDefinitions().containsKey(id)) {\r\n throw new IllegalArgumentException(\"Unknown property: \" + id);\r\n }\r\n\r\n String queryName = type.getPropertyDefinitions().get(id).getQueryName();\r\n\r\n if ((queryName != null) && (filter != null)) {\r\n if (!filter.contains(queryName)) {\r\n return false;\r\n } else {\r\n filter.remove(queryName);\r\n }\r\n }\r\n\r\n return true;\r\n }",
"public GVRMesh findMesh(GVRSceneObject model)\n {\n class MeshFinder implements GVRSceneObject.ComponentVisitor\n {\n private GVRMesh meshFound = null;\n public GVRMesh getMesh() { return meshFound; }\n public boolean visit(GVRComponent comp)\n {\n GVRRenderData rdata = (GVRRenderData) comp;\n meshFound = rdata.getMesh();\n return (meshFound == null);\n }\n };\n MeshFinder findMesh = new MeshFinder();\n model.forAllComponents(findMesh, GVRRenderData.getComponentType());\n return findMesh.getMesh();\n }",
"private Collection<TestClassResults> flattenResults(List<ISuite> suites)\n {\n Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();\n for (ISuite suite : suites)\n {\n for (ISuiteResult suiteResult : suite.getResults().values())\n {\n // Failed and skipped configuration methods are treated as test failures.\n organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);\n // Successful configuration methods are not included.\n \n organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);\n organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);\n }\n }\n return flattenedResults.values();\n }"
] |
Generate the next permutation and return a list containing
the elements in the appropriate order.
@see #nextPermutationAsList(java.util.List)
@see #nextPermutationAsArray()
@return The next permutation as a list. | [
"public List<T> nextPermutationAsList()\n {\n List<T> permutation = new ArrayList<T>(elements.length);\n return nextPermutationAsList(permutation);\n }"
] | [
"public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }",
"public GVRAnimator start(int animIndex)\n {\n if ((animIndex < 0) || (animIndex >= mAnimations.size()))\n {\n throw new IndexOutOfBoundsException(\"Animation index out of bounds\");\n }\n GVRAnimator anim = mAnimations.get(animIndex);\n start(anim);\n return anim;\n }",
"public static void setFlag(Activity activity, final int bits, boolean on) {\n Window win = activity.getWindow();\n WindowManager.LayoutParams winParams = win.getAttributes();\n if (on) {\n winParams.flags |= bits;\n } else {\n winParams.flags &= ~bits;\n }\n win.setAttributes(winParams);\n }",
"public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException {\n\n FileChannel channel = null;\n try {\n channel = new FileInputStream(file).getChannel();\n\n long size = channel.size();\n if (size < ENDLEN) { // Obvious case\n return false;\n }\n else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment\n return true;\n }\n\n // Either file is incomplete or the end of central directory record includes an arbitrary length comment\n // So, we have to scan backwards looking for an end of central directory record\n return scanForEndSig(file, channel);\n }\n finally {\n safeClose(channel);\n }\n }",
"private void createAndAddButton(PatternType pattern, String messageKey) {\n\n CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));\n btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());\n btn.setGroup(m_groupPattern);\n m_patternButtons.put(pattern, btn);\n m_patternRadioButtonsPanel.add(btn);\n\n }",
"public boolean unlink(D declaration, ServiceReference<S> declarationBinderRef) {\n S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);\n try {\n declarationBinder.removeDeclaration(declaration);\n } catch (BinderException e) {\n LOG.debug(declarationBinder + \" throw an exception when removing of it the Declaration \"\n + declaration, e);\n declaration.unhandle(declarationBinderRef);\n return false;\n } finally {\n declaration.unbind(declarationBinderRef);\n }\n return true;\n }",
"public void schedule(BackoffTask task, long initialDelay, long fixedDelay) {\n \tsynchronized (queue) {\n\t \tstart();\n\t queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay));\n \t}\n }",
"public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }",
"private ColorItem buildColorItem(Message menuItem) {\n final int colorId = (int) ((NumberField) menuItem.arguments.get(1)).getValue();\n final String label = ((StringField) menuItem.arguments.get(3)).getValue();\n return buildColorItem(colorId, label);\n }"
] |
perform rollback on all tx-states | [
"public void rollback()\r\n {\r\n try\r\n {\r\n Iterator iter = mvOrderOfIds.iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n if(log.isDebugEnabled())\r\n log.debug(\"rollback: \" + mod);\r\n // if the Object has been modified by transaction, mark object as dirty\r\n if(mod.hasChanged(transaction.getBroker()))\r\n {\r\n mod.setModificationState(mod.getModificationState().markDirty());\r\n }\r\n mod.getModificationState().rollback(mod);\r\n }\r\n }\r\n finally\r\n {\r\n needsCommit = false;\r\n }\r\n afterWriteCleanup();\r\n }"
] | [
"public void loadModel(GVRAndroidResource avatarResource, String attachBone)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n GVRSceneObject boneObject;\n int boneIndex;\n\n if (mSkeleton == null)\n {\n throw new IllegalArgumentException(\"Cannot attach model to avatar - there is no skeleton\");\n }\n boneIndex = mSkeleton.getBoneIndex(attachBone);\n if (boneIndex < 0)\n {\n throw new IllegalArgumentException(attachBone + \" is not a bone in the avatar skeleton\");\n }\n boneObject = mSkeleton.getBone(boneIndex);\n if (boneObject == null)\n {\n throw new IllegalArgumentException(attachBone +\n \" does not have a bone object in the avatar skeleton\");\n }\n boneObject.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }",
"private void init() {\n logger.info(\"metadata init().\");\n\n writeLock.lock();\n try {\n // Required keys\n initCache(CLUSTER_KEY);\n\n // If stores definition storage engine is not null, initialize metadata\n // Add the mapping from key to the storage engine used\n if(this.storeDefinitionsStorageEngine != null) {\n initStoreDefinitions(null);\n } else {\n initCache(STORES_KEY);\n }\n\n // Initialize system store in the metadata cache\n initSystemCache();\n initSystemRoutingStrategies(getCluster());\n\n // Initialize with default if not present\n initCache(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY, true);\n initCache(QUOTA_ENFORCEMENT_ENABLED_KEY, true);\n initCache(REBALANCING_STEAL_INFO, new RebalancerState(new ArrayList<RebalanceTaskInfo>()));\n initCache(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER.toString());\n initCache(REBALANCING_SOURCE_CLUSTER_XML, null);\n initCache(REBALANCING_SOURCE_STORES_XML, null);\n\n\n } finally {\n writeLock.unlock();\n }\n }",
"@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}",
"public long remove(final String... fields) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.hdel(getKey(), fields);\n }\n });\n }",
"private void addChildrenForGroupsNode(I_CmsOuTreeType type, String ouItem) {\n\n try {\n // Cut of type-specific prefix from ouItem with substring()\n List<CmsGroup> groups = m_app.readGroupsForOu(m_cms, ouItem.substring(1), type, false);\n for (CmsGroup group : groups) {\n Pair<String, CmsUUID> key = Pair.of(type.getId(), group.getId());\n Item groupItem = m_treeContainer.addItem(key);\n if (groupItem == null) {\n groupItem = getItem(key);\n }\n groupItem.getItemProperty(PROP_SID).setValue(group.getId());\n groupItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(group, CmsOuTreeType.GROUP));\n groupItem.getItemProperty(PROP_TYPE).setValue(type);\n setChildrenAllowed(key, false);\n m_treeContainer.setParent(key, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }",
"public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {\n MultipartContent.Part part = new MultipartContent.Part()\n .setContent(new InputStreamContent(fileType, fileContent))\n .setHeaders(new HttpHeaders().set(\n \"Content-Disposition\",\n String.format(\"form-data; name=\\\"file\\\"; filename=\\\"%s\\\"\", fileName) // TODO: escape fileName?\n ));\n MultipartContent content = new MultipartContent()\n .setMediaType(new HttpMediaType(\"multipart/form-data\").setParameter(\"boundary\", UUID.randomUUID().toString()))\n .addPart(part);\n\n String path = String.format(\"/tasks/%s/attachments\", task);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"POST\")\n .data(content);\n }",
"public boolean hasForeignkey(String name)\r\n {\r\n String realName = (name == null ? \"\" : name);\r\n ForeignkeyDef def = null;\r\n\r\n for (Iterator it = getForeignkeys(); it.hasNext();)\r\n {\r\n def = (ForeignkeyDef)it.next();\r\n if (realName.equals(def.getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }",
"public static void applyHyperLinkToElement(DynamicJasperDesign design, DJHyperLink djlink, JRDesignChart chart, String name) {\n\t\tJRDesignExpression hlpe = ExpressionUtils.createAndRegisterExpression(design, name, djlink.getExpression());\n\t\tchart.setHyperlinkReferenceExpression(hlpe);\n\t\tchart.setHyperlinkType( HyperlinkTypeEnum.REFERENCE ); //FIXME Should this be a parameter in the future?\n\t\t\t\t\n\t\tif (djlink.getTooltip() != null){\t\t\t\n\t\t\tJRDesignExpression tooltipExp = ExpressionUtils.createAndRegisterExpression(design, \"tooltip_\" + name, djlink.getTooltip());\n\t\t\tchart.setHyperlinkTooltipExpression(tooltipExp);\n\t\t}\n\t}"
] |
Lock the given region. Does not report failures. | [
"public static void mlock(Pointer addr, long len) {\n\n int res = Delegate.mlock(addr, new NativeLong(len));\n if(res != 0) {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Mlock failed probably because of insufficient privileges, errno:\"\n + errno.strerror() + \", return value:\" + res);\n }\n } else {\n if(logger.isDebugEnabled())\n logger.debug(\"Mlock successfull\");\n\n }\n\n }"
] | [
"public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }",
"public static void readAndCheckVersion(ObjectInput input, int supportedVersion, Class<?> externalizedType) throws IOException {\n\t\tint version = input.readInt();\n\n\t\tif ( version != supportedVersion ) {\n\t\t\tthrow LOG.unexpectedKeyVersion( externalizedType, version, supportedVersion );\n\t\t}\n\t}",
"private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }",
"public Curve getRegressionCurve(){\n\t\t// @TODO Add threadsafe lazy init.\n\t\tif(regressionCurve !=null) {\n\t\t\treturn regressionCurve;\n\t\t}\n\t\tDoubleMatrix a = solveEquationSystem();\n\t\tdouble[] curvePoints=new double[partition.getLength()];\n\t\tcurvePoints[0]=a.get(0);\n\t\tfor(int i=1;i<curvePoints.length;i++) {\n\t\t\tcurvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));\n\t\t}\n\t\treturn new CurveInterpolation(\n\t\t\t\t\"RegressionCurve\",\n\t\t\t\treferenceDate,\n\t\t\t\tCurveInterpolation.InterpolationMethod.LINEAR,\n\t\t\t\tCurveInterpolation.ExtrapolationMethod.CONSTANT,\n\t\t\t\tCurveInterpolation.InterpolationEntity.VALUE,\n\t\t\t\tpartition.getPoints(),\n\t\t\t\tcurvePoints);\n\t}",
"public static Index index(String keyspace, String table, String name) {\n return new Index(table, name).keyspace(keyspace);\n }",
"private Event createEvent(Endpoint endpoint, EventTypeEnum type) {\n\n Event event = new Event();\n MessageInfo messageInfo = new MessageInfo();\n Originator originator = new Originator();\n event.setMessageInfo(messageInfo);\n event.setOriginator(originator);\n\n Date date = new Date();\n event.setTimestamp(date);\n event.setEventType(type);\n\n messageInfo.setPortType(\n endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString());\n\n String transportType = null;\n if (endpoint.getBinding() instanceof SoapBinding) {\n SoapBinding soapBinding = (SoapBinding)endpoint.getBinding();\n if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) {\n SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo();\n transportType = soapBindingInfo.getTransportURI();\n }\n }\n messageInfo.setTransportType((transportType != null) ? transportType : \"Unknown transport type\");\n\n originator.setProcessId(Converter.getPID());\n try {\n InetAddress inetAddress = InetAddress.getLocalHost();\n originator.setIp(inetAddress.getHostAddress());\n originator.setHostname(inetAddress.getHostName());\n } catch (UnknownHostException e) {\n originator.setHostname(\"Unknown hostname\");\n originator.setIp(\"Unknown ip address\");\n }\n\n String address = endpoint.getEndpointInfo().getAddress();\n event.getCustomInfo().put(\"address\", address);\n\n return event;\n }",
"public double[] eigenToSampleSpace( double[] eigenData ) {\n if( eigenData.length != numComponents )\n throw new IllegalArgumentException(\"Unexpected sample length\");\n\n DMatrixRMaj s = new DMatrixRMaj(A.getNumCols(),1);\n DMatrixRMaj r = DMatrixRMaj.wrap(numComponents,1,eigenData);\n \n CommonOps_DDRM.multTransA(V_t,r,s);\n\n DMatrixRMaj mean = DMatrixRMaj.wrap(A.getNumCols(),1,this.mean);\n CommonOps_DDRM.add(s,mean,s);\n\n return s.data;\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 <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException {\n\t\tString[] split = signedRequest.split(\"\\\\.\");\n\t\tString encodedSignature = split[0];\n\t\tString payload = split[1];\t\t\n\t\tString decoded = base64DecodeToString(payload);\t\t\n\t\tbyte[] signature = base64DecodeToBytes(encodedSignature);\n\t\ttry {\n\t\t\tT data = objectMapper.readValue(decoded, type);\t\t\t\n\t\t\tString algorithm = objectMapper.readTree(decoded).get(\"algorithm\").textValue();\n\t\t\tif (algorithm == null || !algorithm.equals(\"HMAC-SHA256\")) {\n\t\t\t\tthrow new SignedRequestException(\"Unknown encryption algorithm: \" + algorithm);\n\t\t\t}\t\t\t\n\t\t\tbyte[] expectedSignature = encrypt(payload, secret);\n\t\t\tif (!Arrays.equals(expectedSignature, signature)) {\n\t\t\t\tthrow new SignedRequestException(\"Invalid signature.\");\n\t\t\t}\t\t\t\n\t\t\treturn data;\n\t\t} catch (IOException e) {\n\t\t\tthrow new SignedRequestException(\"Error parsing payload.\", e);\n\t\t}\n\t}"
] |
Tells it to process the submatrix at the next split. Should be called after the
current submatrix has been processed. | [
"public boolean nextSplit() {\n if( numSplits == 0 )\n return false;\n x2 = splits[--numSplits];\n if( numSplits > 0 )\n x1 = splits[numSplits-1]+1;\n else\n x1 = 0;\n\n return true;\n }"
] | [
"public double getAccruedInterest(double time, AnalyticModel model) {\n\t\tLocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time);\n\t\treturn getAccruedInterest(date, model);\n\t}",
"@Override\n @SuppressLint(\"NewApi\")\n public boolean onTouch(View v, MotionEvent event) {\n if(touchable) {\n\n if (event.getAction() == MotionEvent.ACTION_DOWN) {\n view.setBackgroundColor(colorPressed);\n\n return true;\n }\n\n if (event.getAction() == MotionEvent.ACTION_CANCEL) {\n if (isSelected)\n view.setBackgroundColor(colorSelected);\n else\n view.setBackgroundColor(colorUnpressed);\n\n return true;\n }\n\n\n if (event.getAction() == MotionEvent.ACTION_UP) {\n\n view.setBackgroundColor(colorSelected);\n afterClick();\n\n return true;\n }\n }\n\n return false;\n }",
"private void map(Resource root) {\n\n for (Resource.ResourceEntry serverGroup : root.getChildren(SERVER_GROUP)) {\n String serverGroupName = serverGroup.getName();\n ModelNode serverGroupModel = serverGroup.getModel();\n String profile = serverGroupModel.require(PROFILE).asString();\n store(serverGroupName, profile, profilesToGroups);\n String socketBindingGroup = serverGroupModel.require(SOCKET_BINDING_GROUP).asString();\n store(serverGroupName, socketBindingGroup, socketsToGroups);\n\n for (Resource.ResourceEntry deployment : serverGroup.getChildren(DEPLOYMENT)) {\n store(serverGroupName, deployment.getName(), deploymentsToGroups);\n }\n\n for (Resource.ResourceEntry overlay : serverGroup.getChildren(DEPLOYMENT_OVERLAY)) {\n store(serverGroupName, overlay.getName(), overlaysToGroups);\n }\n\n }\n\n for (Resource.ResourceEntry host : root.getChildren(HOST)) {\n String hostName = host.getPathElement().getValue();\n for (Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n ModelNode serverConfigModel = serverConfig.getModel();\n String serverGroupName = serverConfigModel.require(GROUP).asString();\n store(serverGroupName, hostName, hostsToGroups);\n }\n }\n }",
"private void checkAndAddForbiddenStrings(final List<String> forbiddenSubStrings) {\n\t\tfor( String forbidden : forbiddenSubStrings ) {\n\t\t\tif( forbidden == null ) {\n\t\t\t\tthrow new NullPointerException(\"forbidden substring should not be null\");\n\t\t\t}\n\t\t\tthis.forbiddenSubStrings.add(forbidden);\n\t\t}\n\t}",
"public void removeAt(int index) {\n synchronized (mLock) {\n if (mOriginalValues != null) {\n mOriginalValues.remove(index);\n } else {\n mObjects.remove(index);\n }\n }\n if (mNotifyOnChange) notifyDataSetChanged();\n }",
"public Set<Class<?>> getPrevented() {\n if (this.prevent == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(this.prevent);\n }",
"public void run(Configuration configuration, InjectableStepsFactory stepsFactory, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n RunContext context = new RunContext(configuration, stepsFactory, story.getPath(), filter);\n if (beforeStories != null) {\n context.stateIs(beforeStories);\n }\n Map<String, String> storyParameters = new HashMap<>();\n run(context, story, storyParameters);\n }",
"private Client getClient(){\n final ClientConfig cfg = new DefaultClientConfig();\n cfg.getClasses().add(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider.class);\n cfg.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout);\n\n return Client.create(cfg);\n }",
"private float getQuaternionW(float x, float y, float z) {\n return (float) Math.cos(Math.asin(Math.sqrt(x * x + y * y + z * z)));\n }"
] |
remove drag support from the given Component.
@param c the Component to remove | [
"public void unregisterComponent(java.awt.Component c)\r\n {\r\n java.awt.dnd.DragGestureRecognizer recognizer = \r\n (java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);\r\n if (recognizer != null)\r\n recognizer.setComponent(null);\r\n }"
] | [
"public String getNamefromId(int id) {\n return (String) sqlService.getFromTable(\n Constants.PROFILE_PROFILE_NAME, Constants.GENERIC_ID,\n id, Constants.DB_TABLE_PROFILE);\n }",
"public void setClassOfObject(Class c)\r\n {\r\n m_Class = c;\r\n isAbstract = Modifier.isAbstract(m_Class.getModifiers());\r\n // TODO : Shouldn't the HashMap in DescriptorRepository be updated as well?\r\n }",
"public Object extractJavaFieldValue(Object object) throws SQLException {\n\n\t\tObject val = extractRawJavaFieldValue(object);\n\n\t\t// if this is a foreign object then we want its reference field\n\t\tif (foreignRefField != null && val != null) {\n\t\t\tval = foreignRefField.extractRawJavaFieldValue(val);\n\t\t}\n\n\t\treturn val;\n\t}",
"public static base_response delete(nitro_service client, String ipv6prefix) throws Exception {\n\t\tonlinkipv6prefix deleteresource = new onlinkipv6prefix();\n\t\tdeleteresource.ipv6prefix = ipv6prefix;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public static double normP2( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return normF(A);\n } else {\n return inducedP2(A);\n }\n }",
"public void addAppenderEvent(final Category cat, final Appender appender) {\n\n\t\tupdateDefaultLayout(appender);\n\n\t\tif (appender instanceof FoundationFileRollingAppender) {\n\t\t\tfinal FoundationFileRollingAppender timeSizeRollingAppender = (FoundationFileRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\t//updateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout(); //So application state will not make any problems\n\n\t\t}else if(!(appender instanceof FoundationFileRollingAppender) && (appender instanceof TimeAndSizeRollingAppender)){ //TimeAndSizeRollingAppender\n\t\t\tfinal TimeAndSizeRollingAppender timeSizeRollingAppender = (TimeAndSizeRollingAppender) appender;\n\n\t\t\t// update the appender with default vales such as logging pattern, file size etc.\n\t\t\tupdateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);\n\n\t\t\t// read teh proeprties and determine if archiving should be enabled.\n\t\t\tupdateArchivingSupport(timeSizeRollingAppender);\n\n\t\t\t// by default add the rolling file listener to enable application\n\t\t\t// state.\n\t\t\ttimeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());\n\n\t\t\tboolean rollOnStartup = true;\n\n\t\t\tif (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {\n\t\t\t\trollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));\n\t\t\t}\n\n\t\t\ttimeSizeRollingAppender.setRollOnStartup(rollOnStartup);\n\n\t\t\t// refresh the appender\n\t\t\ttimeSizeRollingAppender.activateOptions();\n\n\t\t\t\n\t\t//\ttimeSizeRollingAppender.setOriginalLayout();\n\t\t}\n\t\tif ( ! (appender instanceof org.apache.log4j.AsyncAppender))\n initiateAsyncSupport(appender);\n\n\t}",
"private Iterable<BoxRetentionPolicyAssignment.Info> getAssignments(String type, int limit, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (type != null) {\r\n queryString.appendParam(\"type\", type);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString(), getID());\r\n return new BoxResourceIterable<BoxRetentionPolicyAssignment.Info>(getAPI(), url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicyAssignment assignment\r\n = new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get(\"id\").asString());\r\n return assignment.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }",
"public void setMonth(String monthStr) {\n\n final Month month = Month.valueOf(monthStr);\n if ((m_model.getMonth() == null) || !m_model.getMonth().equals(monthStr)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setMonth(month);\n onValueChange();\n\n }\n });\n }\n }",
"public String getUnicodeString(Integer type)\n {\n String result = null;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getUnicodeString(item, 0);\n }\n\n return (result);\n }"
] |
Inflate the main layout used to render videos in the list view.
@param inflater LayoutInflater service to inflate.
@param parent ViewGroup used to inflate xml.
@return view inflated. | [
"@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) {\n View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false);\n /*\n * You don't have to use ButterKnife library to implement the mapping between your layout\n * and your widgets you can implement setUpView and hookListener methods declared in\n * Renderer<T> class.\n */\n ButterKnife.bind(this, inflatedView);\n return inflatedView;\n }"
] | [
"private void setPlaybackPosition(long milliseconds) {\n PlaybackState oldState = currentSimpleState();\n if (oldState != null && oldState.position != milliseconds) {\n setPlaybackState(oldState.player, milliseconds, oldState.playing);\n }\n }",
"public static JmsDestinationType getTypeFromClass(String aClass)\n {\n if (StringUtils.equals(aClass, \"javax.jms.Queue\") || StringUtils.equals(aClass, \"javax.jms.QueueConnectionFactory\"))\n {\n return JmsDestinationType.QUEUE;\n }\n else if (StringUtils.equals(aClass, \"javax.jms.Topic\") || StringUtils.equals(aClass, \"javax.jms.TopicConnectionFactory\"))\n {\n return JmsDestinationType.TOPIC;\n }\n else\n {\n return null;\n }\n }",
"private void addMetadataProviderForMedia(String key, MetadataProvider provider) {\n if (!metadataProviders.containsKey(key)) {\n metadataProviders.put(key, Collections.newSetFromMap(new ConcurrentHashMap<MetadataProvider, Boolean>()));\n }\n Set<MetadataProvider> providers = metadataProviders.get(key);\n providers.add(provider);\n }",
"public void setStatusBarColor(int statusBarColor) {\n if (mBuilder.mScrimInsetsLayout != null) {\n mBuilder.mScrimInsetsLayout.setInsetForeground(statusBarColor);\n mBuilder.mScrimInsetsLayout.getView().invalidate();\n }\n }",
"protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)\r\n {\r\n Class fieldType = desc.getPersistentField().getType();\r\n ManageableCollection col;\r\n\r\n if (collectionClass == null)\r\n {\r\n if (ManageableCollection.class.isAssignableFrom(fieldType))\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)fieldType.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the default collection type \"+fieldType.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))\r\n {\r\n col = new RemovalAwareCollection();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareList.class))\r\n {\r\n col = new RemovalAwareList();\r\n }\r\n else if (fieldType.isAssignableFrom(RemovalAwareSet.class))\r\n {\r\n col = new RemovalAwareSet();\r\n }\r\n else\r\n {\r\n throw new MetadataException(\"Cannot determine a default collection type for collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n col = (ManageableCollection)collectionClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot instantiate the collection class \"+collectionClass.getName()+\" of collection \"+desc.getAttributeName()+\" in type \"+desc.getClassDescriptor().getClassNameOfObject());\r\n }\r\n }\r\n return col;\r\n }",
"public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) {\n\t\tMap<String, Object> params = params( columnValues );\n\t\tResult result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params );\n\t\treturn singleResult( result );\n\t}",
"public void retrieveProxyCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, true);\r\n }",
"public ThreadInfo[] getThreadDump() {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n return threadMxBean.dumpAllThreads(true, true);\n }",
"@Override\n public boolean decompose(DMatrixRBlock A) {\n if( A.numCols != A.numRows )\n throw new IllegalArgumentException(\"A must be square\");\n\n this.T = A;\n\n if( lower )\n return decomposeLower();\n else\n return decomposeUpper();\n }"
] |
Get the MonetaryAmount implementation class.
@return the implementation class of the containing amount instance, never null.
@see MonetaryAmount#getContext() | [
"public Class<? extends MonetaryAmount> getAmountType() {\n Class<?> clazz = get(AMOUNT_TYPE, Class.class);\n return clazz.asSubclass(MonetaryAmount.class);\n }"
] | [
"public String getHiveExecutionEngine() {\n String executionEngine = hiveConfSystemOverride.get(HiveConf.ConfVars.HIVE_EXECUTION_ENGINE.varname);\n return executionEngine == null ? HiveConf.ConfVars.HIVE_EXECUTION_ENGINE.getDefaultValue() : executionEngine;\n }",
"public static base_response update(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig updateresource = new nsconfig();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.nsvlan = resource.nsvlan;\n\t\tupdateresource.ifnum = resource.ifnum;\n\t\tupdateresource.tagged = resource.tagged;\n\t\tupdateresource.httpport = resource.httpport;\n\t\tupdateresource.maxconn = resource.maxconn;\n\t\tupdateresource.maxreq = resource.maxreq;\n\t\tupdateresource.cip = resource.cip;\n\t\tupdateresource.cipheader = resource.cipheader;\n\t\tupdateresource.cookieversion = resource.cookieversion;\n\t\tupdateresource.securecookie = resource.securecookie;\n\t\tupdateresource.pmtumin = resource.pmtumin;\n\t\tupdateresource.pmtutimeout = resource.pmtutimeout;\n\t\tupdateresource.ftpportrange = resource.ftpportrange;\n\t\tupdateresource.crportrange = resource.crportrange;\n\t\tupdateresource.timezone = resource.timezone;\n\t\tupdateresource.grantquotamaxclient = resource.grantquotamaxclient;\n\t\tupdateresource.exclusivequotamaxclient = resource.exclusivequotamaxclient;\n\t\tupdateresource.grantquotaspillover = resource.grantquotaspillover;\n\t\tupdateresource.exclusivequotaspillover = resource.exclusivequotaspillover;\n\t\tupdateresource.nwfwmode = resource.nwfwmode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"protected void resize( VariableMatrix mat , int numRows , int numCols ) {\n if( mat.isTemp() ) {\n mat.matrix.reshape(numRows,numCols);\n }\n }",
"@SuppressWarnings(\"unused\")\n public Phonenumber.PhoneNumber getPhoneNumber() {\n try {\n String iso = null;\n if (mSelectedCountry != null) {\n iso = mSelectedCountry.getIso();\n }\n return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso);\n } catch (NumberParseException ignored) {\n return null;\n }\n }",
"public static Collection<CurrencyUnit> getCurrencies(String... providers) {\n return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(\n () -> new MonetaryException(\"No MonetaryCurrenciesSingletonSpi loaded, check your system setup.\"))\n .getCurrencies(providers);\n }",
"public static cachepolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel obj = new cachepolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel response = (cachepolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static base_responses reset(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface resetresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tresetresources[i] = new Interface();\n\t\t\t\tresetresources[i].id = resources[i].id;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, resetresources,\"reset\");\n\t\t}\n\t\treturn result;\n\t}",
"@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }",
"private void processDays(ProjectCalendar calendar) throws Exception\n {\n // Default all days to non-working\n for (Day day : Day.values())\n {\n calendar.setWorkingDay(day, false);\n }\n\n List<Row> rows = getRows(\"select * from zcalendarrule where zcalendar1=? and z_ent=?\", calendar.getUniqueID(), m_entityMap.get(\"CalendarWeekDayRule\"));\n for (Row row : rows)\n {\n Day day = row.getDay(\"ZWEEKDAY\");\n String timeIntervals = row.getString(\"ZTIMEINTERVALS\");\n if (timeIntervals == null)\n {\n calendar.setWorkingDay(day, false);\n }\n else\n {\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n NodeList nodes = getNodeList(timeIntervals, m_dayTimeIntervals);\n calendar.setWorkingDay(day, nodes.getLength() > 0);\n\n for (int loop = 0; loop < nodes.getLength(); loop++)\n {\n NamedNodeMap attributes = nodes.item(loop).getAttributes();\n Date startTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"startTime\").getTextContent());\n Date endTime = m_calendarTimeFormat.parse(attributes.getNamedItem(\"endTime\").getTextContent());\n\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }"
] |
This method will be intercepted by the proxy if it is enabled to return the internal target.
@return the target. | [
"public Object getProxyTarget(){\r\n\t\ttry {\r\n\t\t\treturn Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod(\"getProxyTarget\"), null);\r\n\t\t} catch (Throwable t) {\r\n\t\t\tthrow new RuntimeException(\"BoneCP: Internal error - transaction replay log is not turned on?\", t);\r\n\t\t}\r\n\t}"
] | [
"private int findYOffsetForGroupLabel(JRDesignBand band) {\n\t\tint offset = 0;\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\tif (elem.getKey() != null && elem.getKey().startsWith(\"variable_for_column_\")) {\n\t\t\t\toffset = elem.getY();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn offset;\n\t}",
"@Override\n\tpublic List<String> contentTypes() {\n\t\tList<String> contentTypes = null;\n\t\tfinal HttpServletRequest request = getHttpRequest();\n\n\t\tif (favorParameterOverAcceptHeader) {\n\t\t\tcontentTypes = getFavoredParameterValueAsList(request);\n\t\t} else {\n\t\t\tcontentTypes = getAcceptHeaderValues(request);\n\t\t}\n\n\t\tif (isEmpty(contentTypes)) {\n\t\t\tlogger.debug(\"Setting content types to default: {}.\", DEFAULT_SUPPORTED_CONTENT_TYPES);\n\n\t\t\tcontentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES;\n\t\t}\n\n\t\treturn unmodifiableList(contentTypes);\n\t}",
"private void writeTask(Task task) throws IOException\n {\n writeFields(null, task, TaskField.values());\n for (Task child : task.getChildTasks())\n {\n writeTask(child);\n }\n }",
"@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException\n {\n try\n {\n populateMemberData(reader, file, root);\n processProjectProperties();\n\n if (!reader.getReadPropertiesOnly())\n {\n processSubProjectData();\n processGraphicalIndicators();\n processCustomValueLists();\n processCalendarData();\n processResourceData();\n processTaskData();\n processConstraintData();\n processAssignmentData();\n postProcessTasks();\n\n if (reader.getReadPresentationData())\n {\n processViewPropertyData();\n processTableData();\n processViewData();\n processFilterData();\n processGroupData();\n processSavedViewState();\n }\n }\n }\n\n finally\n {\n clearMemberData();\n }\n }",
"public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public void end() {\n if (TransitionConfig.isPrintDebug()) {\n getTransitionStateHolder().end();\n getTransitionStateHolder().print();\n }\n\n for (int i = 0, size = mTransitionControls.size(); i < size; i++) {\n mTransitionControls.get(i).end();\n }\n }",
"public double distanceToPlane(Point3d p) {\n return normal.x * p.x + normal.y * p.y + normal.z * p.z - planeOffset;\n }",
"public ConfigurableMessages getConfigurableMessages(CmsMessages defaultMessages, Locale locale) {\n\n return new ConfigurableMessages(defaultMessages, locale, m_configuredBundle);\n\n }",
"public static Integer getDurationUnits(RecurringTask recurrence)\n {\n Duration duration = recurrence.getDuration();\n Integer result = null;\n\n if (duration != null)\n {\n result = UNITS_MAP.get(duration.getUnits());\n }\n\n return (result);\n }"
] |
This method writes project extended attribute data into an MSPDI file.
@param project Root node of the MSPDI file | [
"private void writeProjectExtendedAttributes(Project project)\n {\n Project.ExtendedAttributes attributes = m_factory.createProjectExtendedAttributes();\n project.setExtendedAttributes(attributes);\n List<Project.ExtendedAttributes.ExtendedAttribute> list = attributes.getExtendedAttribute();\n\n Set<FieldType> customFields = new HashSet<FieldType>();\n for (CustomField customField : m_projectFile.getCustomFields())\n {\n FieldType fieldType = customField.getFieldType();\n if (fieldType != null)\n {\n customFields.add(fieldType);\n }\n }\n\n customFields.addAll(m_extendedAttributesInUse);\n \n List<FieldType> customFieldsList = new ArrayList<FieldType>();\n customFieldsList.addAll(customFields);\n \n\n // Sort to ensure consistent order in file\n final CustomFieldContainer customFieldContainer = m_projectFile.getCustomFields();\n Collections.sort(customFieldsList, new Comparator<FieldType>()\n {\n @Override public int compare(FieldType o1, FieldType o2)\n {\n CustomField customField1 = customFieldContainer.getCustomField(o1);\n CustomField customField2 = customFieldContainer.getCustomField(o2);\n String name1 = o1.getClass().getSimpleName() + \".\" + o1.getName() + \" \" + customField1.getAlias();\n String name2 = o2.getClass().getSimpleName() + \".\" + o2.getName() + \" \" + customField2.getAlias();\n return name1.compareTo(name2);\n }\n });\n\n for (FieldType fieldType : customFieldsList)\n {\n Project.ExtendedAttributes.ExtendedAttribute attribute = m_factory.createProjectExtendedAttributesExtendedAttribute();\n list.add(attribute);\n attribute.setFieldID(String.valueOf(FieldTypeHelper.getFieldID(fieldType)));\n attribute.setFieldName(fieldType.getName());\n\n CustomField customField = customFieldContainer.getCustomField(fieldType);\n attribute.setAlias(customField.getAlias());\n }\n }"
] | [
"public static Chart getMSDLineWithFreeModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double intercept) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = intercept + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + a\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"@SuppressWarnings(\"unchecked\")\n public void updateStoreDefinitions(Versioned<byte[]> valueBytes) {\n // acquire write lock\n writeLock.lock();\n\n try {\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n Versioned<Object> valueObject = convertStringToObject(STORES_KEY, value);\n StoreDefinitionsMapper mapper = new StoreDefinitionsMapper();\n List<StoreDefinition> storeDefinitions = (List<StoreDefinition>) valueObject.getValue();\n\n // Check for backwards compatibility\n StoreDefinitionUtils.validateSchemasAsNeeded(storeDefinitions);\n\n StoreDefinitionUtils.validateNewStoreDefsAreNonBreaking(getStoreDefList(), storeDefinitions);\n\n // Go through each store definition and do a corresponding put\n for(StoreDefinition storeDef: storeDefinitions) {\n if(!this.storeNames.contains(storeDef.getName())) {\n throw new VoldemortException(\"Cannot update a store which does not exist !\");\n }\n\n String storeDefStr = mapper.writeStore(storeDef);\n Versioned<String> versionedValueStr = new Versioned<String>(storeDefStr,\n value.getVersion());\n this.storeDefinitionsStorageEngine.put(storeDef.getName(), versionedValueStr, \"\");\n\n // Update the metadata cache\n this.metadataCache.put(storeDef.getName(),\n new Versioned<Object>(storeDefStr, value.getVersion()));\n }\n\n // Re-initialize the store definitions\n initStoreDefinitions(value.getVersion());\n\n // Update routing strategies\n // TODO: Make this more fine grained.. i.e only update listeners for\n // a specific store.\n updateRoutingStrategies(getCluster(), getStoreDefList());\n } finally {\n writeLock.unlock();\n }\n }",
"protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) {\n\n\t\treturn (Connection) Proxy.newProxyInstance(\n\t\t\t\tConnectionProxy.class.getClassLoader(),\n\t\t\t\tnew Class[] {ConnectionProxy.class},\n\t\t\t\tnew MemorizeTransactionProxy(target, connectionHandle));\n\t}",
"public void addAttribute(String attributeName, String attributeValue)\r\n {\r\n if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))\r\n {\r\n final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);\r\n jdbcProperties.setProperty(jdbcPropertyName, attributeValue);\r\n }\r\n else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))\r\n {\r\n final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);\r\n dbcpProperties.setProperty(dbcpPropertyName, attributeValue);\r\n }\r\n else\r\n {\r\n super.addAttribute(attributeName, attributeValue);\r\n }\r\n }",
"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 }",
"protected List<Integer> getPageSizes() {\n\n try {\n return Collections.singletonList(Integer.valueOf(m_configObject.getInt(JSON_KEY_PAGESIZE)));\n } catch (JSONException e) {\n List<Integer> result = null;\n String pageSizesString = null;\n try {\n pageSizesString = m_configObject.getString(JSON_KEY_PAGESIZE);\n String[] pageSizesArray = pageSizesString.split(\"-\");\n if (pageSizesArray.length > 0) {\n result = new ArrayList<>(pageSizesArray.length);\n for (int i = 0; i < pageSizesArray.length; i++) {\n result.add(Integer.valueOf(pageSizesArray[i]));\n }\n }\n return result;\n } catch (NumberFormatException | JSONException e1) {\n LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizesString), e);\n }\n if (null == m_baseConfig) {\n if (LOG.isInfoEnabled()) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_PAGESIZE_SPECIFIED_0), e);\n }\n return null;\n } else {\n return m_baseConfig.getPaginationConfig().getPageSizes();\n }\n }\n }",
"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 static Resource getSetupPage(I_SetupUiContext context, String name) {\n\n String path = CmsStringUtil.joinPaths(context.getSetupBean().getContextPath(), CmsSetupBean.FOLDER_SETUP, name);\n Resource resource = new ExternalResource(path);\n return resource;\n }",
"public static void fire(I_CmsHasDateBoxEventHandlers source, Date date, boolean isTyping) {\n\n if (TYPE != null) {\n CmsDateBoxEvent event = new CmsDateBoxEvent(date, isTyping);\n source.fireEvent(event);\n }\n }"
] |
Subsets and Splits