query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Apply the AAD algorithm to this very variable NOTE: in this case it is indeed correct to assume that the output dimension is "one" meaning that there is only one {@link RandomVariableUniqueVariable} as an output. @return gradient for the built up function
[ "public RandomVariable[] getGradient(){\r\n\r\n\t\t// for now let us take the case for output-dimension equal to one!\r\n\t\tint numberOfVariables = getNumberOfVariablesInList();\r\n\t\tint numberOfCalculationSteps = factory.getNumberOfEntriesInList();\r\n\r\n\t\tRandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\t// first entry gets initialized\r\n\t\tomega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\t/*\r\n\t\t * TODO: Find way that calculations form here on are not 'recorded' by the factory\r\n\t\t * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!\r\n\t\t * */\r\n\r\n\t\tfor(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){\r\n\t\t\t// apply chain rule\r\n\t\t\tomega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\t/*TODO: save all D_{i,j}*\\omega_j in vector and sum up later */\r\n\t\t\tfor(RandomVariableUniqueVariable parent:parentsVariables){\r\n\r\n\t\t\t\tint variableIndex = parent.getVariableID();\r\n\r\n\t\t\t\tomega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex]));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!\r\n\t\t * Thus save the indices of the true variables and recover them after finalizing all the calculations\r\n\t\t * IDEA: quit calculation after minimal true variable index is reached */\r\n\t\tRandomVariable[] gradient = new RandomVariable[numberOfVariables];\r\n\r\n\t\t/* TODO: sort array in correct manner! */\r\n\t\tint[] indicesOfVariables = getIDsOfVariablesInList();\r\n\r\n\t\tfor(int i = 0; i < numberOfVariables; i++){\r\n\t\t\tgradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]];\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}" ]
[ "private void\n executeSubBatch(final int batchId,\n RebalanceBatchPlanProgressBar progressBar,\n final Cluster batchRollbackCluster,\n final List<StoreDefinition> batchRollbackStoreDefs,\n final List<RebalanceTaskInfo> rebalanceTaskPlanList,\n boolean hasReadOnlyStores,\n boolean hasReadWriteStores,\n boolean finishedReadOnlyStores) {\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Submitting rebalance tasks \");\n\n // Get an ExecutorService in place used for submitting our tasks\n ExecutorService service = RebalanceUtils.createExecutors(maxParallelRebalancing);\n\n // Sub-list of the above list\n final List<RebalanceTask> failedTasks = Lists.newArrayList();\n final List<RebalanceTask> incompleteTasks = Lists.newArrayList();\n\n // Semaphores for donor nodes - To avoid multiple disk sweeps\n Map<Integer, Semaphore> donorPermits = new HashMap<Integer, Semaphore>();\n for(Node node: batchRollbackCluster.getNodes()) {\n donorPermits.put(node.getId(), new Semaphore(1));\n }\n\n try {\n // List of tasks which will run asynchronously\n List<RebalanceTask> allTasks = executeTasks(batchId,\n progressBar,\n service,\n rebalanceTaskPlanList,\n donorPermits);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"All rebalance tasks submitted\");\n\n // Wait and shutdown after (infinite) timeout\n RebalanceUtils.executorShutDown(service, Long.MAX_VALUE);\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Finished waiting for executors\");\n\n // Collects all failures + incomplete tasks from the rebalance\n // tasks.\n List<Exception> failures = Lists.newArrayList();\n for(RebalanceTask task: allTasks) {\n if(task.hasException()) {\n failedTasks.add(task);\n failures.add(task.getError());\n } else if(!task.isComplete()) {\n incompleteTasks.add(task);\n }\n }\n\n if(failedTasks.size() > 0) {\n throw new VoldemortRebalancingException(\"Rebalance task terminated unsuccessfully on tasks \"\n + failedTasks,\n failures);\n }\n\n // If there were no failures, then we could have had a genuine\n // timeout ( Rebalancing took longer than the operator expected ).\n // We should throw a VoldemortException and not a\n // VoldemortRebalancingException ( which will start reverting\n // metadata ). The operator may want to manually then resume the\n // process.\n if(incompleteTasks.size() > 0) {\n throw new VoldemortException(\"Rebalance tasks are still incomplete / running \"\n + incompleteTasks);\n }\n\n } catch(VoldemortRebalancingException e) {\n\n logger.error(\"Failure while migrating partitions for rebalance task \"\n + batchId);\n\n if(hasReadOnlyStores && hasReadWriteStores\n && finishedReadOnlyStores) {\n // Case 0\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n true,\n true,\n false,\n false,\n false);\n } else if(hasReadWriteStores && finishedReadOnlyStores) {\n // Case 4\n adminClient.rebalanceOps.rebalanceStateChange(null,\n batchRollbackCluster,\n null,\n batchRollbackStoreDefs,\n null,\n false,\n true,\n false,\n false,\n false);\n }\n\n throw e;\n\n } finally {\n if(!service.isShutdown()) {\n RebalanceUtils.printErrorLog(batchId,\n logger,\n \"Could not shutdown service cleanly for rebalance task \"\n + batchId,\n null);\n service.shutdownNow();\n }\n }\n }", "public static void checkRequired(OptionSet options, String opt) throws VoldemortException {\n List<String> opts = Lists.newArrayList();\n opts.add(opt);\n checkRequired(options, opts);\n }", "public static IBlur getIBlurAlgorithm(EBlurAlgorithm algorithm, ContextWrapper contextWrapper) {\n RenderScript rs = contextWrapper.getRenderScript();\n Context ctx = contextWrapper.getContext();\n\n switch (algorithm) {\n case RS_GAUSS_FAST:\n return new RenderScriptGaussianBlur(rs);\n case RS_BOX_5x5:\n return new RenderScriptBox5x5Blur(rs);\n case RS_GAUSS_5x5:\n return new RenderScriptGaussian5x5Blur(rs);\n case RS_STACKBLUR:\n return new RenderScriptStackBlur(rs, ctx);\n case STACKBLUR:\n return new StackBlur();\n case GAUSS_FAST:\n return new GaussianFastBlur();\n case BOX_BLUR:\n return new BoxBlur();\n default:\n return new IgnoreBlur();\n }\n }", "private static int getTrimmedWidth(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int trimmedWidth = 0;\n\n for (int i = 0; i < height; i++) {\n for (int j = width - 1; j >= 0; j--) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {\n trimmedWidth = j;\n break;\n }\n }\n }\n\n return trimmedWidth;\n }", "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 void logAttributeWarning(PathAddress address, Set<String> attributes) {\n logAttributeWarning(address, null, null, attributes);\n }", "public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {\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\tTimeDiscretization fixTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tTimeDiscretization floatTenor\t= new TimeDiscretizationFromArray(swapTenor);\n\t\tdouble forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);\n\t\tdouble swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);\n\t\tdouble payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);\n\t\treturn AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);\n\t}", "public static base_response add(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite addresource = new gslbsite();\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.sitetype = resource.sitetype;\n\t\taddresource.siteipaddress = resource.siteipaddress;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.metricexchange = resource.metricexchange;\n\t\taddresource.nwmetricexchange = resource.nwmetricexchange;\n\t\taddresource.sessionexchange = resource.sessionexchange;\n\t\taddresource.triggermonitor = resource.triggermonitor;\n\t\taddresource.parentsite = resource.parentsite;\n\t\treturn addresource.add_resource(client);\n\t}", "public static String makePropertyName(String name) {\n char[] buf = new char[name.length() + 3];\n int pos = 0;\n buf[pos++] = 's';\n buf[pos++] = 'e';\n buf[pos++] = 't';\n\n for (int ix = 0; ix < name.length(); ix++) {\n char ch = name.charAt(ix);\n if (ix == 0)\n ch = Character.toUpperCase(ch);\n else if (ch == '-') {\n ix++;\n if (ix == name.length())\n break;\n ch = Character.toUpperCase(name.charAt(ix));\n }\n\n buf[pos++] = ch;\n }\n\n return new String(buf, 0, pos);\n }" ]
Read an int from an input stream. @param is input stream @return int value
[ "public static final int getInt(InputStream is) throws IOException\n {\n byte[] data = new byte[4];\n is.read(data);\n return getInt(data, 0);\n }" ]
[ "public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException {\n Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames);\n Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create();\n if (deploymentNames.isEmpty()) {\n for (String s : runtimeNames) {\n ServerLogger.ROOT_LOGGER.debugf(\"We haven't found any deployment for %s in server-group %s\", s, deploymentsRootAddress.getLastElement().getValue());\n }\n }\n if(removeOperation != null) {\n opBuilder.addStep(removeOperation);\n }\n for (String deploymentName : deploymentNames) {\n opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName)));\n }\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n final ModelNode slave = opBuilder.build().getOperation();\n transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress()));\n }", "public void stop()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"stopping audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().stopSound(getSourceId());\n }\n }", "public static gslbservice[] get(nitro_service service) throws Exception{\n\t\tgslbservice obj = new gslbservice();\n\t\tgslbservice[] response = (gslbservice[])obj.get_resources(service);\n\t\treturn response;\n\t}", "private String parseMandatoryStringValue(final String path) throws Exception {\n\n final String value = parseOptionalStringValue(path);\n if (value == null) {\n throw new Exception();\n }\n return value;\n }", "public void addRow(String primaryKeyColumnName, Map<String, Object> map)\n {\n Integer rowNumber = Integer.valueOf(m_rowNumber++);\n map.put(\"ROW_NUMBER\", rowNumber);\n Object primaryKey = null;\n if (primaryKeyColumnName != null)\n {\n primaryKey = map.get(primaryKeyColumnName);\n }\n\n if (primaryKey == null)\n {\n primaryKey = rowNumber;\n }\n\n MapRow newRow = new MapRow(map);\n MapRow oldRow = m_rows.get(primaryKey);\n if (oldRow == null)\n {\n m_rows.put(primaryKey, newRow);\n }\n else\n {\n int oldVersion = oldRow.getInteger(\"ROW_VERSION\").intValue();\n int newVersion = newRow.getInteger(\"ROW_VERSION\").intValue();\n if (newVersion > oldVersion)\n {\n m_rows.put(primaryKey, newRow);\n }\n }\n }", "private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {\n\t\tif (to.equals(from))\n\t\t\treturn true;\n\n\t\tif (from instanceof TypeVariable) {\n\t\t\treturn to.equals(typeMap.get(((TypeVariable<?>) from).getName()));\n\t\t}\n\n\t\treturn false;\n\t}", "public static final Date getTimestampFromTenths(byte[] data, int offset)\n {\n long ms = ((long) getInt(data, offset)) * 6000;\n return (DateHelper.getTimestampFromLong(EPOCH + ms));\n }", "public static cmppolicylabel_cmppolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_cmppolicy_binding obj = new cmppolicylabel_cmppolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_cmppolicy_binding response[] = (cmppolicylabel_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "@Override\n public void finish() {\n if (started.get() && !finished.getAndSet(true)) {\n waitUntilFinished();\n super.finish();\n // recreate thread (don't start) for processor reuse\n createProcessorThread();\n clearQueues();\n started.set(false);\n }\n }" ]
Sets left and right padding for all cells in the row. @param padding new padding for left and right, ignored if smaller than 0 @return this to allow chaining
[ "public AT_Row setPaddingLeftRight(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}" ]
[ "public CollectionRequest<Task> subtasks(String task) {\n \n String path = String.format(\"/tasks/%s/subtasks\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "public 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 }", "private void addCheckBox(Date date, boolean checkState) {\n\n CmsCheckBox cb = generateCheckBox(date, checkState);\n m_checkBoxes.add(cb);\n reInitLayoutElements();\n\n }", "@Subscribe\n public void onQuit(AggregatedQuitEvent e) {\n if (summaryFile != null) {\n try {\n Persister persister = new Persister();\n persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile);\n } catch (Exception x) {\n junit4.log(\"Could not serialize summary report.\", x, Project.MSG_WARN);\n }\n }\n }", "public static base_response unset(nitro_service client, snmpmanager resource, String[] args) throws Exception{\n\t\tsnmpmanager unsetresource = new snmpmanager();\n\t\tunsetresource.ipaddress = resource.ipaddress;\n\t\tunsetresource.netmask = resource.netmask;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public void setHtml(String html) {\n this.html = html;\n\n if (widget != null) {\n if (widget.isAttached()) {\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\");\n } else {\n widget.addAttachHandler(event ->\n tooltipElement.find(\"span\")\n .html(html != null ? html : \"\"));\n }\n } else {\n GWT.log(\"Please initialize the Target widget.\", new IllegalStateException());\n }\n }", "public DynamicReportBuilder setTemplateFile(String path, boolean importFields, boolean importVariables, boolean importParameters, boolean importDatasets) {\n report.setTemplateFileName(path);\n report.setTemplateImportFields(importFields);\n report.setTemplateImportParameters(importParameters);\n report.setTemplateImportVariables(importVariables);\n report.setTemplateImportDatasets(importDatasets);\n return this;\n }", "public static String getRelativePathName(Path root, Path path) {\n Path relative = root.relativize(path);\n return Files.isDirectory(path) && !relative.toString().endsWith(\"/\") ? String.format(\"%s/\", relative.toString()) : relative.toString();\n }", "private void emitSuiteEnd(AggregatedSuiteResultEvent e, int suitesCompleted) throws IOException {\n assert showSuiteSummary;\n\n final StringBuilder b = new StringBuilder();\n final int totalErrors = this.totalErrors.addAndGet(e.isSuccessful() ? 0 : 1);\n b.append(String.format(Locale.ROOT, \"%sCompleted [%d/%d%s]%s in %.2fs, \",\n shortTimestamp(e.getStartTimestamp() + e.getExecutionTime()),\n suitesCompleted,\n totalSuites,\n totalErrors == 0 ? \"\" : \" (\" + totalErrors + \"!)\",\n e.getSlave().slaves > 1 ? \" on J\" + e.getSlave().id : \"\",\n e.getExecutionTime() / 1000.0d));\n b.append(e.getTests().size()).append(Pluralize.pluralize(e.getTests().size(), \" test\"));\n\n int failures = e.getFailureCount();\n if (failures > 0) {\n b.append(\", \").append(failures).append(Pluralize.pluralize(failures, \" failure\"));\n }\n\n int errors = e.getErrorCount();\n if (errors > 0) {\n b.append(\", \").append(errors).append(Pluralize.pluralize(errors, \" error\"));\n }\n\n int ignored = e.getIgnoredCount();\n if (ignored > 0) {\n b.append(\", \").append(ignored).append(\" skipped\");\n }\n\n if (!e.isSuccessful()) {\n b.append(FAILURE_STRING);\n }\n\n b.append(\"\\n\");\n logShort(b, false);\n }" ]
Use this API to update Interface.
[ "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 String getProject(CmsObject cms, CmsFavoriteEntry entry) throws CmsException {\n\n String result = m_projectLabels.get(entry.getProjectId());\n if (result == null) {\n result = cms.readProject(entry.getProjectId()).getName();\n m_projectLabels.put(entry.getProjectId(), result);\n }\n return result;\n }", "public boolean isUpToDate(final DbArtifact artifact) {\n final List<String> versions = repoHandler.getArtifactVersions(artifact);\n final String currentVersion = artifact.getVersion();\n\n final String lastDevVersion = getLastVersion(versions);\n final String lastReleaseVersion = getLastRelease(versions);\n\n if(lastDevVersion == null || lastReleaseVersion == null) {\n // Plain Text comparison against version \"strings\"\n for(final String version: versions){\n if(version.compareTo(currentVersion) > 0){\n return false;\n }\n }\n return true;\n } else {\n return currentVersion.equals(lastDevVersion) || currentVersion.equals(lastReleaseVersion);\n }\n }", "protected synchronized void handleCompleted() {\n latch.countDown();\n for (final ShutdownListener listener : listeners) {\n listener.handleCompleted();\n }\n listeners.clear();\n }", "public HomekitRoot createBridge(\n HomekitAuthInfo authInfo,\n String label,\n String manufacturer,\n String model,\n String serialNumber)\n throws IOException {\n HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);\n root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));\n return root;\n }", "public void extractFieldTypes(DatabaseType databaseType) throws SQLException {\n\t\tif (fieldTypes == null) {\n\t\t\tif (fieldConfigs == null) {\n\t\t\t\tfieldTypes = extractFieldTypes(databaseType, dataClass, tableName);\n\t\t\t} else {\n\t\t\t\tfieldTypes = convertFieldConfigs(databaseType, tableName, fieldConfigs);\n\t\t\t}\n\t\t}\n\t}", "public String stripUnnecessaryComments(String javaContent, AntlrOptions options) {\n\t\tif (!options.isOptimizeCodeQuality()) {\n\t\t\treturn javaContent;\n\t\t}\n\t\tjavaContent = stripMachineDependentPaths(javaContent);\n\t\tif (options.isStripAllComments()) {\n\t\t\tjavaContent = stripAllComments(javaContent);\n\t\t}\n\t\treturn javaContent;\n\t}", "public synchronized void unregisterJmxIfRequired() {\n referenceCount--;\n if (isRegistered == true && referenceCount <= 0) {\n JmxUtils.unregisterMbean(this.jmxObjectName);\n isRegistered = false;\n }\n }", "public Where<T, ID> eq(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.EQUAL_TO_OPERATION));\n\t\treturn this;\n\t}", "@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }" ]
Fetch the outermost Hashmap as a TwoDHashMap. @param firstKey first key @return the the innermost hashmap
[ "public TwoDHashMap<K2, K3, V> getAs2d(final K1 firstKey) {\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 != null ) {\n\t\t\treturn new TwoDHashMap<K2, K3, V>(innerMap1);\n\t\t} else {\n\t\t\treturn new TwoDHashMap<K2, K3, V>();\n\t\t}\n\t\t\n\t}" ]
[ "public String translatePath(String path) {\n String translated;\n // special character: ~ maps to the user's home directory\n if (path.startsWith(\"~\" + File.separator)) {\n translated = System.getProperty(\"user.home\") + path.substring(1);\n } else if (path.startsWith(\"~\")) {\n String userName = path.substring(1);\n translated = new File(new File(System.getProperty(\"user.home\")).getParent(),\n userName).getAbsolutePath();\n // Keep the path separator in translated or add one if no user home specified\n translated = userName.isEmpty() || path.endsWith(File.separator) ? translated + File.separator : translated;\n } else if (!new File(path).isAbsolute()) {\n translated = ctx.getCurrentDir().getAbsolutePath() + File.separator + path;\n } else {\n translated = path;\n }\n return translated;\n }", "public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) {\n\n\t\t/*\n\t\t * The internal data structure is not optimal here (a map would make more sense here),\n\t\t * if the user does not require access to the products, we would allow non-unique symbols.\n\t\t * Hence we store both in two side by side vectors.\n\t\t */\n\t\tfor(int i=0; i<calibrationProductsSymbols.size(); i++) {\n\t\t\tString calibrationProductSymbol = calibrationProductsSymbols.get(i);\n\t\t\tif(calibrationProductSymbol.equals(symbol)) {\n\t\t\t\treturn calibrationProducts.get(i);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "public Iterable<V> sorted(Iterator<V> input) {\n ExecutorService executor = new ThreadPoolExecutor(this.numThreads,\n this.numThreads,\n 1000L,\n TimeUnit.MILLISECONDS,\n new SynchronousQueue<Runnable>(),\n new CallerRunsPolicy());\n final AtomicInteger count = new AtomicInteger(0);\n final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());\n while(input.hasNext()) {\n final int segmentId = count.getAndIncrement();\n final long segmentStartMs = System.currentTimeMillis();\n logger.info(\"Segment \" + segmentId + \": filling sort buffer for segment...\");\n @SuppressWarnings(\"unchecked\")\n final V[] buffer = (V[]) new Object[internalSortSize];\n int segmentSizeIter = 0;\n for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)\n buffer[segmentSizeIter] = input.next();\n final int segmentSize = segmentSizeIter;\n logger.info(\"Segment \" + segmentId + \": sort buffer filled...adding to sort queue.\");\n\n // sort and write out asynchronously\n executor.execute(new Runnable() {\n\n public void run() {\n logger.info(\"Segment \" + segmentId + \": sorting buffer.\");\n long start = System.currentTimeMillis();\n Arrays.sort(buffer, 0, segmentSize, comparator);\n long elapsed = System.currentTimeMillis() - start;\n logger.info(\"Segment \" + segmentId + \": sort completed in \" + elapsed\n + \" ms, writing to temp file.\");\n\n // write out values to a temp file\n try {\n File tempFile = File.createTempFile(\"segment-\", \".dat\", tempDir);\n tempFile.deleteOnExit();\n tempFiles.add(tempFile);\n OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),\n bufferSize);\n if(gzip)\n os = new GZIPOutputStream(os);\n DataOutputStream output = new DataOutputStream(os);\n for(int i = 0; i < segmentSize; i++)\n writeValue(output, buffer[i]);\n output.close();\n } catch(IOException e) {\n throw new VoldemortException(e);\n }\n long segmentElapsed = System.currentTimeMillis() - segmentStartMs;\n logger.info(\"Segment \" + segmentId + \": completed processing of segment in \"\n + segmentElapsed + \" ms.\");\n }\n });\n }\n\n // wait for all sorting to complete\n executor.shutdown();\n try {\n executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n // create iterator over sorted values\n return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize\n / tempFiles.size()));\n } catch(InterruptedException e) {\n throw new RuntimeException(e);\n }\n }", "public void setLinearLowerLimits(float limitX, float limitY, float limitZ) {\n Native3DGenericConstraint.setLinearLowerLimits(getNative(), limitX, limitY, limitZ);\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 }", "private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset)\n {\n if (previousItemOffset != null)\n {\n int itemSize = itemOffset.intValue() - previousItemOffset.intValue();\n byte[] itemData = new byte[itemSize];\n System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize);\n m_map.put(previousItemKey, itemData);\n }\n }", "public void setValue(float value) {\n\t\tmBarPointerPosition = Math.round((mSVToPosFactor * (1 - value))\n\t\t\t\t+ mBarPointerHaloRadius + (mBarLength / 2));\n\t\tcalculateColor(mBarPointerPosition);\n\t\tmBarPointerPaint.setColor(mColor);\n\t\t// Check whether the Saturation/Value bar is added to the ColorPicker\n\t\t// wheel\n\t\tif (mPicker != null) {\n\t\t\tmPicker.setNewCenterColor(mColor);\n\t\t\tmPicker.changeOpacityBarColor(mColor);\n\t\t}\n\t\tinvalidate();\n\t}", "public static Duration add(Duration a, Duration b, ProjectProperties defaults)\n {\n if (a == null && b == null)\n {\n return null;\n }\n if (a == null)\n {\n return b;\n }\n if (b == null)\n {\n return a;\n }\n TimeUnit unit = a.getUnits();\n if (b.getUnits() != unit)\n {\n b = b.convertUnits(unit, defaults);\n }\n\n return Duration.getInstance(a.getDuration() + b.getDuration(), unit);\n }", "public void getRepresentationContent(String representationHint, String assetPath, OutputStream output) {\n\n List<Representation> reps = this.getInfoWithRepresentations(representationHint).getRepresentations();\n if (reps.size() < 1) {\n throw new BoxAPIException(\"No matching representations found\");\n }\n Representation representation = reps.get(0);\n String repState = representation.getStatus().getState();\n\n if (repState.equals(\"viewable\") || repState.equals(\"success\")) {\n\n this.makeRepresentationContentRequest(representation.getContent().getUrlTemplate(),\n assetPath, output);\n return;\n } else if (repState.equals(\"pending\") || repState.equals(\"none\")) {\n\n String repContentURLString = null;\n while (repContentURLString == null) {\n repContentURLString = this.pollRepInfo(representation.getInfo().getUrl());\n }\n\n this.makeRepresentationContentRequest(repContentURLString, assetPath, output);\n return;\n\n } else if (repState.equals(\"error\")) {\n\n throw new BoxAPIException(\"Representation had error status\");\n } else {\n\n throw new BoxAPIException(\"Representation had unknown status\");\n }\n\n }" ]
Create a set containing all the processor at the current node and the entire subgraph.
[ "public Set<? extends Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n all.put(this.getProcessor(), null);\n for (ProcessorGraphNode<?, ?> dependency: this.dependencies) {\n for (Processor<?, ?> p: dependency.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }" ]
[ "public static void removeZeros( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) {\n ImplCommonOps_DSCC.removeZeros(input,output,tol);\n }", "public void deleteInactiveContent() throws PatchingException {\n List<File> dirs = getInactiveHistory();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n dirs = getInactiveOverlays();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n }", "public 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 }", "public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) {\n\n if (showModeSwitch != m_showModeSwitch) {\n m_upperLeftComponent.removeAllComponents();\n m_upperLeftComponent.addComponent(m_languageSwitch);\n if (showModeSwitch) {\n m_upperLeftComponent.addComponent(m_modeSwitch);\n }\n m_upperLeftComponent.addComponent(m_filePathLabel);\n m_showModeSwitch = showModeSwitch;\n }\n if (showAddKeyOption != m_showAddKeyOption) {\n if (showAddKeyOption) {\n m_optionsComponent.addComponent(m_lowerLeftComponent, 0, 1);\n m_optionsComponent.addComponent(m_lowerRightComponent, 1, 1);\n } else {\n m_optionsComponent.removeComponent(0, 1);\n m_optionsComponent.removeComponent(1, 1);\n }\n m_showAddKeyOption = showAddKeyOption;\n }\n }", "public void saveFavorites(List<CmsFavoriteEntry> favorites) throws CmsException {\n\n try {\n JSONObject json = new JSONObject();\n JSONArray array = new JSONArray();\n for (CmsFavoriteEntry entry : favorites) {\n array.put(entry.toJson());\n }\n json.put(BASE_KEY, array);\n String data = json.toString();\n CmsUser user = readUser();\n user.setAdditionalInfo(ADDINFO_KEY, data);\n m_cms.writeUser(user);\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n\n }", "@SuppressWarnings(\"unchecked\")\r\n public static <E> E[] filter(E[] elems, Filter<E> filter) {\r\n List<E> filtered = new ArrayList<E>();\r\n for (E elem: elems) {\r\n if (filter.accept(elem)) {\r\n filtered.add(elem);\r\n }\r\n }\r\n return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));\r\n }", "private static void writeCharSequence(CharSequence seq, CharBuf buffer) {\n if (seq.length() > 0) {\n buffer.addJsonEscapedString(seq.toString());\n } else {\n buffer.addChars(EMPTY_STRING_CHARS);\n }\n }", "List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files) throws IOException {\n HashFunction hashFun = Hashing.md5();\n File dir = new File(new File(project.getFile().getParent(), \"target\"), outputDirectory);\n if (dir.exists()) {\n URI baseDir = getFileURI(dir);\n for (File f : findThriftFilesInDirectory(dir)) {\n URI fileURI = getFileURI(f);\n String relPath = baseDir.relativize(fileURI).getPath();\n File destFolder = getResourcesOutputDirectory();\n destFolder.mkdirs();\n File destFile = new File(destFolder, relPath);\n if (!destFile.exists() || (destFile.isFile() && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {\n getLog().info(format(\"copying %s to %s\", f.getCanonicalPath(), destFile.getCanonicalPath()));\n copyFile(f, destFile);\n }\n files.add(destFile);\n }\n }\n Map<String, MavenProject> refs = project.getProjectReferences();\n for (String name : refs.keySet()) {\n getRecursiveThriftFiles(refs.get(name), outputDirectory, files);\n }\n return files;\n }", "public RangeInfo subListBorders(int size) {\n if (inclusive == null) throw new IllegalStateException(\"Should not call subListBorders on a non-inclusive aware IntRange\");\n int tempFrom = from;\n if (tempFrom < 0) {\n tempFrom += size;\n }\n int tempTo = to;\n if (tempTo < 0) {\n tempTo += size;\n }\n if (tempFrom > tempTo) {\n return new RangeInfo(inclusive ? tempTo : tempTo + 1, tempFrom + 1, true);\n }\n return new RangeInfo(tempFrom, inclusive ? tempTo + 1 : tempTo, false);\n }" ]
Check that the range resulting from the mask is contiguous, otherwise we cannot represent it. For instance, for the range 0 to 3 (bits are 00 to 11), if we mask all 4 numbers from 0 to 3 with 2 (ie bits are 10), then we are left with 1 and 3. 2 is not included. So we cannot represent 1 and 3 as a contiguous range. The underlying rule is that mask bits that are 0 must be above the resulting range in each segment. Any bit in the mask that is 0 must not fall below any bit in the masked segment range that is different between low and high. Any network mask must eliminate the entire segment range. Any host mask is fine. @param maskValue @param segmentPrefixLength @return @throws PrefixLenException
[ "public boolean isMaskCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\tif(!isMultiple()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn super.isMaskCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}" ]
[ "public DynamicReportBuilder setColspan(int colNumber, int colQuantity, String colspanTitle) {\n this.setColspan(colNumber, colQuantity, colspanTitle, null);\n\n return this;\n\n }", "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }", "String buildProjectEndpoint(DatastoreOptions options) {\n if (options.getProjectEndpoint() != null) {\n return options.getProjectEndpoint();\n }\n // DatastoreOptions ensures either project endpoint or project ID is set.\n String projectId = checkNotNull(options.getProjectId());\n if (options.getHost() != null) {\n return validateUrl(String.format(\"https://%s/%s/projects/%s\",\n options.getHost(), VERSION, projectId));\n } else if (options.getLocalHost() != null) {\n return validateUrl(String.format(\"http://%s/%s/projects/%s\",\n options.getLocalHost(), VERSION, projectId));\n }\n return validateUrl(String.format(\"%s/%s/projects/%s\",\n DEFAULT_HOST, VERSION, projectId));\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 }", "static <T extends GridDialect> T getDialectFacetOrNull(GridDialect gridDialect, Class<T> facetType) {\n\t\tif ( hasFacet( gridDialect, facetType ) ) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tT asFacet = (T) gridDialect;\n\t\t\treturn asFacet;\n\t\t}\n\n\t\treturn null;\n\t}", "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 double Y(int n, double x) {\r\n double by, bym, byp, tox;\r\n\r\n if (n == 0) return Y0(x);\r\n if (n == 1) return Y(x);\r\n\r\n tox = 2.0 / x;\r\n by = Y(x);\r\n bym = Y0(x);\r\n for (int j = 1; j < n; j++) {\r\n byp = j * tox * by - bym;\r\n bym = by;\r\n by = byp;\r\n }\r\n return by;\r\n }", "public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}", "public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){\n\t\tTrajectory track = null;\n\t\tfor(int i = 0; i < t.size() ; i++){\n\t\t\tif(t.get(i).getID()==id){\n\t\t\t\ttrack = t.get(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn track;\n\t}" ]
Update max min. @param n the n @param c the c
[ "private void updateMaxMin(IntervalRBTreeNode<T> n, IntervalRBTreeNode<T> c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n if (n.min > c.min) {\n n.min = c.min;\n }\n }\n }" ]
[ "public static boolean checkConfiguredInModules() {\n\n Boolean result = m_moduleCheckCache.get();\n if (result == null) {\n result = Boolean.valueOf(getConfiguredTemplateMapping() != null);\n m_moduleCheckCache.set(result);\n }\n return result.booleanValue();\n }", "public static BoxStoragePolicyAssignment.Info create(BoxAPIConnection api, String policyID, String userID) {\n URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST);\n JsonObject requestJSON = new JsonObject()\n .add(\"storage_policy\", new JsonObject()\n .add(\"type\", \"storage_policy\")\n .add(\"id\", policyID))\n .add(\"assigned_to\", new JsonObject()\n .add(\"type\", \"user\")\n .add(\"id\", userID));\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,\n responseJSON.get(\"id\").asString());\n\n return storagePolicyAssignment.new Info(responseJSON);\n }", "public void set( int row , int col , double real , double imaginary ) {\n if( imaginary == 0 ) {\n set(row,col,real);\n } else {\n ops.set(mat,row,col, real, imaginary);\n }\n }", "public static AnnotationNode getAnnotation(AnnotatedNode node, String name) {\r\n List<AnnotationNode> annotations = node.getAnnotations();\r\n for (AnnotationNode annot : annotations) {\r\n if (annot.getClassNode().getName().equals(name)) {\r\n return annot;\r\n }\r\n }\r\n return null;\r\n }", "public ItemRequest<Project> removeMembers(String project) {\n \n String path = String.format(\"/projects/%s/removeMembers\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public boolean load(GVRScene scene)\n {\n GVRAssetLoader loader = getGVRContext().getAssetLoader();\n\n if (scene == null)\n {\n scene = getGVRContext().getMainScene();\n }\n if (mReplaceScene)\n {\n loader.loadScene(getOwnerObject(), mVolume, mImportSettings, scene, null);\n }\n else\n {\n loader.loadModel(getOwnerObject(), mVolume, mImportSettings, scene);\n }\n return true;\n }", "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 }", "public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }", "private void internalWriteNameValuePair(String name, String value) throws IOException\n {\n writeComma();\n writeNewLineIndent();\n writeName(name);\n\n if (m_pretty)\n {\n m_writer.write(' ');\n }\n\n m_writer.write(value);\n }" ]
Utility method to retrieve the next working date start time, given a date and time as a starting point. @param date date and time start point @return date and time of next work start
[ "public Date getNextWorkStart(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToNextWorkStart(cal);\n return cal.getTime();\n }" ]
[ "protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tif (!this.cachedPoolStrategy){\r\n\t\t\tconnectionHandle.clearStatementCaches(false);\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.getReplayLog() != null){\r\n\t\t\tconnectionHandle.getReplayLog().clear();\r\n\t\t\tconnectionHandle.recoveryResult.getReplaceTarget().clear();\r\n\t\t}\r\n\r\n\t\tif (connectionHandle.isExpired() || \r\n\t\t\t\t(!this.poolShuttingDown \r\n\t\t\t\t\t\t&& connectionHandle.isPossiblyBroken()\r\n\t\t\t\t&& !isConnectionHandleAlive(connectionHandle))){\r\n\r\n if (connectionHandle.isExpired()) {\r\n connectionHandle.internalClose();\r\n }\r\n\r\n\t\t\tConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition();\r\n\t\t\tpostDestroyConnection(connectionHandle);\r\n\r\n\t\t\tmaybeSignalForMoreConnections(connectionPartition);\r\n\t\t\tconnectionHandle.clearStatementCaches(true);\r\n\t\t\treturn; // don't place back in queue - connection is broken or expired.\r\n\t\t}\r\n\r\n\r\n\t\tconnectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis());\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tputConnectionBackInPartition(connectionHandle);\r\n\t\t} else {\r\n\t\t\tconnectionHandle.internalClose();\r\n\t\t}\r\n\t}", "public static String determineFieldName(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);\n\t}", "private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}", "public Class getPersistentFieldClass()\r\n {\r\n if (m_persistenceClass == null)\r\n {\r\n Properties properties = new Properties();\r\n try\r\n {\r\n this.logWarning(\"Loading properties file: \" + getPropertiesFile());\r\n properties.load(new FileInputStream(getPropertiesFile()));\r\n }\r\n catch (IOException e)\r\n {\r\n this.logWarning(\"Could not load properties file '\" + getPropertiesFile()\r\n + \"'. Using PersistentFieldDefaultImpl.\");\r\n e.printStackTrace();\r\n }\r\n try\r\n {\r\n String className = properties.getProperty(\"PersistentFieldClass\");\r\n\r\n m_persistenceClass = loadClass(className);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n e.printStackTrace();\r\n m_persistenceClass = PersistentFieldPrivilegedImpl.class;\r\n }\r\n logWarning(\"PersistentFieldClass: \" + m_persistenceClass.toString());\r\n }\r\n return m_persistenceClass;\r\n }", "public static BufferedImage convertImageToARGB( Image image ) {\n\t\tif ( image instanceof BufferedImage && ((BufferedImage)image).getType() == BufferedImage.TYPE_INT_ARGB )\n\t\t\treturn (BufferedImage)image;\n\t\tBufferedImage p = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics2D g = p.createGraphics();\n\t\tg.drawImage( image, 0, 0, null );\n\t\tg.dispose();\n\t\treturn p;\n\t}", "@Beta\n public MSICredentials withObjectId(String objectId) {\n this.objectId = objectId;\n this.clientId = null;\n this.identityId = null;\n return this;\n }", "@Override\n public String printHelp() {\n List<CommandLineParser<CI>> parsers = getChildParsers();\n if (parsers != null && parsers.size() > 0) {\n StringBuilder sb = new StringBuilder();\n sb.append(processedCommand.printHelp(helpNames()))\n .append(Config.getLineSeparator())\n .append(processedCommand.name())\n .append(\" commands:\")\n .append(Config.getLineSeparator());\n\n int maxLength = 0;\n\n for (CommandLineParser child : parsers) {\n int length = child.getProcessedCommand().name().length();\n if (length > maxLength) {\n maxLength = length;\n }\n }\n\n for (CommandLineParser child : parsers) {\n sb.append(child.getFormattedCommand(4, maxLength + 2))\n .append(Config.getLineSeparator());\n }\n\n return sb.toString();\n }\n else\n return processedCommand.printHelp(helpNames());\n }", "public QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't orderBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddOrderBy(new OrderBy(columnName, ascending));\n\t\treturn this;\n\t}", "private boolean somethingMayHaveChanged(PhaseInterceptorChain pic) {\n Iterator<Interceptor<? extends Message>> it = pic.iterator();\n Interceptor<? extends Message> last = null;\n while (it.hasNext()) {\n Interceptor<? extends Message> cur = it.next();\n if (cur == this) {\n if (last instanceof DemoInterceptor) {\n return false;\n }\n return true;\n }\n last = cur;\n }\n return true;\n }" ]
Check, if the current user has permissions on the document's resource. @param cms the context @param doc the solr document (from the search result) @param filter the resource filter to use for checking permissions @return <code>true</code> iff the resource mirrored by the search result can be read by the current user.
[ "protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }" ]
[ "public static appqoepolicy get(nitro_service service, String name) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tobj.set_name(name);\n\t\tappqoepolicy response = (appqoepolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {\n Message inMsg = exchange.getInMessage();\n\n EventProducerInterceptor epi = null;\n FlowIdHelper.setFlowId(inMsg, reqFid);\n\n ListIterator<Interceptor<? extends Message>> interceptors = inMsg\n .getInterceptorChain().getIterator();\n\n while (interceptors.hasNext() && epi == null) {\n Interceptor<? extends Message> interceptor = interceptors.next();\n\n if (interceptor instanceof EventProducerInterceptor) {\n epi = (EventProducerInterceptor) interceptor;\n epi.handleMessage(inMsg);\n }\n }\n }", "boolean resumeSyncForDocument(\n final MongoNamespace namespace,\n final BsonValue documentId\n ) {\n if (namespace == null || documentId == null) {\n return false;\n }\n\n final NamespaceSynchronizationConfig namespaceSynchronizationConfig;\n final CoreDocumentSynchronizationConfig config;\n\n if ((namespaceSynchronizationConfig = syncConfig.getNamespaceConfig(namespace)) == null\n || (config = namespaceSynchronizationConfig.getSynchronizedDocument(documentId)) == null) {\n return false;\n }\n\n config.setPaused(false);\n return !config.isPaused();\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 static Trajectory resample(Trajectory t, int n){\n\t\tTrajectory t1 = new Trajectory(2);\n\t\t\n\t\tfor(int i = 0; i < t.size(); i=i+n){\n\t\t\tt1.add(t.get(i));\n\t\t}\n\t\t\n\t\treturn t1;\n\t}", "private EditorState getDefaultState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(1);\n cols.add(TableProperty.TRANSLATION);\n\n return new EditorState(cols, false);\n }", "public static boolean isClosureDeclaration(ASTNode expression) {\r\n if (expression instanceof DeclarationExpression) {\r\n if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n if (expression instanceof FieldNode) {\r\n ClassNode type = ((FieldNode) expression).getType();\r\n if (AstUtil.classNodeImplementsType(type, Closure.class)) {\r\n return true;\r\n } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "public String getRemoteUrl(String defaultRemoteUrl) {\n if (StringUtils.isBlank(defaultRemoteUrl)) {\n RemoteConfig remoteConfig = getJenkinsScm().getRepositories().get(0);\n URIish uri = remoteConfig.getURIs().get(0);\n return uri.toPrivateString();\n }\n\n return defaultRemoteUrl;\n }", "@Override\n\tpublic void visit(FeatureTypeStyle fts) {\n\n\t\tFeatureTypeStyle copy = new FeatureTypeStyleImpl(\n\t\t\t\t(FeatureTypeStyleImpl) fts);\n\t\tRule[] rules = fts.getRules();\n\t\tint length = rules.length;\n\t\tRule[] rulesCopy = new Rule[length];\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tif (rules[i] != null) {\n\t\t\t\trules[i].accept(this);\n\t\t\t\trulesCopy[i] = (Rule) pages.pop();\n\t\t\t}\n\t\t}\n\t\tcopy.setRules(rulesCopy);\n\t\tif (fts.getTransformation() != null) {\n\t\t\tcopy.setTransformation(copy(fts.getTransformation()));\n\t\t}\n\t\tif (STRICT && !copy.equals(fts)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided FeatureTypeStyle:\" + fts);\n\t\t}\n\t\tpages.push(copy);\n\t}" ]
Override this method to change the default splash screen size or position. This method will be called <em>before</em> {@link #onInit(GVRContext) onInit()} and before the normal render pipeline starts up. In particular, this means that any {@linkplain GVRAnimation animations} will not start until the first {@link #onStep()} and normal rendering starts. @param splashScreen The splash object created from {@link #getSplashTexture(GVRContext)}, {@link #getSplashMesh(GVRContext)}, and {@link #getSplashShader(GVRContext)}. @since 1.6.4
[ "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }" ]
[ "protected void splitCriteria()\r\n {\r\n Criteria whereCrit = getQuery().getCriteria();\r\n Criteria havingCrit = getQuery().getHavingCriteria();\r\n\r\n if (whereCrit == null || whereCrit.isEmpty())\r\n {\r\n getJoinTreeToCriteria().put(getRoot(), null);\r\n }\r\n else\r\n {\r\n // TODO: parameters list shold be modified when the form is reduced to DNF.\r\n getJoinTreeToCriteria().put(getRoot(), whereCrit);\r\n buildJoinTree(whereCrit);\r\n }\r\n\r\n if (havingCrit != null && !havingCrit.isEmpty())\r\n {\r\n buildJoinTree(havingCrit);\r\n }\r\n\r\n }", "@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }", "public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n return null;\n }\n return stack.peek();\n }", "public static gslbsite[] get(nitro_service service, String sitename[]) throws Exception{\n\t\tif (sitename !=null && sitename.length>0) {\n\t\t\tgslbsite response[] = new gslbsite[sitename.length];\n\t\t\tgslbsite obj[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++) {\n\t\t\t\tobj[i] = new gslbsite();\n\t\t\t\tobj[i].set_sitename(sitename[i]);\n\t\t\t\tresponse[i] = (gslbsite) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "public Triple<Double, Integer, Integer> getAccuracyInfo()\r\n {\r\n int totalCorrect = tokensCorrect;\r\n int totalWrong = tokensCount - tokensCorrect;\r\n return new Triple<Double, Integer, Integer>((((double) totalCorrect) / tokensCount),\r\n totalCorrect, totalWrong);\r\n }", "public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }", "public static ModelNode getAccessControl(ModelControllerClient client, OperationRequestAddress address, boolean operations) {\n return getAccessControl(client, null, address, operations);\n }", "public boolean verify(String signatureVersion, String signatureAlgorithm, String primarySignature,\n String secondarySignature, String webHookPayload, String deliveryTimestamp) {\n\n // enforce versions supported by this implementation\n if (!SUPPORTED_VERSIONS.contains(signatureVersion)) {\n return false;\n }\n\n // enforce algorithms supported by this implementation\n BoxSignatureAlgorithm algorithm = BoxSignatureAlgorithm.byName(signatureAlgorithm);\n if (!SUPPORTED_ALGORITHMS.contains(algorithm)) {\n return false;\n }\n\n // check primary key signature if primary key exists\n if (this.primarySignatureKey != null && this.verify(this.primarySignatureKey, algorithm, primarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // check secondary key signature if secondary key exists\n if (this.secondarySignatureKey != null && this.verify(this.secondarySignatureKey, algorithm, secondarySignature,\n webHookPayload, deliveryTimestamp)) {\n return true;\n }\n\n // default strategy is false, to minimize security issues\n return false;\n }", "public static base_response add(nitro_service client, policydataset resource) throws Exception {\n\t\tpolicydataset addresource = new policydataset();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.indextype = resource.indextype;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Returns the full record for a single story. @param story Globally unique identifier for the story. @return Request object
[ "public ItemRequest<Story> findById(String story) {\n \n String path = String.format(\"/stories/%s\", story);\n return new ItemRequest<Story>(this, Story.class, path, \"GET\");\n }" ]
[ "public static base_response unset(nitro_service client, systemuser resource, String[] args) throws Exception{\n\t\tsystemuser unsetresource = new systemuser();\n\t\tunsetresource.username = resource.username;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "private void flushHotCacheSlot(SlotReference slot) {\n // Iterate over a copy to avoid concurrent modification issues\n for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {\n if (slot == SlotReference.getSlotReference(entry.getValue().trackReference)) {\n logger.debug(\"Evicting cached metadata in response to unmount report {}\", entry.getValue());\n hotCache.remove(entry.getKey());\n }\n }\n }", "public Long getLong(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "public void updateExceptions(SortedSet<Date> exceptions) {\r\n\r\n SortedSet<Date> e = null == exceptions ? new TreeSet<Date>() : exceptions;\r\n if (!m_model.getExceptions().equals(e)) {\r\n m_model.setExceptions(e);\r\n m_view.updateExceptions();\r\n valueChanged();\r\n sizeChanged();\r\n }\r\n\r\n }", "public boolean isMaintenanceModeEnabled(String appName) {\n App app = connection.execute(new AppInfo(appName), apiKey);\n return app.isMaintenance();\n }", "public List<Ticket> checkTickets(Set<String> tickets) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CHECK_TICKETS);\r\n\r\n StringBuffer sb = new StringBuffer();\r\n Iterator<String> it = tickets.iterator();\r\n while (it.hasNext()) {\r\n if (sb.length() > 0) {\r\n sb.append(\",\");\r\n }\r\n Object obj = it.next();\r\n if (obj instanceof Ticket) {\r\n sb.append(((Ticket) obj).getTicketId());\r\n } else {\r\n sb.append(obj);\r\n }\r\n }\r\n parameters.put(\"tickets\", sb.toString());\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\r\n // <uploader>\r\n // <ticket id=\"128\" complete=\"1\" photoid=\"2995\" />\r\n // <ticket id=\"129\" complete=\"0\" />\r\n // <ticket id=\"130\" complete=\"2\" />\r\n // <ticket id=\"131\" invalid=\"1\" />\r\n // </uploader>\r\n\r\n List<Ticket> list = new ArrayList<Ticket>();\r\n Element uploaderElement = response.getPayload();\r\n NodeList ticketNodes = uploaderElement.getElementsByTagName(\"ticket\");\r\n int n = ticketNodes.getLength();\r\n for (int i = 0; i < n; i++) {\r\n Element ticketElement = (Element) ticketNodes.item(i);\r\n String id = ticketElement.getAttribute(\"id\");\r\n String complete = ticketElement.getAttribute(\"complete\");\r\n boolean invalid = \"1\".equals(ticketElement.getAttribute(\"invalid\"));\r\n String photoId = ticketElement.getAttribute(\"photoid\");\r\n Ticket info = new Ticket();\r\n info.setTicketId(id);\r\n info.setInvalid(invalid);\r\n info.setStatus(Integer.parseInt(complete));\r\n info.setPhotoId(photoId);\r\n list.add(info);\r\n }\r\n return list;\r\n }", "private void parseResponse(InputStream inputStream) {\n\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputStream);\n doc.getDocumentElement().normalize();\n\n NodeList nodes = doc.getElementsByTagName(\"place\");\n\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element = (Element) node;\n _woeid = getValue(\"woeid\", element);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }", "public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}", "public static void createMetadataCache(SlotReference slot, int playlistId, File cache) throws Exception {\n createMetadataCache(slot, playlistId, cache, null);\n }" ]
Initialize the field factories for the messages table.
[ "private void initFieldFactories() {\n\n if (m_model.hasMasterMode()) {\n TranslateTableFieldFactory masterFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.MASTER));\n masterFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.MASTER, masterFieldFactory);\n }\n TranslateTableFieldFactory defaultFieldFactory = new CmsMessageBundleEditorTypes.TranslateTableFieldFactory(\n m_table,\n m_model.getEditableColumns(CmsMessageBundleEditorTypes.EditMode.DEFAULT));\n defaultFieldFactory.registerKeyChangeListener(this);\n m_fieldFactories.put(CmsMessageBundleEditorTypes.EditMode.DEFAULT, defaultFieldFactory);\n\n }" ]
[ "public V get(K key) {\n ManagedReference<V> ref = internalMap.get(key);\n if (ref!=null) return ref.get();\n return null;\n }", "public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {\n\t\treturn isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );\n\t}", "public void seekToHoliday(String holidayString, String direction, String seekAmount) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount);\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void recordScreen(String screenName){\n if(screenName == null || (!currentScreenName.isEmpty() && currentScreenName.equals(screenName))) return;\n getConfigLogger().debug(getAccountId(), \"Screen changed to \" + screenName);\n currentScreenName = screenName;\n recordPageEventWithExtras(null);\n }", "public static boolean isBigInteger(CharSequence self) {\n try {\n new BigInteger(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public KeyChangeResult handleKeyChange(EntryChangeEvent event, boolean allLanguages) {\n\n if (m_keyset.getKeySet().contains(event.getNewValue())) {\n m_container.getItem(event.getItemId()).getItemProperty(TableProperty.KEY).setValue(event.getOldValue());\n return KeyChangeResult.FAILED_DUPLICATED_KEY;\n }\n if (allLanguages && !renameKeyForAllLanguages(event.getOldValue(), event.getNewValue())) {\n m_container.getItem(event.getItemId()).getItemProperty(TableProperty.KEY).setValue(event.getOldValue());\n return KeyChangeResult.FAILED_FOR_OTHER_LANGUAGE;\n }\n return KeyChangeResult.SUCCESS;\n }", "@Override\n public com.flickr4java.flickr.Response get(String path, Map<String, Object> parameters, String apiKey, String sharedSecret) throws FlickrException {\n\n OAuthRequest request = new OAuthRequest(Verb.GET, buildUrl(path));\n for (Map.Entry<String, Object> entry : parameters.entrySet()) {\n request.addQuerystringParameter(entry.getKey(), String.valueOf(entry.getValue()));\n }\n\n if (proxyAuth) {\n request.addHeader(\"Proxy-Authorization\", \"Basic \" + getProxyCredentials());\n }\n\n RequestContext requestContext = RequestContext.getRequestContext();\n Auth auth = requestContext.getAuth();\n OAuth10aService service = createOAuthService(apiKey, sharedSecret);\n if (auth != null) {\n OAuth1AccessToken requestToken = new OAuth1AccessToken(auth.getToken(), auth.getTokenSecret());\n service.signRequest(requestToken, request);\n } else {\n // For calls that do not require authorization e.g. flickr.people.findByUsername which could be the\n // first call if the user did not supply the user-id (i.e. nsid).\n if (!parameters.containsKey(Flickr.API_KEY)) {\n request.addQuerystringParameter(Flickr.API_KEY, apiKey);\n }\n }\n\n if (Flickr.debugRequest) {\n logger.debug(\"GET: \" + request.getCompleteUrl());\n }\n\n try {\n return handleResponse(request, service);\n } catch (IllegalAccessException | InstantiationException | SAXException | IOException | InterruptedException | ExecutionException | ParserConfigurationException e) {\n throw new FlickrRuntimeException(e);\n }\n }", "public static String blur(int radius, int sigma) {\n if (radius < 1) {\n throw new IllegalArgumentException(\"Radius must be greater than zero.\");\n }\n if (radius > 150) {\n throw new IllegalArgumentException(\"Radius must be lower or equal than 150.\");\n }\n if (sigma < 0) {\n throw new IllegalArgumentException(\"Sigma must be greater than zero.\");\n }\n return FILTER_BLUR + \"(\" + radius + \",\" + sigma + \")\";\n }", "private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)\n {\n Project.Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();\n for (Project.Calendars.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, map, baseCalendars);\n }\n updateBaseCalendarNames(baseCalendars, map);\n }\n\n try\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());\n ProjectCalendar calendar = map.get(calendarID);\n m_projectFile.setDefaultCalendar(calendar);\n }\n\n catch (Exception ex)\n {\n // Ignore exceptions\n }\n }" ]
Calculates the static drift. Static means, that the drift does not change direction or intensity over time. @param tracks Tracks which seems to exhibit a local drift @return The static drift over all trajectories
[ "public double[] calculateDrift(ArrayList<T> tracks){\n\t\tdouble[] result = new double[3];\n\t\t\n\t\tdouble sumX =0;\n\t\tdouble sumY = 0;\n\t\tdouble sumZ = 0;\n\t\tint N=0;\n\t\tfor(int i = 0; i < tracks.size(); i++){\n\t\t\tT t = tracks.get(i);\n\t\t\tTrajectoryValidIndexTimelagIterator it = new TrajectoryValidIndexTimelagIterator(t,1);\n\t\n\t\t\t//for(int j = 1; j < t.size(); j++){\n\t\t\twhile(it.hasNext()) {\n\t\t\t\tint j = it.next();\n\t\t\t\tsumX += t.get(j+1).x - t.get(j).x;\n\t\t\t\tsumY += t.get(j+1).y - t.get(j).y;\n\t\t\t\tsumZ += t.get(j+1).z - t.get(j).z;\n\t\t\t\tN++;\n\t\t\t}\n\t\t}\n\t\tresult[0] = sumX/N;\n\t\tresult[1] = sumY/N;\n\t\tresult[2] = sumZ/N;\n\t\treturn result;\n\t}" ]
[ "private void updateMax(MtasRBTreeNode n, MtasRBTreeNode c) {\n if (c != null) {\n if (n.max < c.max) {\n n.max = c.max;\n }\n }\n }", "private boolean activityIsStartMilestone(Activity activity)\n {\n String type = activity.getType();\n return type != null && type.indexOf(\"StartMilestone\") != -1;\n }", "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 Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}", "public static String convertToSQL92(char escape, char multi, char single, String pattern)\n\t\t\tthrows IllegalArgumentException {\n\t\tif ((escape == '\\'') || (multi == '\\'') || (single == '\\'')) {\n\t\t\tthrow new IllegalArgumentException(\"do not use single quote (') as special char!\");\n\t\t}\n\t\t\n\t\tStringBuilder result = new StringBuilder(pattern.length() + 5);\n\t\tint i = 0;\n\t\twhile (i < pattern.length()) {\n\t\t\tchar chr = pattern.charAt(i);\n\t\t\tif (chr == escape) {\n\t\t\t\t// emit the next char and skip it\n\t\t\t\tif (i != (pattern.length() - 1)) {\n\t\t\t\t\tresult.append(pattern.charAt(i + 1));\n\t\t\t\t}\n\t\t\t\ti++; // skip next char\n\t\t\t} else if (chr == single) {\n\t\t\t\tresult.append('_');\n\t\t\t} else if (chr == multi) {\n\t\t\t\tresult.append('%');\n\t\t\t} else if (chr == '\\'') {\n\t\t\t\tresult.append('\\'');\n\t\t\t\tresult.append('\\'');\n\t\t\t} else {\n\t\t\t\tresult.append(chr);\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\n\t\treturn result.toString();\n\t}", "public static appfwlearningsettings[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappfwlearningsettings[] response = (appfwlearningsettings[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}", "public PhotoList<Photo> photosForLocation(GeoData location, Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n parameters.put(\"method\", METHOD_PHOTOS_FOR_LOCATION);\r\n\r\n if (extras.size() > 0) {\r\n parameters.put(\"extras\", StringUtilities.join(extras, \",\"));\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n parameters.put(\"lat\", Float.toString(location.getLatitude()));\r\n parameters.put(\"lon\", Float.toString(location.getLongitude()));\r\n parameters.put(\"accuracy\", Integer.toString(location.getAccuracy()));\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoElements = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }", "static final TimeBasedRollStrategy findRollStrategy(\n final AppenderRollingProperties properties) {\n if (properties.getDatePattern() == null) {\n LogLog.error(\"null date pattern\");\n return ROLL_ERROR;\n }\n // Strip out quoted sections so that we may safely scan the undecorated\n // pattern for characters that are meaningful to SimpleDateFormat.\n final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(\n properties.getDatePatternLocale());\n final String undecoratedDatePattern = localizedDateFormatPatternHelper\n .excludeQuoted(properties.getDatePattern());\n if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MINUTE;\n }\n if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HOUR;\n }\n if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_HALF_DAY;\n }\n if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_DAY;\n }\n if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_WEEK;\n }\n if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,\n undecoratedDatePattern)) {\n return ROLL_EACH_MONTH;\n }\n return ROLL_ERROR;\n }", "@Override\n public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deploymentConfig = entities.stream()\n .filter(hm -> hm instanceof DeploymentConfig)\n .map(hm -> (DeploymentConfig) hm)\n .map(dc -> dc.getMetadata().getName()).findFirst();\n\n deploymentConfig.ifPresent(name -> this.applicationName = name);\n }\n }" ]
Processes an anonymous reference definition. @param attributes The attributes of the tag @exception XDocletException If an error occurs @doc.tag type="content" @doc.param name="attributes" optional="true" description="Attributes of the reference as name-value pairs 'name=value', separated by commas" @doc.param name="auto-delete" optional="true" description="Whether to automatically delete the referenced object on object deletion" @doc.param name="auto-retrieve" optional="true" description="Whether to automatically retrieve the referenced object" @doc.param name="auto-update" optional="true" description="Whether to automatically update the referenced object" @doc.param name="class-ref" optional="false" description="The fully qualified name of the class owning the referenced field" @doc.param name="documentation" optional="true" description="Documentation on the reference" @doc.param name="foreignkey" optional="true" description="The fields in the current type used for implementing the reference" @doc.param name="otm-dependent" optional="true" description="Whether the reference is dependent on otm" @doc.param name="proxy" optional="true" description="Whether to use a proxy for the reference" @doc.param name="proxy-prefetching-limit" optional="true" description="Specifies the amount of objects to prefetch" @doc.param name="refresh" optional="true" description="Whether to automatically refresh the reference" @doc.param name="remote-foreignkey" optional="true" description="The fields in the referenced type corresponding to the local fields (is only used for the table definition)"
[ "public void processAnonymousReference(Properties attributes) throws XDocletException\r\n {\r\n ReferenceDescriptorDef refDef = _curClassDef.getReference(\"super\");\r\n String attrName;\r\n\r\n if (refDef == null)\r\n {\r\n refDef = new ReferenceDescriptorDef(\"super\");\r\n _curClassDef.addReference(refDef);\r\n }\r\n refDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousReference\", \" Processing anonymous reference\");\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n refDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n }" ]
[ "public void onDrawFrame(float frameTime)\n {\n if (isEnabled() && (mScene != null) && mPickEventLock.tryLock())\n {\n // Don't call if we are in the middle of processing another pick\n try\n {\n doPick();\n }\n finally\n {\n mPickEventLock.unlock();\n }\n }\n }", "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 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 }", "public void setName(int pathId, String pathName) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_PATHNAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, pathName);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public HostName toHostName() {\n\t\tHostName host = fromHost;\n\t\tif(host == null) {\n\t\t\tfromHost = host = toCanonicalHostName();\n\t\t}\n\t\treturn host;\n\t}", "private double goldenMean(double a, double b) {\r\n if (geometric) {\r\n return a * Math.pow(b / a, GOLDEN_SECTION);\r\n } else {\r\n return a + (b - a) * GOLDEN_SECTION;\r\n }\r\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 int[] sampleBatchWithReplacement() {\n // Sample the indices with replacement.\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n batch[i] = Prng.nextInt(numExamples);\n }\n return batch;\n }", "Object lookup(String key) throws ObjectNameNotFoundException\r\n {\r\n Object result = null;\r\n NamedEntry entry = localLookup(key);\r\n // can't find local bound object\r\n if(entry == null)\r\n {\r\n try\r\n {\r\n PersistenceBroker broker = tx.getBroker();\r\n // build Identity to lookup entry\r\n Identity oid = broker.serviceIdentity().buildIdentity(NamedEntry.class, key);\r\n entry = (NamedEntry) broker.getObjectByIdentity(oid);\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Can't materialize bound object for key '\" + key + \"'\", e);\r\n }\r\n }\r\n if(entry == null)\r\n {\r\n log.info(\"No object found for key '\" + key + \"'\");\r\n }\r\n else\r\n {\r\n Object obj = entry.getObject();\r\n // found a persistent capable object associated with that key\r\n if(obj instanceof Identity)\r\n {\r\n Identity objectIdentity = (Identity) obj;\r\n result = tx.getBroker().getObjectByIdentity(objectIdentity);\r\n // lock the persistance capable object\r\n RuntimeObject rt = new RuntimeObject(result, objectIdentity, tx, false);\r\n tx.lockAndRegister(rt, Transaction.READ, tx.getRegistrationList());\r\n }\r\n else\r\n {\r\n // nothing else to do\r\n result = obj;\r\n }\r\n }\r\n if(result == null) throw new ObjectNameNotFoundException(\"Can't find named object for name '\" + key + \"'\");\r\n return result;\r\n }" ]
Reports a dependency of this node has been faulted. @param dependencyKey the id of the dependency node @param throwable the reason for unsuccessful resolution
[ "protected void onFaultedResolution(String dependencyKey, Throwable throwable) {\n if (toBeResolved == 0) {\n throw new RuntimeException(\"invalid state - \" + this.key() + \": The dependency '\" + dependencyKey + \"' is already reported or there is no such dependencyKey\");\n }\n toBeResolved--;\n }" ]
[ "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}", "public Info getInfo(String ... fields) {\r\n QueryStringBuilder builder = new QueryStringBuilder();\r\n if (fields.length > 0) {\r\n builder.appendParam(\"fields\", fields);\r\n }\r\n URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\r\n BoxJSONResponse response = (BoxJSONResponse) request.send();\r\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\r\n return new Info(responseJSON);\r\n }", "private boolean checkZoneRequirement(HashMap<Integer, Integer> requiredRepFactor, int zoneId) {\n if(requiredRepFactor.containsKey(zoneId)) {\n if(requiredRepFactor.get(zoneId) == 0) {\n return false;\n } else {\n requiredRepFactor.put(zoneId, requiredRepFactor.get(zoneId) - 1);\n return true;\n }\n }\n return false;\n\n }", "private static CmsUUID toUuid(String uuid) {\n\n if (\"null\".equals(uuid) || CmsStringUtil.isEmpty(uuid)) {\n return null;\n }\n return new CmsUUID(uuid);\n\n }", "public int bindShader(GVRContext context, IRenderable rdata, GVRScene scene, boolean isMultiview)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n GVRMaterial mtl = rdata.getMaterial();\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, mtl);\n }\n if (nativeShader > 0)\n {\n rdata.setShader(nativeShader, isMultiview);\n }\n return nativeShader;\n }\n }", "private void createPropertyVfsBundleFiles() throws CmsIllegalArgumentException, CmsLoaderException, CmsException {\n\n String bundleFileBasePath = m_sitepath + m_basename + \"_\";\n for (Locale l : m_localizations.keySet()) {\n CmsResource res = m_cms.createResource(\n bundleFileBasePath + l.toString(),\n OpenCms.getResourceManager().getResourceType(\n CmsMessageBundleEditorTypes.BundleType.PROPERTY.toString()));\n m_bundleFiles.put(l, res);\n LockedFile file = LockedFile.lockResource(m_cms, res);\n file.setCreated(true);\n m_lockedBundleFiles.put(l, file);\n m_changedTranslations.add(l);\n }\n\n }", "public FieldLocation getFieldLocation(FieldType type)\n {\n FieldLocation result = null;\n\n FieldItem item = m_map.get(type);\n if (item != null)\n {\n result = item.getFieldLocation();\n }\n return result;\n }", "public static void validateZip(File file) throws IOException {\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n zipEntry = zipInput.getNextEntry();\n }\n\n try {\n if (zipInput != null) {\n zipInput.close();\n }\n } catch (IOException e) {\n }\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 }" ]
Sanity checks the input or declares a new matrix. Return matrix is an identity matrix.
[ "public static DMatrixRBlock initializeQ(DMatrixRBlock Q,\n int numRows , int numCols , int blockLength ,\n boolean compact) {\n int minLength = Math.min(numRows,numCols);\n if( compact ) {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,minLength,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != minLength ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n } else {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,numRows,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != numRows ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n }\n return Q;\n }" ]
[ "public static Object executeXPath(Node document, String xpathExpression, Map<String, String> namespaceMapping, QName result)\n throws XPathException, MarshallingException\n {\n NamespaceMapContext mapContext = new NamespaceMapContext(namespaceMapping);\n try\n {\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n xpath.setNamespaceContext(mapContext);\n XPathExpression expr = xpath.compile(xpathExpression);\n\n return executeXPath(document, expr, result);\n }\n catch (XPathExpressionException e)\n {\n throw new XPathException(\"Xpath(\" + xpathExpression + \") cannot be compiled\", e);\n }\n catch (Exception e)\n {\n throw new MarshallingException(\"Exception unmarshalling XML.\", e);\n }\n }", "public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {\n\t\tDuration duration = Duration.between(referenceDate, date);\n\t\treturn ((double)duration.getSeconds()) / SECONDS_PER_DAY;\n\t}", "private static Object checkComponentType(Object array, Class<?> expectedComponentType) {\n\t\tClass<?> actualComponentType = array.getClass().getComponentType();\n\t\tif (!expectedComponentType.isAssignableFrom(actualComponentType)) {\n\t\t\tthrow new ArrayStoreException(\n\t\t\t\t\tString.format(\"The expected component type %s is not assignable from the actual type %s\",\n\t\t\t\t\t\t\texpectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));\n\t\t}\n\t\treturn array;\n\t}", "static Property getProperty(String propName, ModelNode attrs) {\n String[] arr = propName.split(\"\\\\.\");\n ModelNode attrDescr = attrs;\n for (String item : arr) {\n // Remove list part.\n if (item.endsWith(\"]\")) {\n int i = item.indexOf(\"[\");\n if (i < 0) {\n return null;\n }\n item = item.substring(0, i);\n }\n ModelNode descr = attrDescr.get(item);\n if (!descr.isDefined()) {\n if (attrDescr.has(Util.VALUE_TYPE)) {\n ModelNode vt = attrDescr.get(Util.VALUE_TYPE);\n if (vt.has(item)) {\n attrDescr = vt.get(item);\n continue;\n }\n }\n return null;\n }\n attrDescr = descr;\n }\n return new Property(propName, attrDescr);\n }", "public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\n }", "static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex,\n ArtifactResolver resolver)\n throws VersionRangeResolutionException, ArtifactResolutionException {\n boolean latest = gav.endsWith(\":LATEST\");\n if (latest || gav.endsWith(\":RELEASE\")) {\n Artifact a = new DefaultArtifact(gav);\n\n if (latest) {\n versionRegex = versionRegex == null ? ANY : versionRegex;\n } else {\n versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex;\n }\n\n String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId())\n ? project.getVersion()\n : null;\n\n return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest);\n } else {\n String projectGav = getProjectArtifactCoordinates(project, null);\n Artifact ret = null;\n\n if (projectGav.equals(gav)) {\n ret = findProjectArtifact(project);\n }\n\n return ret == null ? resolver.resolveArtifact(gav) : ret;\n }\n }", "public ApiResponse<String> getPingWithHttpInfo() throws ApiException {\n com.squareup.okhttp.Call call = getPingValidateBeforeCall(null);\n Type localVarReturnType = new TypeToken<String>() {\n }.getType();\n return apiClient.execute(call, localVarReturnType);\n }", "@Override\n protected StatisticsMatrix createMatrix(int numRows, int numCols, MatrixType type) {\n return new StatisticsMatrix(numRows,numCols);\n }", "private static void readAndAddDocumentsFromStream(\n final SolrClient client,\n final String lang,\n final InputStream is,\n final List<SolrInputDocument> documents,\n final boolean closeStream) {\n\n final BufferedReader br = new BufferedReader(new InputStreamReader(is));\n\n try {\n String line = br.readLine();\n while (null != line) {\n\n final SolrInputDocument document = new SolrInputDocument();\n // Each field is named after the schema \"entry_xx\" where xx denotes\n // the two digit language code. See the file spellcheck/conf/schema.xml.\n document.addField(\"entry_\" + lang, line);\n documents.add(document);\n\n // Prevent OutOfMemoryExceptions ...\n if (documents.size() >= MAX_LIST_SIZE) {\n addDocuments(client, documents, false);\n documents.clear();\n }\n\n line = br.readLine();\n }\n } catch (IOException e) {\n LOG.error(\"Could not read spellcheck dictionary from input stream.\");\n } catch (SolrServerException e) {\n LOG.error(\"Error while adding documents to Solr server. \");\n } finally {\n try {\n if (closeStream) {\n br.close();\n }\n } catch (Exception e) {\n // Nothing to do here anymore ....\n }\n }\n }" ]
Gets the listener classes to which dispatching should be prevented while this event is being dispatched. @return The listener classes marked to prevent. @see #preventCascade(Class)
[ "public Set<Class<?>> getPrevented() {\n if (this.prevent == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(this.prevent);\n }" ]
[ "@Override public void setID(Integer val)\n {\n ProjectFile parent = getParentFile();\n Integer previous = getID();\n if (previous != null)\n {\n parent.getResources().unmapID(previous);\n }\n parent.getResources().mapID(val, this);\n\n set(ResourceField.ID, val);\n }", "private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"properties.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\tint count = 0;\n\t\t\tfor (Entry<Integer, PropertyRecord> propertyEntry : this.propertyRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + propertyEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, propertyEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" properties.\");\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) {\n\t\tString fileName=currentLogFile.getName();\n\t\tPattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN);\n\t\tMatcher m = p.matcher(fileName);\n\t\tif(m.find()){\n\t\t\tint year=Integer.parseInt(m.group(1));\n\t\t\tint month=Integer.parseInt(m.group(2));\n\t\t\tint dayOfMonth=Integer.parseInt(m.group(3));\n\t\t\tGregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth);\n\t\t\tfileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0\n\t\t\treturn fileDate.compareTo(lastRelevantDate)>0;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}", "public Bundler put(String key, CharSequence[] value) {\n delegate.putCharSequenceArray(key, value);\n return this;\n }", "public void reset() {\n state = BreakerState.CLOSED;\n isHardTrip = false;\n byPass = false;\n isAttemptLive = false;\n\n notifyBreakerStateChange(getStatus());\n }", "@Override\n public void sendResponse(StoreStats performanceStats,\n boolean isFromLocalZone,\n long startTimeInMs) throws Exception {\n\n /*\n * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.\n * However when writing to the outputStream we only send the multiPart object and not the entire\n * mimeMessage. This is intentional.\n *\n * In the earlier version of this code we used to create a multiPart object and just send that multiPart\n * across the wire.\n *\n * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates\n * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated\n * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the\n * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()\n * on the body part. It's this updateHeaders call that transfers the content type from the\n * DataHandler to the part's MIME Content-Type header.\n *\n * To make sure that the Content-Type headers are being updated (without changing too much code), we decided\n * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.\n * This is to make sure multiPart's headers are updated accurately.\n */\n\n MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));\n MimeMultipart multiPart = new MimeMultipart();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n String base64Key = RestUtils.encodeVoldemortKey(key.get());\n String contentLocationKey = \"/\" + this.storeName + \"/\" + base64Key;\n\n for(Versioned<byte[]> versionedValue: versionedValues) {\n\n byte[] responseValue = versionedValue.getValue();\n\n VectorClock vectorClock = (VectorClock) versionedValue.getVersion();\n String eTag = RestUtils.getSerializedVectorClock(vectorClock);\n numVectorClockEntries += vectorClock.getVersionMap().size();\n\n // Create the individual body part for each versioned value of the\n // requested key\n MimeBodyPart body = new MimeBodyPart();\n try {\n // Add the right headers\n body.addHeader(CONTENT_TYPE, \"application/octet-stream\");\n body.addHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);\n body.setContent(responseValue, \"application/octet-stream\");\n body.addHeader(RestMessageHeaders.CONTENT_LENGTH,\n Integer.toString(responseValue.length));\n\n multiPart.addBodyPart(body);\n } catch(MessagingException me) {\n logger.error(\"Exception while constructing body part\", me);\n outputStream.close();\n throw me;\n }\n\n }\n message.setContent(multiPart);\n message.saveChanges();\n try {\n multiPart.writeTo(outputStream);\n } catch(Exception e) {\n logger.error(\"Exception while writing multipart to output stream\", e);\n outputStream.close();\n throw e;\n }\n ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();\n responseContent.writeBytes(outputStream.toByteArray());\n\n // Create the Response object\n HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);\n\n // Set the right headers\n response.setHeader(CONTENT_TYPE, \"multipart/binary\");\n response.setHeader(CONTENT_TRANSFER_ENCODING, \"binary\");\n response.setHeader(CONTENT_LOCATION, contentLocationKey);\n\n // Copy the data into the payload\n response.setContent(responseContent);\n response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());\n\n // Write the response to the Netty Channel\n if(logger.isDebugEnabled()) {\n String keyStr = RestUtils.getKeyHexString(this.key);\n debugLog(\"GET\",\n this.storeName,\n keyStr,\n startTimeInMs,\n System.currentTimeMillis(),\n numVectorClockEntries);\n }\n this.messageEvent.getChannel().write(response);\n\n if(performanceStats != null && isFromLocalZone) {\n recordStats(performanceStats, startTimeInMs, Tracked.GET);\n }\n\n outputStream.close();\n\n }", "public void set(Vector3d v1) {\n x = v1.x;\n y = v1.y;\n z = v1.z;\n }", "public boolean isAlive(Connection conn)\r\n {\r\n try\r\n {\r\n return con != null ? !con.isClosed() : false;\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"IsAlive check failed, running connection was invalid!!\", e);\r\n return false;\r\n }\r\n }", "private Project.Calendars.Calendar writeCalendar(ProjectCalendar bc)\n {\n //\n // Create a calendar\n //\n Project.Calendars.Calendar calendar = m_factory.createProjectCalendarsCalendar();\n calendar.setUID(NumberHelper.getBigInteger(bc.getUniqueID()));\n calendar.setIsBaseCalendar(Boolean.valueOf(!bc.isDerived()));\n\n ProjectCalendar base = bc.getParent();\n // SF-329: null default required to keep Powerproject happy when importing MSPDI files\n calendar.setBaseCalendarUID(base == null ? NULL_CALENDAR_ID : NumberHelper.getBigInteger(base.getUniqueID()));\n calendar.setName(bc.getName());\n\n //\n // Create a list of normal days\n //\n Project.Calendars.Calendar.WeekDays days = m_factory.createProjectCalendarsCalendarWeekDays();\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time;\n ProjectCalendarHours bch;\n\n List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList = days.getWeekDay();\n\n for (int loop = 1; loop < 8; loop++)\n {\n DayType workingFlag = bc.getWorkingDay(Day.getInstance(loop));\n\n if (workingFlag != DayType.DEFAULT)\n {\n Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay();\n dayList.add(day);\n day.setDayType(BigInteger.valueOf(loop));\n day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING));\n\n if (workingFlag == DayType.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 bch = bc.getCalendarHours(Day.getInstance(loop));\n if (bch != null)\n {\n for (DateRange range : bch)\n {\n if (range != null)\n {\n time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime();\n timesList.add(time);\n\n time.setFromTime(range.getStart());\n time.setToTime(range.getEnd());\n }\n }\n }\n }\n }\n }\n\n //\n // Create a list of exceptions\n //\n // A quirk of MS Project is that these exceptions must be\n // in date order in the file, otherwise they are ignored\n //\n List<ProjectCalendarException> exceptions = new ArrayList<ProjectCalendarException>(bc.getCalendarExceptions());\n if (!exceptions.isEmpty())\n {\n Collections.sort(exceptions);\n writeExceptions(calendar, dayList, exceptions);\n }\n\n //\n // Do not add a weekdays tag to the calendar unless it\n // has valid entries.\n // Fixes SourceForge bug 1854747: MPXJ and MSP 2007 XML formats\n //\n if (!dayList.isEmpty())\n {\n calendar.setWeekDays(days);\n }\n\n writeWorkWeeks(calendar, bc);\n\n m_eventManager.fireCalendarWrittenEvent(bc);\n\n return (calendar);\n }" ]
Operates on one dimension at a time.
[ "private List<Pair<Integer, Double>> integerPixelCoordinatesAndWeights(double d, int numPixels) {\n if (d <= 0.5) return Collections.singletonList(new Pair<>(0, 1.0));\n else if (d >= numPixels - 0.5) return Collections.singletonList(new Pair<>(numPixels - 1, 1.0));\n else {\n double shifted = d - 0.5;\n double floor = Math.floor(shifted);\n double floorWeight = 1 - (shifted - floor);\n double ceil = Math.ceil(shifted);\n double ceilWeight = 1 - floorWeight;\n assert (floorWeight + ceilWeight == 1);\n return Arrays.asList(new Pair<>((int) floor, floorWeight), new Pair<>((int) ceil, ceilWeight));\n }\n }" ]
[ "protected void endPersistence(final BufferedWriter writer) throws IOException {\n // Append any additional users to the end of the file.\n for (Object currentKey : toSave.keySet()) {\n String key = (String) currentKey;\n if (!key.contains(DISABLE_SUFFIX_KEY)) {\n writeProperty(writer, key, null);\n }\n }\n\n toSave = null;\n }", "private ProctorContext getProctorContext(final HttpServletRequest request) throws IllegalAccessException, InstantiationException {\n final ProctorContext proctorContext = contextClass.newInstance();\n final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext);\n for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) {\n final String propertyName = descriptor.getName();\n if (!\"class\".equals(propertyName)) { // ignore class property which every object has\n final String parameterValue = request.getParameter(propertyName);\n if (parameterValue != null) {\n beanWrapper.setPropertyValue(propertyName, parameterValue);\n }\n }\n }\n return proctorContext;\n }", "@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}", "@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 }", "public void checkAllGroupsSatisfied(final String currentPath) {\n StringBuilder errors = new StringBuilder();\n\n for (OneOfGroup group: this.mapping.values()) {\n\n if (group.satisfiedBy.isEmpty()) {\n errors.append(\"\\n\");\n errors.append(\"\\t* The OneOf choice: \").append(group.name)\n .append(\" was not satisfied. One (and only one) of the \");\n errors.append(\"following fields is required in the request data: \")\n .append(toNames(group.choices));\n }\n\n Collection<OneOfSatisfier> oneOfSatisfiers =\n Collections2.filter(group.satisfiedBy, input -> !input.isCanSatisfy);\n if (oneOfSatisfiers.size() > 1) {\n errors.append(\"\\n\");\n errors.append(\"\\t* The OneOf choice: \").append(group.name)\n .append(\" was satisfied by too many fields. Only one choice \");\n errors.append(\"may be in the request data. The fields found were: \")\n .append(toNames(toFields(group.satisfiedBy)));\n }\n }\n\n Assert.equals(0, errors.length(),\n \"\\nErrors were detected when analysing the @OneOf dependencies of '\" + currentPath +\n \"': \\n\" + errors);\n }", "private synchronized void initSystemCache() {\n List<StoreDefinition> value = storeMapper.readStoreList(new StringReader(SystemStoreConstants.SYSTEM_STORE_SCHEMA));\n metadataCache.put(SYSTEM_STORES_KEY, new Versioned<Object>(value));\n }", "protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "private void populateDefaultSettings(Record record, ProjectProperties properties) throws MPXJException\n {\n properties.setDefaultDurationUnits(record.getTimeUnit(0));\n properties.setDefaultDurationIsFixed(record.getNumericBoolean(1));\n properties.setDefaultWorkUnits(record.getTimeUnit(2));\n properties.setMinutesPerDay(Double.valueOf(NumberHelper.getDouble(record.getFloat(3)) * 60));\n properties.setMinutesPerWeek(Double.valueOf(NumberHelper.getDouble(record.getFloat(4)) * 60));\n properties.setDefaultStandardRate(record.getRate(5));\n properties.setDefaultOvertimeRate(record.getRate(6));\n properties.setUpdatingTaskStatusUpdatesResourceStatus(record.getNumericBoolean(7));\n properties.setSplitInProgressTasks(record.getNumericBoolean(8));\n }", "public PhotoContext getContext(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_CONTEXT);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n PhotoContext photoContext = new PhotoContext();\r\n Collection<Element> payload = response.getPayloadCollection();\r\n for (Element payloadElement : payload) {\r\n String tagName = payloadElement.getTagName();\r\n if (tagName.equals(\"prevphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setPreviousPhoto(photo);\r\n } else if (tagName.equals(\"nextphoto\")) {\r\n Photo photo = new Photo();\r\n photo.setId(payloadElement.getAttribute(\"id\"));\r\n photo.setSecret(payloadElement.getAttribute(\"secret\"));\r\n photo.setTitle(payloadElement.getAttribute(\"title\"));\r\n photo.setFarm(payloadElement.getAttribute(\"farm\"));\r\n photo.setUrl(payloadElement.getAttribute(\"url\"));\r\n photoContext.setNextPhoto(photo);\r\n }\r\n }\r\n return photoContext;\r\n }" ]
Parse currency. @param value currency value @return currency value
[ "public static final Double parseCurrency(Number value)\n {\n return (value == null ? null : NumberHelper.getDouble(value.doubleValue() / 100));\n }" ]
[ "public void setLocale(String locale) {\n\n try {\n m_locale = LocaleUtils.toLocale(locale);\n } catch (IllegalArgumentException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_TAG_INVALID_LOCALE_1, \"cms:navigation\"), e);\n m_locale = null;\n }\n }", "private void updateBeatGrid(TrackMetadataUpdate update, BeatGrid beatGrid) {\n hotCache.put(DeckReference.getDeckReference(update.player, 0), beatGrid); // Main deck\n if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well\n for (CueList.Entry entry : update.metadata.getCueList().entries) {\n if (entry.hotCueNumber != 0) {\n hotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), beatGrid);\n }\n }\n }\n deliverBeatGridUpdate(update.player, beatGrid);\n }", "public boolean clearSelection(boolean requestLayout) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"clearSelection [%d]\", mSelectedItemsList.size());\n\n boolean updateLayout = false;\n List<ListItemHostWidget> views = getAllHosts();\n for (ListItemHostWidget host: views) {\n if (host.isSelected()) {\n host.setSelected(false);\n updateLayout = true;\n if (requestLayout) {\n host.requestLayout();\n }\n }\n }\n clearSelectedItemsList();\n return updateLayout;\n }", "public static boolean isAllWhitespace(CharSequence self) {\n String s = self.toString();\n for (int i = 0; i < s.length(); i++) {\n if (!Character.isWhitespace(s.charAt(i)))\n return false;\n }\n return true;\n }", "private boolean evaluateLogicalOperator(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = false;\n\n if (m_criteriaList.size() == 0)\n {\n result = true;\n }\n else\n {\n for (GenericCriteria criteria : m_criteriaList)\n {\n result = criteria.evaluate(container, promptValues);\n if ((m_operator == TestOperator.AND && !result) || (m_operator == TestOperator.OR && result))\n {\n break;\n }\n }\n }\n\n return result;\n }", "private void verifyApplicationName(String name) {\n if (name == null) {\n throw new IllegalArgumentException(\"Application name cannot be null\");\n }\n if (name.isEmpty()) {\n throw new IllegalArgumentException(\"Application name length must be > 0\");\n }\n String reason = null;\n char[] chars = name.toCharArray();\n char c;\n for (int i = 0; i < chars.length; i++) {\n c = chars[i];\n if (c == 0) {\n reason = \"null character not allowed @\" + i;\n break;\n } else if (c == '/' || c == '.' || c == ':') {\n reason = \"invalid character '\" + c + \"'\";\n break;\n } else if (c > '\\u0000' && c <= '\\u001f' || c >= '\\u007f' && c <= '\\u009F'\n || c >= '\\ud800' && c <= '\\uf8ff' || c >= '\\ufff0' && c <= '\\uffff') {\n reason = \"invalid character @\" + i;\n break;\n }\n }\n if (reason != null) {\n throw new IllegalArgumentException(\n \"Invalid application name \\\"\" + name + \"\\\" caused by \" + reason);\n }\n }", "public static base_response save(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup saveresource = new cachecontentgroup();\n\t\tsaveresource.name = resource.name;\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}", "protected void ensureColumns(List columns, List existingColumns)\r\n {\r\n if (columns == null || columns.isEmpty())\r\n {\r\n return;\r\n }\r\n \r\n Iterator iter = columns.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n FieldHelper cf = (FieldHelper) iter.next();\r\n if (!existingColumns.contains(cf.name))\r\n {\r\n getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());\r\n }\r\n }\r\n }", "public static linkset get(nitro_service service, String id) throws Exception{\n\t\tlinkset obj = new linkset();\n\t\tobj.set_id(id);\n\t\tlinkset response = (linkset) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Update the default time unit for durations based on data read from the file. @param column column data
[ "private void updateDurationTimeUnit(FastTrackColumn column)\n {\n if (m_durationTimeUnit == null && isDurationColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_durationTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }" ]
[ "private static void checkSorted(int[] sorted) {\r\n for (int i = 0; i < sorted.length-1; i++) {\r\n if (sorted[i] > sorted[i+1]) {\r\n throw new RuntimeException(\"input must be sorted!\");\r\n }\r\n }\r\n }", "@Deprecated\n public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {\n this.threadIdleMs = unit.toMillis(threadIdleTime);\n return this;\n }", "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }", "public Changes parameter(String name, String value) {\n this.databaseHelper.query(name, value);\n return this;\n }", "public ManageableCollection getCollectionByQuery(Class collectionClass, Query query)\n throws PersistenceBrokerException\n {\n return referencesBroker.getCollectionByQuery(collectionClass, query, false);\n }", "final protected char next(final ByteBuffer buffer, boolean allow8859) throws BaseExceptions.BadMessage {\n\n if (!buffer.hasRemaining()) return HttpTokens.EMPTY_BUFF;\n\n if (_segmentByteLimit <= _segmentBytePosition) {\n shutdownParser();\n throw new BaseExceptions.BadMessage(\"Request length limit exceeded: \" + _segmentByteLimit);\n }\n\n final byte b = buffer.get();\n _segmentBytePosition++;\n\n // If we ended on a CR, make sure we are\n if (_cr) {\n if (b != HttpTokens.LF) {\n throw new BadCharacter(\"Invalid sequence: LF didn't follow CR: \" + b);\n }\n _cr = false;\n return (char)b; // must be LF\n }\n\n // Make sure its a valid character\n if (b < HttpTokens.SPACE) {\n if (b == HttpTokens.CR) { // Set the flag to check for _cr and just run again\n _cr = true;\n return next(buffer, allow8859);\n }\n else if (b == HttpTokens.TAB || allow8859 && b < 0) {\n return (char)(b & 0xff);\n }\n else if (b == HttpTokens.LF) {\n return (char)b; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3\n }\n else if (isLenient()) {\n return HttpTokens.REPLACEMENT;\n }\n else {\n shutdownParser();\n throw new BadCharacter(\"Invalid char: '\" + (char)(b & 0xff) + \"', 0x\" + Integer.toHexString(b));\n }\n }\n\n // valid ascii char\n return (char)b;\n }", "private void populateTask(Row row, Task task)\n {\n task.setUniqueID(row.getInteger(\"Z_PK\"));\n task.setName(row.getString(\"ZTITLE\"));\n task.setPriority(Priority.getInstance(row.getInt(\"ZPRIORITY\")));\n task.setMilestone(row.getBoolean(\"ZISMILESTONE\"));\n task.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n task.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n task.setNotes(row.getString(\"ZOBJECTDESCRIPTION\"));\n task.setDuration(row.getDuration(\"ZGIVENDURATION_\"));\n task.setOvertimeWork(row.getWork(\"ZGIVENWORKOVERTIME_\"));\n task.setWork(row.getWork(\"ZGIVENWORK_\"));\n task.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n task.setActualOvertimeWork(row.getWork(\"ZGIVENACTUALWORKOVERTIME_\"));\n task.setActualWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setRemainingWork(row.getWork(\"ZGIVENACTUALWORK_\"));\n task.setGUID(row.getUUID(\"ZUNIQUEID\"));\n\n Integer calendarID = row.getInteger(\"ZGIVENCALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n task.setCalendar(calendar);\n }\n }\n\n populateConstraints(row, task);\n\n // Percent complete is calculated bottom up from assignments and actual work vs. planned work\n\n m_eventManager.fireTaskReadEvent(task);\n }", "private void addSingleUnique(StringBuilder sb, FieldType fieldType, List<String> additionalArgs,\n\t\t\tList<String> statementsAfter) {\n\t\tStringBuilder alterSb = new StringBuilder();\n\t\talterSb.append(\" UNIQUE (\");\n\t\tappendEscapedEntityName(alterSb, fieldType.getColumnName());\n\t\talterSb.append(')');\n\t\tadditionalArgs.add(alterSb.toString());\n\t}", "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }" ]
Use this API to fetch nsrpcnode resource of given name .
[ "public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static Object findResult(Object self, Object defaultResult, Closure closure) {\n Object result = findResult(self, closure);\n if (result == null) return defaultResult;\n return result;\n }", "public void parseVersion( String version )\n {\n DefaultVersioning artifactVersion = new DefaultVersioning( version );\n\n getLog().debug( \"Parsed Version\" );\n getLog().debug( \" major: \" + artifactVersion.getMajor() );\n getLog().debug( \" minor: \" + artifactVersion.getMinor() );\n getLog().debug( \" incremental: \" + artifactVersion.getPatch() );\n getLog().debug( \" buildnumber: \" + artifactVersion.getBuildNumber() );\n getLog().debug( \" qualifier: \" + artifactVersion.getQualifier() );\n\n defineVersionProperty( \"majorVersion\", artifactVersion.getMajor() );\n defineVersionProperty( \"minorVersion\", artifactVersion.getMinor() );\n defineVersionProperty( \"incrementalVersion\", artifactVersion.getPatch() );\n defineVersionProperty( \"buildNumber\", artifactVersion.getBuildNumber() );\n\n defineVersionProperty( \"nextMajorVersion\", artifactVersion.getMajor() + 1 );\n defineVersionProperty( \"nextMinorVersion\", artifactVersion.getMinor() + 1 );\n defineVersionProperty( \"nextIncrementalVersion\", artifactVersion.getPatch() + 1 );\n defineVersionProperty( \"nextBuildNumber\", artifactVersion.getBuildNumber() + 1 );\n\n defineFormattedVersionProperty( \"majorVersion\", String.format( formatMajor, artifactVersion.getMajor() ) );\n defineFormattedVersionProperty( \"minorVersion\", String.format( formatMinor, artifactVersion.getMinor() ) );\n defineFormattedVersionProperty( \"incrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() ) );\n defineFormattedVersionProperty( \"buildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() ));\n\n defineFormattedVersionProperty( \"nextMajorVersion\", String.format( formatMajor, artifactVersion.getMajor() + 1 ));\n defineFormattedVersionProperty( \"nextMinorVersion\", String.format( formatMinor, artifactVersion.getMinor() + 1 ));\n defineFormattedVersionProperty( \"nextIncrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() + 1 ));\n defineFormattedVersionProperty( \"nextBuildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() + 1 ));\n \n String osgi = artifactVersion.getAsOSGiVersion();\n\n String qualifier = artifactVersion.getQualifier();\n String qualifierQuestion = \"\";\n if ( qualifier == null )\n {\n qualifier = \"\";\n } else {\n qualifierQuestion = qualifierPrefix;\n }\n\n defineVersionProperty( \"qualifier\", qualifier );\n defineVersionProperty( \"qualifier?\", qualifierQuestion + qualifier );\n\n defineVersionProperty( \"osgiVersion\", osgi );\n }", "public static Dimension rectangleDoubleToDimension(final Rectangle2D.Double rectangle) {\n return new Dimension(\n (int) Math.round(rectangle.width),\n (int) Math.round(rectangle.height));\n }", "private void ensureLength(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_LENGTH))\r\n {\r\n String defaultLength = JdbcTypeHelper.getDefaultLengthFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultLength != 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 length setting though its jdbc type requires it (in most databases); using default length of \"+defaultLength);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_LENGTH, defaultLength);\r\n }\r\n }\r\n }", "private String generateValue() {\r\n\r\n String result = \"\";\r\n for (CmsCheckBox checkbox : m_checkboxes) {\r\n if (checkbox.isChecked()) {\r\n result += checkbox.getInternalValue() + \",\";\r\n }\r\n }\r\n if (result.contains(\",\")) {\r\n result = result.substring(0, result.lastIndexOf(\",\"));\r\n }\r\n return result;\r\n }", "public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, Class<T> clazz) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tClassConnectionSource key = new ClassConnectionSource(connectionSource, clazz);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) dao;\n\t\treturn castDao;\n\t}", "protected List<Object> executeProcessors(final List<Object> processedColumns, final CellProcessor[] processors) {\n\t\tUtil.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber());\n\t\treturn processedColumns;\n\t}", "public Map<String, Table> process(File directory, String prefix) throws IOException\n {\n String filePrefix = prefix.toUpperCase();\n Map<String, Table> tables = new HashMap<String, Table>();\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n String name = file.getName().toUpperCase();\n if (!name.startsWith(filePrefix))\n {\n continue;\n }\n\n int typeIndex = name.lastIndexOf('.') - 3;\n String type = name.substring(typeIndex, typeIndex + 3);\n TableDefinition definition = TABLE_DEFINITIONS.get(type);\n if (definition != null)\n {\n Table table = new Table();\n TableReader reader = new TableReader(definition);\n reader.read(file, table);\n tables.put(type, table);\n //dumpCSV(type, definition, table);\n }\n }\n }\n return tables;\n }", "protected ValueContainer[] getNonKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getNonKeyRwValues(cld, obj);\r\n }" ]
Checks if the provided organization is valid and could be stored into the database @param organization Organization @throws WebApplicationException if the data is corrupted
[ "public static void validate(final Organization organization) {\n if(organization.getName() == null ||\n organization.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Organization name cannot be null or empty!\")\n .build());\n }\n }" ]
[ "private String validateDuration() {\n\n if (!isValidEndTypeForPattern()) {\n return Messages.ERR_SERIALDATE_INVALID_END_TYPE_FOR_PATTERN_0;\n }\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS))\n ? null\n : Messages.ERR_SERIALDATE_SERIES_END_BEFORE_START_0;\n case TIMES:\n return getOccurrences() > 0 ? null : Messages.ERR_SERIALDATE_INVALID_OCCURRENCES_0;\n default:\n return null;\n }\n\n }", "@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 populateAnnotations(Collection<Annotation> annotations) {\n for (Annotation each : annotations) {\n this.annotations.put(each.annotationType(), each);\n }\n }", "@Override\n public ActivityInterface getActivityInterface() {\n if (activityInterface == null) {\n activityInterface = new ActivityInterface(apiKey, sharedSecret, transport);\n }\n return activityInterface;\n }", "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "private static void verifyJUnit4Present() {\n try {\n Class<?> clazz = Class.forName(\"org.junit.runner.Description\");\n if (!Serializable.class.isAssignableFrom(clazz)) {\n JvmExit.halt(SlaveMain.ERR_OLD_JUNIT);\n }\n } catch (ClassNotFoundException e) {\n JvmExit.halt(SlaveMain.ERR_NO_JUNIT);\n }\n }", "private void processGraphicalIndicators()\n {\n GraphicalIndicatorReader graphicalIndicatorReader = new GraphicalIndicatorReader();\n graphicalIndicatorReader.process(m_file.getCustomFields(), m_file.getProjectProperties(), m_projectProps);\n }", "private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException {\n\n if (cms.getRequestContext().getCurrentUser().isGuestUser()) {\n throw new CmsPermissionViolationException(null);\n }\n }", "public static Object executeXPath(Node document, String xpathExpression, Map<String, String> namespaceMapping, QName result)\n throws XPathException, MarshallingException\n {\n NamespaceMapContext mapContext = new NamespaceMapContext(namespaceMapping);\n try\n {\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n xpath.setNamespaceContext(mapContext);\n XPathExpression expr = xpath.compile(xpathExpression);\n\n return executeXPath(document, expr, result);\n }\n catch (XPathExpressionException e)\n {\n throw new XPathException(\"Xpath(\" + xpathExpression + \") cannot be compiled\", e);\n }\n catch (Exception e)\n {\n throw new MarshallingException(\"Exception unmarshalling XML.\", e);\n }\n }" ]
Serializes any char sequence and writes it into specified buffer.
[ "private static void writeCharSequence(CharSequence seq, CharBuf buffer) {\n if (seq.length() > 0) {\n buffer.addJsonEscapedString(seq.toString());\n } else {\n buffer.addChars(EMPTY_STRING_CHARS);\n }\n }" ]
[ "protected void process(String text, Map params, Writer writer){\n\n try{\n Template t = new Template(\"temp\", new StringReader(text), FreeMarkerTL.getEnvironment().getConfiguration());\n t.process(params, writer);\n }catch(Exception e){ \n throw new ViewException(e);\n }\n }", "public boolean rename(final File from, final File to) {\n boolean renamed = false;\n if (this.isWriteable(from)) {\n renamed = from.renameTo(to);\n } else {\n LogLog.debug(from + \" is not writeable for rename (retrying)\");\n }\n if (!renamed) {\n from.renameTo(to);\n renamed = (!from.exists());\n }\n return renamed;\n }", "public void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }", "private static Object getParam(final Object param) {\n\t\tfinal StringBuilder sb = new StringBuilder();\n\t\tif(param instanceof String){\n\t\t\tsb.append(\"'\");\n\t\t\tsb.append((String)param);\n\t\t\tsb.append(\"'\");\n\t\t}\n\t\telse if(param instanceof Boolean){\n\t\t\tsb.append(String.valueOf((Boolean)param));\t\t\t\n\t\t}\n else if(param instanceof Integer){\n sb.append(String.valueOf((Integer)param));\n }\n else if(param instanceof DBRegExp){\n sb.append('/');\n sb.append(((DBRegExp) param).toString());\n sb.append('/');\n }\n\t\t\n\t\treturn sb.toString();\n\t}", "private void writeCalendar(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws JAXBException\n {\n //\n // Populate basic details\n //\n plannerCalendar.setId(getIntegerString(mpxjCalendar.getUniqueID()));\n plannerCalendar.setName(getString(mpxjCalendar.getName()));\n\n //\n // Set working and non working days\n //\n DefaultWeek dw = m_factory.createDefaultWeek();\n plannerCalendar.setDefaultWeek(dw);\n dw.setMon(getWorkingDayString(mpxjCalendar, Day.MONDAY));\n dw.setTue(getWorkingDayString(mpxjCalendar, Day.TUESDAY));\n dw.setWed(getWorkingDayString(mpxjCalendar, Day.WEDNESDAY));\n dw.setThu(getWorkingDayString(mpxjCalendar, Day.THURSDAY));\n dw.setFri(getWorkingDayString(mpxjCalendar, Day.FRIDAY));\n dw.setSat(getWorkingDayString(mpxjCalendar, Day.SATURDAY));\n dw.setSun(getWorkingDayString(mpxjCalendar, Day.SUNDAY));\n\n //\n // Set working hours\n //\n OverriddenDayTypes odt = m_factory.createOverriddenDayTypes();\n plannerCalendar.setOverriddenDayTypes(odt);\n List<OverriddenDayType> typeList = odt.getOverriddenDayType();\n Sequence uniqueID = new Sequence(0);\n\n //\n // This is a bit arbitrary, so not ideal, however...\n // The idea here is that MS Project allows us to specify working hours\n // for each day of the week individually. Planner doesn't do this,\n // but instead allows us to specify working hours for each day type.\n // What we are doing here is stepping through the days of the week to\n // find the first working day, then using the hours for that day\n // as the hours for the working day type in Planner.\n //\n for (int dayLoop = 1; dayLoop < 8; dayLoop++)\n {\n Day day = Day.getInstance(dayLoop);\n if (mpxjCalendar.isWorkingDay(day))\n {\n processWorkingHours(mpxjCalendar, uniqueID, day, typeList);\n break;\n }\n }\n\n //\n // Process exception days\n //\n Days plannerDays = m_factory.createDays();\n plannerCalendar.setDays(plannerDays);\n List<net.sf.mpxj.planner.schema.Day> dayList = plannerDays.getDay();\n processExceptionDays(mpxjCalendar, dayList);\n\n m_eventManager.fireCalendarWrittenEvent(mpxjCalendar);\n\n //\n // Process any derived calendars\n //\n List<net.sf.mpxj.planner.schema.Calendar> calendarList = plannerCalendar.getCalendar();\n\n for (ProjectCalendar mpxjDerivedCalendar : mpxjCalendar.getDerivedCalendars())\n {\n net.sf.mpxj.planner.schema.Calendar plannerDerivedCalendar = m_factory.createCalendar();\n calendarList.add(plannerDerivedCalendar);\n writeCalendar(mpxjDerivedCalendar, plannerDerivedCalendar);\n }\n }", "public final void loadCollection(\n\t\tfinal SharedSessionContractImplementor session,\n\t\tfinal Serializable id,\n\t\tfinal Type type) throws HibernateException {\n\n\t\tif ( log.isDebugEnabled() ) {\n\t\t\tlog.debug(\n\t\t\t\t\t\"loading collection: \" +\n\t\t\t\t\tMessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() )\n\t\t\t\t);\n\t\t}\n\n\t\tSerializable[] ids = new Serializable[]{id};\n\t\tQueryParameters qp = new QueryParameters( new Type[]{type}, ids, ids );\n\t\tdoQueryAndInitializeNonLazyCollections(\n\t\t\t\tsession,\n\t\t\t\tqp,\n\t\t\t\tOgmLoadingContext.EMPTY_CONTEXT,\n\t\t\t\ttrue\n\t\t\t);\n\n\t\tlog.debug( \"done loading collection\" );\n\n\t}", "public static String constructSerializerInfoXml(StoreDefinition storeDefinition) {\n Element store = new Element(StoreDefinitionsMapper.STORE_ELMT);\n store.addContent(new Element(StoreDefinitionsMapper.STORE_NAME_ELMT).setText(storeDefinition.getName()));\n Element keySerializer = new Element(StoreDefinitionsMapper.STORE_KEY_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(keySerializer, storeDefinition.getKeySerializer());\n store.addContent(keySerializer);\n\n Element valueSerializer = new Element(StoreDefinitionsMapper.STORE_VALUE_SERIALIZER_ELMT);\n StoreDefinitionsMapper.addSerializer(valueSerializer, storeDefinition.getValueSerializer());\n store.addContent(valueSerializer);\n\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n return serializer.outputString(store);\n }", "private void printSuggestion( String arg, List<ConfigOption> co ) {\n List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );\n Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );\n System.err.println( \"Parse error for argument \\\"\" + arg + \"\\\", did you mean \" + sortedList.get( 0 ).getCommandLineOption()\n .showFlagInfo() + \"? Ignoring for now.\" );\n\n }", "public void setBundleActivator(String bundleActivator) {\n\t\tString old = mainAttributes.get(BUNDLE_ACTIVATOR);\n\t\tif (!bundleActivator.equals(old)) {\n\t\t\tthis.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator);\n\t\t\tthis.modified = true;\n\t\t\tthis.bundleActivator = bundleActivator;\n\t\t}\n\t}" ]
Converts a sequence of unicode code points to a sequence of Java characters. @return the number of chars written to the destination buffer
[ "public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) {\n if (srcLen < 0) {\n throw new IllegalArgumentException(\"srcLen must be >= 0\");\n }\n int written = 0;\n for (int i = 0; i < srcLen; ++i) {\n written += Character.toChars(src[srcOff + i], dest, destOff + written);\n }\n return written;\n }" ]
[ "private static LblTree createTree(TreeWalker walker) {\n\t\tNode parent = walker.getCurrentNode();\n\t\tLblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1\n\t\tfor (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {\n\t\t\tnode.add(createTree(walker));\n\t\t}\n\t\twalker.setCurrentNode(parent);\n\t\treturn node;\n\t}", "public Collection<BoxGroupMembership.Info> getMemberships() {\n BoxAPIConnection api = this.getAPI();\n URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n int entriesCount = responseJSON.get(\"total_count\").asInt();\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>(entriesCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n JsonObject entryObject = entry.asObject();\n BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get(\"id\").asString());\n BoxGroupMembership.Info info = membership.new Info(entryObject);\n memberships.add(info);\n }\n\n return memberships;\n }", "public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\n }\n }", "public static FilePath createAndGetTempDir(final FilePath ws) throws IOException, InterruptedException {\n // The token that combines the project name and unique number to create unique workspace directory.\n String workspaceList = System.getProperty(\"hudson.slaves.WorkspaceList\");\n return ws.act(new MasterToSlaveCallable<FilePath, IOException>() {\n @Override\n public FilePath call() {\n final FilePath tempDir = ws.sibling(ws.getName() + Objects.toString(workspaceList, \"@\") + \"tmp\").child(\"artifactory\");\n File tempDirFile = new File(tempDir.getRemote());\n tempDirFile.mkdirs();\n tempDirFile.deleteOnExit();\n return tempDir;\n }\n });\n }", "public static tunneltrafficpolicy get(nitro_service service, String name) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\tobj.set_name(name);\n\t\ttunneltrafficpolicy response = (tunneltrafficpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}", "public static String[] removeDuplicateStrings(String[] array) {\n if (isEmpty(array)) {\n return array;\n }\n Set<String> set = new TreeSet<String>();\n Collections.addAll(set, array);\n return toStringArray(set);\n }", "void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }", "@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }" ]
Extracts the value of this bit flag from the supplied byte array and sets the value in the supplied container. @param container container @param data byte array
[ "public void setValue(FieldContainer container, byte[] data)\n {\n if (data != null)\n {\n container.set(m_type, ((MPPUtility.getInt(data, m_offset) & m_mask) == 0) ? m_zeroValue : m_nonZeroValue);\n }\n }" ]
[ "public static final Rect getViewportBounds() {\n return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight());\n }", "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 }", "private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }", "private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}", "@Override\n public void onBindViewHolder(GalleryAdapter.ViewHolder holder, int position, List<Object> payloads) {\n if (payloads.isEmpty()) { // If doesn't have any payload then bind the fully item\n super.onBindViewHolder(holder, position, payloads);\n } else {\n for (Object payload : payloads) {\n boolean selected = isSelected(position);\n if (SELECTION_PAYLOAD.equals(payload)) {\n if (VIEW_TYPE_MEDIA == getItemViewType(position)) {\n MediaViewHolder viewHolder = (MediaViewHolder) holder;\n viewHolder.mCheckView.setChecked(selected);\n if (selected) {\n AnimationHelper.scaleView(holder.mImageView, SELECTED_SCALE);\n } else {\n AnimationHelper.scaleView(holder.mImageView, UNSELECTED_SCALE);\n }\n }\n }\n }\n }\n }", "public static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size)\n throws CmsUgcException {\n\n if (!config.getUploadParentFolder().isPresent()) {\n String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message);\n }\n\n if (config.getMaxUploadSize().isPresent()) {\n if (config.getMaxUploadSize().get().longValue() < size) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message);\n }\n }\n\n if (config.getValidExtensions().isPresent()) {\n List<String> validExtensions = config.getValidExtensions().get();\n boolean foundExtension = false;\n for (String extension : validExtensions) {\n if (name.toLowerCase().endsWith(extension.toLowerCase())) {\n foundExtension = true;\n break;\n }\n }\n if (!foundExtension) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message);\n }\n }\n }", "@Override\n\tpublic void visit(Rule rule) {\n\t\tRule copy = null;\n\t\tFilter filterCopy = null;\n\n\t\tif (rule.getFilter() != null) {\n\t\t\tFilter filter = rule.getFilter();\n\t\t\tfilterCopy = copy(filter);\n\t\t}\n\n\t\tList<Symbolizer> symsCopy = new ArrayList<Symbolizer>();\n\t\tfor (Symbolizer sym : rule.symbolizers()) {\n\t\t\tif (!skipSymbolizer(sym)) {\n\t\t\t\tSymbolizer symCopy = copy(sym);\n\t\t\t\tsymsCopy.add(symCopy);\n\t\t\t}\n\t\t}\n\n\t\tGraphic[] legendCopy = rule.getLegendGraphic();\n\t\tfor (int i = 0; i < legendCopy.length; i++) {\n\t\t\tlegendCopy[i] = copy(legendCopy[i]);\n\t\t}\n\n\t\tDescription descCopy = rule.getDescription();\n\t\tdescCopy = copy(descCopy);\n\n\t\tcopy = sf.createRule();\n\t\tcopy.symbolizers().addAll(symsCopy);\n\t\tcopy.setDescription(descCopy);\n\t\tcopy.setLegendGraphic(legendCopy);\n\t\tcopy.setName(rule.getName());\n\t\tcopy.setFilter(filterCopy);\n\t\tcopy.setElseFilter(rule.isElseFilter());\n\t\tcopy.setMaxScaleDenominator(rule.getMaxScaleDenominator());\n\t\tcopy.setMinScaleDenominator(rule.getMinScaleDenominator());\n\n\t\tif (STRICT && !copy.equals(rule)) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Was unable to duplicate provided Rule:\" + rule);\n\t\t}\n\t\tpages.push(copy);\n\t}", "private void reInitLayoutElements() {\n\n m_panel.clear();\n for (CmsCheckBox cb : m_checkBoxes) {\n m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));\n }\n }", "private static void setDpiValue(final Multimap<String, String> extraParams, final int dpi) {\n String searchKey = \"FORMAT_OPTIONS\";\n for (String key: extraParams.keys()) {\n if (key.equalsIgnoreCase(searchKey)) {\n Collection<String> values = extraParams.removeAll(key);\n List<String> newValues = new ArrayList<>();\n for (String value: values) {\n if (!StringUtils.isEmpty(value)) {\n value += \";dpi:\" + Integer.toString(dpi);\n newValues.add(value);\n }\n }\n extraParams.putAll(key, newValues);\n return;\n }\n }\n }" ]
Gets the groupby for ReportQueries of all Criteria and Sub Criteria the elements are of class FieldHelper @return List of FieldHelper
[ "List getGroupby()\r\n {\r\n List result = _getGroupby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getGroupby());\r\n }\r\n }\r\n\r\n return result;\r\n }" ]
[ "private void readFile(InputStream is) throws IOException\n {\n StreamHelper.skip(is, 64);\n int index = 64;\n\n ArrayList<Integer> offsetList = new ArrayList<Integer>();\n List<String> nameList = new ArrayList<String>();\n\n while (true)\n {\n byte[] table = new byte[32];\n is.read(table);\n index += 32;\n\n int offset = PEPUtility.getInt(table, 0);\n offsetList.add(Integer.valueOf(offset));\n if (offset == 0)\n {\n break;\n }\n\n nameList.add(PEPUtility.getString(table, 5).toUpperCase());\n }\n\n StreamHelper.skip(is, offsetList.get(0).intValue() - index);\n\n for (int offsetIndex = 1; offsetIndex < offsetList.size() - 1; offsetIndex++)\n {\n String name = nameList.get(offsetIndex - 1);\n Class<? extends Table> tableClass = TABLE_CLASSES.get(name);\n if (tableClass == null)\n {\n tableClass = Table.class;\n }\n\n Table table;\n try\n {\n table = tableClass.newInstance();\n }\n\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n m_tables.put(name, table);\n table.read(is);\n }\n }", "public static base_response update(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver updateresource = new ntpserver();\n\t\tupdateresource.serverip = resource.serverip;\n\t\tupdateresource.servername = resource.servername;\n\t\tupdateresource.minpoll = resource.minpoll;\n\t\tupdateresource.maxpoll = resource.maxpoll;\n\t\tupdateresource.preferredntpserver = resource.preferredntpserver;\n\t\tupdateresource.autokey = resource.autokey;\n\t\tupdateresource.key = resource.key;\n\t\treturn updateresource.update_resource(client);\n\t}", "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 BlurBuilder downScale(int scaleInSample) {\n data.options.inSampleSize = Math.min(Math.max(1, scaleInSample), 16384);\n return this;\n }", "private void executePlan(RebalancePlan rebalancePlan) {\n logger.info(\"Starting to execute rebalance Plan!\");\n\n int batchCount = 0;\n int partitionStoreCount = 0;\n long totalTimeMs = 0;\n\n List<RebalanceBatchPlan> entirePlan = rebalancePlan.getPlan();\n int numBatches = entirePlan.size();\n int numPartitionStores = rebalancePlan.getPartitionStoresMoved();\n\n for(RebalanceBatchPlan batchPlan: entirePlan) {\n logger.info(\"======== REBALANCING BATCH \" + (batchCount + 1)\n + \" ========\");\n RebalanceUtils.printBatchLog(batchCount,\n logger,\n batchPlan.toString());\n\n long startTimeMs = System.currentTimeMillis();\n // ACTUALLY DO A BATCH OF REBALANCING!\n executeBatch(batchCount, batchPlan);\n totalTimeMs += (System.currentTimeMillis() - startTimeMs);\n\n // Bump up the statistics\n batchCount++;\n partitionStoreCount += batchPlan.getPartitionStoreMoves();\n batchStatusLog(batchCount,\n numBatches,\n partitionStoreCount,\n numPartitionStores,\n totalTimeMs);\n }\n }", "public 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}", "private String parseRssFeed(String feed) {\n String[] result = feed.split(\"<br />\");\n String[] result2 = result[2].split(\"<BR />\");\n\n return result2[0];\n }", "public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }", "public long getTimeFor(int player) {\n TrackPositionUpdate update = positions.get(player);\n if (update != null) {\n return interpolateTimeSinceUpdate(update, System.nanoTime());\n }\n return -1; // We don't know.\n }" ]
Specifies convergence criteria @param maxIterations Maximum number of iterations @param ftol convergence based on change in function value. try 1e-12 @param gtol convergence based on residual magnitude. Try 1e-12
[ "public void setConvergence( int maxIterations , double ftol , double gtol ) {\n this.maxIterations = maxIterations;\n this.ftol = ftol;\n this.gtol = gtol;\n }" ]
[ "public static base_response add(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager addresource = new snmpmanager();\n\t\taddresource.ipaddress = resource.ipaddress;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn addresource.add_resource(client);\n\t}", "public ConnectionInfo getConnection(String name) {\n final URI uri = uriWithPath(\"./connections/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, ConnectionInfo.class);\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"classes.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Image\"\n\t\t\t\t\t+ \",Number of direct instances\"\n\t\t\t\t\t+ \",Number of direct subclasses\" + \",Direct superclasses\"\n\t\t\t\t\t+ \",All superclasses\" + \",Related properties\");\n\n\t\t\tList<Entry<EntityIdValue, ClassRecord>> list = new ArrayList<>(\n\t\t\t\t\tthis.classRecords.entrySet());\n\t\t\tCollections.sort(list, new ClassUsageRecordComparator());\n\t\t\tfor (Entry<EntityIdValue, ClassRecord> entry : list) {\n\t\t\t\tif (entry.getValue().itemCount > 0\n\t\t\t\t\t\t|| entry.getValue().subclassCount > 0) {\n\t\t\t\t\tprintClassRecord(out, entry.getValue(), entry.getKey());\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\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 CSTNode set( int index, CSTNode element ) \n {\n \n if( elements == null ) \n {\n throw new GroovyBugError( \"attempt to set() on a EMPTY Reduction\" );\n }\n\n if( index == 0 && !(element instanceof Token) ) \n {\n\n //\n // It's not the greatest of design that the interface allows this, but it\n // is a tradeoff with convenience, and the convenience is more important.\n\n throw new GroovyBugError( \"attempt to set() a non-Token as root of a Reduction\" );\n }\n\n\n //\n // Fill slots with nulls, if necessary.\n\n int count = elements.size();\n if( index >= count ) \n {\n for( int i = count; i <= index; i++ ) \n {\n elements.add( null );\n }\n }\n\n //\n // Then set in the element.\n\n elements.set( index, element );\n\n return element;\n }", "public void addSubmodule(final Module submodule) {\n if (!submodules.contains(submodule)) {\n submodule.setSubmodule(true);\n\n if (promoted) {\n submodule.setPromoted(promoted);\n }\n\n submodules.add(submodule);\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 final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }", "protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) {\n //noinspection unchecked\n return (ActiveOperation<T, A>) activeRequests.get(id);\n }" ]
Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns the defaultResult. @param self an Object with an iterator returning its values @param defaultResult an Object that should be returned if all closure results are null @param closure a closure that returns a non-null value when processing should stop @return the first non-null result of the closure, otherwise the default value @since 1.7.5
[ "public static Object findResult(Object self, Object defaultResult, Closure closure) {\n Object result = findResult(self, closure);\n if (result == null) return defaultResult;\n return result;\n }" ]
[ "private void readPattern(JSONObject patternJson) {\n\n setPatternType(readPatternType(patternJson));\n setInterval(readOptionalInt(patternJson, JsonKey.PATTERN_INTERVAL));\n setWeekDays(readWeekDays(patternJson));\n setDayOfMonth(readOptionalInt(patternJson, JsonKey.PATTERN_DAY_OF_MONTH));\n setEveryWorkingDay(readOptionalBoolean(patternJson, JsonKey.PATTERN_EVERYWORKINGDAY));\n setWeeksOfMonth(readWeeksOfMonth(patternJson));\n setIndividualDates(readDates(readOptionalArray(patternJson, JsonKey.PATTERN_DATES)));\n setMonth(readOptionalMonth(patternJson, JsonKey.PATTERN_MONTH));\n\n }", "@UiHandler(\"m_atNumber\")\r\n void onWeekOfMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setWeekOfMonth(event.getValue());\r\n }\r\n }", "private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException {\n\t\tList<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>();\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read next field from config file\", e);\n\t\t\t}\n\t\t\tif (line == null || line.equals(CONFIG_FILE_FIELDS_END)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader);\n\t\t\tif (fieldConfig == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfields.add(fieldConfig);\n\t\t}\n\t\tconfig.setFieldConfigs(fields);\n\t}", "public boolean removeWriter(Object key, Object resourceId)\r\n {\r\n boolean result = false;\r\n ObjectLocks objectLocks = null;\r\n synchronized(locktable)\r\n {\r\n objectLocks = (ObjectLocks) locktable.get(resourceId);\r\n if(objectLocks != null)\r\n {\r\n /**\r\n * MBAIRD, last one out, close the door and turn off the lights.\r\n * if no locks (readers or writers) exist for this object, let's remove\r\n * it from the locktable.\r\n */\r\n LockEntry entry = objectLocks.getWriter();\r\n if(entry != null && entry.isOwnedBy(key))\r\n {\r\n objectLocks.setWriter(null);\r\n result = true;\r\n\r\n // no need to check if writer is null, we just set it.\r\n if(objectLocks.getReaders().size() == 0)\r\n {\r\n locktable.remove(resourceId);\r\n }\r\n }\r\n }\r\n }\r\n return result;\r\n }", "public final void updateLastCheckTime(final String id, final long lastCheckTime) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.equal(root.get(\"referenceId\"), id));\n update.set(root.get(\"lastCheckTime\"), lastCheckTime);\n getSession().createQuery(update).executeUpdate();\n }", "protected void writeRow(final String... columns) throws IOException {\n\t\t\n\t\tif( columns == null ) {\n\t\t\tthrow new NullPointerException(String.format(\"columns to write should not be null on line %d\", lineNumber));\n\t\t} else if( columns.length == 0 ) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"columns to write should not be empty on line %d\",\n\t\t\t\tlineNumber));\n\t\t}\n\t\t\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor( int i = 0; i < columns.length; i++ ) {\n\t\t\t\n\t\t\tcolumnNumber = i + 1; // column no used by CsvEncoder\n\t\t\t\n\t\t\tif( i > 0 ) {\n\t\t\t\tbuilder.append((char) preference.getDelimiterChar()); // delimiter\n\t\t\t}\n\t\t\t\n\t\t\tfinal String csvElement = columns[i];\n\t\t\tif( csvElement != null ) {\n\t\t\t\tfinal CsvContext context = new CsvContext(lineNumber, rowNumber, columnNumber);\n\t\t\t\tfinal String escapedCsv = encoder.encode(csvElement, context, preference);\n\t\t\t\tbuilder.append(escapedCsv);\n\t\t\t\tlineNumber = context.getLineNumber(); // line number can increment when encoding multi-line columns\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tbuilder.append(preference.getEndOfLineSymbols()); // EOL\n\t\twriter.write(builder.toString());\n\t}", "protected JRDesignGroup getParent(JRDesignGroup group) {\n int index = realGroups.indexOf(group);\n return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;\n }", "private static void checkSorted(int[] sorted) {\r\n for (int i = 0; i < sorted.length-1; i++) {\r\n if (sorted[i] > sorted[i+1]) {\r\n throw new RuntimeException(\"input must be sorted!\");\r\n }\r\n }\r\n }", "public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.ObjectInputStream\",\"java.io.ObjectOutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(output);\n ObjectInputStream ois = new ObjectInputStream(input);\n try {\n T result = closure.call(new Object[]{ois, oos});\n\n InputStream temp1 = ois;\n ois = null;\n temp1.close();\n temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = oos;\n oos = null;\n temp2.close();\n temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(ois);\n closeWithWarning(input);\n closeWithWarning(oos);\n closeWithWarning(output);\n }\n }" ]
Use this API to unset the properties of snmpalarm resource. Properties that need to be unset are specified in args array.
[ "public static base_response unset(nitro_service client, snmpalarm resource, String[] args) throws Exception{\n\t\tsnmpalarm unsetresource = new snmpalarm();\n\t\tunsetresource.trapname = resource.trapname;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
[ "private void readCalendars(Project ganttProject)\n {\n m_mpxjCalendar = m_projectFile.addCalendar();\n m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME);\n\n Calendars gpCalendar = ganttProject.getCalendars();\n setWorkingDays(m_mpxjCalendar, gpCalendar);\n setExceptions(m_mpxjCalendar, gpCalendar);\n m_eventManager.fireCalendarReadEvent(m_mpxjCalendar);\n }", "public static base_response update(nitro_service client, clusternodegroup resource) throws Exception {\n\t\tclusternodegroup updateresource = new clusternodegroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.strict = resource.strict;\n\t\treturn updateresource.update_resource(client);\n\t}", "public final ZoomToFeatures copy() {\n ZoomToFeatures obj = new ZoomToFeatures();\n obj.zoomType = this.zoomType;\n obj.minScale = this.minScale;\n obj.minMargin = this.minMargin;\n return obj;\n }", "public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException {\r\n\r\n // Use TreeMap so keys are automatically sorted alphabetically\r\n Map<String, String> parameters = new TreeMap<String, String>();\r\n parameters.put(\"method\", METHOD_EXCHANGE_TOKEN);\r\n parameters.put(Flickr.API_KEY, apiKey);\r\n // This method call must be signed using Flickr (not OAuth) style signing\r\n parameters.put(\"api_sig\", getSignature(sharedSecret, parameters));\r\n\r\n Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n OAuth1RequestToken accessToken = constructToken(response);\r\n\r\n return accessToken;\r\n }", "public static boolean doAcquireLock(final Jedis jedis, final String namespace, final String lockName, final String lockHolder, final int timeout) {\n final String key = JesqueUtils.createKey(namespace, lockName);\n // If lock already exists, extend it\n String existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n }\n // Check to see if the key exists and is expired for cleanup purposes\n if (jedis.exists(key) && (jedis.ttl(key) < 0)) {\n // It is expired, but it may be in the process of being created, so\n // sleep and check again\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ie) {\n } // Ignore interruptions\n if (jedis.ttl(key) < 0) {\n existingLockHolder = jedis.get(key);\n // If it is our lock mark the time to live\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n if (jedis.expire(key, timeout) == 1) {\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n }\n } else { // The key is expired, whack it!\n jedis.del(key);\n }\n } else { // Someone else locked it while we were sleeping\n return false;\n }\n }\n // Ignore the cleanup steps above, start with no assumptions test\n // creating the key\n if (jedis.setnx(key, lockHolder) == 1) {\n // Created the lock, now set the expiration\n if (jedis.expire(key, timeout) == 1) { // Set the timeout\n existingLockHolder = jedis.get(key);\n if ((existingLockHolder != null) && existingLockHolder.equals(lockHolder)) {\n return true;\n }\n } else { // Don't know why it failed, but for now just report failed\n // acquisition\n return false;\n }\n }\n // Failed to create the lock\n return false;\n }", "public static vpnclientlessaccesspolicy[] get(nitro_service service) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "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 static GVRMesh createQuad(GVRContext gvrContext, float width, float height) {\n GVRMesh mesh = new GVRMesh(gvrContext);\n\n float[] vertices = { width * -0.5f, height * 0.5f, 0.0f, width * -0.5f,\n height * -0.5f, 0.0f, width * 0.5f, height * 0.5f, 0.0f,\n width * 0.5f, height * -0.5f, 0.0f };\n mesh.setVertices(vertices);\n\n final float[] normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f, 1.0f };\n mesh.setNormals(normals);\n\n final float[] texCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,\n 1.0f };\n mesh.setTexCoords(texCoords);\n\n char[] triangles = { 0, 1, 2, 1, 3, 2 };\n mesh.setIndices(triangles);\n\n return mesh;\n }", "public void forAllForeignkeys(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )\r\n {\r\n _curForeignkeyDef = (ForeignkeyDef)it.next();\r\n generate(template);\r\n }\r\n _curForeignkeyDef = null;\r\n }" ]
Get a boolean value from the values or null. @param key the look up key of the value
[ "@Nullable\n public Boolean getBoolean(@Nonnull final String key) {\n return (Boolean) this.values.get(key);\n }" ]
[ "public static boolean isInteger(CharSequence self) {\n try {\n Integer.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "private void addCriteria(List<GenericCriteria> list, byte[] block)\n {\n byte[] leftBlock = getChildBlock(block);\n byte[] rightBlock1 = getListNextBlock(leftBlock);\n byte[] rightBlock2 = getListNextBlock(rightBlock1);\n TestOperator operator = TestOperator.getInstance(MPPUtility.getShort(block, 0) - 0x3E7);\n FieldType leftValue = getFieldType(leftBlock);\n Object rightValue1 = getValue(leftValue, rightBlock1);\n Object rightValue2 = rightBlock2 == null ? null : getValue(leftValue, rightBlock2);\n\n GenericCriteria criteria = new GenericCriteria(m_properties);\n criteria.setLeftValue(leftValue);\n criteria.setOperator(operator);\n criteria.setRightValue(0, rightValue1);\n criteria.setRightValue(1, rightValue2);\n list.add(criteria);\n\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = leftValue.getFieldTypeClass() == FieldTypeClass.TASK;\n m_criteriaType[1] = !m_criteriaType[0];\n }\n\n if (m_fields != null)\n {\n m_fields.add(leftValue);\n }\n\n processBlock(list, getListNextBlock(block));\n }", "private Set<HttpMethod> getHttpMethods(Method method) {\n Set<HttpMethod> httpMethods = new HashSet<>();\n\n if (method.isAnnotationPresent(GET.class)) {\n httpMethods.add(HttpMethod.GET);\n }\n if (method.isAnnotationPresent(PUT.class)) {\n httpMethods.add(HttpMethod.PUT);\n }\n if (method.isAnnotationPresent(POST.class)) {\n httpMethods.add(HttpMethod.POST);\n }\n if (method.isAnnotationPresent(DELETE.class)) {\n httpMethods.add(HttpMethod.DELETE);\n }\n\n return Collections.unmodifiableSet(httpMethods);\n }", "private void putEvent(EventType eventType) throws Exception {\n List<EventType> eventTypes = Collections.singletonList(eventType);\n\n int i;\n for (i = 0; i < retryNum; ++i) {\n try {\n monitoringService.putEvents(eventTypes);\n break;\n } catch (Exception e) {\n LOG.log(Level.SEVERE, e.getMessage(), e);\n }\n Thread.sleep(retryDelay);\n }\n\n if (i == retryNum) {\n LOG.warning(\"Could not send events to monitoring service after \" + retryNum + \" retries.\");\n throw new Exception(\"Send SERVER_START/SERVER_STOP event to SAM Server failed\");\n }\n\n }", "public void createAssignmentFieldMap(Props props)\n {\n //System.out.println(\"ASSIGN\");\n byte[] fieldMapData = null;\n for (Integer key : ASSIGNMENT_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultAssignmentData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public static String readStringFromUrlGeneric(String url)\n throws IOException {\n InputStream is = null;\n URL urlObj = null;\n String responseString = PcConstants.NA;\n try {\n urlObj = new URL(url);\n URLConnection con = urlObj.openConnection();\n\n con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis);\n con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis);\n is = con.getInputStream();\n\n BufferedReader rd = new BufferedReader(new InputStreamReader(is,\n Charset.forName(\"UTF-8\")));\n responseString = PcFileNetworkIoUtils.readAll(rd);\n\n } finally {\n\n if (is != null) {\n is.close();\n }\n\n }\n\n return responseString;\n }", "public static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }", "private boolean ignoreMethod(String name)\n {\n boolean result = false;\n\n for (String ignoredName : IGNORED_METHODS)\n {\n if (name.matches(ignoredName))\n {\n result = true;\n break;\n }\n }\n\n return result;\n }", "private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }" ]
Obtain the ID associated with a profile name @param profileName profile name @return ID of profile
[ "public Integer getIdFromName(String profileName) {\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE +\n \" WHERE \" + Constants.PROFILE_PROFILE_NAME + \" = ?\");\n query.setString(1, profileName);\n results = query.executeQuery();\n if (results.next()) {\n Object toReturn = results.getObject(Constants.GENERIC_ID);\n query.close();\n return (Integer) toReturn;\n }\n query.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n return null;\n }" ]
[ "public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) {\n\n final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);\n if (secret.isEmpty()) {\n return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry);\n } else {\n return CuratorFrameworkFactory.builder().connectString(zookeepers)\n .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry)\n .authorization(\"digest\", (\"fluo:\" + secret).getBytes(StandardCharsets.UTF_8))\n .aclProvider(new ACLProvider() {\n @Override\n public List<ACL> getDefaultAcl() {\n return CREATOR_ALL_ACL;\n }\n\n @Override\n public List<ACL> getAclForPath(String path) {\n switch (path) {\n case ZookeeperPath.ORACLE_GC_TIMESTAMP:\n // The garbage collection iterator running in Accumulo tservers needs to read this\n // value w/o authenticating.\n return PUBLICLY_READABLE_ACL;\n default:\n return CREATOR_ALL_ACL;\n }\n }\n }).build();\n }\n }", "@Nullable\n public final Credentials toCredentials(final AuthScope authscope) {\n try {\n\n if (!matches(MatchInfo.fromAuthScope(authscope))) {\n return null;\n }\n } catch (UnknownHostException | MalformedURLException | SocketException e) {\n throw new RuntimeException(e);\n }\n if (this.username == null) {\n return null;\n }\n\n final String passwordString;\n if (this.password != null) {\n passwordString = new String(this.password);\n } else {\n passwordString = null;\n }\n return new UsernamePasswordCredentials(this.username, passwordString);\n }", "protected Map getAllVariables(){\n try{\n Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();\n Map vars = new HashMap();\n while (names.hasNext()) {\n Object name =names.next();\n vars.put(name, get(name.toString()));\n }\n return vars;\n }catch(Exception e){\n throw new ViewException(e);\n }\n }", "public ConverterServerBuilder baseUri(String baseUri) {\n checkNotNull(baseUri);\n this.baseUri = URI.create(baseUri);\n return this;\n }", "public synchronized RegistrationPoint getOldestRegistrationPoint() {\n return registrationPoints.size() == 0 ? null : registrationPoints.values().iterator().next().get(0);\n }", "public static void clearallLocalDBs() {\n for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) {\n for (final String dbName : entry.getKey().listDatabaseNames()) {\n entry.getKey().getDatabase(dbName).drop();\n }\n }\n }", "private int getFlagResource(Country country) {\n return getContext().getResources().getIdentifier(\"country_\" + country.getIso().toLowerCase(), \"drawable\", getContext().getPackageName());\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 }", "private void processChildTasks(Task task, MapRow row) throws IOException\n {\n List<MapRow> tasks = row.getRows(\"TASKS\");\n if (tasks != null)\n {\n for (MapRow childTask : tasks)\n {\n processTask(task, childTask);\n }\n }\n }" ]
returns a collection of Reader LockEntries for object obj. If now LockEntries could be found an empty Vector is returned.
[ "public Collection getReaders(Object obj)\r\n\t{\r\n\t\tCollection result = null;\r\n try\r\n {\r\n Identity oid = new Identity(obj, getBroker());\r\n byte selector = (byte) 'r';\r\n byte[] requestBarr = buildRequestArray(oid, selector);\r\n \r\n HttpURLConnection conn = getHttpUrlConnection();\r\n \r\n //post request\r\n BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());\r\n out.write(requestBarr,0,requestBarr.length);\r\n out.flush();\t\t\r\n \r\n // read result from \r\n InputStream in = conn.getInputStream();\r\n ObjectInputStream ois = new ObjectInputStream(in);\r\n result = (Collection) ois.readObject();\r\n \r\n // cleanup\r\n ois.close();\r\n out.close();\r\n conn.disconnect();\t\t\r\n }\r\n catch (Throwable t)\r\n {\r\n throw new PersistenceBrokerException(t);\r\n }\r\n return result;\r\n\t}" ]
[ "private ProjectCalendarDateRanges getRanges(Date date, Calendar cal, Day day)\n {\n ProjectCalendarDateRanges ranges = getException(date);\n if (ranges == null)\n {\n ProjectCalendarWeek week = getWorkWeek(date);\n if (week == null)\n {\n week = this;\n }\n\n if (day == null)\n {\n if (cal == null)\n {\n cal = Calendar.getInstance();\n cal.setTime(date);\n }\n day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));\n }\n\n ranges = week.getHours(day);\n }\n return ranges;\n }", "private String filterAttributes(String html) {\n\t\tString filteredHtml = html;\n\t\tfor (String attribute : this.filterAttributes) {\n\t\t\tString regex = \"\\\\s\" + attribute + \"=\\\"[^\\\"]*\\\"\";\n\t\t\tPattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n\t\t\tMatcher m = p.matcher(html);\n\t\t\tfilteredHtml = m.replaceAll(\"\");\n\t\t}\n\t\treturn filteredHtml;\n\t}", "private static void handlePing(final Channel channel, final ManagementProtocolHeader header) throws IOException {\n final ManagementProtocolHeader response = new ManagementPongHeader(header.getVersion());\n final MessageOutputStream output = channel.writeMessage();\n try {\n writeHeader(response, output);\n output.close();\n } finally {\n StreamUtils.safeClose(output);\n }\n }", "public void setEveryWorkingDay(final boolean isEveryWorkingDay) {\n\n if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }", "private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)\r\n {\r\n String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();\r\n ClassDescriptorDef classDef;\r\n ReferenceDescriptorDef refDef;\r\n String targetClassName;\r\n\r\n // only relevant for primarykey fields\r\n if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))\r\n {\r\n for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)classIt.next();\r\n for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)\r\n {\r\n refDef = (ReferenceDescriptorDef)refIt.next();\r\n targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');\r\n if (ownerClassName.equals(targetClassName))\r\n {\r\n // the field is a primary key of the class referenced by this reference descriptor\r\n return refDef;\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }", "@Override\r\n public synchronized long skip(final long length) throws IOException {\r\n final long skip = super.skip(length);\r\n this.count += skip;\r\n return skip;\r\n }", "public void cache(Identity oid, Object obj)\r\n {\r\n try\r\n {\r\n jcsCache.put(oid.toString(), obj);\r\n }\r\n catch (CacheException e)\r\n {\r\n throw new RuntimeCacheException(e);\r\n }\r\n }", "public Number getOvertimeCost()\n {\n Number cost = (Number) getCachedValue(AssignmentField.OVERTIME_COST);\n if (cost == null)\n {\n Number actual = getActualOvertimeCost();\n Number remaining = getRemainingOvertimeCost();\n if (actual != null && remaining != null)\n {\n cost = NumberHelper.getDouble(actual.doubleValue() + remaining.doubleValue());\n set(AssignmentField.OVERTIME_COST, cost);\n }\n }\n return (cost);\n }", "void writeBestRankTriples() {\n\t\tfor (Resource resource : this.rankBuffer.getBestRankedStatements()) {\n\t\t\ttry {\n\t\t\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\t\t\tRdfWriter.RDF_TYPE, RdfWriter.WB_BEST_RANK.toString());\n\t\t\t} catch (RDFHandlerException e) {\n\t\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tthis.rankBuffer.clear();\n\t}" ]
Reads all text of the XML tag and returns it as a String. Assumes that a '<' character has already been read. @param r The reader to read from @return The String representing the tag, or null if one couldn't be read (i.e., EOF). The returned item is a complete tag including angle brackets, such as <code>&lt;TXT&gt;</code>
[ "public static String readTag(Reader r) throws IOException {\r\n if ( ! r.ready()) {\r\n return null;\r\n }\r\n StringBuilder b = new StringBuilder(\"<\");\r\n int c = r.read();\r\n while (c >= 0) {\r\n b.append((char) c);\r\n if (c == '>') {\r\n break;\r\n }\r\n c = r.read();\r\n }\r\n if (b.length() == 1) {\r\n return null;\r\n }\r\n return b.toString();\r\n }" ]
[ "public ModelNode getDeploymentSubsystemModel(final String subsystemName) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);\n }", "public Metadata remove(String path) {\n this.values.remove(this.pathToProperty(path));\n this.addOp(\"remove\", path, (String) null);\n return this;\n }", "public static linkset_interface_binding[] get(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public Logger getLogger(String loggerName)\r\n {\r\n Logger logger;\r\n //lookup in the cache first\r\n logger = (Logger) cache.get(loggerName);\r\n\r\n if(logger == null)\r\n {\r\n try\r\n {\r\n // get the configuration (not from the configurator because this is independent)\r\n logger = createLoggerInstance(loggerName);\r\n if(getBootLogger().isDebugEnabled())\r\n {\r\n getBootLogger().debug(\"Using logger class '\"\r\n + (getConfiguration() != null ? getConfiguration().getLoggerClass() : null)\r\n + \"' for \" + loggerName);\r\n }\r\n // configure the logger\r\n getBootLogger().debug(\"Initializing logger instance \" + loggerName);\r\n logger.configure(conf);\r\n }\r\n catch(Throwable t)\r\n {\r\n // do reassign check and signal logger creation failure\r\n reassignBootLogger(true);\r\n logger = getBootLogger();\r\n getBootLogger().error(\"[\" + this.getClass().getName()\r\n + \"] Could not initialize logger \" + (conf != null ? conf.getLoggerClass() : null), t);\r\n }\r\n //cache it so we can get it faster the next time\r\n cache.put(loggerName, logger);\r\n // do reassign check\r\n reassignBootLogger(false);\r\n }\r\n return logger;\r\n }", "public Table createTable(ProjectFile file, byte[] data, VarMeta varMeta, Var2Data varData)\n {\n Table table = new Table();\n\n table.setID(MPPUtility.getInt(data, 0));\n table.setResourceFlag(MPPUtility.getShort(data, 108) == 1);\n table.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(data, 4)));\n\n byte[] columnData = null;\n Integer tableID = Integer.valueOf(table.getID());\n if (m_tableColumnDataBaseline != null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataBaseline));\n }\n\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataEnterprise));\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataStandard));\n }\n }\n\n processColumnData(file, table, columnData);\n\n //System.out.println(table);\n\n return (table);\n }", "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }", "public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }", "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 }", "@Override\n public void invert( ZMatrixRMaj inv ) {\n if( inv.numRows != n || inv.numCols != n ) {\n throw new RuntimeException(\"Unexpected matrix dimension\");\n }\n if( inv.data == t ) {\n throw new IllegalArgumentException(\"Passing in the same matrix that was decomposed.\");\n }\n\n if(decomposer.isLower()) {\n setToInverseL(inv.data);\n } else {\n throw new RuntimeException(\"Implement\");\n }\n }" ]
Get the VCS url from the Jenkins build environment. The search will one of "SVN_REVISION", "GIT_COMMIT", "P4_CHANGELIST" in the environment. @param env Th Jenkins build environment. @return The vcs url for supported VCS
[ "public static String getVcsUrl(Map<String, String> env) {\n String url = env.get(\"SVN_URL\");\n if (StringUtils.isBlank(url)) {\n url = publicGitUrl(env.get(\"GIT_URL\"));\n }\n if (StringUtils.isBlank(url)) {\n url = env.get(\"P4PORT\");\n }\n return url;\n }" ]
[ "private void internalWriteNameValuePair(String name, String value) throws IOException\n {\n writeComma();\n writeNewLineIndent();\n writeName(name);\n\n if (m_pretty)\n {\n m_writer.write(' ');\n }\n\n m_writer.write(value);\n }", "public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }", "private void writeComma() throws IOException\n {\n if (m_firstNameValuePair.peek().booleanValue())\n {\n m_firstNameValuePair.pop();\n m_firstNameValuePair.push(Boolean.FALSE);\n }\n else\n {\n m_writer.write(',');\n }\n }", "public void fireCalendarWrittenEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarWritten(calendar);\n }\n }\n }", "public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}", "private String mountPath(CdjStatus.TrackSourceSlot slot) {\n switch (slot) {\n case SD_SLOT: return \"/B/\";\n case USB_SLOT: return \"/C/\";\n }\n throw new IllegalArgumentException(\"Don't know how to NFS mount filesystem for slot \" + slot);\n }", "@Override\n public void solve(DMatrixRMaj B, DMatrixRMaj X) {\n X.reshape(blockA.numCols,B.numCols);\n blockB.reshape(B.numRows,B.numCols,false);\n blockX.reshape(X.numRows,X.numCols,false);\n MatrixOps_DDRB.convert(B,blockB);\n\n alg.solve(blockB,blockX);\n\n MatrixOps_DDRB.convert(blockX,X);\n }", "public static void writeBytes(byte[] bytes, long value, int offset, int numBytes) {\n int shift = 0;\n for(int i = offset + numBytes - 1; i >= offset; i--) {\n bytes[i] = (byte) (0xFF & (value >> shift));\n shift += 8;\n }\n }", "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 }" ]
Defers an event for processing in a later phase of the current transaction. @param metadata The event object
[ "private <T> void deferNotification(T event, final EventMetadata metadata, final ObserverMethod<? super T> observer,\n final List<DeferredEventNotification<?>> notifications) {\n TransactionPhase transactionPhase = observer.getTransactionPhase();\n boolean before = transactionPhase.equals(TransactionPhase.BEFORE_COMPLETION);\n Status status = Status.valueOf(transactionPhase);\n notifications.add(new DeferredEventNotification<T>(contextId, event, metadata, observer, currentEventMetadata, status, before));\n }" ]
[ "public static wisite_accessmethod_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_accessmethod_binding obj = new wisite_accessmethod_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_accessmethod_binding response[] = (wisite_accessmethod_binding[]) obj.get_resources(service);\n\t\treturn response;\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 PayloadBuilder category(final String category) {\n if (category != null) {\n aps.put(\"category\", category);\n } else {\n aps.remove(\"category\");\n }\n return this;\n }", "public static void main(String[] args) throws Exception {\r\n System.err.println(\"CRFBiasedClassifier invoked at \" + new Date()\r\n + \" with arguments:\");\r\n for (String arg : args) {\r\n System.err.print(\" \" + arg);\r\n }\r\n System.err.println();\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFBiasedClassifier crf = new CRFBiasedClassifier(props);\r\n String testFile = crf.flags.testFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n if(crf.flags.classBias != null) {\r\n StringTokenizer biases = new java.util.StringTokenizer(crf.flags.classBias,\",\");\r\n while (biases.hasMoreTokens()) {\r\n StringTokenizer bias = new java.util.StringTokenizer(biases.nextToken(),\":\");\r\n String cname = bias.nextToken();\r\n double w = Double.parseDouble(bias.nextToken());\r\n crf.setBiasWeight(cname,w);\r\n System.err.println(\"Setting bias for class \"+cname+\" to \"+w);\r\n }\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter readerAndWriter = crf.makeReaderAndWriter();\r\n 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 {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n }", "protected void updateNorms( int j ) {\n boolean foundNegative = false;\n for( int col = j; col < numCols; col++ ) {\n double e = dataQR[col][j-1];\n double v = normsCol[col] -= e*e;\n\n if( v < 0 ) {\n foundNegative = true;\n break;\n }\n }\n\n // if a negative sum has been found then clearly too much precision has been lost\n // and it should recompute the column norms from scratch\n if( foundNegative ) {\n for( int col = j; col < numCols; col++ ) {\n double u[] = dataQR[col];\n double actual = 0;\n for( int i=j; i < numRows; i++ ) {\n double v = u[i];\n actual += v*v;\n }\n normsCol[col] = actual;\n }\n }\n }", "private void addMembers(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n if (!type.isInterface() && (type.getFields() != null)) {\r\n XField field;\r\n\r\n for (Iterator it = type.getFields().iterator(); it.hasNext(); ) {\r\n field = (XField)it.next();\r\n if (!field.isFinal() && !field.isStatic() && !field.isTransient()) {\r\n if (checkTagAndParam(field.getDoc(), tagName, paramName, paramValue)) {\r\n // already processed ?\r\n if (!members.containsKey(field.getName())) {\r\n memberNames.add(field.getName());\r\n members.put(field.getName(), field);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (type.getMethods() != null) {\r\n XMethod method;\r\n String propertyName;\r\n\r\n for (Iterator it = type.getMethods().iterator(); it.hasNext(); ) {\r\n method = (XMethod)it.next();\r\n if (!method.isConstructor() && !method.isNative() && !method.isStatic()) {\r\n if (checkTagAndParam(method.getDoc(), tagName, paramName, paramValue)) {\r\n if (MethodTagsHandler.isGetterMethod(method) || MethodTagsHandler.isSetterMethod(method)) {\r\n propertyName = MethodTagsHandler.getPropertyNameFor(method);\r\n if (!members.containsKey(propertyName)) {\r\n memberNames.add(propertyName);\r\n members.put(propertyName, method);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }", "public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(startDate);\n gc.add(period, amount);\n return new java.util.Date(gc.getTime().getTime());\n }", "public static DocumentBuilder getXmlParser() {\r\n DocumentBuilder db = null;\r\n try {\r\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\r\n dbf.setValidating(false);\r\n\r\n //Disable DTD loading and validation\r\n //See http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\r\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\r\n\r\n db = dbf.newDocumentBuilder();\r\n db.setErrorHandler(new SAXErrorHandler());\r\n\r\n } catch (ParserConfigurationException e) {\r\n System.err.printf(\"%s: Unable to create XML parser\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n\r\n } catch(UnsupportedOperationException e) {\r\n System.err.printf(\"%s: API error while setting up XML parser. Check your JAXP version\\n\", XMLUtils.class.getName());\r\n e.printStackTrace();\r\n }\r\n\r\n return db;\r\n }", "public void useXopAttachmentServiceWithProxy() throws Exception {\n\n final String serviceURI = \"http://localhost:\" + port + \"/services/attachments\";\n \n XopAttachmentService proxy = JAXRSClientFactory.create(serviceURI, \n XopAttachmentService.class);\n \n XopBean xop = createXopBean();\n \n System.out.println();\n System.out.println(\"Posting a XOP attachment with a proxy\");\n \n XopBean xopResponse = proxy.echoXopAttachment(xop);\n \n verifyXopResponse(xop, xopResponse);\n }" ]
Filters a dot at the end of the passed package name if present. @param pkgName a package name @return a filtered package name
[ "private static String removeLastDot(final String pkgName) {\n\t\treturn pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;\n\t}" ]
[ "protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException {\n Class c = this.findLoadedClass(name);\n if (c != null) return c;\n c = (Class) customClasses.get(name);\n if (c != null) return c;\n\n try {\n c = oldFindClass(name);\n } catch (ClassNotFoundException cnfe) {\n // IGNORE\n }\n if (c == null) c = super.loadClass(name, resolve);\n\n if (resolve) resolveClass(c);\n\n return c;\n }", "@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/{clientUUID}\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @PathVariable(\"profileIdentifier\") String profileIdentifier,\n @PathVariable(\"clientUUID\") String clientUUID) throws Exception {\n logger.info(\"Attempting to remove the following client: {}\", clientUUID);\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n clientService.remove(profileId, clientUUID);\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }", "public GVRAnimator animate(int animIndex, float timeInSec)\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 anim.animate(timeInSec);\n return anim;\n }", "public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}", "private int getClosingParenthesisPosition(String text, int opening)\n {\n if (text.charAt(opening) != '(')\n {\n return -1;\n }\n\n int count = 0;\n for (int i = opening; i < text.length(); i++)\n {\n char c = text.charAt(i);\n switch (c)\n {\n case '(':\n {\n ++count;\n break;\n }\n\n case ')':\n {\n --count;\n if (count == 0)\n {\n return i;\n }\n break;\n }\n }\n }\n\n return -1;\n }", "@Deprecated\n public static RemoteProxyController create(final ManagementChannelHandler channelAssociation, final PathAddress pathAddress, final ProxyOperationAddressTranslator addressTranslator) {\n final TransactionalProtocolClient client = TransactionalProtocolHandlers.createClient(channelAssociation);\n // the remote proxy\n return create(client, pathAddress, addressTranslator, ModelVersion.CURRENT);\n }", "protected String sourceLineTrimmed(ASTNode node) {\r\n return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }", "public void setRefreshing(boolean refreshing) {\n if (refreshing && mRefreshing != refreshing) {\n // scale and show\n mRefreshing = refreshing;\n int endTarget = 0;\n if (!mUsingCustomStart) {\n switch (mDirection) {\n case BOTTOM:\n endTarget = getMeasuredHeight() - (int) (mSpinnerFinalOffset);\n break;\n case TOP:\n default:\n endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));\n break;\n }\n } else {\n endTarget = (int) mSpinnerFinalOffset;\n }\n setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,\n true /* requires update */);\n mNotify = false;\n startScaleUpAnimation(mRefreshListener);\n } else {\n setRefreshing(refreshing, false /* notify */);\n }\n }", "public void setOutRGB(IntRange outRGB) {\r\n this.outRed = outRGB;\r\n this.outGreen = outRGB;\r\n this.outBlue = outRGB;\r\n\r\n CalculateMap(inRed, outRGB, mapRed);\r\n CalculateMap(inGreen, outRGB, mapGreen);\r\n CalculateMap(inBlue, outRGB, mapBlue);\r\n }" ]
This method calculates the total amount of working time in a single day, which intersects with the supplied time range. @param hours collection of working hours in a day @param startDate time range start @param endDate time range end @return length of time in milliseconds
[ "private long getTotalTime(ProjectCalendarDateRanges hours, Date startDate, Date endDate)\n {\n long total = 0;\n if (startDate.getTime() != endDate.getTime())\n {\n Date start = DateHelper.getCanonicalTime(startDate);\n Date end = DateHelper.getCanonicalTime(endDate);\n\n for (DateRange range : hours)\n {\n Date rangeStart = range.getStart();\n Date rangeEnd = range.getEnd();\n if (rangeStart != null && rangeEnd != null)\n {\n Date canoncialRangeStart = DateHelper.getCanonicalTime(rangeStart);\n Date canonicalRangeEnd = DateHelper.getCanonicalTime(rangeEnd);\n\n Date startDay = DateHelper.getDayStartDate(rangeStart);\n Date finishDay = DateHelper.getDayStartDate(rangeEnd);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n canonicalRangeEnd = DateHelper.addDays(canonicalRangeEnd, 1);\n }\n\n if (canoncialRangeStart.getTime() == canonicalRangeEnd.getTime() && rangeEnd.getTime() > rangeStart.getTime())\n {\n total += (24 * 60 * 60 * 1000);\n }\n else\n {\n total += getTime(start, end, canoncialRangeStart, canonicalRangeEnd);\n }\n }\n }\n }\n\n return (total);\n }" ]
[ "private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) {\n String fileName = file.getAbsolutePath().replace(\"\\\\\", \"/\");\n return fileName.substring(classPathRootOnDisk.length());\n }", "public static String getDateTimeStr(Date d) {\n if (d == null)\n return \"\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSSZ\");\n // 20140315 test will problem +0000\n return sdf.format(d);\n }", "private void addOp(String op, String path, String value) {\n if (this.operations == null) {\n this.operations = new JsonArray();\n }\n\n this.operations.add(new JsonObject()\n .add(\"op\", op)\n .add(\"path\", path)\n .add(\"value\", value));\n }", "public static String getModuleName(final String moduleId) {\n final int splitter = moduleId.indexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(0, splitter);\n }", "public void putAll(Map<KEY, VALUE> mapDataToPut) {\n int targetSize = maxSize - mapDataToPut.size();\n if (maxSize > 0 && values.size() > targetSize) {\n evictToTargetSize(targetSize);\n }\n Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();\n for (Entry<KEY, VALUE> entry : entries) {\n put(entry.getKey(), entry.getValue());\n }\n }", "public boolean isFunctionName( String s ) {\n if( input1.containsKey(s))\n return true;\n if( inputN.containsKey(s))\n return true;\n\n return false;\n }", "private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) {\n final Cluster batchCurrentCluster = batchPlan.getCurrentCluster();\n final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs();\n final Cluster batchFinalCluster = batchPlan.getFinalCluster();\n final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs();\n\n try {\n final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan();\n\n if(rebalanceTaskInfoList.isEmpty()) {\n RebalanceUtils.printBatchLog(batchId, logger, \"Skipping batch \"\n + batchId + \" since it is empty.\");\n // Even though there is no rebalancing work to do, cluster\n // metadata must be updated so that the server is aware of the\n // new cluster xml.\n adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster,\n batchFinalCluster,\n batchCurrentStoreDefs,\n batchFinalStoreDefs,\n rebalanceTaskInfoList,\n false,\n true,\n false,\n false,\n true);\n return;\n }\n\n RebalanceUtils.printBatchLog(batchId, logger, \"Starting batch \"\n + batchId + \".\");\n\n // Split the store definitions\n List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n true);\n List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n false);\n boolean hasReadOnlyStores = readOnlyStoreDefs != null\n && readOnlyStoreDefs.size() > 0;\n boolean hasReadWriteStores = readWriteStoreDefs != null\n && readWriteStoreDefs.size() > 0;\n\n // STEP 1 - Cluster state change\n boolean finishedReadOnlyPhase = false;\n List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readOnlyStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 2 - Move RO data\n if(hasReadOnlyStores) {\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n // STEP 3 - Cluster change state\n finishedReadOnlyPhase = true;\n filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readWriteStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 4 - Move RW data\n if(hasReadWriteStores) {\n proxyPause();\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Successfully terminated batch \"\n + batchId + \".\");\n\n } catch(Exception e) {\n RebalanceUtils.printErrorLog(batchId, logger, \"Error in batch \"\n + batchId + \" - \" + e.getMessage(), e);\n throw new VoldemortException(\"Rebalance failed on batch \" + batchId,\n e);\n }\n }", "public ParallelTaskBuilder prepareHttpDelete(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n\n cb.getHttpMeta().setHttpMethod(HttpMethod.DELETE);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n }", "public void setProxyClass(Class newProxyClass)\r\n {\r\n proxyClass = newProxyClass;\r\n if (proxyClass == null)\r\n {\r\n setProxyClassName(null);\r\n }\r\n else\r\n {\r\n proxyClassName = proxyClass.getName();\r\n }\r\n }" ]
Converts a byte array to a hexadecimal string representation @param bb the byte array to convert @return string the string representation
[ "static public String bb2hex(byte[] bb) {\n\t\tString result = \"\";\n\t\tfor (int i=0; i<bb.length; i++) {\n\t\t\tresult = result + String.format(\"%02X \", bb[i]);\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public Replication targetOauth(String consumerSecret,\r\n String consumerKey, String tokenSecret, String token) {\r\n this.replication = replication.targetOauth(consumerSecret, consumerKey,\r\n tokenSecret, token);\r\n return this;\r\n }", "public CompositeGeneratorNode appendTemplate(final CompositeGeneratorNode parent, final StringConcatenationClient templateString) {\n final TemplateNode proc = new TemplateNode(templateString, this);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(proc);\n return parent;\n }", "static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {\n\t\tfor (Map.Entry<String, List<String>> entry : headers.entrySet()) {\n\t\t\tString headerName = entry.getKey();\n\t\t\tif (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265\n\t\t\t\tString headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), \"; \");\n\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t}\n\t\t\telse if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) &&\n\t\t\t\t\t!HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) {\n\t\t\t\tfor (String headerValue : entry.getValue()) {\n\t\t\t\t\thttpRequest.addHeader(headerName, headerValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "private void loadAllRemainingLocalizations() throws CmsException, UnsupportedEncodingException, IOException {\n\n if (!m_alreadyLoadedAllLocalizations) {\n // is only necessary for property bundles\n if (m_bundleType.equals(BundleType.PROPERTY)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n CmsResource resource = m_bundleFiles.get(l);\n if (resource != null) {\n CmsFile file = m_cms.readFile(resource);\n m_bundleFiles.put(l, file);\n SortedProperties props = new SortedProperties();\n props.load(\n new InputStreamReader(\n new ByteArrayInputStream(file.getContents()),\n CmsFileUtil.getEncoding(m_cms, file)));\n m_localizations.put(l, props);\n }\n }\n }\n }\n if (m_bundleType.equals(BundleType.XML)) {\n for (Locale l : m_locales) {\n if (null == m_localizations.get(l)) {\n loadLocalizationFromXmlBundle(l);\n }\n }\n }\n m_alreadyLoadedAllLocalizations = true;\n }\n\n }", "public Gallery lookupGallery(String galleryId) throws FlickrException {\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GALLERY);\r\n parameters.put(\"url\", galleryId);\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 galleryElement = response.getPayload();\r\n Gallery gallery = new Gallery();\r\n gallery.setId(galleryElement.getAttribute(\"id\"));\r\n gallery.setUrl(galleryElement.getAttribute(\"url\"));\r\n\r\n User owner = new User();\r\n owner.setId(galleryElement.getAttribute(\"owner\"));\r\n gallery.setOwner(owner);\r\n gallery.setCreateDate(galleryElement.getAttribute(\"date_create\"));\r\n gallery.setUpdateDate(galleryElement.getAttribute(\"date_update\"));\r\n gallery.setPrimaryPhotoId(galleryElement.getAttribute(\"primary_photo_id\"));\r\n gallery.setPrimaryPhotoServer(galleryElement.getAttribute(\"primary_photo_server\"));\r\n gallery.setVideoCount(galleryElement.getAttribute(\"count_videos\"));\r\n gallery.setPhotoCount(galleryElement.getAttribute(\"count_photos\"));\r\n gallery.setPrimaryPhotoFarm(galleryElement.getAttribute(\"farm\"));\r\n gallery.setPrimaryPhotoSecret(galleryElement.getAttribute(\"secret\"));\r\n\r\n gallery.setTitle(XMLUtilities.getChildValue(galleryElement, \"title\"));\r\n gallery.setDesc(XMLUtilities.getChildValue(galleryElement, \"description\"));\r\n return gallery;\r\n }", "public static Set<String> commaDelimitedListToSet(String str) {\n Set<String> set = new TreeSet<String>();\n String[] tokens = commaDelimitedListToStringArray(str);\n Collections.addAll(set, tokens);\n return set;\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 static PropertyOrder.Builder makeOrder(String property,\n PropertyOrder.Direction direction) {\n return PropertyOrder.newBuilder()\n .setProperty(makePropertyReference(property))\n .setDirection(direction);\n }", "public static int positionOf(char value, char[] array) {\n for (int i = 0; i < array.length; i++) {\n if (value == array[i]) {\n return i;\n }\n }\n throw new OkapiException(\"Unable to find character '\" + value + \"' in character array.\");\n }" ]
Add a dependency to the graph @param dependency @param graph @param depth @param parentId
[ "private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {\n // In that case of Axway artifact we will add a module to the graph\n if (filters.getCorporateFilter().filter(dependency)) {\n final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());\n\n // if there is no module, add the artifact to the graph\n if(dbTarget == null){\n LOG.error(\"Got missing reference: \" + dependency.getTarget());\n final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());\n final String targetElementId = graph.getId(dbArtifact);\n graph.addElement(targetElementId, dbArtifact.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n return;\n }\n\n // Add the element to the graph\n addModuleToGraph(dbTarget, graph, depth + 1);\n\n //Add the dependency to the graph\n final String moduleElementId = graph.getId(dbTarget);\n graph.addDependency(parentId, moduleElementId, dependency.getScope());\n }\n // In case a third-party we will add an artifact\n else {\n final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());\n if(dbTarget == null){\n LOG.error(\"Got missing artifact: \" + dependency.getTarget());\n return;\n }\n\n if(!graph.isTreated(graph.getId(dbTarget))){\n final ModelMapper modelMapper = new ModelMapper(repoHandler);\n final Artifact target = modelMapper.getArtifact(dbTarget);\n final String targetElementId = graph.getId(target);\n graph.addElement(targetElementId, target.getVersion(), false);\n graph.addDependency(parentId, targetElementId, dependency.getScope());\n }\n }\n }" ]
[ "public File curDir() {\n File file = session().attribute(ATTR_PWD);\n if (null == file) {\n file = new File(System.getProperty(\"user.dir\"));\n session().attribute(ATTR_PWD, file);\n }\n return file;\n }", "public static base_responses add(nitro_service client, snmpmanager resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpmanager addresources[] = new snmpmanager[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new snmpmanager();\n\t\t\t\taddresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\taddresources[i].netmask = resources[i].netmask;\n\t\t\t\taddresources[i].domainresolveretry = resources[i].domainresolveretry;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }", "public static boolean checkConfiguredInModules() {\n\n Boolean result = m_moduleCheckCache.get();\n if (result == null) {\n result = Boolean.valueOf(getConfiguredTemplateMapping() != null);\n m_moduleCheckCache.set(result);\n }\n return result.booleanValue();\n }", "private String getBearerToken(HttpConnectionInterceptorContext context) {\n final AtomicReference<String> iamTokenResponse = new AtomicReference<String>();\n boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody,\n \"application/x-www-form-urlencoded\", \"application/json\",\n new StoreBearerCallable(iamTokenResponse));\n if (result) {\n return iamTokenResponse.get();\n } else {\n return null;\n }\n }", "@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\n }\n }", "private String validateDuration() {\n\n if (!isValidEndTypeForPattern()) {\n return Messages.ERR_SERIALDATE_INVALID_END_TYPE_FOR_PATTERN_0;\n }\n switch (getEndType()) {\n case DATE:\n return (getStart().getTime() < (getSeriesEndDate().getTime() + DAY_IN_MILLIS))\n ? null\n : Messages.ERR_SERIALDATE_SERIES_END_BEFORE_START_0;\n case TIMES:\n return getOccurrences() > 0 ? null : Messages.ERR_SERIALDATE_INVALID_OCCURRENCES_0;\n default:\n return null;\n }\n\n }", "private ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }", "private boolean replaceValues(Locale locale) {\n\n try {\n SortedProperties localization = getLocalization(locale);\n if (hasDescriptor()) {\n for (Object itemId : m_container.getItemIds()) {\n Item item = m_container.getItem(itemId);\n String key = item.getItemProperty(TableProperty.KEY).getValue().toString();\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n } else {\n m_container.removeAllItems();\n Set<Object> keyset = m_keyset.getKeySet();\n for (Object key : keyset) {\n Object itemId = m_container.addItem();\n Item item = m_container.getItem(itemId);\n item.getItemProperty(TableProperty.KEY).setValue(key);\n Object value = localization.get(key);\n item.getItemProperty(TableProperty.TRANSLATION).setValue(null == value ? \"\" : value);\n }\n if (m_container.getItemIds().isEmpty()) {\n m_container.addItem();\n }\n }\n return true;\n } catch (IOException | CmsException e) {\n // The problem should typically be a problem with locking or reading the file containing the translation.\n // This should be reported in the editor, if false is returned here.\n return false;\n }\n }" ]
Returns the list of nodes which match the expression xpathExpr in the Document dom. @param dom the Document to search in @param xpathExpr the xpath query @return the list of nodes which match the query @throws XPathExpressionException On error.
[ "public static NodeList evaluateXpathExpression(Document dom, String xpathExpr)\n\t\t\tthrows XPathExpressionException {\n\t\tXPathFactory factory = XPathFactory.newInstance();\n\t\tXPath xpath = factory.newXPath();\n\t\tXPathExpression expr = xpath.compile(xpathExpr);\n\t\tObject result = expr.evaluate(dom, XPathConstants.NODESET);\n\t\treturn (NodeList) result;\n\t}" ]
[ "public static server_service_binding[] get(nitro_service service, String name) throws Exception{\n\t\tserver_service_binding obj = new server_service_binding();\n\t\tobj.set_name(name);\n\t\tserver_service_binding response[] = (server_service_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "final public void addPosition(int position) {\n if (tokenPosition == null) {\n tokenPosition = new MtasPosition(position);\n } else {\n tokenPosition.add(position);\n }\n }", "public static base_response add(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile addresource = new dbdbprofile();\n\t\taddresource.name = resource.name;\n\t\taddresource.interpretquery = resource.interpretquery;\n\t\taddresource.stickiness = resource.stickiness;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\taddresource.conmultiplex = resource.conmultiplex;\n\t\treturn addresource.add_resource(client);\n\t}", "public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationForLocations(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {alert('rec:'+status);\\ndocument.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n LOG.trace(\"ElevationService direct call: \" + r.toString());\n \n getJSObject().eval(r.toString());\n \n }", "private void readNormalDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay weekDay)\n {\n int dayNumber = weekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n calendar.setWorkingDay(day, BooleanHelper.getBoolean(weekDay.isDayWorking()));\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = weekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }", "protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(message);\n return violation;\n }", "private static String buildErrorMsg(List<String> dependencies, String message) {\n final StringBuilder buffer = new StringBuilder();\n boolean isFirstElement = true;\n for (String dependency : dependencies) {\n if (!isFirstElement) {\n buffer.append(\", \");\n }\n // check if it is an instance of Artifact - add the gavc else append the object\n buffer.append(dependency);\n\n isFirstElement = false;\n }\n return String.format(message, buffer.toString());\n }", "public ProjectCalendarException getException(Date date)\n {\n ProjectCalendarException exception = null;\n\n // We're working with expanded exceptions, which includes any recurring exceptions\n // expanded into individual entries.\n populateExpandedExceptions();\n if (!m_expandedExceptions.isEmpty())\n {\n sortExceptions();\n\n int low = 0;\n int high = m_expandedExceptions.size() - 1;\n long targetDate = date.getTime();\n\n while (low <= high)\n {\n int mid = (low + high) >>> 1;\n ProjectCalendarException midVal = m_expandedExceptions.get(mid);\n int cmp = 0 - DateHelper.compare(midVal.getFromDate(), midVal.getToDate(), targetDate);\n\n if (cmp < 0)\n {\n low = mid + 1;\n }\n else\n {\n if (cmp > 0)\n {\n high = mid - 1;\n }\n else\n {\n exception = midVal;\n break;\n }\n }\n }\n }\n\n if (exception == null && getParent() != null)\n {\n // Check base calendar as well for an exception.\n exception = getParent().getException(date);\n }\n return (exception);\n }", "public static Properties getProps(Properties props, String name, Properties defaultProperties) {\n final String propString = props.getProperty(name);\n if (propString == null) return defaultProperties;\n String[] propValues = propString.split(\",\");\n if (propValues.length < 1) {\n throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propString + \"'\");\n }\n Properties properties = new Properties();\n for (int i = 0; i < propValues.length; i++) {\n String[] prop = propValues[i].split(\"=\");\n if (prop.length != 2) throw new IllegalArgumentException(\"Illegal format of specifying properties '\" + propValues[i] + \"'\");\n properties.put(prop[0], prop[1]);\n }\n return properties;\n }" ]
Get EditMode based on os and mode @return edit mode
[ "@Override\n public EditMode editMode() {\n if(readInputrc) {\n try {\n return EditModeBuilder.builder().parseInputrc(new FileInputStream(inputrc())).create();\n }\n catch(FileNotFoundException e) {\n return EditModeBuilder.builder(mode()).create();\n }\n }\n else\n return EditModeBuilder.builder(mode()).create();\n }" ]
[ "public ParallelTaskBuilder setReplaceVarMapToSingleTargetSingleVar(\n String variable, List<String> replaceList, String uniformTargetHost) {\n\n if (Strings.isNullOrEmpty(uniformTargetHost)) {\n logger.error(\"uniform target host is empty or null. skil setting.\");\n return this;\n }\n this.replacementVarMapNodeSpecific.clear();\n this.targetHosts.clear();\n int i = 0;\n for (String replace : replaceList) {\n if (replace == null){\n logger.error(\"null replacement.. skip\");\n continue;\n }\n String hostName = PcConstants.API_PREFIX + i;\n\n replacementVarMapNodeSpecific.put(\n hostName,\n new StrStrMap().addPair(variable, replace).addPair(\n PcConstants.UNIFORM_TARGET_HOST_VAR,\n uniformTargetHost));\n targetHosts.add(hostName);\n ++i;\n }\n this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;\n logger.info(\n \"Set requestReplacementType as {} for single target. Will disable the set target hosts.\"\n + \"Also Simulated \"\n + \"Now Already set targetHost list with size {}. \\nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.\",\n requestReplacementType.toString(), targetHosts.size());\n\n return this;\n }", "private List<TokenStream> collectTokenStreams(TokenStream stream) {\n \n // walk through the token stream and build a collection \n // of sub token streams that represent possible date locations\n List<Token> currentGroup = null;\n List<List<Token>> groups = new ArrayList<List<Token>>();\n Token currentToken;\n int currentTokenType;\n StringBuilder tokenString = new StringBuilder();\n while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) {\n currentTokenType = currentToken.getType();\n tokenString.append(DateParser.tokenNames[currentTokenType]).append(\" \");\n\n // we're currently NOT collecting for a possible date group\n if(currentGroup == null) {\n // skip over white space and known tokens that cannot be the start of a date\n if(currentTokenType != DateLexer.WHITE_SPACE &&\n DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) {\n\n currentGroup = new ArrayList<Token>();\n currentGroup.add(currentToken);\n }\n }\n\n // we're currently collecting\n else {\n // preserve white space\n if(currentTokenType == DateLexer.WHITE_SPACE) {\n currentGroup.add(currentToken);\n }\n\n else {\n // if this is an unknown token, we'll close out the current group\n if(currentTokenType == DateLexer.UNKNOWN) {\n addGroup(currentGroup, groups);\n currentGroup = null;\n }\n // otherwise, the token is known and we're currently collecting for\n // a group, so we'll add it to the current group\n else {\n currentGroup.add(currentToken);\n }\n }\n }\n }\n\n if(currentGroup != null) {\n addGroup(currentGroup, groups);\n }\n \n _logger.info(\"STREAM: \" + tokenString.toString());\n List<TokenStream> streams = new ArrayList<TokenStream>();\n for(List<Token> group:groups) {\n if(!group.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"GROUP: \");\n for (Token token : group) {\n builder.append(DateParser.tokenNames[token.getType()]).append(\" \");\n }\n _logger.info(builder.toString());\n\n streams.add(new CommonTokenStream(new NattyTokenSource(group)));\n }\n }\n\n return streams;\n }", "private void addCalendarDay(MpxjTreeNode parentNode, ProjectCalendar calendar, final Day day)\n {\n MpxjTreeNode dayNode = new MpxjTreeNode(day)\n {\n @Override public String toString()\n {\n return day.name();\n }\n };\n parentNode.add(dayNode);\n addHours(dayNode, calendar.getHours(day));\n }", "private static void parseRessource(ArrayList<Shape> shapes,\n HashMap<String, JSONObject> flatJSON,\n String resourceId,\n Boolean keepGlossaryLink)\n throws JSONException {\n JSONObject modelJSON = flatJSON.get(resourceId);\n Shape current = getShapeWithId(modelJSON.getString(\"resourceId\"),\n shapes);\n\n parseStencil(modelJSON,\n current);\n\n parseProperties(modelJSON,\n current,\n keepGlossaryLink);\n parseOutgoings(shapes,\n modelJSON,\n current);\n parseChildShapes(shapes,\n modelJSON,\n current);\n parseDockers(modelJSON,\n current);\n parseBounds(modelJSON,\n current);\n parseTarget(shapes,\n modelJSON,\n current);\n }", "public static HostController createHostController(String jbossHomePath, String modulePath, String[] systemPackages, String[] cmdargs) {\n if (jbossHomePath == null || jbossHomePath.isEmpty()) {\n throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath);\n }\n File jbossHomeDir = new File(jbossHomePath);\n if (!jbossHomeDir.isDirectory()) {\n throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath);\n }\n return createHostController(\n Configuration.Builder.of(jbossHomeDir)\n .setModulePath(modulePath)\n .setSystemPackages(systemPackages)\n .setCommandArguments(cmdargs)\n .build()\n );\n }", "public static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static sslfipskey[] get(nitro_service service, String fipskeyname[]) throws Exception{\n\t\tif (fipskeyname !=null && fipskeyname.length>0) {\n\t\t\tsslfipskey response[] = new sslfipskey[fipskeyname.length];\n\t\t\tsslfipskey obj[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++) {\n\t\t\t\tobj[i] = new sslfipskey();\n\t\t\t\tobj[i].set_fipskeyname(fipskeyname[i]);\n\t\t\t\tresponse[i] = (sslfipskey) 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 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 void logout() throws IOException {\n\t\tif (this.loggedIn) {\n\t\t\tMap<String, String> params = new HashMap<>();\n\t\t\tparams.put(\"action\", \"logout\");\n\t\t\tparams.put(\"format\", \"json\"); // reduce the output\n\t\t\ttry {\n\t\t\t\tsendJsonRequest(\"POST\", params);\n\t\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\t\tthrow new IOException(e.getMessage(), e); //TODO: we should throw a better exception\n\t\t\t}\n\n\t\t\tthis.loggedIn = false;\n\t\t\tthis.username = \"\";\n\t\t\tthis.password = \"\";\n\t\t}\n\t}" ]
Create all the links possible between the DeclarationBinder and all the ImportDeclaration matching the. ImportDeclarationFilter of the Linker. @param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder
[ "public void createLinks(ServiceReference<S> declarationBinderRef) {\n for (D declaration : linkerManagement.getMatchedDeclaration()) {\n if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {\n linkerManagement.link(declaration, declarationBinderRef);\n }\n }\n }" ]
[ "public static String pad(String str, int totalChars) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int slen = str.length();\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < totalChars - slen; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n }", "private void readTasks(Project project)\n {\n Project.Tasks tasks = project.getTasks();\n if (tasks != null)\n {\n int tasksWithoutIDCount = 0;\n\n for (Project.Tasks.Task task : tasks.getTask())\n {\n Task mpxjTask = readTask(task);\n if (mpxjTask.getID() == null)\n {\n ++tasksWithoutIDCount;\n }\n }\n\n for (Project.Tasks.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n\n //\n // MS Project will happily read tasks from an MSPDI file without IDs,\n // it will just generate ID values based on the task order in the file.\n // If we find that there are no ID values present, we'll do the same.\n //\n if (tasksWithoutIDCount == tasks.getTask().size())\n {\n m_projectFile.getTasks().renumberIDs();\n }\n }\n\n m_projectFile.updateStructure();\n }", "public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }", "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 }", "synchronized public void completeTask(int taskId, int partitionStoresMigrated) {\n tasksInFlight.remove(taskId);\n\n numTasksCompleted++;\n numPartitionStoresMigrated += partitionStoresMigrated;\n\n updateProgressBar();\n }", "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 }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<InternationalFixedDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<InternationalFixedDate>) super.localDateTime(temporal);\n }", "public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, \"local-host-name\");\n ModelNode response = client.execute(op);\n if (Operations.isSuccessfulOutcome(response)) {\n return DeploymentOperations.createAddress(\"host\", Operations.readResult(response).asString());\n }\n throw new OperationExecutionException(op, response);\n }", "public void commandContinuationRequest()\r\n throws ProtocolException {\r\n try {\r\n output.write('+');\r\n output.write(' ');\r\n output.write('O');\r\n output.write('K');\r\n output.write('\\r');\r\n output.write('\\n');\r\n output.flush();\r\n } catch (IOException e) {\r\n throw new ProtocolException(\"Unexpected exception in sending command continuation request.\", e);\r\n }\r\n }" ]
Returns a list of the compact representation of all of the custom fields in a workspace. @param workspace The workspace or organization to find custom field definitions in. @return Request object
[ "public CollectionRequest<CustomField> findByWorkspace(String workspace) {\n \n String path = String.format(\"/workspaces/%s/custom_fields\", workspace);\n return new CollectionRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }" ]
[ "public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }", "private void initWsClient(BundleContext context) throws Exception {\n ServiceReference serviceRef = context.getServiceReference(ConfigurationAdmin.class.getName());\n ConfigurationAdmin cfgAdmin = (ConfigurationAdmin)context.getService(serviceRef); \n Configuration config = cfgAdmin.getConfiguration(\"org.talend.esb.sam.agent\");\n\n String serviceURL = (String)config.getProperties().get(\"service.url\");\n retryNum = Integer.parseInt((String)config.getProperties().get(\"service.retry.number\"));\n retryDelay = Long.parseLong((String)config.getProperties().get(\"service.retry.delay\"));\n\n JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();\n factory.setServiceClass(org.talend.esb.sam.monitoringservice.v1.MonitoringService.class);\n factory.setAddress(serviceURL);\n monitoringService = (MonitoringService)factory.create();\n }", "protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n return broker.serviceBrokerHelper().getKeyValues(cld, obj);\r\n }", "private TrackMetadata requestMetadataInternal(final DataReference track, final CdjStatus.TrackType trackType,\n final boolean failIfPassive) {\n // First check if we are using cached data for this request.\n MetadataCache cache = getMetadataCache(SlotReference.getSlotReference(track));\n if (cache != null && trackType == CdjStatus.TrackType.REKORDBOX) {\n return cache.getTrackMetadata(null, track);\n }\n\n // Then see if any registered metadata providers can offer it for us.\n final MediaDetails sourceDetails = getMediaDetailsFor(track.getSlotReference());\n if (sourceDetails != null) {\n final TrackMetadata provided = allMetadataProviders.getTrackMetadata(sourceDetails, track);\n if (provided != null) {\n return provided;\n }\n }\n\n // At this point, unless we are allowed to actively request the data, we are done. We can always actively\n // request tracks from rekordbox.\n if (passive.get() && failIfPassive && track.slot != CdjStatus.TrackSourceSlot.COLLECTION) {\n return null;\n }\n\n // Use the dbserver protocol implementation to request the metadata.\n ConnectionManager.ClientTask<TrackMetadata> task = new ConnectionManager.ClientTask<TrackMetadata>() {\n @Override\n public TrackMetadata useClient(Client client) throws Exception {\n return queryMetadata(track, trackType, client);\n }\n };\n\n try {\n return ConnectionManager.getInstance().invokeWithClientSession(track.player, task, \"requesting metadata\");\n } catch (Exception e) {\n logger.error(\"Problem requesting metadata, returning null\", e);\n }\n return null;\n }", "public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static void touch(final File folder , final String fileName) throws IOException {\n if(!folder.exists()){\n folder.mkdirs();\n }\n\n final File touchedFile = new File(folder, fileName);\n\n // The JVM will only 'touch' the file if you instantiate a\n // FileOutputStream instance for the file in question.\n // You don't actually write any data to the file through\n // the FileOutputStream. Just instantiate it and close it.\n\n try (\n FileOutputStream doneFOS = new FileOutputStream(touchedFile);\n ) {\n // Touching the file\n }\n catch (FileNotFoundException e) {\n throw new FileNotFoundException(\"Failed to the find file.\" + e);\n }\n }", "public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public static void printDocumentation() {\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t\tSystem.out.println(\"*** Wikidata Toolkit: GenderRatioProcessor\");\n\t\tSystem.out.println(\"*** \");\n\t\tSystem.out\n\t\t\t\t.println(\"*** This program will download and process dumps from Wikidata.\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** It will compute the numbers of articles about humans across\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** Wikimedia projects, and in particular it will count the articles\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** for each sex/gender. Results will be stored in a CSV file.\");\n\t\tSystem.out.println(\"*** See source code for further details.\");\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t}", "private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)\r\n {\r\n FieldDescriptor fields[] = cld.getLockingFields();\r\n\r\n for (int i=0; i<fields.length; i++)\r\n {\r\n PersistentField field = fields[i].getPersistentField();\r\n Object lockVal = oldLockingValues[i].getValue();\r\n\r\n field.set(obj, lockVal);\r\n }\r\n }" ]
Checks if is file exist. @param filePath the file path @return true, if is file exist
[ "public static boolean isFileExist(String filePath) {\n\n File f = new File(filePath);\n\n return f.exists() && !f.isDirectory();\n }" ]
[ "private void readPredecessors(Project.Tasks.Task task)\n {\n Integer uid = task.getUID();\n if (uid != null)\n {\n Task currTask = m_projectFile.getTaskByUniqueID(uid);\n if (currTask != null)\n {\n for (Project.Tasks.Task.PredecessorLink link : task.getPredecessorLink())\n {\n readPredecessor(currTask, link);\n }\n }\n }\n }", "private void logMigration(DbMigration migration, boolean wasSuccessful) {\n BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(),\n migration.getScriptName(), migration.getMigrationScript(), new Date());\n session.execute(boundStatement);\n }", "public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) {\n if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) {\n for (int i = 0; i <= a.numCols; i++) {\n if( a.col_idx[i] != b.col_idx[i] )\n return false;\n }\n for (int i = 0; i < a.nz_length; i++) {\n if( a.nz_rows[i] != b.nz_rows[i] )\n return false;\n }\n return true;\n }\n return false;\n }", "private String getParentOutlineNumber(String outlineNumber)\n {\n String result;\n int index = outlineNumber.lastIndexOf('.');\n if (index == -1)\n {\n result = \"\";\n }\n else\n {\n result = outlineNumber.substring(0, index);\n }\n return result;\n }", "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 com.cloudant.client.api.model.ReplicationResult trigger() {\r\n ReplicationResult couchDbReplicationResult = replication.trigger();\r\n com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant\r\n .client.api.model.ReplicationResult(couchDbReplicationResult);\r\n return replicationResult;\r\n }", "public 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 }", "public List<File> getAutoAttachCacheFiles() {\n ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);\n Collections.sort(currentFiles, new Comparator<File>() {\n @Override\n public int compare(File o1, File o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n return Collections.unmodifiableList(currentFiles);\n }", "public static void applyWsdlExtensions(Bus bus) {\n\n ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry();\n\n try {\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Definition.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class);\n\n JAXBExtensionHelper.addExtensions(registry,\n javax.wsdl.Binding.class,\n org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class);\n\n } catch (JAXBException e) {\n throw new RuntimeException(\"Failed to add WSDL JAXB extensions\", e);\n }\n }" ]
Use this API to flush cacheobject resources.
[ "public static base_responses flush(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject flushresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tflushresources[i] = new cacheobject();\n\t\t\t\tflushresources[i].locator = resources[i].locator;\n\t\t\t\tflushresources[i].url = resources[i].url;\n\t\t\t\tflushresources[i].host = resources[i].host;\n\t\t\t\tflushresources[i].port = resources[i].port;\n\t\t\t\tflushresources[i].groupname = resources[i].groupname;\n\t\t\t\tflushresources[i].httpmethod = resources[i].httpmethod;\n\t\t\t\tflushresources[i].force = resources[i].force;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, flushresources,\"flush\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) {\n if (clazz == null || prototype == null) {\n throw new IllegalArgumentException(\n \"The binding RecyclerView binding can't be configured using null instances\");\n }\n prototypes.add(prototype);\n binding.put(clazz, prototype.getClass());\n return this;\n }", "public static base_response save(nitro_service client) throws Exception {\n\t\tnsconfig saveresource = new nsconfig();\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}", "private void countCoordinates(int xCoord, int yCoord,\n\t\t\tItemDocument itemDocument) {\n\n\t\tfor (String siteKey : itemDocument.getSiteLinks().keySet()) {\n\t\t\tInteger count = this.siteCounts.get(siteKey);\n\t\t\tif (count == null) {\n\t\t\t\tthis.siteCounts.put(siteKey, 1);\n\t\t\t} else {\n\t\t\t\tthis.siteCounts.put(siteKey, count + 1);\n\t\t\t}\n\t\t}\n\n\t\tfor (ValueMap vm : this.valueMaps) {\n\t\t\tvm.countCoordinates(xCoord, yCoord, itemDocument);\n\t\t}\n\t}", "private void setHeaderList(Map<String, List<String>> headers, String name, String value) {\n\n List<String> values = new ArrayList<String>();\n values.add(SET_HEADER + value);\n headers.put(name, values);\n }", "public static double computeHouseholder(double []x , int xStart , int xEnd , double max , DScalar gamma ) {\n double tau = 0;\n for (int i = xStart; i < xEnd ; i++) {\n double val = x[i] /= max;\n tau += val*val;\n }\n tau = Math.sqrt(tau);\n if( x[xStart] < 0 ) {\n tau = -tau;\n }\n double u_0 = x[xStart] + tau;\n gamma.value = u_0/tau;\n x[xStart] = 1;\n for (int i = xStart+1; i < xEnd ; i++) {\n x[i] /= u_0;\n }\n\n return -tau*max;\n }", "public static 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}", "private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException {\n if (properties != null) {\n JSONObject propertiesObject = new JSONObject();\n\n for (String key : properties.keySet()) {\n String propertyValue = properties.get(key);\n\n /*\n * if(propertyValue.matches(\"true|false\")) {\n * \n * propertiesObject.put(key, propertyValue.equals(\"true\"));\n * \n * } else if(propertyValue.matches(\"[0-9]+\")) {\n * \n * Integer value = Integer.parseInt(propertyValue);\n * propertiesObject.put(key, value);\n * \n * } else\n */\n if (propertyValue.startsWith(\"{\") && propertyValue.endsWith(\"}\")) {\n propertiesObject.put(key,\n new JSONObject(propertyValue));\n } else {\n propertiesObject.put(key,\n propertyValue.toString());\n }\n }\n\n return propertiesObject;\n }\n\n return new JSONObject();\n }", "public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) {\n if(!groupClass.isEnum()) {\n throw new IllegalArgumentException(\"The group class \"+groupClass+\" is not an enum\");\n }\n groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>());\n return this;\n }", "public static final BigInteger printDay(Day day)\n {\n return (day == null ? null : BigInteger.valueOf(day.getValue() - 1));\n }" ]
Get all the handlers at a specific address. @param address the address @param inherited true to include the inherited operations @return the handlers
[ "@Override\n public final Map<String, OperationEntry> getOperationDescriptions(final PathAddress address, boolean inherited) {\n\n if (parent != null) {\n RootInvocation ri = getRootInvocation();\n return ri.root.getOperationDescriptions(ri.pathAddress.append(address), inherited);\n }\n // else we are the root\n Map<String, OperationEntry> providers = new TreeMap<String, OperationEntry>();\n getOperationDescriptions(address.iterator(), providers, inherited);\n return providers;\n }" ]
[ "public void addDependencyTaskGroup(TaskGroup dependencyTaskGroup) {\n if (dependencyTaskGroup.proxyTaskGroupWrapper.isActive()) {\n dependencyTaskGroup.proxyTaskGroupWrapper.addDependentTaskGroup(this);\n } else {\n DAGraph<TaskItem, TaskGroupEntry<TaskItem>> dependencyGraph = dependencyTaskGroup;\n super.addDependencyGraph(dependencyGraph);\n }\n }", "protected String getJavaExecutablePath() {\n String executableName = isWindows() ? \"bin/java.exe\" : \"bin/java\";\n return PROPERTIES.getJavaHome().resolve(executableName).toAbsolutePath().toString();\n }", "@Override\n public boolean isTempoMaster() {\n DeviceUpdate master = VirtualCdj.getInstance().getTempoMaster();\n return (master != null) && master.getAddress().equals(address);\n }", "public static Object executeXPath(Node document, String xpathExpression, Map<String, String> namespaceMapping, QName result)\n throws XPathException, MarshallingException\n {\n NamespaceMapContext mapContext = new NamespaceMapContext(namespaceMapping);\n try\n {\n XPathFactory xPathfactory = XPathFactory.newInstance();\n XPath xpath = xPathfactory.newXPath();\n xpath.setNamespaceContext(mapContext);\n XPathExpression expr = xpath.compile(xpathExpression);\n\n return executeXPath(document, expr, result);\n }\n catch (XPathExpressionException e)\n {\n throw new XPathException(\"Xpath(\" + xpathExpression + \") cannot be compiled\", e);\n }\n catch (Exception e)\n {\n throw new MarshallingException(\"Exception unmarshalling XML.\", e);\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 void setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(charTranslator!=null){\r\n\t\t\tthis.charTranslator = charTranslator;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}", "public static base_response add(nitro_service client, ipset resource) throws Exception {\n\t\tipset addresource = new ipset();\n\t\taddresource.name = resource.name;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "@SuppressWarnings(\"unchecked\") public final List<MapRow> getRows(String name)\n {\n return (List<MapRow>) getObject(name);\n }", "private void readLSD() {\n // Logical screen size.\n header.width = readShort();\n header.height = readShort();\n // Packed fields\n int packed = read();\n // 1 : global color table flag.\n header.gctFlag = (packed & 0x80) != 0;\n // 2-4 : color resolution.\n // 5 : gct sort flag.\n // 6-8 : gct size.\n header.gctSize = 2 << (packed & 7);\n // Background color index.\n header.bgIndex = read();\n // Pixel aspect ratio\n header.pixelAspect = read();\n }" ]
Processes a stencilset template file @throws IOException
[ "public void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }" ]
[ "public void mergeSubtree(final OperationTransformerRegistry targetRegistry, final Map<PathAddress, ModelVersion> subTree) {\n for(Map.Entry<PathAddress, ModelVersion> entry: subTree.entrySet()) {\n mergeSubtree(targetRegistry, entry.getKey(), entry.getValue());\n }\n }", "private ProjectFile handleDosExeFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".tmp\");\n InputStream is = null;\n\n try\n {\n is = new FileInputStream(file);\n if (is.available() > 1350)\n {\n StreamHelper.skip(is, 1024);\n\n // Bytes at offset 1024\n byte[] data = new byte[2];\n is.read(data);\n\n if (matchesFingerprint(data, WINDOWS_NE_EXE_FINGERPRINT))\n {\n StreamHelper.skip(is, 286);\n\n // Bytes at offset 1312\n data = new byte[34];\n is.read(data);\n if (matchesFingerprint(data, PRX_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new P3PRXFileReader(), file);\n }\n }\n\n if (matchesFingerprint(data, STX_FINGERPRINT))\n {\n StreamHelper.skip(is, 31742);\n // Bytes at offset 32768\n data = new byte[4];\n is.read(data);\n if (matchesFingerprint(data, PRX3_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new SureTrakSTXFileReader(), file);\n }\n }\n }\n return null;\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n FileHelper.deleteQuietly(file);\n }\n }", "public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }", "private void writeInterfaceCriteria(final XMLExtendedStreamWriter writer, final ModelNode subModel, final boolean nested) throws XMLStreamException {\n for (final Property property : subModel.asPropertyList()) {\n if (property.getValue().isDefined()) {\n writeInterfaceCriteria(writer, property, nested);\n }\n }\n }", "public AccrueType getAccrueType(int field)\n {\n AccrueType result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = AccrueTypeUtility.getInstance(m_fields[field], m_locale);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static authenticationvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationradiuspolicy_binding obj = new authenticationvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationradiuspolicy_binding response[] = (authenticationvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static synchronized List<Class< ? >> locateAll(final String serviceName) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n List<Class< ? >> classes = new ArrayList<Class< ? >>();\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n for ( Callable<Class< ? >> c : l ) {\n try {\n classes.add( c.call() );\n } catch ( Exception e ) {\n }\n }\n }\n }\n return classes;\n }", "public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public ModelNode getDeploymentSubsystemModel(final String subsystemName) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);\n }" ]
Retrieves child nodes from a directory entry. @param parent parent directory entry @return list of child nodes
[ "private List<Entry> getChildNodes(DirectoryEntry parent)\n {\n List<Entry> result = new ArrayList<Entry>();\n Iterator<Entry> entries = parent.getEntries();\n while (entries.hasNext())\n {\n result.add(entries.next());\n }\n return result;\n }" ]
[ "public int numOccurrences(int year, int month, int day) {\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime date = parser.parseDateTime(year + \"-\" + month + \"-\" + \"01\");\n Calendar cal = Calendar.getInstance();\n cal.setTime(date.toDate());\n GregorianChronology calendar = GregorianChronology.getInstance();\n DateTimeField field = calendar.dayOfMonth();\n\n int days = 0;\n int count = 0;\n int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));\n while (days < num) {\n if (cal.get(Calendar.DAY_OF_WEEK) == day) {\n count++;\n }\n date = date.plusDays(1);\n cal.setTime(date.toDate());\n\n days++;\n }\n return count;\n }", "@Override\n public String getName() {\n CommonProfile profile = this.getProfile();\n if(null == principalNameAttribute) {\n return profile.getId();\n }\n Object attrValue = profile.getAttribute(principalNameAttribute);\n return (null == attrValue) ? null : String.valueOf(attrValue);\n }", "public static ModelNode getParentAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final ModelNode result = new ModelNode();\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n for (int i = 0; i < addressParts.size() - 1; ++i) {\n final Property property = addressParts.get(i);\n result.add(property.getName(), property.getValue());\n }\n return result;\n }", "private void stripCommas(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n\n while( t != null ) {\n TokenList.Token next = t.next;\n if( t.getSymbol() == Symbol.COMMA ) {\n tokens.remove(t);\n }\n t = next;\n }\n }", "private InputValue getInputValue(FormInput input) {\n\n\t\t/* Get the DOM element from Selenium. */\n\t\tWebElement inputElement = browser.getWebElement(input.getIdentification());\n\n\t\tswitch (input.getType()) {\n\t\t\tcase TEXT:\n\t\t\tcase PASSWORD:\n\t\t\tcase HIDDEN:\n\t\t\tcase SELECT:\n\t\t\tcase TEXTAREA:\n\t\t\t\treturn new InputValue(inputElement.getAttribute(\"value\"));\n\t\t\tcase RADIO:\n\t\t\tcase CHECKBOX:\n\t\t\tdefault:\n\t\t\t\tString value = inputElement.getAttribute(\"value\");\n\t\t\t\tBoolean checked = inputElement.isSelected();\n\t\t\t\treturn new InputValue(value, checked);\n\t\t}\n\n\t}", "@Override public void close() throws IOException\n {\n long skippedLast = 0;\n if (m_remaining > 0)\n {\n skippedLast = skip(m_remaining);\n while (m_remaining > 0 && skippedLast > 0)\n {\n skippedLast = skip(m_remaining);\n }\n }\n }", "public String toStringByValue() {\r\n\tIntArrayList theKeys = new IntArrayList();\r\n\tkeysSortedByValue(theKeys);\r\n\r\n\tStringBuffer buf = new StringBuffer();\r\n\tbuf.append(\"[\");\r\n\tint maxIndex = theKeys.size() - 1;\r\n\tfor (int i = 0; i <= maxIndex; i++) {\r\n\t\tint key = theKeys.get(i);\r\n\t buf.append(String.valueOf(key));\r\n\t\tbuf.append(\"->\");\r\n\t buf.append(String.valueOf(get(key)));\r\n\t\tif (i < maxIndex) buf.append(\", \");\r\n\t}\r\n\tbuf.append(\"]\");\r\n\treturn buf.toString();\r\n}", "private List<Bucket> lookup(Record record) {\n List<Bucket> buckets = new ArrayList();\n for (Property p : config.getLookupProperties()) {\n String propname = p.getName();\n Collection<String> values = record.getValues(propname);\n if (values == null)\n continue;\n\n for (String value : values) {\n String[] tokens = StringUtils.split(value);\n for (int ix = 0; ix < tokens.length; ix++) {\n Bucket b = store.lookupToken(propname, tokens[ix]);\n if (b == null || b.records == null)\n continue;\n long[] ids = b.records;\n if (DEBUG)\n System.out.println(propname + \", \" + tokens[ix] + \": \" + b.nextfree + \" (\" + b.getScore() + \")\");\n buckets.add(b);\n }\n }\n }\n\n return buckets;\n }", "public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = true;\n if (m_criteria != null)\n {\n result = m_criteria.evaluate(container, promptValues);\n\n //\n // If this row has failed, but it is a summary row, and we are\n // including related summary rows, then we need to recursively test\n // its children\n //\n if (!result && m_showRelatedSummaryRows && container instanceof Task)\n {\n for (Task task : ((Task) container).getChildTasks())\n {\n if (evaluate(task, promptValues))\n {\n result = true;\n break;\n }\n }\n }\n }\n\n return (result);\n }" ]
Print channels to the left of log messages @param width The width (in characters) to print the channels @return this
[ "public RedwoodConfiguration printChannels(final int width){\r\n tasks.add(new Runnable() { public void run() { Redwood.Util.printChannels(width);} });\r\n return this;\r\n }" ]
[ "public Replication targetOauth(String consumerSecret,\r\n String consumerKey, String tokenSecret, String token) {\r\n this.replication = replication.targetOauth(consumerSecret, consumerKey,\r\n tokenSecret, token);\r\n return this;\r\n }", "public final void notifyContentItemMoved(int fromPosition, int toPosition) {\n if (fromPosition < 0 || toPosition < 0 || fromPosition >= contentItemCount || toPosition >= contentItemCount) {\n throw new IndexOutOfBoundsException(\"The given fromPosition \" + fromPosition + \" or toPosition \"\n + toPosition + \" is not within the position bounds for content items [0 - \" + (contentItemCount - 1) + \"].\");\n }\n notifyItemMoved(fromPosition + headerItemCount, toPosition + headerItemCount);\n }", "public static boolean toBoolean(String value, boolean defaultValue)\r\n {\r\n return \"true\".equals(value) ? true : (\"false\".equals(value) ? false : defaultValue);\r\n }", "public Client findClient(String clientUUID, Integer profileId) throws Exception {\n Client client = null;\n /* ERROR CODE: 500 WHEN TRYING TO DELETE A SERVER GROUP.\n THIS APPEARS TO BE BECAUSE CLIENT UUID IS NULL.\n */\n /* CODE ADDED TO PREVENT NULL POINTERS. */\n if (clientUUID == null) {\n clientUUID = \"\";\n }\n\n // first see if the clientUUID is actually a uuid.. it might be a friendlyName and need conversion\n /* A UUID IS A UNIVERSALLY UNIQUE IDENTIFIER. */\n if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) != 0 &&\n !clientUUID.matches(\"[\\\\w]{8}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{12}\")) {\n Client tmpClient = this.findClientFromFriendlyName(profileId, clientUUID);\n\n // if we can't find a client then fall back to the default ID\n if (tmpClient == null) {\n clientUUID = Constants.PROFILE_CLIENT_DEFAULT_ID;\n } else {\n return tmpClient;\n }\n }\n\n PreparedStatement statement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = ?\";\n\n if (profileId != null) {\n queryString += \" AND \" + Constants.GENERIC_PROFILE_ID + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n if (profileId != null) {\n statement.setInt(2, profileId);\n }\n\n results = statement.executeQuery();\n if (results.next()) {\n client = this.getClientFromResultSet(results);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return client;\n }", "protected static void checkChannels(final Iterable<String> channels) {\n if (channels == null) {\n throw new IllegalArgumentException(\"channels must not be null\");\n }\n for (final String channel : channels) {\n if (channel == null || \"\".equals(channel)) {\n throw new IllegalArgumentException(\"channels' members must not be null: \" + channels);\n }\n }\n }", "public static TagModel getSingleParent(TagModel tag)\n {\n final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();\n if (!parents.hasNext())\n throw new WindupException(\"Tag is not designated by any tags: \" + tag);\n\n final TagModel maybeOnlyParent = parents.next();\n\n if (parents.hasNext()) {\n StringBuilder sb = new StringBuilder();\n tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(\", \"));\n throw new WindupException(String.format(\"Tag %s is designated by multiple tags: %s\", tag, sb.toString()));\n }\n\n return maybeOnlyParent;\n }", "public long number(ImapRequestLineReader request) throws ProtocolException {\n String digits = consumeWord(request, new DigitCharValidator());\n return Long.parseLong(digits);\n }", "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 }", "protected void copyFile(File outputDirectory,\n File sourceFile,\n String targetFileName) throws IOException\n {\n InputStream fileStream = new FileInputStream(sourceFile);\n try\n {\n copyStream(outputDirectory, fileStream, targetFileName);\n }\n finally\n {\n fileStream.close();\n }\n }" ]
Adds is Null criteria, customer_id is Null The attribute will NOT be translated into column name @param column The column name to be used without translation
[ "public void addColumnIsNull(String column)\r\n {\r\n\t\t// PAW\r\n\t\t//SelectionCriteria c = ValueCriteria.buildNullCriteria(column, getAlias());\r\n\t\tSelectionCriteria c = ValueCriteria.buildNullCriteria(column, getUserAlias(column));\r\n c.setTranslateAttribute(false);\r\n addSelectionCriteria(c);\r\n }" ]
[ "@Override\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n final ServletRequest r1 = request;\n chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {\n @SuppressWarnings(\"unchecked\")\n public void setHeader(String name, String value) {\n ArrayList<String> headersToRemove = new ArrayList<String>();\n \n if (r1.getAttribute(\"com.groupon.odo.removeHeaders\") != null)\n headersToRemove = (ArrayList<String>) r1.getAttribute(\"com.groupon.odo.removeHeaders\");\n\n boolean removeHeader = false;\n // need to loop through removeHeaders to make things case insensitive\n for (String headerToRemove : headersToRemove) {\n if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {\n removeHeader = true;\n break;\n }\n }\n\n if (! removeHeader) {\n super.setHeader(name, value);\n }\n }\n });\n }", "private void readRecord(byte[] buffer, Table table)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, true, 16, \"\"));\n int deletedFlag = getShort(buffer, 0);\n if (deletedFlag != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(0, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n table.addRow(m_definition.getPrimaryKeyColumnName(), row);\n }\n }", "public ItemRequest<Project> removeCustomFieldSetting(String project) {\n \n String path = String.format(\"/projects/%s/removeCustomFieldSetting\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"POST\");\n }", "public static void resetNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).reset();\n\t}", "public DynamicReportBuilder setProperty(String name, String value) {\n this.report.setProperty(name, value);\n return this;\n }", "@RequestMapping(value = \"api/edit/server\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerRedirect addRedirectToProfile(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier,\n @RequestParam(value = \"srcUrl\", required = true) String srcUrl,\n @RequestParam(value = \"destUrl\", required = true) String destUrl,\n @RequestParam(value = \"clientUUID\", required = true) String clientUUID,\n @RequestParam(value = \"hostHeader\", required = false) String hostHeader) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId();\n\n int redirectId = ServerRedirectService.getInstance().addServerRedirectToProfile(\"\", srcUrl, destUrl, hostHeader,\n profileId, clientId);\n return ServerRedirectService.getInstance().getRedirect(redirectId);\n }", "public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){\r\n\t\tStringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType,\r\n\t\t\t\tresultSetConcurrency);\r\n\r\n\t\ttmp.append(\", H:\");\r\n\t\ttmp.append(resultSetHoldability);\r\n\r\n\t\treturn tmp.toString();\r\n\t}", "private static File getUserDirectory(final String prefix, final String suffix, final File parent) {\n final String dirname = formatDirName(prefix, suffix);\n return new File(parent, dirname);\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 }" ]
Use this API to fetch all the sslaction resources that are configured on netscaler.
[ "public static sslaction[] get(nitro_service service) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tsslaction[] response = (sslaction[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "@SuppressWarnings(\"deprecation\")\n\tprivate static WriteConcern mergeWriteConcern(WriteConcern original, WriteConcern writeConcern) {\n\t\tif ( original == null ) {\n\t\t\treturn writeConcern;\n\t\t}\n\t\telse if ( writeConcern == null ) {\n\t\t\treturn original;\n\t\t}\n\t\telse if ( original.equals( writeConcern ) ) {\n\t\t\treturn original;\n\t\t}\n\n\t\tObject wObject;\n\t\tint wTimeoutMS;\n\t\tboolean fsync;\n\t\tBoolean journal;\n\n\t\tif ( original.getWObject() instanceof String ) {\n\t\t\twObject = original.getWString();\n\t\t}\n\t\telse if ( writeConcern.getWObject() instanceof String ) {\n\t\t\twObject = writeConcern.getWString();\n\t\t}\n\t\telse {\n\t\t\twObject = Math.max( original.getW(), writeConcern.getW() );\n\t\t}\n\n\t\twTimeoutMS = Math.min( original.getWtimeout(), writeConcern.getWtimeout() );\n\n\t\tfsync = original.getFsync() || writeConcern.getFsync();\n\n\t\tif ( original.getJournal() == null ) {\n\t\t\tjournal = writeConcern.getJournal();\n\t\t}\n\t\telse if ( writeConcern.getJournal() == null ) {\n\t\t\tjournal = original.getJournal();\n\t\t}\n\t\telse {\n\t\t\tjournal = original.getJournal() || writeConcern.getJournal();\n\t\t}\n\n\t\tif ( wObject instanceof String ) {\n\t\t\treturn new WriteConcern( (String) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t\telse {\n\t\t\treturn new WriteConcern( (int) wObject, wTimeoutMS, fsync, journal );\n\t\t}\n\t}", "public static Map<String, String> parseProperties(String s) {\n\t\tMap<String, String> properties = new HashMap<String, String>();\n\t\tif (!StringUtils.isEmpty(s)) {\n\t\t\tMatcher matcher = PROPERTIES_PATTERN.matcher(s);\n\t\t\tint start = 0;\n\t\t\twhile (matcher.find()) {\n\t\t\t\taddKeyValuePairAsProperty(s.substring(start, matcher.start()), properties);\n\t\t\t\tstart = matcher.start() + 1;\n\t\t\t}\n\t\t\taddKeyValuePairAsProperty(s.substring(start), properties);\n\t\t}\n\t\treturn properties;\n\t}", "public Search groupField(String fieldName, boolean isNumber) {\r\n assertNotEmpty(fieldName, \"fieldName\");\r\n if (isNumber) {\r\n databaseHelper.query(\"group_field\", fieldName + \"<number>\");\r\n } else {\r\n databaseHelper.query(\"group_field\", fieldName);\r\n }\r\n return this;\r\n }", "static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException {\n final LayersConfig layersConfig = LayersConfig.getLayersConfig(root);\n // Process layers\n final File layersDir = new File(root, layersConfig.getLayersPath());\n if (!layersDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath());\n }\n // else this isn't a root that has layers and add-ons\n } else {\n // check for a valid layer configuration\n for (final String layer : layersConfig.getLayers()) {\n File layerDir = new File(layersDir, layer);\n if (!layerDir.exists()) {\n if (layersConfig.isConfigured()) {\n // Bad config from user\n throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath());\n }\n // else this isn't a standard layers and add-ons structure\n return;\n }\n layers.addLayer(layer, layerDir, setter);\n }\n }\n // Finally process the add-ons\n final File addOnsDir = new File(root, layersConfig.getAddOnsPath());\n final File[] addOnsList = addOnsDir.listFiles();\n if (addOnsList != null) {\n for (final File addOn : addOnsList) {\n layers.addAddOn(addOn.getName(), addOn, setter);\n }\n }\n }", "protected String getPayload(Message message) {\n try {\n String encoding = (String) message.get(Message.ENCODING);\n if (encoding == null) {\n encoding = \"UTF-8\";\n }\n CachedOutputStream cos = message.getContent(CachedOutputStream.class);\n if (cos == null) {\n LOG.warning(\"Could not find CachedOutputStream in message.\"\n + \" Continuing without message content\");\n return \"\";\n }\n return new String(cos.getBytes(), encoding);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }", "public static String getByteArrayDataAsString(String contentEncoding, byte[] bytes) {\n ByteArrayOutputStream byteout = null;\n if (contentEncoding != null &&\n contentEncoding.equals(\"gzip\")) {\n // GZIP\n ByteArrayInputStream bytein = null;\n GZIPInputStream zis = null;\n try {\n bytein = new ByteArrayInputStream(bytes);\n zis = new GZIPInputStream(bytein);\n byteout = new ByteArrayOutputStream();\n\n int res = 0;\n byte buf[] = new byte[1024];\n while (res >= 0) {\n res = zis.read(buf, 0, buf.length);\n if (res > 0) {\n byteout.write(buf, 0, res);\n }\n }\n\n zis.close();\n bytein.close();\n byteout.close();\n return byteout.toString();\n } catch (Exception e) {\n // No action to take\n }\n } else if (contentEncoding != null &&\n contentEncoding.equals(\"deflate\")) {\n try {\n // DEFLATE\n byte[] buffer = new byte[1024];\n Inflater decompresser = new Inflater();\n byteout = new ByteArrayOutputStream();\n decompresser.setInput(bytes);\n while (!decompresser.finished()) {\n int count = decompresser.inflate(buffer);\n byteout.write(buffer, 0, count);\n }\n byteout.close();\n decompresser.end();\n\n return byteout.toString();\n } catch (Exception e) {\n // No action to take\n }\n }\n\n return new String(bytes);\n }", "protected void process(String text, Map params, Writer writer){\n\n try{\n Template t = new Template(\"temp\", new StringReader(text), FreeMarkerTL.getEnvironment().getConfiguration());\n t.process(params, writer);\n }catch(Exception e){ \n throw new ViewException(e);\n }\n }", "private ProjectCalendar getTaskCalendar(Project.Tasks.Task task)\n {\n ProjectCalendar calendar = null;\n\n BigInteger calendarID = task.getCalendarUID();\n if (calendarID != null)\n {\n calendar = m_projectFile.getCalendarByUniqueID(Integer.valueOf(calendarID.intValue()));\n }\n\n return (calendar);\n }", "public byte[] encrypt(byte[] plainData) {\n checkArgument(plainData.length >= OVERHEAD_SIZE,\n \"Invalid plainData, %s bytes\", plainData.length);\n\n // workBytes := initVector || payload || zeros:4\n byte[] workBytes = plainData.clone();\n ByteBuffer workBuffer = ByteBuffer.wrap(workBytes);\n boolean success = false;\n\n try {\n // workBytes := initVector || payload || I(signature)\n int signature = hmacSignature(workBytes);\n workBuffer.putInt(workBytes.length - SIGNATURE_SIZE, signature);\n // workBytes := initVector || E(payload) || I(signature)\n xorPayloadToHmacPad(workBytes);\n\n if (logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted\", plainData, workBytes));\n }\n\n success = true;\n return workBytes;\n } finally {\n if (!success && logger.isDebugEnabled()) {\n logger.debug(dump(\"Encrypted (failed)\", plainData, workBytes));\n }\n }\n }" ]
Mapping originator. @param originator the originator @return the originator type
[ "private static OriginatorType mapOriginator(Originator originator) {\n if (originator == null) {\n return null;\n }\n OriginatorType origType = new OriginatorType();\n origType.setProcessId(originator.getProcessId());\n origType.setIp(originator.getIp());\n origType.setHostname(originator.getHostname());\n origType.setCustomId(originator.getCustomId());\n origType.setPrincipal(originator.getPrincipal());\n return origType;\n }" ]
[ "protected boolean checkActionPackages(String classPackageName) {\n\t\tif (actionPackages != null) {\n\t\t\tfor (String packageName : actionPackages) {\n\t\t\t\tString strictPackageName = packageName + \".\";\n\t\t\t\tif (classPackageName.equals(packageName) || classPackageName.startsWith(strictPackageName))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public void removeAllChildren() {\n for (final GVRSceneObject so : headTransformObject.getChildren()) {\n final boolean notCamera = (so != leftCameraObject && so != rightCameraObject && so != centerCameraObject);\n if (notCamera) {\n headTransformObject.removeChildObject(so);\n }\n }\n }", "public static String[] allUpperCase(String... strings){\n\t\tString[] tmp = new String[strings.length];\n\t\tfor(int idx=0;idx<strings.length;idx++){\n\t\t\tif(strings[idx] != null){\n\t\t\t\ttmp[idx] = strings[idx].toUpperCase();\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}", "public FileModel getChildFile(ArchiveModel archiveModel, String filePath)\n {\n filePath = FilenameUtils.separatorsToUnix(filePath);\n StringTokenizer stk = new StringTokenizer(filePath, \"/\");\n\n FileModel currentFileModel = archiveModel;\n while (stk.hasMoreTokens() && currentFileModel != null)\n {\n String pathElement = stk.nextToken();\n\n currentFileModel = findFileModel(currentFileModel, pathElement);\n }\n return currentFileModel;\n }", "public static boolean readBooleanAttributeElement(final XMLExtendedStreamReader reader, final String attributeName)\n throws XMLStreamException {\n requireSingleAttribute(reader, attributeName);\n final boolean value = Boolean.parseBoolean(reader.getAttributeValue(0));\n requireNoContent(reader);\n return value;\n }", "public static ModelNode getAccessControl(ModelControllerClient client, OperationRequestAddress address, boolean operations) {\n return getAccessControl(client, null, address, operations);\n }", "static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\n }", "public static boolean containsAtLeastOneNonBlank(List<String> list){\n\t\tfor(String str : list){\n\t\t\tif(StringUtils.isNotBlank(str)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public Swagger read(Set<Class<?>> classes) {\n Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {\n if (class1.equals(class2)) {\n return 0;\n } else if (class1.isAssignableFrom(class2)) {\n return -1;\n } else if (class2.isAssignableFrom(class1)) {\n return 1;\n }\n return class1.getName().compareTo(class2.getName());\n });\n sortedClasses.addAll(classes);\n\n Map<Class<?>, ReaderListener> listeners = new HashMap<Class<?>, ReaderListener>();\n\n for (Class<?> cls : sortedClasses) {\n if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {\n try {\n listeners.put(cls, (ReaderListener) cls.newInstance());\n } catch (Exception e) {\n LOGGER.error(\"Failed to create ReaderListener\", e);\n }\n }\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.beforeScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking beforeScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n // process SwaggerDefinitions first - so we get tags in desired order\n for (Class<?> cls : sortedClasses) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n }\n\n for (Class<?> cls : sortedClasses) {\n read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }\n\n// for (ReaderListener listener : listeners.values()) {\n// try {\n// listener.afterScan(this, swagger);\n// } catch (Exception e) {\n// LOGGER.error(\"Unexpected error invoking afterScan listener [\" + listener.getClass().getName() + \"]\", e);\n// }\n// }\n\n return swagger;\n }" ]
Adds tags to the If-Match header. @param tag the tag to add, may be null. This means the same as adding {@link Tag#ALL} @throws IllegalArgumentException if ALL is supplied more than once, or you add a null tag more than once. @return a new Conditionals object with the If-Match tag added.
[ "public Conditionals addIfMatch(Tag tag) {\n Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));\n Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));\n List<Tag> match = new ArrayList<>(this.match);\n\n if (tag == null) {\n tag = Tag.ALL;\n }\n if (Tag.ALL.equals(tag)) {\n match.clear();\n }\n if (!match.contains(Tag.ALL)) {\n if (!match.contains(tag)) {\n match.add(tag);\n }\n }\n else {\n throw new IllegalArgumentException(\"Tag ALL already in the list\");\n }\n return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);\n }" ]
[ "public void selectTab() {\n for (Widget child : getChildren()) {\n if (child instanceof HasHref) {\n String href = ((HasHref) child).getHref();\n if (parent != null && !href.isEmpty()) {\n parent.selectTab(href.replaceAll(\"[^a-zA-Z\\\\d\\\\s:]\", \"\"));\n parent.reload();\n break;\n }\n }\n }\n }", "public List<? super OpenShiftResource> processTemplateResources() {\n List<? extends OpenShiftResource> resources;\n final List<? super OpenShiftResource> processedResources = new ArrayList<>();\n templates = OpenShiftResourceFactory.getTemplates(getType());\n boolean sync_instantiation = OpenShiftResourceFactory.syncInstantiation(getType());\n\n /* Instantiate templates */\n for (Template template : templates) {\n resources = processTemplate(template);\n if (resources != null) {\n if (sync_instantiation) {\n /* synchronous template instantiation */\n processedResources.addAll(resources);\n } else {\n /* asynchronous template instantiation */\n try {\n delay(openShiftAdapter, resources);\n } catch (Throwable t) {\n throw new IllegalArgumentException(asynchronousDelayErrorMessage(), t);\n }\n }\n }\n }\n\n return processedResources;\n }", "BeatGrid getBeatGrid(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n Message response = client.simpleRequest(Message.KnownType.BEAT_GRID_REQ, null,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot), new NumberField(rekordboxId));\n if (response.knownType == Message.KnownType.BEAT_GRID) {\n return new BeatGrid(new DataReference(slot, rekordboxId), response);\n }\n logger.error(\"Unexpected response type when requesting beat grid: {}\", response);\n return null;\n }", "private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)\n {\n for (Filter field : filters)\n {\n final Filter f = field;\n MpxjTreeNode childNode = new MpxjTreeNode(field)\n {\n @Override public String toString()\n {\n return f.getName();\n }\n };\n parentNode.add(childNode);\n }\n }", "private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList)\n {\n if (isWorkingDay(mpxjCalendar, day))\n {\n ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day);\n if (mpxjHours != null)\n {\n OverriddenDayType odt = m_factory.createOverriddenDayType();\n typeList.add(odt);\n odt.setId(getIntegerString(uniqueID.next()));\n List<Interval> intervalList = odt.getInterval();\n for (DateRange mpxjRange : mpxjHours)\n {\n Date rangeStart = mpxjRange.getStart();\n Date rangeEnd = mpxjRange.getEnd();\n\n if (rangeStart != null && rangeEnd != null)\n {\n Interval interval = m_factory.createInterval();\n intervalList.add(interval);\n interval.setStart(getTimeString(rangeStart));\n interval.setEnd(getTimeString(rangeEnd));\n }\n }\n }\n }\n }", "public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }", "public static vpnsessionaction get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionaction obj = new vpnsessionaction();\n\t\tobj.set_name(name);\n\t\tvpnsessionaction response = (vpnsessionaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static <X, T> ProducerMethod<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedMethod<T, ? super X> method, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {\n return new ProducerMethod<X, T>(createId(attributes, method, declaringBean), attributes, method, declaringBean, disposalMethod, beanManager, services);\n }", "public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) {\n final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address);\n op.get(RECURSIVE).set(recursive);\n return op;\n }" ]
Append a Handler to every parent of the given class @param parent The class of the parents to add the child to @param child The Handler to add.
[ "protected static void appendHandler(Class<? extends LogRecordHandler> parent, LogRecordHandler child){\r\n List<LogRecordHandler> toAdd = new LinkedList<LogRecordHandler>();\r\n //--Find Parents\r\n for(LogRecordHandler term : handlers){\r\n if(parent.isAssignableFrom(term.getClass())){\r\n toAdd.add(term);\r\n }\r\n }\r\n //--Add Handler\r\n for(LogRecordHandler p : toAdd){\r\n appendHandler(p, child);\r\n }\r\n }" ]
[ "public String getHeaderField(String fieldName) {\n // headers map is null for all regular response calls except when made as a batch request\n if (this.headers == null) {\n if (this.connection != null) {\n return this.connection.getHeaderField(fieldName);\n } else {\n return null;\n }\n } else {\n return this.headers.get(fieldName);\n }\n }", "protected InternalHttpResponse sendInternalRequest(HttpRequest request) {\n InternalHttpResponder responder = new InternalHttpResponder();\n httpResourceHandler.handle(request, responder);\n return responder.getResponse();\n }", "public void add(Vector3d v1) {\n x += v1.x;\n y += v1.y;\n z += v1.z;\n }", "boolean hasNoAlternativeWildcardRegistration() {\n return parent == null || PathElement.WILDCARD_VALUE.equals(valueString) || !parent.getChildNames().contains(PathElement.WILDCARD_VALUE);\n }", "public static String fill(int color) {\n final String colorCode = Integer.toHexString(color & 0xFFFFFF); // Strip alpha\n return FILTER_FILL + \"(\" + colorCode + \")\";\n }", "public Map<String, String> resolve(Map<String, String> config) {\n config = resolveSystemEnvironmentVariables(config);\n config = resolveSystemDefaultSetup(config);\n config = resolveDockerInsideDocker(config);\n config = resolveDownloadDockerMachine(config);\n config = resolveAutoStartDockerMachine(config);\n config = resolveDefaultDockerMachine(config);\n config = resolveServerUriByOperativeSystem(config);\n config = resolveServerIp(config);\n config = resolveTlsVerification(config);\n return config;\n }", "protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {\n final String parameterString = servletContext.getInitParameter(parameterName);\n if(parameterString != null && parameterString.trim().length() > 0) {\n try {\n return Integer.parseInt(parameterString);\n }\n catch (NumberFormatException e) {\n // Do nothing, return default value\n }\n }\n return defaultValue;\n }", "public static <IN extends CoreMap> CRFClassifier<IN> getClassifier(File file) throws IOException, ClassCastException,\r\n ClassNotFoundException {\r\n CRFClassifier<IN> crf = new CRFClassifier<IN>();\r\n crf.loadClassifier(file);\r\n return crf;\r\n }", "public static base_response unset(nitro_service client, nsacl6 resource, String[] args) throws Exception{\n\t\tnsacl6 unsetresource = new nsacl6();\n\t\tunsetresource.acl6name = resource.acl6name;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}" ]
Creates PollingState from another polling state. @param other other polling state @param result the final result of the LRO @param <ResultT> the result that the poll operation produces @return the polling state
[ "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 }" ]
[ "public static appfwpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_stats response = (appfwpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "private static int findTrackIdAtOffset(SlotReference slot, Client client, int offset) throws IOException {\n Message entry = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot.slot, CdjStatus.TrackType.REKORDBOX, offset, 1).get(0);\n if (entry.getMenuItemType() == Message.MenuItemType.UNKNOWN) {\n logger.warn(\"Encountered unrecognized track list entry item type: {}\", entry);\n }\n return (int)((NumberField)entry.arguments.get(1)).getValue();\n }", "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 }", "public ProteusApplication addDefaultRoutes(RoutingHandler router)\n {\n\n if (config.hasPath(\"health.statusPath\")) {\n try {\n final String statusPath = config.getString(\"health.statusPath\");\n\n router.add(Methods.GET, statusPath, (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, MediaType.TEXT_PLAIN);\n exchange.getResponseSender().send(\"OK\");\n });\n\n this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(\"*/*\").withProduces(\"text/plain\").withPathTemplate(statusPath).withControllerName(\"Internal\").withMethod(Methods.GET).build());\n\n } catch (Exception e) {\n log.error(\"Error adding health status route.\", e.getMessage());\n }\n }\n\n if (config.hasPath(\"application.favicon\")) {\n try {\n\n final ByteBuffer faviconImageBuffer;\n\n final File faviconFile = new File(config.getString(\"application.favicon\"));\n\n if (!faviconFile.exists()) {\n try (final InputStream stream = this.getClass().getResourceAsStream(config.getString(\"application.favicon\"))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n\n } else {\n try (final InputStream stream = Files.newInputStream(Paths.get(config.getString(\"application.favicon\")))) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n byte[] buffer = new byte[4096];\n int read = 0;\n while (read != -1) {\n read = stream.read(buffer);\n if (read > 0) {\n baos.write(buffer, 0, read);\n }\n }\n\n faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());\n }\n }\n\n router.add(Methods.GET, \"favicon.ico\", (final HttpServerExchange exchange) ->\n {\n exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, io.sinistral.proteus.server.MediaType.IMAGE_X_ICON.toString());\n exchange.getResponseSender().send(faviconImageBuffer);\n });\n\n } catch (Exception e) {\n log.error(\"Error adding favicon route.\", e.getMessage());\n }\n }\n\n return this;\n }", "private void writeResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource)\n {\n Project.Resources.Resource.Baseline baseline = m_factory.createProjectResourcesResourceBaseline();\n boolean populated = false;\n\n Number cost = mpxjResource.getBaselineCost();\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n Duration work = mpxjResource.getBaselineWork();\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.ZERO);\n }\n\n for (int loop = 1; loop <= 10; loop++)\n {\n baseline = m_factory.createProjectResourcesResourceBaseline();\n populated = false;\n\n cost = mpxjResource.getBaselineCost(loop);\n if (cost != null && cost.intValue() != 0)\n {\n populated = true;\n baseline.setCost(DatatypeConverter.printCurrency(cost));\n }\n\n work = mpxjResource.getBaselineWork(loop);\n if (work != null && work.getDuration() != 0)\n {\n populated = true;\n baseline.setWork(DatatypeConverter.printDuration(this, work));\n }\n\n if (populated)\n {\n xmlResource.getBaseline().add(baseline);\n baseline.setNumber(BigInteger.valueOf(loop));\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 Date getYearlyAbsoluteAsDate(RecurringData data)\n {\n Date result;\n Integer yearlyAbsoluteDay = data.getDayNumber();\n Integer yearlyAbsoluteMonth = data.getMonthNumber();\n Date startDate = data.getStartDate();\n\n if (yearlyAbsoluteDay == null || yearlyAbsoluteMonth == null || startDate == null)\n {\n result = null;\n }\n else\n {\n Calendar cal = DateHelper.popCalendar(startDate);\n cal.set(Calendar.MONTH, yearlyAbsoluteMonth.intValue() - 1);\n cal.set(Calendar.DAY_OF_MONTH, yearlyAbsoluteDay.intValue());\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n return result;\n }", "private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n addMembers(memberNames, members, type, tagName, paramName, paramValue);\r\n if (type.getInterfaces() != null) {\r\n for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) {\r\n addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue);\r\n }\r\n }\r\n if (!type.isInterface() && (type.getSuperclass() != null)) {\r\n addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue);\r\n }\r\n }", "private void registerProxyCreator(Node source,\n BeanDefinitionHolder holder,\n ParserContext context) {\n\n String beanName = holder.getBeanName();\n String proxyName = beanName + \"Proxy\";\n String interceptorName = beanName + \"PerformanceMonitorInterceptor\";\n\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class);\n\n initializer.addPropertyValue(\"beanNames\", beanName);\n initializer.addPropertyValue(\"interceptorNames\", interceptorName);\n\n BeanDefinitionRegistry registry = context.getRegistry();\n registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition());\n }" ]
Apply the necessary rotation to the transform so that it is in front of the camera. The actual rotation is performed not using the yaw angle but using equivalent quaternion values for better accuracy. But the yaw angle is still returned for backward compatibility. @param widget The transform to modify. @return The camera's yaw in degrees.
[ "public float rotateToFaceCamera(final Widget widget) {\n final float yaw = getMainCameraRigYaw();\n GVRTransform t = getMainCameraRig().getHeadTransform();\n widget.rotateWithPivot(t.getRotationW(), 0, t.getRotationY(), 0, 0, 0, 0);\n return yaw;\n }" ]
[ "private void readPredecessors(Project.Tasks.Task task)\n {\n Integer uid = task.getUID();\n if (uid != null)\n {\n Task currTask = m_projectFile.getTaskByUniqueID(uid);\n if (currTask != null)\n {\n for (Project.Tasks.Task.PredecessorLink link : task.getPredecessorLink())\n {\n readPredecessor(currTask, link);\n }\n }\n }\n }", "public Weld property(String key, Object value) {\n properties.put(key, value);\n return this;\n }", "public List<String> deviceTypes() {\n Integer count = json().size(DEVICE_FAMILIES);\n List<String> deviceTypes = new ArrayList<String>(count);\n for(int i = 0 ; i < count ; i++) {\n String familyNumber = json().stringValue(DEVICE_FAMILIES, i);\n if(familyNumber.equals(\"1\")) deviceTypes.add(\"iPhone\");\n if(familyNumber.equals(\"2\")) deviceTypes.add(\"iPad\");\n }\n return deviceTypes;\n }", "public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }", "public void removePath(int pathId) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n // remove any enabled overrides with this path\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, pathId);\n statement.executeUpdate();\n statement.close();\n\n // remove path\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH\n + \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, pathId);\n statement.executeUpdate();\n statement.close();\n\n //remove path from responseRequest\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_REQUEST_RESPONSE\n + \" WHERE \" + Constants.REQUEST_RESPONSE_PATH_ID + \" = ?\"\n );\n statement.setInt(1, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {\r\n SizeList<Size> sizes = new SizeList<Size>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_SIZES);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element sizesElement = response.getPayload();\r\n sizes.setIsCanBlog(\"1\".equals(sizesElement.getAttribute(\"canblog\")));\r\n sizes.setIsCanDownload(\"1\".equals(sizesElement.getAttribute(\"candownload\")));\r\n sizes.setIsCanPrint(\"1\".equals(sizesElement.getAttribute(\"canprint\")));\r\n NodeList sizeNodes = sizesElement.getElementsByTagName(\"size\");\r\n for (int i = 0; i < sizeNodes.getLength(); i++) {\r\n Element sizeElement = (Element) sizeNodes.item(i);\r\n Size size = new Size();\r\n size.setLabel(sizeElement.getAttribute(\"label\"));\r\n size.setWidth(sizeElement.getAttribute(\"width\"));\r\n size.setHeight(sizeElement.getAttribute(\"height\"));\r\n size.setSource(sizeElement.getAttribute(\"source\"));\r\n size.setUrl(sizeElement.getAttribute(\"url\"));\r\n size.setMedia(sizeElement.getAttribute(\"media\"));\r\n sizes.add(size);\r\n }\r\n return sizes;\r\n }", "protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {\n try {\n if (getBeanType().isInterface()) {\n ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());\n } else {\n boolean constructorFound = false;\n for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {\n if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {\n constructorFound = true;\n String[] exceptions = new String[constructor.getExceptionTypes().length];\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = constructor.getExceptionTypes()[i].getName();\n }\n ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag());\n }\n }\n if (!constructorFound) {\n // the bean only has private constructors, we need to generate\n // two fake constructors that call each other\n addConstructorsForBeanWithPrivateConstructors(proxyClassType);\n }\n }\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }", "@SuppressWarnings(\"unchecked\")\r\n\tpublic List<Difference> compare() {\r\n\t\tDiff diff = new Diff(this.controlDOM, this.testDOM);\r\n\t\tDetailedDiff detDiff = new DetailedDiff(diff);\r\n\t\treturn detDiff.getAllDifferences();\r\n\t}", "public LuaScript endScript(LuaScriptConfig config) {\n if (!endsWithReturnStatement()) {\n add(new LuaAstReturnStatement());\n }\n String scriptText = buildScriptText();\n return new BasicLuaScript(scriptText, config);\n }" ]
Process StepStartedEvent. New step will be created and added to stepStorage. @param event to process
[ "public void fire(StepStartedEvent event) {\n Step step = new Step();\n event.process(step);\n stepStorage.put(step);\n\n notifier.fire(event);\n }" ]
[ "public void awaitPodReadinessOrFail(Predicate<Pod> filter) {\n await().atMost(5, TimeUnit.MINUTES).until(() -> {\n List<Pod> list = client.pods().inNamespace(namespace).list().getItems();\n return list.stream()\n .filter(filter)\n .filter(Readiness::isPodReady)\n .collect(Collectors.toList()).size() >= 1;\n }\n );\n }", "public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException {\n MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature();\n\n Object[] values = new Object[parameterInfoArray.length];\n String[] types = new String[parameterInfoArray.length];\n\n MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap);\n\n for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) {\n MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum];\n String type = parameterInfo.getType();\n types[parameterNum] = type;\n values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type);\n }\n\n return mBeanServer.invoke(objectName, operationInfo.getName(), values, types);\n }", "public BlurBuilder contrast(float contrast) {\n data.preProcessors.add(new ContrastProcessor(data.contextWrapper.getRenderScript(), Math.max(Math.min(1500.f, contrast), -1500.f)));\n return this;\n }", "public boolean isInBounds(int row, int col) {\n return row >= 0 && col >= 0 && row < mat.getNumRows() && col < mat.getNumCols();\n }", "public void setSize(int size) {\n if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {\n return;\n }\n final DisplayMetrics metrics = getResources().getDisplayMetrics();\n if (size == MaterialProgressDrawable.LARGE) {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);\n } else {\n mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);\n }\n // force the bounds of the progress circle inside the circle view to\n // update by setting it to null before updating its size and then\n // re-setting it\n mCircleView.setImageDrawable(null);\n mProgress.updateSizes(size);\n mCircleView.setImageDrawable(mProgress);\n }", "public void process(String name) throws Exception\n {\n ProjectFile file = new UniversalProjectReader().read(name);\n for (Task task : file.getTasks())\n {\n if (!task.getSummary())\n {\n System.out.print(task.getWBS());\n System.out.print(\"\\t\");\n System.out.print(task.getName());\n System.out.print(\"\\t\");\n System.out.print(format(task.getStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualStart()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getFinish()));\n System.out.print(\"\\t\");\n System.out.print(format(task.getActualFinish()));\n System.out.println();\n }\n }\n }", "private String getCachedETag(HttpHost host, String file) {\n Map<String, Object> cachedETags = readCachedETags();\n\n @SuppressWarnings(\"unchecked\")\n Map<String, Object> hostMap =\n (Map<String, Object>)cachedETags.get(host.toURI());\n if (hostMap == null) {\n return null;\n }\n\n @SuppressWarnings(\"unchecked\")\n Map<String, String> etagMap = (Map<String, String>)hostMap.get(file);\n if (etagMap == null) {\n return null;\n }\n\n return etagMap.get(\"ETag\");\n }", "public static Pair<String, String> stringIntern(Pair<String, String> p) {\r\n return new MutableInternedPair(p);\r\n }", "public boolean equalId(Element otherElement) {\r\n\t\tif (getElementId() == null || otherElement.getElementId() == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn getElementId().equalsIgnoreCase(otherElement.getElementId());\r\n\t}" ]
Given a list of typedDependencies, returns true if the node "node" is the governor of a conj relation with a dependent which is not a preposition @param node A node in this GrammaticalStructure @param list A list of typedDependencies @return true If node is the governor of a conj relation in the list with the dep not being a preposition
[ "private static boolean isConjWithNoPrep(TreeGraphNode node, Collection<TypedDependency> list) {\r\n for (TypedDependency td : list) {\r\n if (td.gov() == node && td.reln() == CONJUNCT) {\r\n // we have a conjunct\r\n // check the POS of the dependent\r\n String tdDepPOS = td.dep().parent().value();\r\n if (!(tdDepPOS.equals(\"IN\") || tdDepPOS.equals(\"TO\"))) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }" ]
[ "public Path relativize(Path other) {\n\t\tif (other.isAbsolute() != isAbsolute())\n\t\t\tthrow new IllegalArgumentException(\"This path and the given path are not both absolute or both relative: \" + toString() + \" | \" + other.toString());\n\t\tif (startsWith(other)) {\n\t\t\treturn internalRelativize(this, other);\n\t\t} else if (other.startsWith(this)) {\n\t\t\treturn internalRelativize(other, this);\n\t\t}\n\t\treturn null;\n\t}", "public static void skip(InputStream stream, long skip) throws IOException\n {\n long count = skip;\n while (count > 0)\n {\n count -= stream.skip(count);\n }\n }", "public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) {\n\t\tArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1);\n\t\tfactories.addAll(this.factories);\n\t\tfactories.add(0, factory);\n\t\treturn new ProductFactoryCascade<>(factories);\n\t}", "private SiteRecord getSiteRecord(String siteKey) {\n\t\tSiteRecord siteRecord = this.siteRecords.get(siteKey);\n\t\tif (siteRecord == null) {\n\t\t\tsiteRecord = new SiteRecord(siteKey);\n\t\t\tthis.siteRecords.put(siteKey, siteRecord);\n\t\t}\n\t\treturn siteRecord;\n\t}", "public int size(final K1 firstKey, final K2 secondKey) {\n\t\t// existence check on inner map\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t// existence check on inner map1\n\t\tfinal HashMap<K3, V> innerMap2 = innerMap1.get(secondKey);\n\t\tif( innerMap2 == null ) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn innerMap2.size();\n\t}", "public History[] filterHistory(String... filters) throws Exception {\n BasicNameValuePair[] params;\n if (filters.length > 0) {\n params = new BasicNameValuePair[filters.length];\n for (int i = 0; i < filters.length; i++) {\n params[i] = new BasicNameValuePair(\"source_uri[]\", filters[i]);\n }\n } else {\n return refreshHistory();\n }\n\n return constructHistory(params);\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory,\n SerializerDefinition serializerDefinition) {\n return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition);\n }", "public static DatagramPacket buildPacket(PacketType type, ByteBuffer deviceName, ByteBuffer payload) {\n ByteBuffer content = ByteBuffer.allocate(0x1f + payload.remaining());\n content.put(getMagicHeader());\n content.put(type.protocolValue);\n content.put(deviceName);\n content.put(payload);\n return new DatagramPacket(content.array(), content.capacity());\n }", "private Double getDuration(Duration duration)\n {\n Double result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.HOURS)\n {\n duration = duration.convertUnits(TimeUnit.HOURS, m_projectFile.getProjectProperties());\n }\n\n result = Double.valueOf(duration.getDuration());\n }\n return result;\n }" ]
Determines if we need to calculate more dates. If we do not have a finish date, this method falls back on using the occurrences attribute. If we have a finish date, we'll use that instead. We're assuming that the recurring data has one or other of those values. @param calendar current date @param dates dates generated so far @return true if we should calculate another date
[ "private boolean moreDates(Calendar calendar, List<Date> dates)\n {\n boolean result;\n if (m_finishDate == null)\n {\n int occurrences = NumberHelper.getInt(m_occurrences);\n if (occurrences < 1)\n {\n occurrences = 1;\n }\n result = dates.size() < occurrences;\n }\n else\n {\n result = calendar.getTimeInMillis() <= m_finishDate.getTime();\n }\n return result;\n }" ]
[ "public static void acceptsNodeSingle(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id\")\n .withRequiredArg()\n .describedAs(\"node-id\")\n .ofType(Integer.class);\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 LogStreamResponse getLogs(String appName, Boolean tail) {\n return connection.execute(new Log(appName, tail), apiKey);\n }", "protected List<I_CmsFacetQueryItem> parseFacetQueryItems(JSONObject queryFacetObject) throws JSONException {\n\n JSONArray items = queryFacetObject.getJSONArray(JSON_KEY_QUERY_FACET_QUERY);\n List<I_CmsFacetQueryItem> result = new ArrayList<I_CmsFacetQueryItem>(items.length());\n for (int i = 0; i < items.length(); i++) {\n I_CmsFacetQueryItem item = parseFacetQueryItem(items.getJSONObject(i));\n if (item != null) {\n result.add(item);\n }\n }\n return result;\n }", "public Stats getPhotosetStats(String photosetId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSET_STATS, \"photoset_id\", photosetId, date);\n }", "public String getPermalinkForCurrentPage(CmsObject cms) {\n\n return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId());\n }", "protected List<Integer> cancelAllActiveOperations() {\n final List<Integer> operations = new ArrayList<Integer>();\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n activeOperation.asyncCancel(false);\n operations.add(activeOperation.getOperationId());\n }\n return operations;\n }", "public void 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<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) {\n\treturn bridge.lift(f);\n }" ]
Produce an iterator over the input values in sorted order. Sorting will occur in the fixed space configured in the constructor, data will be dumped to disk as necessary. @param input An iterator over the input values @return An iterator over the values
[ "public Iterable<V> sorted(Iterator<V> input) {\n ExecutorService executor = new ThreadPoolExecutor(this.numThreads,\n this.numThreads,\n 1000L,\n TimeUnit.MILLISECONDS,\n new SynchronousQueue<Runnable>(),\n new CallerRunsPolicy());\n final AtomicInteger count = new AtomicInteger(0);\n final List<File> tempFiles = Collections.synchronizedList(new ArrayList<File>());\n while(input.hasNext()) {\n final int segmentId = count.getAndIncrement();\n final long segmentStartMs = System.currentTimeMillis();\n logger.info(\"Segment \" + segmentId + \": filling sort buffer for segment...\");\n @SuppressWarnings(\"unchecked\")\n final V[] buffer = (V[]) new Object[internalSortSize];\n int segmentSizeIter = 0;\n for(; segmentSizeIter < internalSortSize && input.hasNext(); segmentSizeIter++)\n buffer[segmentSizeIter] = input.next();\n final int segmentSize = segmentSizeIter;\n logger.info(\"Segment \" + segmentId + \": sort buffer filled...adding to sort queue.\");\n\n // sort and write out asynchronously\n executor.execute(new Runnable() {\n\n public void run() {\n logger.info(\"Segment \" + segmentId + \": sorting buffer.\");\n long start = System.currentTimeMillis();\n Arrays.sort(buffer, 0, segmentSize, comparator);\n long elapsed = System.currentTimeMillis() - start;\n logger.info(\"Segment \" + segmentId + \": sort completed in \" + elapsed\n + \" ms, writing to temp file.\");\n\n // write out values to a temp file\n try {\n File tempFile = File.createTempFile(\"segment-\", \".dat\", tempDir);\n tempFile.deleteOnExit();\n tempFiles.add(tempFile);\n OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile),\n bufferSize);\n if(gzip)\n os = new GZIPOutputStream(os);\n DataOutputStream output = new DataOutputStream(os);\n for(int i = 0; i < segmentSize; i++)\n writeValue(output, buffer[i]);\n output.close();\n } catch(IOException e) {\n throw new VoldemortException(e);\n }\n long segmentElapsed = System.currentTimeMillis() - segmentStartMs;\n logger.info(\"Segment \" + segmentId + \": completed processing of segment in \"\n + segmentElapsed + \" ms.\");\n }\n });\n }\n\n // wait for all sorting to complete\n executor.shutdown();\n try {\n executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n // create iterator over sorted values\n return new DefaultIterable<V>(new ExternalSorterIterator(tempFiles, bufferSize\n / tempFiles.size()));\n } catch(InterruptedException e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "private void getYearlyAbsoluteDates(Calendar calendar, List<Date> dates)\n {\n long startDate = calendar.getTimeInMillis();\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.set(Calendar.MONTH, NumberHelper.getInt(m_monthNumber) - 1);\n int requiredDayNumber = NumberHelper.getInt(m_dayNumber);\n\n while (moreDates(calendar, dates))\n {\n int useDayNumber = requiredDayNumber;\n int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n if (useDayNumber > maxDayNumber)\n {\n useDayNumber = maxDayNumber;\n }\n\n calendar.set(Calendar.DAY_OF_MONTH, useDayNumber);\n if (calendar.getTimeInMillis() < startDate)\n {\n calendar.add(Calendar.YEAR, 1);\n }\n\n dates.add(calendar.getTime());\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n calendar.add(Calendar.YEAR, 1);\n }\n }", "public List<Long> getOffsets(OffsetRequest offsetRequest) {\n ILog log = getLog(offsetRequest.topic, offsetRequest.partition);\n if (log != null) {\n return log.getOffsetsBefore(offsetRequest);\n }\n return ILog.EMPTY_OFFSETS;\n }", "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 }", "public Float getFloat(String fieldName) {\n\t\ttry {\n\t\t\treturn hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a number.\", e);\n\t\t}\n\t}", "private void unmarshalDescriptor() throws CmsXmlException, CmsException {\n\n if (null != m_desc) {\n\n // unmarshal descriptor\n m_descContent = CmsXmlContentFactory.unmarshal(m_cms, m_cms.readFile(m_desc));\n\n // configure messages if wanted\n CmsProperty bundleProp = m_cms.readPropertyObject(m_desc, PROPERTY_BUNDLE_DESCRIPTOR_LOCALIZATION, true);\n if (!(bundleProp.isNullProperty() || bundleProp.getValue().trim().isEmpty())) {\n m_configuredBundle = bundleProp.getValue();\n }\n }\n\n }", "public void addCommandClass(ZWaveCommandClass commandClass)\n\t{\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\n\t\t\n\t\tif (!supportedCommandClasses.containsKey(key)) {\n\t\t\tsupportedCommandClasses.put(key, commandClass);\n\t\t\t\n\t\t\tif (commandClass instanceof ZWaveEventListener)\n\t\t\t\tthis.controller.addEventListener((ZWaveEventListener)commandClass);\n\t\t\t\n\t\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t\t}\n\t}", "@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 QueryBuilder<T, ID> selectColumns(String... columns) {\n\t\tfor (String column : columns) {\n\t\t\taddSelectColumnToList(column);\n\t\t}\n\t\treturn this;\n\t}", "public static void readAndCheckVersion(ObjectInput input, int supportedVersion, Class<?> externalizedType) throws IOException {\n\t\tint version = input.readInt();\n\n\t\tif ( version != supportedVersion ) {\n\t\t\tthrow LOG.unexpectedKeyVersion( externalizedType, version, supportedVersion );\n\t\t}\n\t}" ]
This method is used to process an MPP14 file. This is the file format used by Project 14. @param reader parent file reader @param file parent MPP file @param root Root of the POI file system.
[ "@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 int compare(final Version other) throws IncomparableException{\n\t\t// Cannot compare branch versions and others \n\t\tif(!isBranch().equals(other.isBranch())){\n\t\t\tthrow new IncomparableException();\n\t\t}\n\t\t\n\t\t// Compare digits\n\t\tfinal int minDigitSize = getDigitsSize() < other.getDigitsSize()? getDigitsSize(): other.getDigitsSize();\n\t\t\n\t\tfor(int i = 0; i < minDigitSize ; i++){\n\t\t\tif(!getDigit(i).equals(other.getDigit(i))){\n\t\t\t\treturn getDigit(i).compareTo(other.getDigit(i));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If not the same number of digits and the first digits are equals, the longest is the newer\n\t\tif(!getDigitsSize().equals(other.getDigitsSize())){\n\t\t\treturn getDigitsSize() > other.getDigitsSize()? 1: -1;\n\t\t}\n\n if(isBranch() && !getBranchId().equals(other.getBranchId())){\n\t\t\treturn getBranchId().compareTo(other.getBranchId());\n\t\t}\n\t\t\n\t\t// if the digits are the same, a snapshot is newer than a release\n\t\tif(isSnapshot() && other.isRelease()){\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tif(isRelease() && other.isSnapshot()){\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t// if both versions are releases, compare the releaseID\n\t\tif(isRelease() && other.isRelease()){\n\t\t\treturn getReleaseId().compareTo(other.getReleaseId());\n\t\t}\n\t\t\n\t\treturn 0;\n\t}", "public void removePathnameFromProfile(int path_id, int profileId) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_PATH +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, path_id);\n statement.executeUpdate();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public IndexDescriptorDef getIndexDescriptor(String name)\r\n {\r\n IndexDescriptorDef indexDef = null;\r\n\r\n for (Iterator it = _indexDescriptors.iterator(); it.hasNext(); )\r\n {\r\n indexDef = (IndexDescriptorDef)it.next();\r\n if (indexDef.getName().equals(name))\r\n {\r\n return indexDef;\r\n }\r\n }\r\n return null;\r\n }", "private String getNotes(Row row)\n {\n String notes = row.getString(\"NOTET\");\n if (notes != null)\n {\n if (notes.isEmpty())\n {\n notes = null;\n }\n else\n {\n if (notes.indexOf(LINE_BREAK) != -1)\n {\n notes = notes.replace(LINE_BREAK, \"\\n\");\n }\n }\n }\n return notes;\n }", "private void processResources() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zresource where zproject=? order by zorderinproject\", m_projectID);\n for (Row row : rows)\n {\n Resource resource = m_project.addResource();\n resource.setUniqueID(row.getInteger(\"Z_PK\"));\n resource.setEmailAddress(row.getString(\"ZEMAIL\"));\n resource.setInitials(row.getString(\"ZINITIALS\"));\n resource.setName(row.getString(\"ZTITLE_\"));\n resource.setGUID(row.getUUID(\"ZUNIQUEID\"));\n resource.setType(row.getResourceType(\"ZTYPE\"));\n resource.setMaterialLabel(row.getString(\"ZMATERIALUNIT\"));\n\n if (resource.getType() == ResourceType.WORK)\n {\n resource.setMaxUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZAVAILABLEUNITS_\")) * 100.0));\n }\n\n Integer calendarID = row.getInteger(\"ZRESOURCECALENDAR\");\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);\n if (calendar != null)\n {\n calendar.setName(resource.getName());\n resource.setResourceCalendar(calendar);\n }\n }\n\n m_eventManager.fireResourceReadEvent(resource);\n }\n }", "public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {\r\n InputStream instream = null;\r\n try {\r\n Reader reader = new InputStreamReader(instream = queryForStream(query), \"UTF-8\");\r\n JsonObject json = new JsonParser().parse(reader).getAsJsonObject();\r\n Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();\r\n if (json.has(\"groups\")) {\r\n for (JsonElement e : json.getAsJsonArray(\"groups\")) {\r\n String groupName = e.getAsJsonObject().get(\"by\").getAsString();\r\n List<T> orows = new ArrayList<T>();\r\n if (!includeDocs) {\r\n log.warning(\"includeDocs set to false and attempting to retrieve doc. \" +\r\n \"null object will be returned\");\r\n }\r\n for (JsonElement rows : e.getAsJsonObject().getAsJsonArray(\"rows\")) {\r\n orows.add(jsonToObject(client.getGson(), rows, \"doc\", classOfT));\r\n }\r\n result.put(groupName, orows);\r\n }// end for(groups)\r\n }// end hasgroups\r\n else {\r\n log.warning(\"No grouped results available. Use query() if non grouped query\");\r\n }\r\n return result;\r\n } catch (UnsupportedEncodingException e1) {\r\n // This should never happen as every implementation of the java platform is required\r\n // to support UTF-8.\r\n throw new RuntimeException(e1);\r\n } finally {\r\n close(instream);\r\n }\r\n }", "public static void main(String[] args) {\n CmdLine cmd = new CmdLine();\n Configuration conf = new Configuration();\n int res = 0;\n try {\n res = ToolRunner.run(conf, cmd, args);\n } catch (Exception e) {\n System.err.println(\"Error while running MR job\");\n e.printStackTrace();\n }\n System.exit(res);\n }", "private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException {\n\t\tif (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultSvgDocument document = new DefaultSvgDocument(writer, false);\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer()));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new SvgTileWriter());\n\t\t\treturn document;\n\t\t} else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) {\n\t\t\tDefaultVmlDocument document = new DefaultVmlDocument(writer);\n\t\t\tint coordWidth = tile.getScreenWidth();\n\t\t\tint coordHeight = tile.getScreenHeight();\n\t\t\tdocument.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth,\n\t\t\t\t\tcoordHeight));\n\t\t\tdocument.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight));\n\t\t\tdocument.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);\n\t\t\treturn document;\n\t\t} else {\n\t\t\tthrow new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer);\n\t\t}\n\t}" ]
Parses a code block with no parentheses and no commas. After it is done there should be a single token left, which is returned.
[ "protected TokenList.Token parseBlockNoParentheses(TokenList tokens, Sequence sequence, boolean insideMatrixConstructor) {\n\n // search for matrix bracket operations\n if( !insideMatrixConstructor ) {\n parseBracketCreateMatrix(tokens, sequence);\n }\n\n // First create sequences from anything involving a colon\n parseSequencesWithColons(tokens, sequence );\n\n // process operators depending on their priority\n parseNegOp(tokens, sequence);\n parseOperationsL(tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.POWER, Symbol.ELEMENT_POWER}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.TIMES, Symbol.RDIVIDE, Symbol.LDIVIDE, Symbol.ELEMENT_TIMES, Symbol.ELEMENT_DIVIDE}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.PLUS, Symbol.MINUS}, tokens, sequence);\n\n // Commas are used in integer sequences. Can be used to force to compiler to treat - as negative not\n // minus. They can now be removed since they have served their purpose\n stripCommas(tokens);\n\n // now construct rest of the lists and combine them together\n parseIntegerLists(tokens);\n parseCombineIntegerLists(tokens);\n\n if( !insideMatrixConstructor ) {\n if (tokens.size() > 1) {\n System.err.println(\"Remaining tokens: \"+tokens.size);\n TokenList.Token t = tokens.first;\n while( t != null ) {\n System.err.println(\" \"+t);\n t = t.next;\n }\n throw new RuntimeException(\"BUG in parser. There should only be a single token left\");\n }\n return tokens.first;\n } else {\n return null;\n }\n }" ]
[ "public static String[] slice(String[] strings, int begin, int length) {\n\t\tString[] result = new String[length];\n\t\tSystem.arraycopy( strings, begin, result, 0, length );\n\t\treturn result;\n\t}", "public static Bic valueOf(final String bic) throws BicFormatException,\n UnsupportedCountryException {\n BicUtil.validate(bic);\n return new Bic(bic);\n }", "protected void capture3DScreenShot(GVRRenderTarget renderTarget, boolean isMultiview) {\n if (mScreenshot3DCallback == null) {\n return;\n }\n final Bitmap[] bitmaps = new Bitmap[6];\n renderSixCamerasAndReadback(mMainScene.getMainCameraRig(), bitmaps, renderTarget, isMultiview);\n returnScreenshot3DToCaller(mScreenshot3DCallback, bitmaps, mReadbackBufferWidth, mReadbackBufferHeight);\n\n mScreenshot3DCallback = null;\n }", "protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) {\n try {\n Client client = new Client(profileName, false);\n client.toggleProfile(true);\n client.setCustom(isResponse, pathName, customData);\n if (isResponse) {\n client.toggleResponseOverride(pathName, true);\n } else {\n client.toggleRequestOverride(pathName, true);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "private boolean isToIgnore(CtElement element) {\n\t\tif (element instanceof CtStatementList && !(element instanceof CtCase)) {\n\t\t\tif (element.getRoleInParent() == CtRole.ELSE || element.getRoleInParent() == CtRole.THEN) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn element.isImplicit() || element instanceof CtReference;\n\t}", "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 }", "public static String constructResourceId(\n final String subscriptionId,\n final String resourceGroupName,\n final String resourceProviderNamespace,\n final String resourceType,\n final String resourceName,\n final String parentResourcePath) {\n String prefixedParentPath = parentResourcePath;\n if (parentResourcePath != null && !parentResourcePath.isEmpty()) {\n prefixedParentPath = \"/\" + parentResourcePath;\n }\n return String.format(\n \"/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s\",\n subscriptionId,\n resourceGroupName,\n resourceProviderNamespace,\n prefixedParentPath,\n resourceType,\n resourceName);\n }", "public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }", "public static void writeCorrelationId(Message message, String correlationId) {\n if (!(message instanceof SoapMessage)) {\n return;\n }\n SoapMessage soapMessage = (SoapMessage) message;\n Header hdCorrelationId = soapMessage.getHeader(CORRELATION_ID_QNAME);\n if (hdCorrelationId != null) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n if ((soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) != null)\n && (soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class) instanceof SAAJStreamWriter)\n && (((SAAJStreamWriter) soapMessage.getContent(javax.xml.stream.XMLStreamWriter.class))\n .getDocument()\n .getElementsByTagNameNS(\"http://www.talend.com/esb/sam/correlationId/v1\",\n \"correlationId\").getLength() > 0)) {\n LOG.warning(\"CorrelationId already existing in soap header, need not to write CorrelationId header.\");\n return;\n }\n\n try {\n soapMessage.getHeaders().add(\n new Header(CORRELATION_ID_QNAME, correlationId, new JAXBDataBinding(String.class)));\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Stored correlationId '\" + correlationId + \"' in soap header: \"\n + CORRELATION_ID_QNAME);\n }\n } catch (JAXBException e) {\n LOG.log(Level.SEVERE, \"Couldn't create correlationId header.\", e);\n }\n\n }" ]
Drop down item view @param position position of item @param convertView View of item @param parent parent view of item's view @return covertView
[ "@Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n final ViewHolder viewHolder;\n if (convertView == null) {\n convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false);\n viewHolder = new ViewHolder();\n viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image);\n viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name);\n viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode);\n convertView.setTag(viewHolder);\n } else {\n viewHolder = (ViewHolder) convertView.getTag();\n }\n\n Country country = getItem(position);\n viewHolder.mImageView.setImageResource(getFlagResource(country));\n viewHolder.mNameView.setText(country.getName());\n viewHolder.mDialCode.setText(String.format(\"+%s\", country.getDialCode()));\n return convertView;\n }" ]
[ "public static Object[] filterMapToObjectArray(final Map<String, ?> values, final String[] nameMapping) {\n\t\t\n\t\tif( values == null ) {\n\t\t\tthrow new NullPointerException(\"values should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal Object[] targetArray = new Object[nameMapping.length];\n\t\tint i = 0;\n\t\tfor( final String name : nameMapping ) {\n\t\t\ttargetArray[i++] = values.get(name);\n\t\t}\n\t\treturn targetArray;\n\t}", "private int indexFor(int hash)\r\n {\r\n // mix the bits to avoid bucket collisions...\r\n hash += ~(hash << 15);\r\n hash ^= (hash >>> 10);\r\n hash += (hash << 3);\r\n hash ^= (hash >>> 6);\r\n hash += ~(hash << 11);\r\n hash ^= (hash >>> 16);\r\n return hash & (table.length - 1);\r\n }", "@Override\n public final float getFloat(final String key) {\n Float result = optFloat(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "public void add(ServiceReference<D> declarationSRef) {\n D declaration = getDeclaration(declarationSRef);\n boolean matchFilter = declarationFilter.matches(declaration.getMetadata());\n declarations.put(declarationSRef, matchFilter);\n }", "public void addHandlerFactory(ManagementRequestHandlerFactory factory) {\n for (;;) {\n final ManagementRequestHandlerFactory[] snapshot = updater.get(this);\n final int length = snapshot.length;\n final ManagementRequestHandlerFactory[] newVal = new ManagementRequestHandlerFactory[length + 1];\n System.arraycopy(snapshot, 0, newVal, 0, length);\n newVal[length] = factory;\n if (updater.compareAndSet(this, snapshot, newVal)) {\n return;\n }\n }\n }", "@Override\n public final double getDouble(final String key) {\n Double result = optDouble(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "@SuppressWarnings(\"UnusedDeclaration\")\n public void init() throws Exception {\n initBuilderSpecific();\n resetFields();\n if (!UserPluginInfo.NO_PLUGIN_KEY.equals(getSelectedStagingPluginName())) {\n PluginSettings selectedStagingPluginSettings = getSelectedStagingPlugin();\n try {\n stagingStrategy = getArtifactoryServer().getStagingStrategy(selectedStagingPluginSettings, Util.rawEncode(project.getName()), project);\n } catch (Exception e) {\n log.log(Level.WARNING, \"Failed to obtain staging strategy: \" + e.getMessage(), e);\n strategyRequestFailed = true;\n strategyRequestErrorMessage = \"Failed to obtain staging strategy '\" +\n selectedStagingPluginSettings.getPluginName() + \"': \" + e.getMessage() +\n \".\\nPlease review the log for further information.\";\n stagingStrategy = null;\n }\n strategyPluginExists = (stagingStrategy != null) && !stagingStrategy.isEmpty();\n }\n\n prepareDefaultVersioning();\n prepareDefaultGlobalModule();\n prepareDefaultModules();\n prepareDefaultVcsSettings();\n prepareDefaultPromotionConfig();\n }", "public TransformersSubRegistration getHostRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }", "public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n final List<String> list = readLines(self);\n T result = null;\n for (String line : list) {\n List vals = Arrays.asList(pattern.split(line));\n result = closure.call(vals);\n }\n return result;\n }" ]
Gets or creates id of the entity type. @param entityType entity type name. @param allowCreate if set to true and if there is no entity type like entityType, create the new id for the entityType. @return entity type id.
[ "@Deprecated\n public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) {\n return getEntityTypeId(txnProvider, entityType, allowCreate);\n }" ]
[ "String getQueryString(Map<String, String> params) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\ttry {\n\t\t\tboolean first = true;\n\t\t\tfor (Map.Entry<String,String> entry : params.entrySet()) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tbuilder.append(\"&\");\n\t\t\t\t}\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getKey(), \"UTF-8\"));\n\t\t\t\tbuilder.append(\"=\");\n\t\t\t\tbuilder.append(URLEncoder.encode(entry.getValue(), \"UTF-8\"));\n\t\t\t}\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Your Java version does not support UTF-8 encoding.\");\n\t\t}\n\n\t\treturn builder.toString();\n\t}", "public void enable(ConduitSelectorHolder conduitSelectorHolder, SLPropertiesMatcher matcher,\n String selectionStrategy) {\n LocatorTargetSelector selector = new LocatorTargetSelector();\n selector.setEndpoint(conduitSelectorHolder.getConduitSelector().getEndpoint());\n\n String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy;\n \n LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy(actualStrategy);\n locatorSelectionStrategy.setServiceLocator(locatorClient);\n if (matcher != null) {\n locatorSelectionStrategy.setMatcher(matcher);\n }\n selector.setLocatorSelectionStrategy(locatorSelectionStrategy);\n\n if (LOG.isLoggable(Level.INFO)) {\n LOG.log(Level.INFO, \"Client enabled with strategy \"\n + locatorSelectionStrategy.getClass().getName() + \".\");\n }\n conduitSelectorHolder.setConduitSelector(selector);\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Successfully enabled client \" + conduitSelectorHolder\n + \" for the service locator\");\n }\n }", "public void addImportedPackages(Set<String> importedPackages) {\n\t\taddImportedPackages(importedPackages.toArray(new String[importedPackages.size()]));\n\t}", "private void readPattern(JSONObject patternJson) {\n\n setPatternType(readPatternType(patternJson));\n setInterval(readOptionalInt(patternJson, JsonKey.PATTERN_INTERVAL));\n setWeekDays(readWeekDays(patternJson));\n setDayOfMonth(readOptionalInt(patternJson, JsonKey.PATTERN_DAY_OF_MONTH));\n setEveryWorkingDay(readOptionalBoolean(patternJson, JsonKey.PATTERN_EVERYWORKINGDAY));\n setWeeksOfMonth(readWeeksOfMonth(patternJson));\n setIndividualDates(readDates(readOptionalArray(patternJson, JsonKey.PATTERN_DATES)));\n setMonth(readOptionalMonth(patternJson, JsonKey.PATTERN_MONTH));\n\n }", "private boolean fireEventWait(WebElement webElement, Eventable eventable)\n\t\t\tthrows ElementNotVisibleException, InterruptedException {\n\t\tswitch (eventable.getEventType()) {\n\t\t\tcase click:\n\t\t\t\ttry {\n\t\t\t\t\twebElement.click();\n\t\t\t\t} catch (ElementNotVisibleException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (WebDriverException e) {\n\t\t\t\t\tthrowIfConnectionException(e);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase hover:\n\t\t\t\tLOGGER.info(\"EventType hover called but this isn't implemented yet\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tLOGGER.info(\"EventType {} not supported in WebDriver.\", eventable.getEventType());\n\t\t\t\treturn false;\n\t\t}\n\n\t\tThread.sleep(this.crawlWaitEvent);\n\t\treturn true;\n\t}", "private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback,\n BeanDeployment deployment) {\n for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) {\n Class<?> enabledClass = iterator.next();\n if (globallyEnabledClasses.contains(enabledClass)) {\n logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId());\n iterator.remove();\n }\n }\n return enabledClasses;\n }", "public void disableAllOverrides(int pathID, String clientUUID) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ? \" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n statement.execute();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "public static void showOnlyChannels(Object... channels){\r\n for(LogRecordHandler handler : handlers){\r\n if(handler instanceof VisibilityHandler){\r\n VisibilityHandler visHandler = (VisibilityHandler) handler;\r\n visHandler.hideAll();\r\n for (Object channel : channels) {\r\n visHandler.alsoShow(channel);\r\n }\r\n }\r\n }\r\n }", "public double[] Kernel1D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n int r = size / 2;\n // kernel\n double[] kernel = new double[size];\n\n // compute kernel\n for (int x = -r, i = 0; i < size; x++, i++) {\n kernel[i] = Function1D(x);\n }\n\n return kernel;\n }" ]
Creates a replica of the node with the new partitions list @param node The node whose replica we are creating @param partitionsList The new partitions list @return Replica of node with new partitions list
[ "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 }" ]
[ "public void addWord(MtasCQLParserWordFullCondition w) throws ParseException {\n assert w.getCondition()\n .not() == false : \"condition word should be positive in sentence definition\";\n if (!simplified) {\n partList.add(w);\n } else {\n throw new ParseException(\"already simplified\");\n }\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 }", "private static void checkPreconditions(final String dateFormat, final Locale locale) {\n\t\tif( dateFormat == null ) {\n\t\t\tthrow new NullPointerException(\"dateFormat should not be null\");\n\t\t} else if( locale == null ) {\n\t\t\tthrow new NullPointerException(\"locale should not be null\");\n\t\t}\n\t}", "public static sslparameter get(nitro_service service) throws Exception{\n\t\tsslparameter obj = new sslparameter();\n\t\tsslparameter[] response = (sslparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "public static void setFaceNames(String[] nameArray)\n {\n if (nameArray.length != 6)\n {\n throw new IllegalArgumentException(\"nameArray length is not 6.\");\n }\n for (int i = 0; i < 6; i++)\n {\n faceIndexMap.put(nameArray[i], i);\n }\n }", "void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }", "public static PasswordSpec parse(String spec) {\n char[] ca = spec.toCharArray();\n int len = ca.length;\n illegalIf(0 == len, spec);\n Builder builder = new Builder();\n StringBuilder minBuf = new StringBuilder();\n StringBuilder maxBuf = new StringBuilder();\n boolean lenSpecStart = false;\n boolean minPart = false;\n for (int i = 0; i < len; ++i) {\n char c = ca[i];\n switch (c) {\n case SPEC_LOWERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireLowercase();\n break;\n case SPEC_UPPERCASE:\n illegalIf(lenSpecStart, spec);\n builder.requireUppercase();\n break;\n case SPEC_SPECIAL_CHAR:\n illegalIf(lenSpecStart, spec);\n builder.requireSpecialChar();\n break;\n case SPEC_LENSPEC_START:\n lenSpecStart = true;\n minPart = true;\n break;\n case SPEC_LENSPEC_CLOSE:\n illegalIf(minPart, spec);\n lenSpecStart = false;\n break;\n case SPEC_LENSPEC_SEP:\n minPart = false;\n break;\n case SPEC_DIGIT:\n if (!lenSpecStart) {\n builder.requireDigit();\n } else {\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n break;\n default:\n illegalIf(!lenSpecStart || !isDigit(c), spec);\n if (minPart) {\n minBuf.append(c);\n } else {\n maxBuf.append(c);\n }\n }\n }\n illegalIf(lenSpecStart, spec);\n if (minBuf.length() != 0) {\n builder.minLength(Integer.parseInt(minBuf.toString()));\n }\n if (maxBuf.length() != 0) {\n builder.maxLength(Integer.parseInt(maxBuf.toString()));\n }\n return builder;\n }", "public static int countNonZero(DMatrixRMaj A){\n int total = 0;\n for (int row = 0, index=0; row < A.numRows; row++) {\n for (int col = 0; col < A.numCols; col++,index++) {\n if( A.data[index] != 0 ) {\n total++;\n }\n }\n }\n return total;\n }", "public static Module createModule(final String name,final String version){\n final Module module = new Module();\n\n module.setName(name);\n module.setVersion(version);\n module.setPromoted(false);\n\n return module;\n\n }" ]
Returns a string representation of map of chunk id to number of chunks @return String of map of chunk id to number of chunks
[ "@JmxGetter(name = \"getChunkIdToNumChunks\", description = \"Returns a string representation of the map of chunk id to number of chunks\")\n public String getChunkIdToNumChunks() {\n StringBuilder builder = new StringBuilder();\n for(Entry<Object, Integer> entry: fileSet.getChunkIdToNumChunks().entrySet()) {\n builder.append(entry.getKey().toString() + \" - \" + entry.getValue().toString() + \", \");\n }\n return builder.toString();\n }" ]
[ "protected boolean isFirstVisit(Object expression) {\r\n if (visited.contains(expression)) {\r\n return false;\r\n }\r\n visited.add(expression);\r\n return true;\r\n }", "public int length() {\n int length = 1 + 2 + deviceToken.length + 2 + payload.length;\n final int marshalledLength = marshall().length;\n assert marshalledLength == length;\n return length;\n }", "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}", "public static void openLogFile() throws IOException\n {\n if (LOG_FILE != null)\n {\n System.out.println(\"SynchroLogger Configured\");\n LOG = new PrintWriter(new FileWriter(LOG_FILE));\n }\n }", "private boolean isAllNumeric(TokenStream stream) {\n List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();\n for(Token token:tokens) {\n try {\n Integer.parseInt(token.getText());\n } catch(NumberFormatException e) {\n return false;\n }\n }\n return true;\n }", "private List<String> getRotatedList(List<String> strings) {\n int index = RANDOM.nextInt(strings.size());\n List<String> rotated = new ArrayList<String>();\n for (int i = 0; i < strings.size(); i++) {\n rotated.add(strings.get(index));\n index = (index + 1) % strings.size();\n }\n return rotated;\n }", "public static sslcertkey_sslocspresponder_binding[] get(nitro_service service, String certkey) throws Exception{\n\t\tsslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding();\n\t\tobj.set_certkey(certkey);\n\t\tsslcertkey_sslocspresponder_binding response[] = (sslcertkey_sslocspresponder_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static int validateZone(CharSequence zone) {\n\t\tfor(int i = 0; i < zone.length(); i++) {\n\t\t\tchar c = zone.charAt(i);\n\t\t\tif (c == IPAddress.PREFIX_LEN_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tif (c == IPv6Address.SEGMENT_SEPARATOR) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}", "private String getActivityStatus(Task mpxj)\n {\n String result;\n if (mpxj.getActualStart() == null)\n {\n result = \"Not Started\";\n }\n else\n {\n if (mpxj.getActualFinish() == null)\n {\n result = \"In Progress\";\n }\n else\n {\n result = \"Completed\";\n }\n }\n return result;\n }" ]
Register the entity as batch loadable, if enabled Copied from {@link org.hibernate.type.ManyToOneType#scheduleBatchLoadIfNeeded}
[ "private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException {\n\t\t//cannot batch fetch by unique key (property-ref associations)\n\t\tif ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) {\n\t\t\tEntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() );\n\t\t\tEntityKey entityKey = session.generateEntityKey( id, persister );\n\t\t\tif ( !session.getPersistenceContext().containsEntity( entityKey ) ) {\n\t\t\t\tsession.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );\n\t\t\t}\n\t\t}\n\t}" ]
[ "@Override\n\tpublic Object getCurrentVersion(Serializable id, SharedSessionContractImplementor session) throws HibernateException {\n\n\t\tif ( log.isTraceEnabled() ) {\n\t\t\tlog.trace( \"Getting version: \" + MessageHelper.infoString( this, id, getFactory() ) );\n\t\t}\n\t\tfinal Tuple resultset = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );\n\n\t\tif ( resultset == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse {\n\t\t\treturn gridVersionType.nullSafeGet( resultset, getVersionColumnName(), session, null );\n\t\t}\n\t}", "public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase(\n String privKeyRelativePath, String passphrase) {\n this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);\n this.sshMeta.setPrivKeyUsePassphrase(true);\n this.sshMeta.setPassphrase(passphrase);\n this.sshMeta.setSshLoginType(SshLoginType.KEY);\n return this;\n }", "@UiHandler({\"m_atMonth\", \"m_everyMonth\"})\r\n void onMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setMonth(event.getValue());\r\n }\r\n }", "@SuppressWarnings(\"unchecked\")\n\tpublic Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException {\n\t\treturn decodeSignedRequest(signedRequest, Map.class);\n\t}", "public boolean checkKeyBelongsToNode(byte[] key, int nodeId) {\n List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();\n List<Integer> replicatingPartitions = getReplicatingPartitionList(key);\n // remove all partitions from the list, except those that belong to the\n // node\n replicatingPartitions.retainAll(nodePartitions);\n return replicatingPartitions.size() > 0;\n }", "public float getSphereBound(float[] sphere)\n {\n if ((sphere == null) || (sphere.length != 4) ||\n ((NativeVertexBuffer.getBoundingVolume(getNative(), sphere)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy sphere bound into array provided\");\n }\n return sphere[0];\n }", "protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }", "public ParallelTaskBuilder prepareSsh() {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.setProtocol(RequestProtocol.SSH);\n return cb;\n }", "private Cluster expandCluster(final Cluster cluster,\n final Point2D point,\n final List<Point2D> neighbors,\n final KDTree<Point2D> points,\n final Map<Point2D, PointStatus> visited) {\n cluster.addPoint(point);\n visited.put(point, PointStatus.PART_OF_CLUSTER);\n\n List<Point2D> seeds = new ArrayList<Point2D>(neighbors);\n int index = 0;\n while (index < seeds.size()) {\n Point2D current = seeds.get(index);\n PointStatus pStatus = visited.get(current);\n // only check non-visited points\n if (pStatus == null) {\n final List<Point2D> currentNeighbors = getNeighbors(current, points);\n if (currentNeighbors.size() >= minPoints) {\n seeds = merge(seeds, currentNeighbors);\n }\n }\n\n if (pStatus != PointStatus.PART_OF_CLUSTER) {\n visited.put(current, PointStatus.PART_OF_CLUSTER);\n cluster.addPoint(current);\n }\n\n index++;\n }\n return cluster;\n }" ]
Callback from the worker when it terminates
[ "private void stopDone() {\n synchronized (stopLock) {\n final StopContext stopContext = this.stopContext;\n this.stopContext = null;\n if (stopContext != null) {\n stopContext.complete();\n }\n stopLock.notifyAll();\n }\n }" ]
[ "private static JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\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}", "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 }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\n }", "public static String getTabularData(String[] labels, String[][] data, int padding) {\n int[] size = new int[labels.length];\n \n for (int i = 0; i < labels.length; i++) {\n size[i] = labels[i].length() + padding;\n }\n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n if (row[i].length() >= size[i]) {\n size[i] = row[i].length() + padding;\n }\n }\n }\n \n StringBuffer tabularData = new StringBuffer();\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(labels[i]);\n tabularData.append(fill(' ', size[i] - labels[i].length()));\n }\n \n tabularData.append(\"\\n\");\n \n for (int i = 0; i < labels.length; i++) {\n tabularData.append(fill('=', size[i] - 1)).append(\" \");\n }\n \n tabularData.append(\"\\n\");\n \n \n for (String[] row : data) {\n for (int i = 0; i < labels.length; i++) {\n tabularData.append(row[i]);\n tabularData.append(fill(' ', size[i] - row[i].length()));\n }\n \n tabularData.append(\"\\n\");\n }\n \n return tabularData.toString();\n }", "public static IntRange GetRange( int[] values, double percent ){\n int total = 0, n = values.length;\n\n // for all values\n for ( int i = 0; i < n; i++ )\n {\n // accumalate total\n total += values[i];\n }\n\n int min, max, hits;\n int h = (int) ( total * ( percent + ( 1 - percent ) / 2 ) );\n\n // get range min value\n for ( min = 0, hits = total; min < n; min++ )\n {\n hits -= values[min];\n if ( hits < h )\n break;\n }\n // get range max value\n for ( max = n - 1, hits = total; max >= 0; max-- )\n {\n hits -= values[max];\n if ( hits < h )\n break;\n }\n return new IntRange( min, max );\n }", "public static synchronized FormInputValueHelper getInstance(\n\t\t\tInputSpecification inputSpecification, FormFillMode formFillMode) {\n\t\tif (instance == null)\n\t\t\tinstance = new FormInputValueHelper(inputSpecification,\n\t\t\t\t\tformFillMode);\n\t\treturn instance;\n\t}", "public static base_responses expire(nitro_service client, cachecontentgroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcachecontentgroup expireresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texpireresources[i] = new cachecontentgroup();\n\t\t\t\texpireresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, expireresources,\"expire\");\n\t\t}\n\t\treturn result;\n\t}", "public double nextDouble(double lo, double hi) {\n if (lo < 0) {\n if (nextInt(2) == 0)\n return -nextDouble(0, -lo);\n else\n return nextDouble(0, hi);\n } else {\n return (lo + (hi - lo) * nextDouble());\n }\n }" ]
Checks the foreignkeys of all collections in the model. @param modelDef The model @param checkLevel The current check level (this constraint is checked in basic and strict) @exception ConstraintException If the value for foreignkey is invalid
[ "private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n ClassDescriptorDef classDef;\r\n CollectionDescriptorDef collDef;\r\n\r\n for (Iterator it = modelDef.getClasses(); it.hasNext();)\r\n {\r\n classDef = (ClassDescriptorDef)it.next();\r\n for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)\r\n {\r\n collDef = (CollectionDescriptorDef)collIt.next();\r\n if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))\r\n {\r\n checkIndirectionTable(modelDef, collDef);\r\n }\r\n else\r\n { \r\n checkCollectionForeignkeys(modelDef, collDef);\r\n }\r\n }\r\n }\r\n }\r\n }" ]
[ "private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef)\r\n {\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName());\r\n\r\n if ((curCollDef != null) &&\r\n !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "protected Iterable<URI> getTargetURIs(final EObject primaryTarget) {\n\t\tfinal TargetURIs result = targetURIsProvider.get();\n\t\turiCollector.add(primaryTarget, result);\n\t\treturn result;\n\t}", "public void hide() {\n div.removeFromParent();\n if (scrollDisabled) {\n RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.AUTO);\n }\n if (type == LoaderType.CIRCULAR) {\n preLoader.removeFromParent();\n } else if (type == LoaderType.PROGRESS) {\n progress.removeFromParent();\n }\n }", "@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\n }", "private String generateValue() {\r\n\r\n String result = \"\";\r\n for (CmsCheckBox checkbox : m_checkboxes) {\r\n if (checkbox.isChecked()) {\r\n result += checkbox.getInternalValue() + \",\";\r\n }\r\n }\r\n if (result.contains(\",\")) {\r\n result = result.substring(0, result.lastIndexOf(\",\"));\r\n }\r\n return result;\r\n }", "private AirMapViewBuilder getWebMapViewBuilder() {\n if (context != null) {\n try {\n ApplicationInfo ai = context.getPackageManager()\n .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);\n Bundle bundle = ai.metaData;\n String accessToken = bundle.getString(\"com.mapbox.ACCESS_TOKEN\");\n String mapId = bundle.getString(\"com.mapbox.MAP_ID\");\n\n if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(mapId)) {\n return new MapboxWebMapViewBuilder(accessToken, mapId);\n }\n } catch (PackageManager.NameNotFoundException e) {\n Log.e(TAG, \"Failed to load Mapbox access token and map id\", e);\n }\n }\n return new WebAirMapViewBuilder();\n }", "public ApnsServiceBuilder withSocksProxy(String host, int port) {\n Proxy proxy = new Proxy(Proxy.Type.SOCKS,\n new InetSocketAddress(host, port));\n return withProxy(proxy);\n }", "public static String getImageIdFromAgent(Launcher launcher, final String imageTag, final String host) throws IOException, InterruptedException {\n return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {\n public String call() throws IOException {\n return DockerUtils.getImageIdFromTag(imageTag, host);\n }\n });\n }", "public float rotateToFaceCamera(final Widget widget) {\n final float yaw = getMainCameraRigYaw();\n GVRTransform t = getMainCameraRig().getHeadTransform();\n widget.rotateWithPivot(t.getRotationW(), 0, t.getRotationY(), 0, 0, 0, 0);\n return yaw;\n }" ]
Mapping message info. @param messageInfo the message info @return the message info type
[ "private static MessageInfoType mapMessageInfo(MessageInfo messageInfo) {\n if (messageInfo == null) {\n return null;\n }\n MessageInfoType miType = new MessageInfoType();\n miType.setMessageId(messageInfo.getMessageId());\n miType.setFlowId(messageInfo.getFlowId());\n miType.setPorttype(convertString(messageInfo.getPortType()));\n miType.setOperationName(messageInfo.getOperationName());\n miType.setTransport(messageInfo.getTransportType());\n return miType;\n }" ]
[ "public void add(K key, V value) {\r\n if (treatCollectionsAsImmutable) {\r\n Collection<V> newC = cf.newCollection();\r\n Collection<V> c = map.get(key);\r\n if (c != null) {\r\n newC.addAll(c);\r\n }\r\n newC.add(value);\r\n map.put(key, newC); // replacing the old collection\r\n } else {\r\n Collection<V> c = map.get(key);\r\n if (c == null) {\r\n c = cf.newCollection();\r\n map.put(key, c);\r\n }\r\n c.add(value); // modifying the old collection\r\n }\r\n }", "PollingState<T> withResponse(Response<ResponseBody> response) {\n this.response = response;\n withPollingUrlFromResponse(response);\n withPollingRetryTimeoutFromResponse(response);\n return this;\n }", "public static int getActionBarHeight(Context context) {\n int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);\n if (actionBarHeight == 0) {\n actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);\n }\n return actionBarHeight;\n }", "public static ResourceResolutionContext context(ResourceResolutionComponent[] components,\n Map<String, Object> messageParams) {\n return new ResourceResolutionContext(components, messageParams);\n }", "private List<Object> convertType(DataType type, byte[] data)\n {\n List<Object> result = new ArrayList<Object>();\n int index = 0;\n\n while (index < data.length)\n {\n switch (type)\n {\n case STRING:\n {\n String value = MPPUtility.getUnicodeString(data, index);\n result.add(value);\n index += ((value.length() + 1) * 2);\n break;\n }\n\n case CURRENCY:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index) / 100);\n result.add(value);\n index += 8;\n break;\n }\n\n case NUMERIC:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index));\n result.add(value);\n index += 8;\n break;\n }\n\n case DATE:\n {\n Date value = MPPUtility.getTimestamp(data, index);\n result.add(value);\n index += 4;\n break;\n\n }\n\n case DURATION:\n {\n TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, index + 4), m_properties.getDefaultDurationUnits());\n Duration value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(data, index), units);\n result.add(value);\n index += 6;\n break;\n }\n\n case BOOLEAN:\n {\n Boolean value = Boolean.valueOf(MPPUtility.getShort(data, index) == 1);\n result.add(value);\n index += 2;\n break;\n }\n\n default:\n {\n index = data.length;\n break;\n }\n }\n }\n\n return result;\n }", "protected boolean check(String value, String regex) {\n\t\tPattern pattern = Pattern.compile(regex);\n\t\treturn pattern.matcher(value).matches();\n\t}", "private int getCacheKey(InputDevice device, GVRControllerType controllerType) {\n if (controllerType != GVRControllerType.UNKNOWN &&\n controllerType != GVRControllerType.EXTERNAL) {\n // Sometimes a device shows up using two device ids\n // here we try to show both devices as one using the\n // product and vendor id\n\n int key = device.getVendorId();\n key = 31 * key + device.getProductId();\n key = 31 * key + controllerType.hashCode();\n\n return key;\n }\n return -1; // invalid key\n }", "public String getAuthorizationUri(final String redirectUri, final Set<String> scopes, final String state) {\n if (account == null)\n throw new IllegalArgumentException(\"Auth is not set\");\n if (account.getClientId() == null)\n throw new IllegalArgumentException(\"client_id is not set\");\n StringBuilder builder = new StringBuilder();\n builder.append(URI_AUTHENTICATION);\n builder.append(\"?\");\n builder.append(\"response_type=\");\n builder.append(encode(\"code\"));\n builder.append(\"&redirect_uri=\");\n builder.append(encode(redirectUri));\n builder.append(\"&client_id=\");\n builder.append(encode(account.getClientId()));\n builder.append(\"&scope=\");\n builder.append(encode(getScopesString(scopes)));\n builder.append(\"&state=\");\n builder.append(encode(state));\n builder.append(\"&code_challenge\");\n builder.append(getCodeChallenge()); // Already url encoded\n builder.append(\"&code_challenge_method=\");\n builder.append(encode(\"S256\"));\n return builder.toString();\n }", "public static void removeColumns( DMatrixRMaj A , int col0 , int col1 )\n {\n if( col1 < col0 ) {\n throw new IllegalArgumentException(\"col1 must be >= col0\");\n } else if( col0 >= A.numCols || col1 >= A.numCols ) {\n throw new IllegalArgumentException(\"Columns which are to be removed must be in bounds\");\n }\n\n int step = col1-col0+1;\n int offset = 0;\n for (int row = 0, idx=0; row < A.numRows; row++) {\n for (int i = 0; i < col0; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n offset += step;\n for (int i = col1+1; i < A.numCols; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n }\n A.numCols -= step;\n }" ]
>>>>>> measureUntilFull helper methods
[ "protected int getCenterChild(CacheDataSet cache) {\n if (cache.count() == 0)\n return -1;\n\n int id = cache.getId(0);\n switch (getGravityInternal()) {\n case TOP:\n case LEFT:\n case FRONT:\n case FILL:\n break;\n case BOTTOM:\n case RIGHT:\n case BACK:\n id = cache.getId(cache.count() - 1);\n break;\n case CENTER:\n int i = cache.count() / 2;\n while (i < cache.count() && i >= 0) {\n id = cache.getId(i);\n if (cache.getStartDataOffset(id) <= 0) {\n if (cache.getEndDataOffset(id) >= 0) {\n break;\n } else {\n i++;\n }\n } else {\n i--;\n }\n }\n break;\n default:\n break;\n }\n\n Log.d(LAYOUT, TAG, \"getCenterChild = %d \", id);\n return id;\n }" ]
[ "public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }", "public static void acceptsFile(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_F, OPT_FILE), \"file path for input/output\")\n .withRequiredArg()\n .describedAs(\"file-path\")\n .ofType(String.class);\n }", "public List<Class<?>> scanClasses(Predicate<String> filter)\n {\n List<Class<?>> discoveredClasses = new ArrayList<>(128);\n\n // For each Forge addon...\n for (Addon addon : furnace.getAddonRegistry().getAddons(AddonFilters.allStarted()))\n {\n List<String> discoveredFileNames = filterAddonResources(addon, filter);\n\n // Then try to load the classes.\n for (String discoveredFilename : discoveredFileNames)\n {\n String clsName = PathUtil.classFilePathToClassname(discoveredFilename);\n try\n {\n Class<?> clazz = addon.getClassLoader().loadClass(clsName);\n discoveredClasses.add(clazz);\n }\n catch (ClassNotFoundException ex)\n {\n LOG.log(Level.WARNING, \"Failed to load class for name '\" + clsName + \"':\\n\" + ex.getMessage(), ex);\n }\n }\n }\n return discoveredClasses;\n }", "private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }", "public EventBus emitAsync(String event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }", "private void validateAttributesToCreateANewRendererViewHolder() {\n if (viewType == null) {\n throw new NullContentException(\n \"RendererBuilder needs a view type to create a RendererViewHolder\");\n }\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\");\n }\n if (parent == null) {\n throw new NullParentException(\n \"RendererBuilder needs a parent to create a RendererViewHolder\");\n }\n }", "public void rotateToFaceCamera(final GVRTransform transform) {\n //see http://stackoverflow.com/questions/5782658/extracting-yaw-from-a-quaternion\n final GVRTransform t = getMainCameraRig().getHeadTransform();\n final Quaternionf q = new Quaternionf(0, t.getRotationY(), 0, t.getRotationW()).normalize();\n\n transform.rotateWithPivot(q.w, q.x, q.y, q.z, 0, 0, 0);\n }", "@Override\n public void close() {\n if (closed)\n return;\n closed = true;\n tcpSocketConsumer.prepareToShutdown();\n\n if (shouldSendCloseMessage)\n\n eventLoop.addHandler(new EventHandler() {\n @Override\n public boolean action() throws InvalidEventHandlerException {\n try {\n TcpChannelHub.this.sendCloseMessage();\n tcpSocketConsumer.stop();\n closed = true;\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"closing connection to \" + socketAddressSupplier);\n\n while (clientChannel != null) {\n\n if (LOG.isDebugEnabled())\n Jvm.debug().on(getClass(), \"waiting for disconnect to \" + socketAddressSupplier);\n }\n } catch (ConnectionDroppedException e) {\n throw new InvalidEventHandlerException(e);\n }\n\n // we just want this to run once\n throw new InvalidEventHandlerException();\n }\n\n @NotNull\n @Override\n public String toString() {\n return TcpChannelHub.class.getSimpleName() + \"..close()\";\n }\n });\n }", "private String getDateString(Date value)\n {\n Calendar cal = DateHelper.popCalendar(value);\n int year = cal.get(Calendar.YEAR);\n int month = cal.get(Calendar.MONTH) + 1;\n int day = cal.get(Calendar.DAY_OF_MONTH);\n DateHelper.pushCalendar(cal);\n \n StringBuilder sb = new StringBuilder(8);\n sb.append(m_fourDigitFormat.format(year));\n sb.append(m_twoDigitFormat.format(month));\n sb.append(m_twoDigitFormat.format(day));\n\n return (sb.toString());\n }" ]
Create a new instance of a two input function from an operator character @param op Which operation @param left Input variable on left @param right Input variable on right @return Resulting operation
[ "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 static base_response unset(nitro_service client, csparameter resource, String[] args) throws Exception{\n\t\tcsparameter unsetresource = new csparameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static DMatrixRMaj insideSpan(DMatrixRMaj[] span , double min , double max , Random rand ) {\n DMatrixRMaj A = new DMatrixRMaj(span.length,1);\n\n DMatrixRMaj B = new DMatrixRMaj(span[0].getNumElements(),1);\n\n for( int i = 0; i < span.length; i++ ) {\n B.set(span[i]);\n double val = rand.nextDouble()*(max-min)+min;\n CommonOps_DDRM.scale(val,B);\n\n CommonOps_DDRM.add(A,B,A);\n\n }\n\n return A;\n }", "private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) {\n ImmutableSet.Builder<Type> types = ImmutableSet.builder();\n // session beans\n Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>();\n HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass());\n for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) {\n // first we need to resolve the local interface\n Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface()));\n SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface);\n if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) {\n // WELD-1675 Only add types also included in Annotated.getTypeClosure()\n for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) {\n if (annotated.getTypeClosure().contains(entry.getValue())) {\n typeMap.put(entry.getKey(), entry.getValue());\n }\n }\n } else {\n // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class\n typeMap.putAll(interfaceDiscovery.getTypeMap());\n }\n }\n if (annotated.isAnnotationPresent(Typed.class)) {\n types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class)));\n } else {\n typeMap.put(Object.class, Object.class);\n types.addAll(typeMap.values());\n }\n return Beans.getLegalBeanTypes(types.build(), annotated);\n }", "public 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 }", "public static <T> Set<T> getSet(Collection<T> collection) {\n Set<T> set = new LinkedHashSet<T>();\n set.addAll(collection);\n\n return set;\n }", "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 void setBaseCalendar(String val)\n {\n set(ResourceField.BASE_CALENDAR, val == null || val.length() == 0 ? \"Standard\" : val);\n }", "public static <T> T notNull(T argument, String argumentName) {\n if (argument == null) {\n throw new IllegalArgumentException(\"Argument \" + argumentName + \" must not be null.\");\n }\n return argument;\n }", "@SuppressWarnings(\"SameParameterValue\")\n private void sendField(Field field) throws IOException {\n if (isConnected()) {\n try {\n field.write(channel);\n } catch (IOException e) {\n logger.warn(\"Problem trying to write field to dbserver, closing connection\", e);\n close();\n throw e;\n }\n return;\n }\n throw new IOException(\"sendField() called after dbserver connection was closed\");\n }" ]
Use this API to enable Interface of given name.
[ "public static base_response enable(nitro_service client, String id) throws Exception {\n\t\tInterface enableresource = new Interface();\n\t\tenableresource.id = id;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}" ]
[ "protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException {\r\n\t\tboolean tryAgain = false;\r\n\t\tConnection result = null;\r\n\t\tConnection oldRawConnection = connectionHandle.getInternalConnection();\r\n\t\tString url = this.getConfig().getJdbcUrl();\r\n\t\t\r\n\t\tint acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts();\r\n\t\tlong acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs();\r\n\t\tAcquireFailConfig acquireConfig = new AcquireFailConfig();\r\n\t\tacquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));\r\n\t\tacquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs);\r\n\t\tacquireConfig.setLogMessage(\"Failed to acquire connection to \"+url);\r\n\t\tConnectionHook connectionHook = this.getConfig().getConnectionHook();\r\n\t\tdo{ \r\n\t\t\tresult = null;\r\n\t\t\ttry { \r\n\t\t\t\t// keep track of this hook.\r\n\t\t\t\tresult = this.obtainRawInternalConnection();\r\n\t\t\t\ttryAgain = false;\r\n\r\n\t\t\t\tif (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){\r\n\t\t\t\t\tlogger.info(\"Successfully re-established connection to \"+url);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tthis.getDbIsDown().set(false);\r\n\t\t\t\t\r\n\t\t\t\tconnectionHandle.setInternalConnection(result);\r\n\t\t\t\t\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\tconnectionHook.onAcquire(connectionHandle);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t\tConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL());\r\n\t\t\t} catch (SQLException e) {\r\n\t\t\t\t// call the hook, if available.\r\n\t\t\t\tif (connectionHook != null){\r\n\t\t\t\t\ttryAgain = connectionHook.onAcquireFail(e, acquireConfig);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlogger.error(String.format(\"Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d\", url, acquireRetryDelayInMs, acquireRetryAttempts), e);\r\n\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (acquireRetryAttempts > 0){\r\n\t\t\t\t\t\t\tThread.sleep(acquireRetryDelayInMs);\r\n\t \t\t\t\t\t}\r\n\t\t\t\t\t\ttryAgain = (acquireRetryAttempts--) > 0;\r\n\t\t\t\t\t} catch (InterruptedException e1) {\r\n\t\t\t\t\t\ttryAgain=false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (!tryAgain){\r\n\t\t\t\t\tif (oldRawConnection != null) {\r\n\t\t\t\t\t\toldRawConnection.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (result != null) {\r\n\t\t\t\t\t\tresult.close();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconnectionHandle.setInternalConnection(oldRawConnection);\r\n\t\t\t\t\tthrow e;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} while (tryAgain);\r\n\r\n\t\treturn result;\r\n\r\n\t}", "public Slice newSlice(long address, int size)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, 0, null);\n }", "public static void append(File file, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new FileWriter(file, true);\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }", "public TransactionImpl getCurrentTransaction()\r\n {\r\n TransactionImpl tx = tx_table.get(Thread.currentThread());\r\n if(tx == null)\r\n {\r\n throw new TransactionNotInProgressException(\"Calling method needed transaction, but no transaction found for current thread :-(\");\r\n }\r\n return tx;\r\n }", "public static String readUntilTag(Reader r) throws IOException {\r\n if (!r.ready()) {\r\n return \"\";\r\n }\r\n StringBuilder b = new StringBuilder();\r\n int c = r.read();\r\n while (c >= 0 && c != '<') {\r\n b.append((char) c);\r\n c = r.read();\r\n }\r\n return b.toString();\r\n }", "private String hibcProcess(String source) {\n\n // HIBC 2.6 allows up to 110 characters, not including the \"+\" prefix or the check digit\n if (source.length() > 110) {\n throw new OkapiException(\"Data too long for HIBC LIC\");\n }\n\n source = source.toUpperCase();\n if (!source.matches(\"[A-Z0-9-\\\\. \\\\$/+\\\\%]+?\")) {\n throw new OkapiException(\"Invalid characters in input\");\n }\n\n int counter = 41;\n for (int i = 0; i < source.length(); i++) {\n counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);\n }\n counter = counter % 43;\n\n char checkDigit = HIBC_CHAR_TABLE[counter];\n\n encodeInfo += \"HIBC Check Digit Counter: \" + counter + \"\\n\";\n encodeInfo += \"HIBC Check Digit: \" + checkDigit + \"\\n\";\n\n return \"+\" + source + checkDigit;\n }", "public static vpnclientlessaccesspolicy[] get(nitro_service service) throws Exception{\n\t\tvpnclientlessaccesspolicy obj = new vpnclientlessaccesspolicy();\n\t\tvpnclientlessaccesspolicy[] response = (vpnclientlessaccesspolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }", "@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformPreview> getLoadedPreviews() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformPreview>(previewHotCache));\n }" ]
Use this API to fetch lbvserver_filterpolicy_binding resources of given name .
[ "public static lbvserver_filterpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_filterpolicy_binding obj = new lbvserver_filterpolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_filterpolicy_binding response[] = (lbvserver_filterpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public HiveShellContainer evaluateStatement(List<? extends Script> scripts, Object target, TemporaryFolder temporaryFolder, Statement base) throws Throwable {\n container = null;\n FileUtil.setPermission(temporaryFolder.getRoot(), FsPermission.getDirDefault());\n try {\n LOGGER.info(\"Setting up {} in {}\", getName(), temporaryFolder.getRoot().getAbsolutePath());\n container = createHiveServerContainer(scripts, target, temporaryFolder);\n base.evaluate();\n return container;\n } finally {\n tearDown();\n }\n }", "protected List<BoxAPIResponse> parseResponse(BoxJSONResponse batchResponse) {\n JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON());\n List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>();\n Iterator<JsonValue> responseIterator = responseJSON.get(\"responses\").asArray().iterator();\n while (responseIterator.hasNext()) {\n JsonObject jsonResponse = responseIterator.next().asObject();\n BoxAPIResponse response = null;\n\n //Gather headers\n Map<String, String> responseHeaders = new HashMap<String, String>();\n\n if (jsonResponse.get(\"headers\") != null) {\n JsonObject batchResponseHeadersObject = jsonResponse.get(\"headers\").asObject();\n for (JsonObject.Member member : batchResponseHeadersObject) {\n String headerName = member.getName();\n String headerValue = member.getValue().asString();\n responseHeaders.put(headerName, headerValue);\n }\n }\n\n // Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response\n // (not anticipating any other response as per current APIs.\n // Ideally we should do it based on response header)\n if (jsonResponse.get(\"response\") == null || jsonResponse.get(\"response\").isNull()) {\n response =\n new BoxAPIResponse(jsonResponse.get(\"status\").asInt(), responseHeaders);\n } else {\n response =\n new BoxJSONResponse(jsonResponse.get(\"status\").asInt(), responseHeaders,\n jsonResponse.get(\"response\").asObject());\n }\n responses.add(response);\n }\n return responses;\n }", "public void addRequiredBundles(Set<String> bundles) {\n\t\t// TODO manage transitive dependencies\n\t\t// don't require self\n\t\tSet<String> bundlesToMerge;\n\t\tString bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);\n\t\tif (bundleName != null) {\n\t\t\tint idx = bundleName.indexOf(';');\n\t\t\tif (idx >= 0) {\n\t\t\t\tbundleName = bundleName.substring(0, idx);\n\t\t\t}\n\t\t}\n\t\tif (bundleName != null && bundles.contains(bundleName)\n\t\t\t\t|| projectName != null && bundles.contains(projectName)) {\n\t\t\tbundlesToMerge = new LinkedHashSet<String>(bundles);\n\t\t\tbundlesToMerge.remove(bundleName);\n\t\t\tbundlesToMerge.remove(projectName);\n\t\t} else {\n\t\t\tbundlesToMerge = bundles;\n\t\t}\n\t\tString s = (String) getMainAttributes().get(REQUIRE_BUNDLE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(REQUIRE_BUNDLE, result);\n\t}", "public String createTorqueSchema(Properties attributes) throws XDocletException\r\n {\r\n String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME);\r\n\r\n _torqueModel = new TorqueModelDef(dbName, _model);\r\n return \"\";\r\n }", "public static String writeSingleClientConfigAvro(Properties props) {\n // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json...\n String avroConfig = \"\";\n Boolean firstProp = true;\n for(String key: props.stringPropertyNames()) {\n if(firstProp) {\n firstProp = false;\n } else {\n avroConfig = avroConfig + \",\\n\";\n }\n avroConfig = avroConfig + \"\\t\\t\\\"\" + key + \"\\\": \\\"\" + props.getProperty(key) + \"\\\"\";\n }\n if(avroConfig.isEmpty()) {\n return \"{}\";\n } else {\n return \"{\\n\" + avroConfig + \"\\n\\t}\";\n }\n }", "private Priority getPriority(Integer gpPriority)\n {\n int result;\n if (gpPriority == null)\n {\n result = Priority.MEDIUM;\n }\n else\n {\n int index = gpPriority.intValue();\n if (index < 0 || index >= PRIORITY.length)\n {\n result = Priority.MEDIUM;\n }\n else\n {\n result = PRIORITY[index];\n }\n }\n return Priority.getInstance(result);\n }", "public static void moveBandsElemnts(int yOffset, JRDesignBand band) {\n\t\tif (band == null)\n\t\t\treturn;\n\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\telem.setY(elem.getY() + yOffset);\n\t\t}\n\t}", "public ParallelTaskBuilder setTargetHostsFromLineByLineText(\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath,\n sourceType);\n return this;\n }", "public static void dumpAnalysisToFile(String outputDirName,\n String baseFileName,\n PartitionBalance partitionBalance) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, baseFileName + \".analysis\"),\n partitionBalance.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpAnalysisToFile: \" + e);\n }\n }\n }" ]
Get the error message with the dependencies appended @param dependencies - the list with dependencies to be attached to the message @param message - the custom error message to be displayed to the user @return String
[ "private static String buildErrorMsg(List<String> dependencies, String message) {\n final StringBuilder buffer = new StringBuilder();\n boolean isFirstElement = true;\n for (String dependency : dependencies) {\n if (!isFirstElement) {\n buffer.append(\", \");\n }\n // check if it is an instance of Artifact - add the gavc else append the object\n buffer.append(dependency);\n\n isFirstElement = false;\n }\n return String.format(message, buffer.toString());\n }" ]
[ "protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }", "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}", "@Override\n public Integer getMasterPartition(byte[] key) {\n return abs(hash.hash(key)) % (Math.max(1, this.partitionToNode.length));\n }", "private StringBuilder calculateCacheKeyInternal(String sql,\r\n\t\t\tint resultSetType, int resultSetConcurrency) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+20);\r\n\t\ttmp.append(sql);\r\n\r\n\t\ttmp.append(\", T\");\r\n\t\ttmp.append(resultSetType);\r\n\t\ttmp.append(\", C\");\r\n\t\ttmp.append(resultSetConcurrency);\r\n\t\treturn tmp;\r\n\t}", "List getOrderby()\r\n {\r\n List result = _getOrderby();\r\n Iterator iter = getCriteria().iterator();\r\n Object crit;\r\n\r\n while (iter.hasNext())\r\n {\r\n crit = iter.next();\r\n if (crit instanceof Criteria)\r\n {\r\n result.addAll(((Criteria) crit).getOrderby());\r\n }\r\n }\r\n\r\n return result;\r\n }", "public List<BuildpackInstallation> listBuildpackInstallations(String appName) {\n return connection.execute(new BuildpackInstallationList(appName), apiKey);\n }", "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 }", "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 Set<String> rangeByScoreReverse(final ScoreRange scoreRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (scoreRange.hasLimit()) {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse(), scoreRange.offset(), scoreRange.count());\n } else {\n return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse());\n }\n }\n });\n }" ]
Attaches locale groups to the copied page. @param copiedPage the copied page. @throws CmsException thrown if the root cms cannot be retrieved.
[ "private void attachLocaleGroups(CmsResource copiedPage) throws CmsException {\n\n CmsLocaleGroupService localeGroupService = getRootCms().getLocaleGroupService();\n if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) {\n try {\n localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n }" ]
[ "public static authenticationradiuspolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnglobal_binding obj = new authenticationradiuspolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnglobal_binding response[] = (authenticationradiuspolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }", "private void initDatesPanel() {\n\n m_startLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_STARTTIME_0));\n m_startTime.setAllowInvalidValue(true);\n m_startTime.setValue(m_model.getStart());\n m_endLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_TIME_ENDTIME_0));\n m_endTime.setAllowInvalidValue(true);\n m_endTime.setValue(m_model.getEnd());\n m_seriesCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_SERIES_CHECKBOX_0));\n m_wholeDayCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_WHOLE_DAY_CHECKBOX_0));\n m_currentTillEndCheckBox.setText(Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_0));\n m_currentTillEndCheckBox.getButton().setTitle(\n Messages.get().key(Messages.GUI_SERIALDATE_CURRENT_TILL_END_CHECKBOX_HELP_0));\n }", "public static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) {\n Map<String, List<String>> ret = new HashMap<String, List<String>>();\n for (String topic : topics) {\n List<String> partList = new ArrayList<String>();\n List<String> brokers = getChildrenParentMayNotExist(zkClient, BrokerTopicsPath + \"/\" + topic);\n if (brokers != null) {\n for (String broker : brokers) {\n final String parts = readData(zkClient, BrokerTopicsPath + \"/\" + topic + \"/\" + broker);\n int nParts = Integer.parseInt(parts);\n for (int i = 0; i < nParts; i++) {\n partList.add(broker + \"-\" + i);\n }\n }\n }\n Collections.sort(partList);\n ret.put(topic, partList);\n }\n return ret;\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static byte checkByte(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInByteRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);\n\t\t}\n\n\t\treturn number.byteValue();\n\t}", "private void serializeEPR(EndpointReferenceType wsAddr, Node parent) throws ServiceLocatorException {\n try {\n JAXBElement<EndpointReferenceType> ep =\n WSA_OBJECT_FACTORY.createEndpointReference(wsAddr);\n createMarshaller().marshal(ep, parent);\n } catch (JAXBException e) {\n if (LOG.isLoggable(Level.SEVERE)) {\n LOG.log(Level.SEVERE,\n \"Failed to serialize endpoint data\", e);\n }\n throw new ServiceLocatorException(\"Failed to serialize endpoint data\", e);\n }\n }", "public void handleStateEvent(String callbackKey) {\n if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {\n ((StateEventHandler) handlers.get(callbackKey)).handle();\n } else {\n System.err.println(\"Error in handle: \" + callbackKey + \" for state handler \");\n }\n }", "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 CmsContextMenu getContextMenuForItem(Object itemId) {\n\n CmsContextMenu result = null;\n try {\n final Item item = m_container.getItem(itemId);\n Property<?> keyProp = item.getItemProperty(TableProperty.KEY);\n String key = (String)keyProp.getValue();\n if ((null != key) && !key.isEmpty()) {\n loadAllRemainingLocalizations();\n final Map<Locale, String> localesWithEntries = new HashMap<Locale, String>();\n for (Locale l : m_localizations.keySet()) {\n if (l != m_locale) {\n String value = m_localizations.get(l).getProperty(key);\n if ((null != value) && !value.isEmpty()) {\n localesWithEntries.put(l, value);\n }\n }\n }\n if (!localesWithEntries.isEmpty()) {\n result = new CmsContextMenu();\n ContextMenuItem mainItem = result.addItem(\n Messages.get().getBundle(UI.getCurrent().getLocale()).key(\n Messages.GUI_BUNDLE_EDITOR_CONTEXT_COPY_LOCALE_0));\n for (final Locale l : localesWithEntries.keySet()) {\n\n ContextMenuItem menuItem = mainItem.addItem(l.getDisplayName(UI.getCurrent().getLocale()));\n menuItem.addItemClickListener(new ContextMenuItemClickListener() {\n\n public void contextMenuItemClicked(ContextMenuItemClickEvent event) {\n\n item.getItemProperty(TableProperty.TRANSLATION).setValue(localesWithEntries.get(l));\n\n }\n });\n }\n }\n }\n } catch (Exception e) {\n LOG.error(e.getLocalizedMessage(), e);\n //TODO: Improve\n }\n return result;\n }" ]
Acquire the exclusive lock, with a max wait timeout to acquire. @param permit - the permit Integer for this operation. May not be {@code null}. @param timeout - the timeout scalar quantity. @param unit - see {@code TimeUnit} for quantities. @return {@code boolean} true on successful acquire. @throws InterruptedException - if the acquiring thread was interrupted. @throws IllegalArgumentException if {@code permit} is null.
[ "boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireNanos(permit, unit.toNanos(timeout));\n }" ]
[ "public static String dump(final int displayOffset, final byte[] data, final int offset, final int len)\n {\n StringBuilder sb = new StringBuilder();\n Formatter formatter = new Formatter(sb);\n StringBuilder ascii = new StringBuilder();\n\n int dataNdx = offset;\n final int maxDataNdx = offset + len;\n final int lines = (len + 16) / 16;\n for (int i = 0; i < lines; i++) {\n ascii.append(\" |\");\n formatter.format(\"%08x \", displayOffset + (i * 16));\n\n for (int j = 0; j < 16; j++) {\n if (dataNdx < maxDataNdx) {\n byte b = data[dataNdx++];\n formatter.format(\"%02x \", b);\n ascii.append((b > MIN_VISIBLE && b < MAX_VISIBLE) ? (char) b : ' ');\n }\n else {\n sb.append(\" \");\n }\n\n if (j == 7) {\n sb.append(' ');\n }\n }\n\n ascii.append('|');\n sb.append(ascii).append('\\n');\n ascii.setLength(0);\n }\n\n formatter.close();\n return sb.toString();\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 }", "public Style createStyle(final List<Rule> styleRules) {\n final Rule[] rulesArray = styleRules.toArray(new Rule[0]);\n final FeatureTypeStyle featureTypeStyle = this.styleBuilder.createFeatureTypeStyle(null, rulesArray);\n final Style style = this.styleBuilder.createStyle();\n style.featureTypeStyles().add(featureTypeStyle);\n return style;\n }", "private boolean isOrdinal(int paramType) {\n\t\tswitch ( paramType ) {\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.NUMERIC:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\tcase Types.BIGINT:\n\t\t\tcase Types.DECIMAL: //for Oracle Driver\n\t\t\tcase Types.DOUBLE: //for Oracle Driver\n\t\t\tcase Types.FLOAT: //for Oracle Driver\n\t\t\t\treturn true;\n\t\t\tcase Types.CHAR:\n\t\t\tcase Types.LONGVARCHAR:\n\t\t\tcase Types.VARCHAR:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\tthrow new HibernateException( \"Unable to persist an Enum in a column of SQL Type: \" + paramType );\n\t\t}\n\t}", "public static nstimer_binding get(nitro_service service, String name) throws Exception{\n\t\tnstimer_binding obj = new nstimer_binding();\n\t\tobj.set_name(name);\n\t\tnstimer_binding response = (nstimer_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, Class<T> clazz) {\n\t\tif (connectionSource == null) {\n\t\t\tthrow new IllegalArgumentException(\"connectionSource argument cannot be null\");\n\t\t}\n\t\tClassConnectionSource key = new ClassConnectionSource(connectionSource, clazz);\n\t\tDao<?, ?> dao = lookupDao(key);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) dao;\n\t\treturn castDao;\n\t}", "public String getOriginalUrl() throws FlickrException {\r\n if (originalSize == null) {\r\n if (originalFormat != null) {\r\n return getOriginalBaseImageUrl() + \"_o.\" + originalFormat;\r\n }\r\n return getOriginalBaseImageUrl() + DEFAULT_ORIGINAL_IMAGE_SUFFIX;\r\n } else {\r\n return originalSize.getSource();\r\n }\r\n }", "public Collection<License> getInfo() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\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 List<License> licenses = new ArrayList<License>();\r\n Element licensesElement = response.getPayload();\r\n NodeList licenseElements = licensesElement.getElementsByTagName(\"license\");\r\n for (int i = 0; i < licenseElements.getLength(); i++) {\r\n Element licenseElement = (Element) licenseElements.item(i);\r\n License license = new License();\r\n license.setId(licenseElement.getAttribute(\"id\"));\r\n license.setName(licenseElement.getAttribute(\"name\"));\r\n license.setUrl(licenseElement.getAttribute(\"url\"));\r\n licenses.add(license);\r\n }\r\n return licenses;\r\n }", "public static List<Integer> getAllNodeIds(AdminClient adminClient) {\n List<Integer> nodeIds = Lists.newArrayList();\n for(Integer nodeId: adminClient.getAdminClientCluster().getNodeIds()) {\n nodeIds.add(nodeId);\n }\n return nodeIds;\n }" ]
This handler will be triggered when search is finish
[ "@Override\n public HandlerRegistration addSearchFinishHandler(final SearchFinishEvent.SearchFinishHandler handler) {\n return addHandler(handler, SearchFinishEvent.TYPE);\n }" ]
[ "private String parsePropertyName(String orgPropertyName, Object userData) {\n\t\t// try to assure the correct separator is used\n\t\tString propertyName = orgPropertyName.replace(HibernateLayerUtil.XPATH_SEPARATOR, HibernateLayerUtil.SEPARATOR);\n\n\t\t// split the path (separator is defined in the HibernateLayerUtil)\n\t\tString[] props = propertyName.split(HibernateLayerUtil.SEPARATOR_REGEXP);\n\t\tString finalName;\n\t\tif (props.length > 1 && userData instanceof Criteria) {\n\t\t\t// the criteria API requires an alias for each join table !!!\n\t\t\tString prevAlias = null;\n\t\t\tfor (int i = 0; i < props.length - 1; i++) {\n\t\t\t\tString alias = props[i] + \"_alias\";\n\t\t\t\tif (!aliases.contains(alias)) {\n\t\t\t\t\tCriteria criteria = (Criteria) userData;\n\t\t\t\t\tif (i == 0) {\n\t\t\t\t\t\tcriteria.createAlias(props[0], alias);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcriteria.createAlias(prevAlias + \".\" + props[i], alias);\n\t\t\t\t\t}\n\t\t\t\t\taliases.add(alias);\n\t\t\t\t}\n\t\t\t\tprevAlias = alias;\n\t\t\t}\n\t\t\tfinalName = prevAlias + \".\" + props[props.length - 1];\n\t\t} else {\n\t\t\tfinalName = propertyName;\n\t\t}\n\t\treturn finalName;\n\t}", "public static void dumpStoreDefsToFile(String outputDirName,\n String fileName,\n List<StoreDefinition> storeDefs) {\n\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n\n try {\n FileUtils.writeStringToFile(new File(outputDirName, fileName),\n new StoreDefinitionsMapper().writeStoreList(storeDefs));\n } catch(IOException e) {\n logger.error(\"IOException during dumpStoreDefsToFile: \" + e);\n }\n }\n }", "public static StringConsumers buildConsumer(\n final String zookeeperConfig,//\n final String topic,//\n final String groupId, //\n final IMessageListener<String> listener) {\n return buildConsumer(zookeeperConfig, topic, groupId, listener, 2);\n }", "public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }", "public static int copyAllBytes(InputStream in, OutputStream out) throws IOException {\n int byteCount = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n while (true) {\n int read = in.read(buffer);\n if (read == -1) {\n break;\n }\n out.write(buffer, 0, read);\n byteCount += read;\n }\n return byteCount;\n }", "public void setOccurence(int min, int max) throws ParseException {\n if (!simplified) {\n if ((min < 0) || (min > max) || (max < 1)) {\n throw new ParseException(\"Illegal number {\" + min + \",\" + max + \"}\");\n }\n if (min == 0) {\n optional = true;\n }\n minimumOccurence = Math.max(1, min);\n maximumOccurence = max;\n } else {\n throw new ParseException(\"already simplified\");\n }\n }", "public AsciiTable setPaddingRight(int paddingRight) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingRight(paddingRight);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static String getOjbClassName(ResultSet rs)\r\n {\r\n try\r\n {\r\n return rs.getString(OJB_CLASS_COLUMN);\r\n }\r\n catch (SQLException e)\r\n {\r\n return null;\r\n }\r\n }", "protected Transformer getTransformer() {\n TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory();\n try {\n Transformer transformer = transformerFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n return transformer;\n }\n catch (TransformerConfigurationException e) {\n throw LOG.unableToCreateTransformer(e);\n }\n }" ]
Recurses the given folder and creates the FileModels vertices for the child files to the graph.
[ "private void recurseAndAddFiles(GraphRewrite event, FileService fileService, WindupJavaConfigurationService javaConfigurationService, FileModel file)\n {\n if (javaConfigurationService.checkIfIgnored(event, file))\n return;\n\n String filePath = file.getFilePath();\n File fileReference = new File(filePath);\n Long directorySize = new Long(0);\n\n if (fileReference.isDirectory())\n {\n File[] subFiles = fileReference.listFiles();\n if (subFiles != null)\n {\n for (File reference : subFiles)\n {\n FileModel subFile = fileService.createByFilePath(file, reference.getAbsolutePath());\n recurseAndAddFiles(event, fileService, javaConfigurationService, subFile);\n if (subFile.isDirectory())\n {\n directorySize = directorySize + subFile.getDirectorySize();\n }\n else\n {\n directorySize = directorySize + subFile.getSize();\n }\n }\n }\n file.setDirectorySize(directorySize);\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 Bundler put(String key, String[] value) {\n delegate.putStringArray(key, value);\n return this;\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 }", "public static void openFavoriteDialog(CmsFileExplorer explorer) {\n\n try {\n CmsExplorerFavoriteContext context = new CmsExplorerFavoriteContext(A_CmsUI.getCmsObject(), explorer);\n CmsFavoriteDialog dialog = new CmsFavoriteDialog(context, new CmsFavoriteDAO(A_CmsUI.getCmsObject()));\n Window window = CmsBasicDialog.prepareWindow(DialogWidth.max);\n window.setContent(dialog);\n window.setCaption(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_FAVORITES_DIALOG_TITLE_0));\n A_CmsUI.get().addWindow(window);\n window.center();\n } catch (CmsException e) {\n CmsErrorDialog.showErrorDialog(e);\n }\n }", "public static String getURLParentDirectory(String urlString) throws IllegalArgumentException {\n URL url = null;\n try {\n url = new URL(urlString);\n } catch (MalformedURLException e) {\n throw Exceptions.IllegalArgument(\"Malformed URL: %s\", url);\n }\n\n String path = url.getPath();\n int lastSlashIndex = path.lastIndexOf(\"/\");\n String directory = lastSlashIndex == -1 ? \"\" : path.substring(0, lastSlashIndex);\n return String.format(\"%s://%s%s%s%s\", url.getProtocol(),\n url.getUserInfo() == null ? \"\" : url.getUserInfo() + \"@\",\n url.getHost(),\n url.getPort() == -1 ? \"\" : \":\" + Integer.toString(url.getPort()),\n directory);\n }", "public static double distance(double lat1, double lon1,\n double lat2, double lon2) {\n double dLat = Math.toRadians(lat2-lat1);\n double dLon = Math.toRadians(lon2-lon1);\n lat1 = Math.toRadians(lat1);\n lat2 = Math.toRadians(lat2);\n\n double a = Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); \n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n return R * c;\n }", "private void merge(Map<String, NodeT> source, Map<String, NodeT> target) {\n for (Map.Entry<String, NodeT> entry : source.entrySet()) {\n String key = entry.getKey();\n if (!target.containsKey(key)) {\n target.put(key, entry.getValue());\n }\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 }", "@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}" ]
Creates an temporary directory. The created directory will be deleted when command will ended.
[ "protected Path createTempDirectory(String prefix) {\n try {\n return Files.createTempDirectory(tempDirectory, prefix);\n } catch (IOException e) {\n throw new AllureCommandException(e);\n }\n }" ]
[ "public Deployment setServerGroups(final Collection<String> serverGroups) {\n this.serverGroups.clear();\n this.serverGroups.addAll(serverGroups);\n return this;\n }", "public void sendMessageToAgentsWithExtraProperties(String[] agent_name,\n String msgtype, Object message_content,\n ArrayList<Object> properties, Connector connector) {\n HashMap<String, Object> hm = new HashMap<String, Object>();\n hm.put(\"performative\", msgtype);\n hm.put(SFipa.CONTENT, message_content);\n\n for (Object property : properties) {\n // Logger logger = Logger.getLogger(\"JadexMessenger\");\n // logger.info(\"Sending message with extra property: \"+property.get(0)+\", with value \"+property.get(1));\n hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));\n }\n\n IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];\n for (int i = 0; i < agent_name.length; i++) {\n ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);\n }\n ((IMessageService) connector.getMessageService()).deliverMessage(hm,\n \"fipa\", ici);\n }", "public CustomField getCustomField(FieldType field)\n {\n CustomField result = m_configMap.get(field);\n if (result == null)\n {\n result = new CustomField(field, this);\n m_configMap.put(field, result);\n }\n return result;\n }", "public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {\n int numSingular = Math.min(W.numRows,W.numCols);\n boolean compact = W.numRows == W.numCols;\n\n if( compact ) {\n if( U != null ) {\n if( tranU && U.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n else if( !tranU && U.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n }\n\n if( V != null ) {\n if( tranV && V.numRows != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n else if( !tranV && V.numCols != numSingular )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n }\n } else {\n if( U != null && U.numRows != U.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix U\");\n if( V != null && V.numRows != V.numCols )\n throw new IllegalArgumentException(\"Unexpected size of matrix V\");\n if( U != null && U.numRows != W.numRows )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n if( V != null && V.numRows != W.numCols )\n throw new IllegalArgumentException(\"Unexpected size of W\");\n }\n }", "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}", "public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case REQUEST_PERMISSIONS_CODE:\n if (listener != null) {\n boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;\n listener.onPermissionResult(granted);\n }\n break;\n default:\n // Ignored\n }\n }", "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 }", "@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 RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {\n\n\t\tArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>();\n\n\t\tRandomVariableInterface basisFunction;\n\n\t\t// Constant\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tbasisFunctions.add(basisFunction);\n\n\t\t// LIBORs\n\t\tint liborPeriodIndex, liborPeriodIndexEnd;\n\t\tRandomVariableInterface rate;\n\n\t\t// 1 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = liborPeriodIndex+1;\n\t\tdouble periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\tbasisFunction = basisFunction.discount(rate, periodLength1);\n\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t// n/2 Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2;\n\n\t\tdouble periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength2 != periodLength1) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength2);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\n\t\t// n Period\n\t\tbasisFunction = model.getRandomVariableForConstant(1.0);\n\t\tliborPeriodIndex = model.getLiborPeriodIndex(exerciseDate);\n\t\tif(liborPeriodIndex < 0) {\n\t\t\tliborPeriodIndex = -liborPeriodIndex-1;\n\t\t}\n\t\tliborPeriodIndexEnd = model.getNumberOfLibors();\n\t\tdouble periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex);\n\n\t\tif(periodLength3 != periodLength1 && periodLength3 != periodLength2) {\n\t\t\trate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd));\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\n\t\t\tbasisFunction = basisFunction.discount(rate, periodLength3);\n\t\t\t//\t\t\tbasisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage())));\n\t\t}\n\n\t\treturn basisFunctions.toArray(new RandomVariableInterface[0]);\n\t}" ]
returns a sorted array of constructors
[ "public GroovyConstructorDoc[] constructors() {\n Collections.sort(constructors);\n return constructors.toArray(new GroovyConstructorDoc[constructors.size()]);\n }" ]
[ "public PeriodicEvent runEvery(Runnable task, float delay, float period,\n int repetitions) {\n if (repetitions < 1) {\n return null;\n } else if (repetitions == 1) {\n // Better to burn a handful of CPU cycles than to churn memory by\n // creating a new callback\n return runAfter(task, delay);\n } else {\n return runEvery(task, delay, period, new RunFor(repetitions));\n }\n }", "public static void setFaceNames(String[] nameArray)\n {\n if (nameArray.length != 6)\n {\n throw new IllegalArgumentException(\"nameArray length is not 6.\");\n }\n for (int i = 0; i < 6; i++)\n {\n faceIndexMap.put(nameArray[i], i);\n }\n }", "public void signIn(String key, WebSocketConnection connection) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);\n bag.put(connection, connection);\n }", "public static final TimeUnit parseWorkUnits(BigInteger value)\n {\n TimeUnit result = TimeUnit.HOURS;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 1:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 3:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 5:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 7:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n }\n }\n\n return (result);\n }", "public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\n }", "public static String getModuleName(final String moduleId) {\n final int splitter = moduleId.indexOf(':');\n if(splitter == -1){\n return moduleId;\n }\n return moduleId.substring(0, splitter);\n }", "public Value get(Object key) {\n /* If the length is under and we are asking for the key, then just look for the key. Don't build the map. */\n if (map == null && items.length < 20) {\n for (Object item : items) {\n MapItemValue miv = (MapItemValue) item;\n if (key.equals(miv.name.toValue())) {\n return miv.value;\n }\n }\n return null;\n } else {\n if (map == null) buildIfNeededMap();\n return map.get(key);\n }\n }", "public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void setOffline(boolean value){\n offline = value;\n if (offline) {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to offline, won't send events queue\");\n } else {\n getConfigLogger().debug(getAccountId(), \"CleverTap Instance has been set to online, sending events queue\");\n flush();\n }\n }" ]
Use this API to fetch vpnsessionpolicy_aaauser_binding resources of given name .
[ "public static vpnsessionpolicy_aaauser_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnsessionpolicy_aaauser_binding obj = new vpnsessionpolicy_aaauser_binding();\n\t\tobj.set_name(name);\n\t\tvpnsessionpolicy_aaauser_binding response[] = (vpnsessionpolicy_aaauser_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "protected LayoutManager getLayOutManagerObj(ActionInvocation _invocation) {\n\t\tif (layoutManager == null || \"\".equals(layoutManager)){\n\t\t\tLOG.warn(\"No valid LayoutManager, using ClassicLayoutManager\");\n\t\t\treturn new ClassicLayoutManager();\n\t\t}\n\n\t\tObject los = conditionalParse(layoutManager, _invocation);\n\n\t\tif (los instanceof LayoutManager){\n\t\t\treturn (LayoutManager) los;\n\t\t}\n\n\t\tLayoutManager lo = null;\n\t\tif (los instanceof String){\n\t\t\tif (LAYOUT_CLASSIC.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ClassicLayoutManager();\n\t\t\telse if (LAYOUT_LIST.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ListLayoutManager();\n\t\t\telse {\n\t\t\t\ttry {\n\t\t\t\t\tlo = (LayoutManager) Class.forName((String) los).newInstance();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.warn(\"No valid LayoutManager: \" + e.getMessage(),e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lo;\n\t}", "private Resolvable createMetadataProvider(Class<?> rawType) {\n Set<Type> types = Collections.<Type>singleton(rawType);\n return new ResolvableImpl(rawType, types, declaringBean, qualifierInstances, delegate);\n }", "public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute)\n\t{\n\t\t_mappedPublicKeys.put(original, substitute);\n\t\tif(persistImmediately) { persistPublicKeyMap(); }\n\t}", "public Deployment setServerGroups(final Collection<String> serverGroups) {\n this.serverGroups.clear();\n this.serverGroups.addAll(serverGroups);\n return this;\n }", "public static final void deleteQuietly(File file)\n {\n if (file != null)\n {\n if (file.isDirectory())\n {\n File[] children = file.listFiles();\n if (children != null)\n {\n for (File child : children)\n {\n deleteQuietly(child);\n }\n }\n }\n file.delete();\n }\n }", "public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }", "public static boolean hasFacet(GridDialect gridDialect, Class<? extends GridDialect> facetType) {\n\t\tif ( gridDialect instanceof ForwardingGridDialect ) {\n\t\t\treturn hasFacet( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), facetType );\n\t\t}\n\t\telse {\n\t\t\treturn facetType.isAssignableFrom( gridDialect.getClass() );\n\t\t}\n\t}", "public 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}", "@Nullable\n private static Converter<List<String>, Object> createPrimitiveTypeConverter(final Class<?> resultClass) {\n Object defaultValue = defaultValue(resultClass);\n\n if (defaultValue == null) {\n // For primitive type, the default value shouldn't be null\n return null;\n }\n\n return new BasicConverter(defaultValue) {\n @Override\n protected Object convert(String value) throws Exception {\n return valueOf(value, resultClass);\n }\n };\n }" ]
Write a single resource. @param mpxj Resource instance
[ "private void writeResource(Resource mpxj)\n {\n ResourceType xml = m_factory.createResourceType();\n m_apibo.getResource().add(xml);\n\n xml.setAutoComputeActuals(Boolean.TRUE);\n xml.setCalculateCostFromUnits(Boolean.TRUE);\n xml.setCalendarObjectId(getCalendarUniqueID(mpxj.getResourceCalendar()));\n xml.setCurrencyObjectId(DEFAULT_CURRENCY_ID);\n xml.setDefaultUnitsPerTime(Double.valueOf(1.0));\n xml.setEmailAddress(mpxj.getEmailAddress());\n xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));\n xml.setId(RESOURCE_ID_PREFIX + mpxj.getUniqueID());\n xml.setIsActive(Boolean.TRUE);\n xml.setMaxUnitsPerTime(getPercentage(mpxj.getMaxUnits()));\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setParentObjectId(mpxj.getParentID());\n xml.setResourceNotes(mpxj.getNotes());\n xml.setResourceType(getResourceType(mpxj));\n xml.getUDF().addAll(writeUDFType(FieldTypeClass.RESOURCE, mpxj));\n }" ]
[ "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 }", "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 }", "public Stamp allocateTimestamp() {\n\n synchronized (this) {\n Preconditions.checkState(!closed, \"tracker closed \");\n\n if (node == null) {\n Preconditions.checkState(allocationsInProgress == 0,\n \"expected allocationsInProgress == 0 when node == null\");\n Preconditions.checkState(!updatingZk, \"unexpected concurrent ZK update\");\n\n createZkNode(getTimestamp().getTxTimestamp());\n }\n\n allocationsInProgress++;\n }\n\n try {\n Stamp ts = getTimestamp();\n\n synchronized (this) {\n timestamps.add(ts.getTxTimestamp());\n }\n\n return ts;\n } catch (RuntimeException re) {\n synchronized (this) {\n allocationsInProgress--;\n }\n throw re;\n }\n }", "public void processCalendar(Row row)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n\n Integer id = row.getInteger(\"clndr_id\");\n m_calMap.put(id, calendar);\n calendar.setName(row.getString(\"clndr_name\"));\n\n try\n {\n calendar.setMinutesPerDay(Integer.valueOf((int) NumberHelper.getDouble(row.getDouble(\"day_hr_cnt\")) * 60));\n calendar.setMinutesPerWeek(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"week_hr_cnt\")) * 60)));\n calendar.setMinutesPerMonth(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"month_hr_cnt\")) * 60)));\n calendar.setMinutesPerYear(Integer.valueOf((int) (NumberHelper.getDouble(row.getDouble(\"year_hr_cnt\")) * 60)));\n }\n catch (ClassCastException ex)\n {\n // We have seen examples of malformed calendar data where fields have been missing\n // from the record. We'll typically get a class cast exception here as we're trying\n // to process something which isn't a double.\n // We'll just return at this point as it's not clear that we can salvage anything\n // sensible from this record.\n return;\n }\n\n // Process data\n String calendarData = row.getString(\"clndr_data\");\n if (calendarData != null && !calendarData.isEmpty())\n {\n Record root = Record.getRecord(calendarData);\n if (root != null)\n {\n processCalendarDays(calendar, root);\n processCalendarExceptions(calendar, root);\n }\n }\n else\n {\n // if there is not DaysOfWeek data, Primavera seems to default to Mon-Fri, 8:00-16:00\n DateRange defaultHourRange = new DateRange(DateHelper.getTime(8, 0), DateHelper.getTime(16, 0));\n for (Day day : Day.values())\n {\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n calendar.setWorkingDay(day, true);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n hours.addRange(defaultHourRange);\n }\n else\n {\n calendar.setWorkingDay(day, false);\n }\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }", "public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void acceptsHex(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), \"fetch key/entry by key value of hex type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "@SuppressWarnings( { \"unchecked\" })\r\n public static <K1, K2> TwoDimensionalCounter<K2, K1> reverseIndexOrder(TwoDimensionalCounter<K1, K2> cc) {\r\n // they typing on the outerMF is violated a bit, but it'll work....\r\n TwoDimensionalCounter<K2, K1> result = new TwoDimensionalCounter<K2, K1>((MapFactory) cc.outerMF,\r\n (MapFactory) cc.innerMF);\r\n\r\n for (K1 key1 : cc.firstKeySet()) {\r\n ClassicCounter<K2> c = cc.getCounter(key1);\r\n for (K2 key2 : c.keySet()) {\r\n double count = c.getCount(key2);\r\n result.setCount(key2, key1, count);\r\n }\r\n }\r\n return result;\r\n }", "@SuppressWarnings(\"unchecked\")\n public static Properties readSingleClientConfigAvro(String configAvro) {\n Properties props = new Properties();\n try {\n JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIG_AVRO_SCHEMA, configAvro);\n GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIG_AVRO_SCHEMA);\n Map<Utf8, Utf8> flowMap = (Map<Utf8, Utf8>) datumReader.read(null, decoder);\n for(Utf8 key: flowMap.keySet()) {\n props.put(key.toString(), flowMap.get(key).toString());\n }\n } catch(Exception e) {\n e.printStackTrace();\n }\n return props;\n }", "public static SQLException create(String message, Throwable cause) {\n\t\tSQLException sqlException;\n\t\tif (cause instanceof SQLException) {\n\t\t\t// if the cause is another SQLException, pass alot of the SQL state\n\t\t\tsqlException = new SQLException(message, ((SQLException) cause).getSQLState());\n\t\t} else {\n\t\t\tsqlException = new SQLException(message);\n\t\t}\n\t\tsqlException.initCause(cause);\n\t\treturn sqlException;\n\t}" ]
Moves a calendar to the last named day of the month. @param calendar current date
[ "private void setCalendarToLastRelativeDay(Calendar calendar)\n {\n calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n int requiredDayOfWeek = getDayOfWeek().getValue();\n int dayOfWeekOffset = 0;\n\n if (currentDayOfWeek > requiredDayOfWeek)\n {\n dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek;\n }\n else\n {\n if (currentDayOfWeek < requiredDayOfWeek)\n {\n dayOfWeekOffset = -7 + (requiredDayOfWeek - currentDayOfWeek);\n }\n }\n\n if (dayOfWeekOffset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset);\n }\n }" ]
[ "private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n //baseline.getBCWP()\n //baseline.getBCWS()\n Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost());\n Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish());\n //baseline.getNumber()\n Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpx.setBaselineCost(cost);\n mpx.setBaselineFinish(finish);\n mpx.setBaselineStart(start);\n mpx.setBaselineWork(work);\n }\n else\n {\n mpx.setBaselineCost(number, cost);\n mpx.setBaselineWork(number, work);\n mpx.setBaselineStart(number, start);\n mpx.setBaselineFinish(number, finish);\n }\n }\n }", "public void removeAllAnimations() {\n for (int i = 0, size = mAnimationList.size(); i < size; i++) {\n mAnimationList.get(i).removeAnimationListener(mAnimationListener);\n }\n mAnimationList.clear();\n }", "public void removeCustomOverride(int path_id, String client_uuid) throws Exception {\n updateRequestResponseTables(\"custom_response\", \"\", getProfileIdFromPathID(path_id), client_uuid, path_id);\n }", "public static cmppolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tobj.set_name(name);\n\t\tcmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "private PlayState1 findPlayState1() {\n PlayState1 result = PLAY_STATE_1_MAP.get(packetBytes[123]);\n if (result == null) {\n return PlayState1.UNKNOWN;\n }\n return result;\n }", "public void filterUnsafeOrUnnecessaryRequest(\n Map<String, NodeReqResponse> nodeDataMapValidSource,\n Map<String, NodeReqResponse> nodeDataMapValidSafe) {\n\n for (Entry<String, NodeReqResponse> entry : nodeDataMapValidSource\n .entrySet()) {\n\n String hostName = entry.getKey();\n NodeReqResponse nrr = entry.getValue();\n\n Map<String, String> map = nrr.getRequestParameters();\n\n /**\n * 20130507: will generally apply to all requests: if have this\n * field and this field is false\n */\n if (map.containsKey(PcConstants.NODE_REQUEST_WILL_EXECUTE)) {\n Boolean willExecute = Boolean.parseBoolean(map\n .get(PcConstants.NODE_REQUEST_WILL_EXECUTE));\n\n if (!willExecute) {\n logger.info(\"NOT_EXECUTE_COMMAND \" + \" on target: \"\n + hostName + \" at \"\n + PcDateUtils.getNowDateTimeStrStandard());\n continue;\n }\n }\n\n // now safely to add this node in.\n nodeDataMapValidSafe.put(hostName, nrr);\n }// end for loop\n\n }", "public String getString(int field)\n {\n String result;\n\n if (field < m_fields.length)\n {\n result = m_fields[field];\n\n if (result != null)\n {\n result = result.replace(MPXConstants.EOL_PLACEHOLDER, '\\n');\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public static Command newInsert(Object object,\n String outIdentifier,\n boolean returnObject,\n String entryPoint ) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier,\n returnObject,\n entryPoint );\n }", "public static String getTokenText(INode node) {\n\t\tif (node instanceof ILeafNode)\n\t\t\treturn ((ILeafNode) node).getText();\n\t\telse {\n\t\t\tStringBuilder builder = new StringBuilder(Math.max(node.getTotalLength(), 1));\n\t\t\tboolean hiddenSeen = false;\n\t\t\tfor (ILeafNode leaf : node.getLeafNodes()) {\n\t\t\t\tif (!leaf.isHidden()) {\n\t\t\t\t\tif (hiddenSeen && builder.length() > 0)\n\t\t\t\t\t\tbuilder.append(' ');\n\t\t\t\t\tbuilder.append(leaf.getText());\n\t\t\t\t\thiddenSeen = false;\n\t\t\t\t} else {\n\t\t\t\t\thiddenSeen = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn builder.toString();\n\t\t}\n\t}" ]
Adds the worker thread pool attributes to the subysystem add method
[ "void parseWorkerThreadPool(final XMLExtendedStreamReader reader, final ModelNode subsystemAdd) throws XMLStreamException {\n final int count = reader.getAttributeCount();\n for (int i = 0; i < count; i++) {\n requireNoNamespaceAttribute(reader, i);\n final String value = reader.getAttributeValue(i);\n final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));\n switch (attribute) {\n case WORKER_READ_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_READ_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_READ_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_READ_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_CORE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_CORE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_CORE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_KEEPALIVE:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_KEEPALIVE)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_KEEPALIVE);\n }\n RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_LIMIT:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_LIMIT)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_LIMIT);\n }\n RemotingSubsystemRootResource.WORKER_TASK_LIMIT.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_TASK_MAX_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_TASK_MAX_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_TASK_MAX_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n case WORKER_WRITE_THREADS:\n if (subsystemAdd.hasDefined(CommonAttributes.WORKER_WRITE_THREADS)) {\n throw duplicateAttribute(reader, CommonAttributes.WORKER_WRITE_THREADS);\n }\n RemotingSubsystemRootResource.WORKER_WRITE_THREADS.parseAndSetParameter(value, subsystemAdd, reader);\n break;\n default:\n throw unexpectedAttribute(reader, i);\n }\n }\n requireNoContent(reader);\n }" ]
[ "public static boolean isClassClassNodeWrappingConcreteType(ClassNode classNode) {\n GenericsType[] genericsTypes = classNode.getGenericsTypes();\n return ClassHelper.CLASS_Type.equals(classNode)\n && classNode.isUsingGenerics()\n && genericsTypes!=null\n && !genericsTypes[0].isPlaceholder()\n && !genericsTypes[0].isWildcard();\n }", "static ItemIdValueImpl fromIri(String iri) {\n\t\tint separator = iri.lastIndexOf('/') + 1;\n\t\ttry {\n\t\t\treturn new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator));\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid Wikibase entity IRI: \" + iri, e);\n\t\t}\n\t}", "public static HashMap<String, JSONObject> flatRessources(JSONObject object) throws JSONException {\n HashMap<String, JSONObject> result = new HashMap<String, JSONObject>();\n\n // no cycle in hierarchies!!\n if (object.has(\"resourceId\") && object.has(\"childShapes\")) {\n result.put(object.getString(\"resourceId\"),\n object);\n JSONArray childShapes = object.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapes.length(); i++) {\n result.putAll(flatRessources(childShapes.getJSONObject(i)));\n }\n }\n ;\n\n return result;\n }", "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 }", "public void processAnonymousField(Properties attributes) throws XDocletException\r\n {\r\n if (!attributes.containsKey(ATTRIBUTE_NAME))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.PARAMETER_IS_REQUIRED,\r\n new String[]{ATTRIBUTE_NAME}));\r\n }\r\n\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n fieldDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousField\", \" Processing anonymous field \"+fieldDef.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 fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"anonymous\");\r\n }", "public void localCommit()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"commit was called\");\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new TransactionNotInProgressException(\"Not in transaction, call begin() before commit()\");\r\n }\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.commit();\r\n }\r\n else if (con != null)\r\n {\r\n con.commit();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Connection.commit() call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Commit on underlying connection failed, try to rollback connection\", e);\r\n this.localRollback();\r\n throw new TransactionAbortedException(\"Commit on connection failed\", e);\r\n }\r\n finally\r\n {\r\n this.isInLocalTransaction = false;\r\n restoreAutoCommitState();\r\n this.releaseConnection();\r\n }\r\n }", "public static boolean zipFolder(File folder, String fileName){\n\t\tboolean success = false;\n\t\tif(!folder.isDirectory()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(fileName == null){\n\t\t\tfileName = folder.getAbsolutePath()+ZIP_EXT;\n\t\t}\n\t\t\n\t\tZipArchiveOutputStream zipOutput = null;\n\t\ttry {\n\t\t\tzipOutput = new ZipArchiveOutputStream(new File(fileName));\n\t\t\t\n\t\t\tsuccess = addFolderContentToZip(folder,zipOutput,\"\");\n\n\t\t\tzipOutput.close();\n\t\t\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\tfinally{\n\t\t\ttry {\n\t\t\t\tif(zipOutput != null){\n\t\t\t\t\tzipOutput.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\treturn success;\n\t}", "public void removeTag(String tagId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_REMOVE_TAG);\r\n\r\n parameters.put(\"tag_id\", tagId);\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 void inputValues(boolean... values) {\n\t\tfor (boolean value : values) {\n\t\t\tInputValue inputValue = new InputValue();\n\t\t\tinputValue.setChecked(value);\n\n\t\t\tthis.inputValues.add(inputValue);\n\t\t}\n\t}" ]
Provides a message which describes the expected format and arguments for this command. This is used to provide user feedback when a command request is malformed. @return A message describing the command protocol format.
[ "protected String getExpectedMessage() {\r\n StringBuilder syntax = new StringBuilder(\"<tag> \");\r\n syntax.append(getName());\r\n\r\n String args = getArgSyntax();\r\n if (args != null && args.length() > 0) {\r\n syntax.append(' ');\r\n syntax.append(args);\r\n }\r\n\r\n return syntax.toString();\r\n }" ]
[ "public 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 MediaType nonBinary( MediaType.Type type, String subType, Charset charSet ) {\n ApiUtil.notNull( charSet, \"charset must not be null\" );\n return new MediaType( type, subType, charSet );\n }", "public static authenticationldappolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationldappolicy_vpnglobal_binding obj = new authenticationldappolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationldappolicy_vpnglobal_binding response[] = (authenticationldappolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void normalizeSelectedCategories() {\r\n\r\n Collection<String> normalizedCategories = new ArrayList<String>(m_selectedCategories.size());\r\n for (CmsTreeItem item : m_categories.values()) {\r\n if (item.getCheckBox().isChecked()) {\r\n normalizedCategories.add(item.getId());\r\n }\r\n }\r\n m_selectedCategories = normalizedCategories;\r\n\r\n }", "public Number getMinutesPerYear()\n {\n return Integer.valueOf(NumberHelper.getInt(getMinutesPerDay()) * NumberHelper.getInt(getDaysPerMonth()) * 12);\n }", "@SuppressWarnings(\"unchecked\")\n public void setVars(final Map<String, ? extends Object> vars) {\n this.vars = (Map<String, Object>)vars;\n }", "void setPaused(final boolean isPaused) {\n docLock.writeLock().lock();\n try {\n docsColl.updateOne(\n getDocFilter(namespace, documentId),\n new BsonDocument(\"$set\",\n new BsonDocument(\n ConfigCodec.Fields.IS_PAUSED,\n new BsonBoolean(isPaused))));\n this.isPaused = isPaused;\n } catch (IllegalStateException e) {\n // eat this\n } finally {\n docLock.writeLock().unlock();\n }\n }", "public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }", "@Override\n public void invert(DMatrixRMaj A_inv) {\n blockB.reshape(A_inv.numRows,A_inv.numCols,false);\n\n alg.invert(blockB);\n\n MatrixOps_DDRB.convert(blockB,A_inv);\n }" ]
Removes a tag from the task. Returns an empty data block. @param task The task to remove a tag from. @return Request object
[ "public ItemRequest<Task> removeTag(String task) {\n \n String path = String.format(\"/tasks/%s/removeTag\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }" ]
[ "protected void mergeImmutableContainerTypesFrom(Configuration otherConfiguration) {\r\n Set<Dotted> union =\r\n Sets.union(hardcodedImmutableContainerClasses.build(), otherConfiguration.immutableContainerClasses());\r\n\r\n hardcodedImmutableContainerClasses = ImmutableSet.<Dotted>builder().addAll(union);\r\n }", "protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }", "public boolean contains(String column) {\n\t\tfor ( String columnName : columnNames ) {\n\t\t\tif ( columnName.equals( column ) ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "public byte[] serialize() throws PersistenceBrokerException\r\n {\r\n // Identity is serialized and written to an ObjectOutputStream\r\n // This ObjectOutputstream is compressed by a GZIPOutputStream\r\n // and finally written to a ByteArrayOutputStream.\r\n // the resulting byte[] is returned\r\n try\r\n {\r\n final ByteArrayOutputStream bao = new ByteArrayOutputStream();\r\n final GZIPOutputStream gos = new GZIPOutputStream(bao);\r\n final ObjectOutputStream oos = new ObjectOutputStream(gos);\r\n oos.writeObject(this);\r\n oos.close();\r\n gos.close();\r\n bao.close();\r\n return bao.toByteArray();\r\n }\r\n catch (Exception ignored)\r\n {\r\n throw new PersistenceBrokerException(ignored);\r\n }\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 }", "protected void handleDeadSlop(SlopStorageEngine slopStorageEngine,\n Pair<ByteArray, Versioned<Slop>> keyAndVal) {\n Versioned<Slop> versioned = keyAndVal.getSecond();\n // If configured to delete the dead slop\n if(voldemortConfig.getAutoPurgeDeadSlops()) {\n slopStorageEngine.delete(keyAndVal.getFirst(), versioned.getVersion());\n\n if(getLogger().isDebugEnabled()) {\n getLogger().debug(\"Auto purging dead slop :\" + versioned.getValue());\n }\n } else {\n // Keep ignoring the dead slops\n if(getLogger().isDebugEnabled()) {\n getLogger().debug(\"Ignoring dead slop :\" + versioned.getValue());\n }\n }\n }", "public static URL classFileUrl(Class<?> clazz) throws IOException {\n ClassLoader cl = clazz.getClassLoader();\n if (cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL res = cl.getResource(clazz.getName().replace('.', '/') + \".class\");\n if (res == null) {\n throw new IllegalArgumentException(\"Unable to locate class file for \" + clazz);\n }\n return res;\n }", "public static Properties loadProps(String filename) {\n Properties props = new Properties();\n FileInputStream fis = null;\n try {\n fis = new FileInputStream(filename);\n props.load(fis);\n return props;\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n } finally {\n Closer.closeQuietly(fis);\n }\n\n }", "public void releaseDbResources()\r\n {\r\n Iterator it = m_rsIterators.iterator();\r\n while (it.hasNext())\r\n {\r\n ((OJBIterator) it.next()).releaseDbResources();\r\n }\r\n }" ]
Use this API to add gslbservice.
[ "public static base_response add(nitro_service client, gslbservice resource) throws Exception {\n\t\tgslbservice addresource = new gslbservice();\n\t\taddresource.servicename = resource.servicename;\n\t\taddresource.cnameentry = resource.cnameentry;\n\t\taddresource.ip = resource.ip;\n\t\taddresource.servername = resource.servername;\n\t\taddresource.servicetype = resource.servicetype;\n\t\taddresource.port = resource.port;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.publicport = resource.publicport;\n\t\taddresource.maxclient = resource.maxclient;\n\t\taddresource.healthmonitor = resource.healthmonitor;\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.state = resource.state;\n\t\taddresource.cip = resource.cip;\n\t\taddresource.cipheader = resource.cipheader;\n\t\taddresource.sitepersistence = resource.sitepersistence;\n\t\taddresource.cookietimeout = resource.cookietimeout;\n\t\taddresource.siteprefix = resource.siteprefix;\n\t\taddresource.clttimeout = resource.clttimeout;\n\t\taddresource.svrtimeout = resource.svrtimeout;\n\t\taddresource.maxbandwidth = resource.maxbandwidth;\n\t\taddresource.downstateflush = resource.downstateflush;\n\t\taddresource.maxaaausers = resource.maxaaausers;\n\t\taddresource.monthreshold = resource.monthreshold;\n\t\taddresource.hashid = resource.hashid;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.appflowlog = resource.appflowlog;\n\t\treturn addresource.add_resource(client);\n\t}" ]
[ "public static Class<?> loadClass(String classname, DataFormat<?> dataFormat) {\n\n // first try context classoader\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n if(cl != null) {\n LOG.tryLoadingClass(classname, cl);\n try {\n return cl.loadClass(classname);\n }\n catch(Exception e) {\n // ignore\n }\n }\n\n // else try the classloader which loaded the dataformat\n cl = dataFormat.getClass().getClassLoader();\n try {\n LOG.tryLoadingClass(classname, cl);\n return cl.loadClass(classname);\n }\n catch (ClassNotFoundException e) {\n throw LOG.classNotFound(classname, e);\n }\n\n }", "protected void updateFontTable()\n {\n PDResources resources = pdpage.getResources();\n if (resources != null)\n {\n try\n {\n processFontResources(resources, fontTable);\n } catch (IOException e) {\n log.error(\"Error processing font resources: \"\n + \"Exception: {} {}\", e.getMessage(), e.getClass());\n }\n }\n }", "public void setBackgroundColor(int colorRes) {\n if (getBackground() instanceof ShapeDrawable) {\n final Resources res = getResources();\n ((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));\n }\n }", "protected LogContext getOrCreate(final String loggingProfile) {\n LogContext result = profileContexts.get(loggingProfile);\n if (result == null) {\n result = LogContext.create();\n final LogContext current = profileContexts.putIfAbsent(loggingProfile, result);\n if (current != null) {\n result = current;\n }\n }\n return result;\n }", "@RequestMapping(value = \"/legendgraphic\", method = RequestMethod.GET)\n\tpublic ModelAndView getGraphic(@RequestParam(\"layerId\") String layerId,\n\t\t\t@RequestParam(value = \"styleName\", required = false) String styleName,\n\t\t\t@RequestParam(value = \"ruleIndex\", required = false) Integer ruleIndex,\n\t\t\t@RequestParam(value = \"format\", required = false) String format,\n\t\t\t@RequestParam(value = \"width\", required = false) Integer width,\n\t\t\t@RequestParam(value = \"height\", required = false) Integer height,\n\t\t\t@RequestParam(value = \"scale\", required = false) Double scale,\n\t\t\t@RequestParam(value = \"allRules\", required = false) Boolean allRules, HttpServletRequest request)\n\t\t\tthrows GeomajasException {\n\t\tif (!allRules) {\n\t\t\treturn getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);\n\t\t} else {\n\t\t\treturn getGraphics(layerId, styleName, format, width, height, scale);\n\t\t}\n\t}", "public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {\n final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();\n for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {\n ResourceRootIndexer.indexResourceRoot(resourceRoot);\n }\n }", "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 }", "private void addErrorCorrection(StringBuilder adjustedString, int codewordSize, int dataBlocks, int eccBlocks) {\r\n\r\n int x, poly, startWeight;\r\n\r\n /* Split into codewords and calculate Reed-Solomon error correction codes */\r\n switch (codewordSize) {\r\n case 6:\r\n x = 32;\r\n poly = 0x43;\r\n startWeight = 0x20;\r\n break;\r\n case 8:\r\n x = 128;\r\n poly = 0x12d;\r\n startWeight = 0x80;\r\n break;\r\n case 10:\r\n x = 512;\r\n poly = 0x409;\r\n startWeight = 0x200;\r\n break;\r\n case 12:\r\n x = 2048;\r\n poly = 0x1069;\r\n startWeight = 0x800;\r\n break;\r\n default:\r\n throw new OkapiException(\"Unrecognized codeword size: \" + codewordSize);\r\n }\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n int[] data = new int[dataBlocks + 3];\r\n int[] ecc = new int[eccBlocks + 3];\r\n\r\n for (int i = 0; i < dataBlocks; i++) {\r\n for (int weight = 0; weight < codewordSize; weight++) {\r\n if (adjustedString.charAt((i * codewordSize) + weight) == '1') {\r\n data[i] += (x >> weight);\r\n }\r\n }\r\n }\r\n\r\n rs.init_gf(poly);\r\n rs.init_code(eccBlocks, 1);\r\n rs.encode(dataBlocks, data);\r\n\r\n for (int i = 0; i < eccBlocks; i++) {\r\n ecc[i] = rs.getResult(i);\r\n }\r\n\r\n for (int i = (eccBlocks - 1); i >= 0; i--) {\r\n for (int weight = startWeight; weight > 0; weight = weight >> 1) {\r\n if ((ecc[i] & weight) != 0) {\r\n adjustedString.append('1');\r\n } else {\r\n adjustedString.append('0');\r\n }\r\n }\r\n }\r\n }", "void addSomeValuesRestriction(Resource subject, String propertyUri,\n\t\t\tString rangeUri) {\n\t\tthis.someValuesQueue.add(new PropertyRestriction(subject, propertyUri,\n\t\t\t\trangeUri));\n\t}" ]
Sets the underlying write timeout in milliseconds. A value of 0 specifies an infinite timeout. @see okhttp3.OkHttpClient.Builder#writeTimeout(long, TimeUnit)
[ "public void setWriteTimeout(int writeTimeout) {\n\t\tthis.client = this.client.newBuilder()\n\t\t\t\t.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)\n\t\t\t\t.build();\n\t}" ]
[ "private Set<String> checkModel(final ModelNode model, TransformationContext context) throws OperationFailedException {\n final Set<String> attributes = new HashSet<String>();\n AttributeTransformationRequirementChecker checker;\n for (final String attribute : attributeNames) {\n if (model.hasDefined(attribute)) {\n if (attributeCheckers != null && (checker = attributeCheckers.get(attribute)) != null) {\n if (checker.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n } else if (SIMPLE_EXPRESSIONS.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {\n attributes.add(attribute);\n }\n }\n }\n return attributes;\n }", "public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }", "public Collection<Contact> getPublicList(String userId) throws FlickrException {\r\n List<Contact> contacts = new ArrayList<Contact>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_LIST);\r\n parameters.put(\"user_id\", userId);\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element contactsElement = response.getPayload();\r\n NodeList contactNodes = contactsElement.getElementsByTagName(\"contact\");\r\n for (int i = 0; i < contactNodes.getLength(); i++) {\r\n Element contactElement = (Element) contactNodes.item(i);\r\n Contact contact = new Contact();\r\n contact.setId(contactElement.getAttribute(\"nsid\"));\r\n contact.setUsername(contactElement.getAttribute(\"username\"));\r\n contact.setIgnored(\"1\".equals(contactElement.getAttribute(\"ignored\")));\r\n contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute(\"online\")));\r\n contact.setIconFarm(contactElement.getAttribute(\"iconfarm\"));\r\n contact.setIconServer(contactElement.getAttribute(\"iconserver\"));\r\n if (contact.getOnline() == OnlineStatus.AWAY) {\r\n contactElement.normalize();\r\n contact.setAwayMessage(XMLUtilities.getValue(contactElement));\r\n }\r\n contacts.add(contact);\r\n }\r\n return contacts;\r\n }", "public Where<T, ID> lt(String columnName, Object value) throws SQLException {\n\t\taddClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,\n\t\t\t\tSimpleComparison.LESS_THAN_OPERATION));\n\t\treturn this;\n\t}", "private TransactionManager getTransactionManager()\r\n {\r\n TransactionManager retval = null;\r\n try\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"getTransactionManager called\");\r\n retval = TransactionManagerFactoryFactory.instance().getTransactionManager();\r\n }\r\n catch (TransactionManagerFactoryException e)\r\n {\r\n log.warn(\"Exception trying to obtain TransactionManager from Factory\", e);\r\n e.printStackTrace();\r\n }\r\n return retval;\r\n }", "void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }", "public Class getSearchClass()\r\n\t{\r\n\t\tObject obj = getExampleObject();\r\n\r\n\t\tif (obj instanceof Identity)\r\n\t\t{\r\n\t\t\treturn ((Identity) obj).getObjectsTopLevelClass();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn obj.getClass();\r\n\t\t}\r\n\t}", "private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }", "public static final Double getDouble(InputStream is) throws IOException\n {\n double result = Double.longBitsToDouble(getLong(is));\n if (Double.isNaN(result))\n {\n result = 0;\n }\n return Double.valueOf(result);\n }" ]
Make sure that we have some reasonable defaults available. These would typically be provided by the rulesets in the real world.
[ "private void addDefaults()\n {\n this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Mandatory\", MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), \"Optional\", OPTIONAL, 1000, true));\n this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), \"Potential Issues\", POTENTIAL, 1000, true));\n this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), \"Cloud Mandatory\", CLOUD_MANDATORY, 1000, true));\n this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), \"Information\", INFORMATION, 1000, true));\n }" ]
[ "public void addAll(Vertex vtx) {\n if (head == null) {\n head = vtx;\n } else {\n tail.next = vtx;\n }\n vtx.prev = tail;\n while (vtx.next != null) {\n vtx = vtx.next;\n }\n tail = vtx;\n }", "public DataSetInfo create(int dataSet) throws InvalidDataSetException {\r\n\t\tDataSetInfo info = dataSets.get(createKey(dataSet));\r\n\t\tif (info == null) {\r\n\t\t\tint recordNumber = (dataSet >> 8) & 0xFF;\r\n\t\t\tint dataSetNumber = dataSet & 0xFF;\r\n\t\t\tthrow new UnsupportedDataSetException(recordNumber + \":\" + dataSetNumber);\r\n\t\t\t// info = super.create(dataSet);\r\n\t\t}\r\n\t\treturn info;\r\n\t}", "private int findIndexForName(String[] fieldNames, String searchName)\r\n {\r\n for(int i = 0; i < fieldNames.length; i++)\r\n {\r\n if(searchName.equals(fieldNames[i]))\r\n {\r\n return i;\r\n }\r\n }\r\n throw new PersistenceBrokerException(\"Can't find field name '\" + searchName +\r\n \"' in given array of field names\");\r\n }", "protected void initializeJdbcConnection(Connection con, JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n try\r\n {\r\n PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(jcd, con);\r\n }\r\n catch (PlatformException e)\r\n {\r\n throw new LookupException(\"Platform dependent initialization of connection failed\", e);\r\n }\r\n }", "public void populateContainer(Class<? extends FieldType> type, FieldContainer container, Integer id, byte[][] fixedData, Var2Data varData)\n {\n //System.out.println(container.getClass().getSimpleName()+\": \" + id);\n for (FieldItem item : m_map.values())\n {\n if (item.getType().getClass().equals(type))\n {\n //System.out.println(item.m_type);\n Object value = item.read(id, fixedData, varData);\n //System.out.println(item.m_type.getClass().getSimpleName() + \".\" + item.m_type + \": \" + value);\n container.set(item.getType(), value);\n }\n }\n }", "public void addImportedPackages(String... importedPackages) {\n\t\tString oldBundles = mainAttributes.get(IMPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : importedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(IMPORT_PACKAGE, result);\n\t}", "private void primeCache() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue()));\n }\n }\n }\n });\n }", "public StandaloneCommandBuilder addSecurityProperty(final String key, final String value) {\n securityProperties.put(key, value);\n return this;\n }", "public static <T> void finish(T query, long correlationId, EventBus bus, String... labels) {\n for (String type : labels) {\n RemoveLabelledQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }" ]
Returns the maximum magnitude of the complex numbers @param u Array of complex numbers @param startU first index to consider in u @param length Number of complex numebrs to consider @return magnitude
[ "public static double findMax( double[] u, int startU , int length ) {\n double max = -1;\n\n int index = startU*2;\n int stopIndex = (startU + length)*2;\n for( ; index < stopIndex;) {\n double real = u[index++];\n double img = u[index++];\n\n double val = real*real + img*img;\n\n if( val > max ) {\n max = val;\n }\n }\n\n return Math.sqrt(max);\n }" ]
[ "public final File getBuildFileFor(\n final Configuration configuration, final File jasperFileXml,\n final String extension, final Logger logger) {\n final String configurationAbsolutePath = configuration.getDirectory().getPath();\n final int prefixToConfiguration = configurationAbsolutePath.length() + 1;\n final String parentDir = jasperFileXml.getAbsoluteFile().getParent();\n final String relativePathToFile;\n if (configurationAbsolutePath.equals(parentDir)) {\n relativePathToFile = FilenameUtils.getBaseName(jasperFileXml.getName());\n } else {\n final String relativePathToContainingDirectory = parentDir.substring(prefixToConfiguration);\n relativePathToFile = relativePathToContainingDirectory + File.separator +\n FilenameUtils.getBaseName(jasperFileXml.getName());\n }\n\n final File buildFile = new File(getJasperCompilation(configuration), relativePathToFile + extension);\n\n if (!buildFile.getParentFile().exists() && !buildFile.getParentFile().mkdirs()) {\n logger.error(\"Unable to create directory for containing compiled jasper report templates: {}\",\n buildFile.getParentFile());\n }\n return buildFile;\n }", "public static void count() {\n long duration = SystemClock.uptimeMillis() - startTime;\n float avgFPS = sumFrames / (duration / 1000f);\n\n Log.v(\"FPSCounter\",\n \"total frames = %d, total elapsed time = %d ms, average fps = %f\",\n sumFrames, duration, avgFPS);\n }", "public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{\n\n\t\tString alias = _subjectMap.get(getSubjectForHostname(hostname));\n\n\t\tif(alias != null) {\n\t\t\treturn (X509Certificate)_ks.getCertificate(alias);\n\t\t}\n return getMappedCertificateForHostname(hostname);\n\t}", "private void requestBlock() {\n next = ByteBuffer.allocate(blockSizeBytes);\n long requestTimeout = retryParams.getRequestTimeoutMillisForCurrentAttempt();\n pendingFetch = raw.readObjectAsync(next, filename, fetchPosition, requestTimeout);\n }", "public ItemRequest<Attachment> findById(String attachment) {\n \n String path = String.format(\"/attachments/%s\", attachment);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"GET\");\n }", "public static String getParentDirectory(String filePath) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, filePath))\n return getURLParentDirectory(filePath);\n\n return new File(filePath).getParent();\n }", "public void execute() {\n State currentState = state.getAndSet(State.RUNNING);\n if (currentState == State.RUNNING) {\n throw new IllegalStateException(\n \"ExecutionChain is already running!\");\n }\n executeRunnable = new ExecuteRunnable();\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 }", "public void checkConstraints(String checkLevel) throws ConstraintException\r\n {\r\n // now checking constraints\r\n FieldDescriptorConstraints fieldConstraints = new FieldDescriptorConstraints();\r\n ReferenceDescriptorConstraints refConstraints = new ReferenceDescriptorConstraints();\r\n CollectionDescriptorConstraints collConstraints = new CollectionDescriptorConstraints();\r\n\r\n for (Iterator it = getFields(); it.hasNext();)\r\n {\r\n fieldConstraints.check((FieldDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getReferences(); it.hasNext();)\r\n {\r\n refConstraints.check((ReferenceDescriptorDef)it.next(), checkLevel);\r\n }\r\n for (Iterator it = getCollections(); it.hasNext();)\r\n {\r\n collConstraints.check((CollectionDescriptorDef)it.next(), checkLevel);\r\n }\r\n new ClassDescriptorConstraints().check(this, checkLevel);\r\n }" ]
Read a field from the supplied stream, starting with the tag that identifies the type, and reading enough to collect the corresponding value. @param is the stream on which a type tag is expected to be the next byte, followed by the field value. @return the field that was found on the stream. @throws IOException if there is a problem reading the field.
[ "public static Field read(DataInputStream is) throws IOException {\n final byte tag = is.readByte();\n final Field result;\n switch (tag) {\n case 0x0f:\n case 0x10:\n case 0x11:\n result = new NumberField(tag, is);\n break;\n\n case 0x14:\n result = new BinaryField(is);\n break;\n\n case 0x26:\n result = new StringField(is);\n break;\n\n default:\n throw new IOException(\"Unable to read a field with type tag \" + tag);\n }\n\n logger.debug(\"..received> {}\", result);\n return result;\n }" ]
[ "public void addFile(InputStream inputStream) {\n String name = \"file\";\n fileStreams.put(normalizeDuplicateName(name), inputStream);\n }", "public void setTextureBufferSize(final int size) {\n mRootViewGroup.post(new Runnable() {\n @Override\n public void run() {\n mRootViewGroup.setTextureBufferSize(size);\n }\n });\n }", "protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd,\r\n ObjectPool connectionPool)\r\n {\r\n final boolean allowConnectionUnwrap;\r\n if (jcd == null)\r\n {\r\n allowConnectionUnwrap = false;\r\n }\r\n else\r\n {\r\n final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties();\r\n final String allowConnectionUnwrapParam;\r\n allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED);\r\n allowConnectionUnwrap = allowConnectionUnwrapParam != null &&\r\n Boolean.valueOf(allowConnectionUnwrapParam).booleanValue();\r\n }\r\n final PoolingDataSource dataSource;\r\n dataSource = new PoolingDataSource(connectionPool);\r\n dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap);\r\n\r\n if(jcd != null)\r\n {\r\n final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();\r\n if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) {\r\n final LoggerWrapperPrintWriter loggerPiggyBack;\r\n loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR);\r\n dataSource.setLogWriter(loggerPiggyBack);\r\n }\r\n }\r\n return dataSource;\r\n }", "private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }", "public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams\n stopped = true;\n // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor\n if (cleanupTaskFuture != null) {\n cleanupTaskFuture.cancel(false);\n }\n\n // Close remaining streams\n for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) {\n InputStreamKey key = entry.getKey();\n TimedStreamEntry timedStreamEntry = entry.getValue();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it\n closeStreamEntry(timedStreamEntry, key.requestId, key.index);\n }\n }\n }", "public Date getTime(String fieldName) {\n\t\ttry {\n\t\t\tif (hasValue(fieldName)) {\n\t\t\t\treturn new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000);\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new FqlException(\"Field '\" + fieldName +\"' is not a time.\", e);\n\t\t}\n\t}", "private void clearBeatGrids(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(hotCache.keySet())) {\n if (deck.player == player) {\n hotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(player, null); // Inform listeners the beat grid is gone.\n }\n }\n }\n }", "public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "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 }" ]
Runs through the log removing segments older than a certain age @throws IOException
[ "private void cleanupLogs() throws IOException {\n logger.trace(\"Beginning log cleanup...\");\n int total = 0;\n Iterator<Log> iter = getLogIterator();\n long startMs = System.currentTimeMillis();\n while (iter.hasNext()) {\n Log log = iter.next();\n total += cleanupExpiredSegments(log) + cleanupSegmentsToMaintainSize(log);\n }\n if (total > 0) {\n logger.warn(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n } else {\n logger.trace(\"Log cleanup completed. \" + total + \" files deleted in \" + (System.currentTimeMillis() - startMs) / 1000 + \" seconds\");\n }\n }" ]
[ "public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());\n for(Integer serverId: serverIds) {\n clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));\n }\n return new VectorClock(clockEntries, timestamp);\n }", "protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(violationMessage);\n return violation;\n }", "public List<MapRow> readTableConditional(Class<? extends TableReader> readerClass) throws IOException\n {\n List<MapRow> result;\n if (DatatypeConverter.getBoolean(m_stream))\n {\n result = readTable(readerClass);\n }\n else\n {\n result = Collections.emptyList();\n }\n return result;\n }", "public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}", "public int getCrossZonePartitionStoreMoves() {\n int xzonePartitionStoreMoves = 0;\n for (RebalanceTaskInfo info : batchPlan) {\n Node donorNode = finalCluster.getNodeById(info.getDonorId());\n Node stealerNode = finalCluster.getNodeById(info.getStealerId());\n\n if(donorNode.getZoneId() != stealerNode.getZoneId()) {\n xzonePartitionStoreMoves += info.getPartitionStoreMoves();\n }\n }\n\n return xzonePartitionStoreMoves;\n }", "private static JsonArray getJsonArray(List<String> keys) {\n JsonArray array = new JsonArray();\n for (String key : keys) {\n array.add(key);\n }\n\n return array;\n }", "public Object get(String name, ObjectFactory<?> factory) {\n\t\tThreadScopeContext context = ThreadScopeContextHolder.getContext();\n\n\t\tObject result = context.getBean(name);\n\t\tif (null == result) {\n\t\t\tresult = factory.getObject();\n\t\t\tcontext.setBean(name, result);\n\t\t}\n\t\treturn result;\n\t}", "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 }", "static ChangeEvent<BsonDocument> changeEventForLocalUpdate(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final UpdateDescription update,\n final BsonDocument fullDocumentAfterUpdate,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.UPDATE,\n fullDocumentAfterUpdate,\n namespace,\n new BsonDocument(\"_id\", documentId),\n update,\n writePending);\n }" ]
Declares a shovel. @param vhost virtual host where to declare the shovel @param info Shovel info.
[ "public void declareShovel(String vhost, ShovelInfo info) {\n Map<String, Object> props = info.getDetails().getPublishProperties();\n if(props != null && props.isEmpty()) {\n throw new IllegalArgumentException(\"Shovel publish properties must be a non-empty map or null\");\n }\n final URI uri = uriWithPath(\"./parameters/shovel/\" + encodePathSegment(vhost) + \"/\" + encodePathSegment(info.getName()));\n this.rt.put(uri, info);\n }" ]
[ "public static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }", "public AT_Row setTextAlignment(TextAlignment textAlignment){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "@SuppressWarnings(\"unchecked\")\n public HttpMethodInfo handle(HttpRequest request,\n HttpResponder responder, Map<String, String> groupValues) throws Exception {\n //TODO: Refactor group values.\n try {\n if (httpMethods.contains(request.method())) {\n //Setup args for reflection call\n Object [] args = new Object[paramsInfo.size()];\n\n int idx = 0;\n for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {\n if (info.containsKey(PathParam.class)) {\n args[idx] = getPathParamValue(info, groupValues);\n }\n if (info.containsKey(QueryParam.class)) {\n args[idx] = getQueryParamValue(info, request.uri());\n }\n if (info.containsKey(HeaderParam.class)) {\n args[idx] = getHeaderParamValue(info, request);\n }\n idx++;\n }\n\n return new HttpMethodInfo(method, handler, responder, args, exceptionHandler);\n } else {\n //Found a matching resource but could not find the right HttpMethod so return 405\n throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format\n (\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n }\n } catch (Throwable e) {\n throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Error in executing request: %s %s\", request.method(),\n request.uri()), e);\n }\n }", "public void commitWorkingCopy(final String commitMessage) throws IOException, InterruptedException {\n build.getWorkspace().act(new SVNCommitWorkingCopyCallable(commitMessage, getLocation(),\n getSvnAuthenticationProvider(build), buildListener));\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 }", "private CoreLabel makeCoreLabel(String line) {\r\n CoreLabel wi = new CoreLabel();\r\n // wi.line = line;\r\n String[] bits = line.split(\"\\\\s+\");\r\n switch (bits.length) {\r\n case 0:\r\n case 1:\r\n wi.setWord(BOUNDARY);\r\n wi.set(AnswerAnnotation.class, OTHER);\r\n break;\r\n case 2:\r\n wi.setWord(bits[0]);\r\n wi.set(AnswerAnnotation.class, bits[1]);\r\n break;\r\n case 3:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(AnswerAnnotation.class, bits[2]);\r\n break;\r\n case 4:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(ChunkAnnotation.class, bits[2]);\r\n wi.set(AnswerAnnotation.class, bits[3]);\r\n break;\r\n case 5:\r\n if (flags.useLemmaAsWord) {\r\n wi.setWord(bits[1]);\r\n } else {\r\n wi.setWord(bits[0]);\r\n }\r\n wi.set(LemmaAnnotation.class, bits[1]);\r\n wi.setTag(bits[2]);\r\n wi.set(ChunkAnnotation.class, bits[3]);\r\n wi.set(AnswerAnnotation.class, bits[4]);\r\n break;\r\n default:\r\n throw new RuntimeIOException(\"Unexpected input (many fields): \" + line);\r\n }\r\n wi.set(OriginalAnswerAnnotation.class, wi.get(AnswerAnnotation.class));\r\n return wi;\r\n }", "public boolean contains(String id) {\n assertNotEmpty(id, \"id\");\n InputStream response = null;\n try {\n response = couchDbClient.head(new DatabaseURIHelper(dbUri).documentUri(id));\n } catch (NoDocumentException e) {\n return false;\n } finally {\n close(response);\n }\n return true;\n }", "private static List<Segment> parseSegments(String origPathStr) {\n String pathStr = origPathStr;\n if (!pathStr.startsWith(\"/\")) {\n pathStr = pathStr + \"/\";\n }\n\n List<Segment> result = new ArrayList<>();\n for (String segmentStr : PATH_SPLITTER.split(pathStr)) {\n Matcher m = SEGMENT_PATTERN.matcher(segmentStr);\n if (!m.matches()) {\n throw new IllegalArgumentException(\"Bad aql path: \" + origPathStr);\n }\n Segment segment = new Segment();\n segment.attribute = m.group(1);\n segment.nodeId = m.groupCount() >= 3 ? m.group(3) : null;\n result.add(segment);\n }\n return result;\n }", "public List<GVRAtlasInformation> getAtlasInformation()\n {\n if ((mImage != null) && (mImage instanceof GVRImageAtlas))\n {\n return ((GVRImageAtlas) mImage).getAtlasInformation();\n }\n return null;\n }" ]
Read the tag structure from the provided stream.
[ "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 void setMesh(GVRMesh mesh) {\n mMesh = mesh;\n NativeMeshCollider.setMesh(getNative(), mesh.getNative());\n }", "protected boolean isChangedByMask(int maskValue, Integer segmentPrefixLength) throws IncompatibleAddressException {\r\n\t\tboolean hasBits = (segmentPrefixLength != null);\r\n\t\tif(hasBits && (segmentPrefixLength < 0 || segmentPrefixLength > getBitCount())) {\r\n\t\t\tthrow new PrefixLenException(this, segmentPrefixLength);\r\n\t\t}\r\n\t\t\r\n\t\t//note that the mask can represent a range (for example a CIDR mask), \r\n\t\t//but we use the lowest value (maskSegment.value) in the range when masking (ie we discard the range)\r\n\t\tint value = getSegmentValue();\r\n\t\tint upperValue = getUpperSegmentValue();\r\n\t\treturn value != (value & maskValue) ||\r\n\t\t\t\tupperValue != (upperValue & maskValue) ||\r\n\t\t\t\t\t\t(isPrefixed() ? !getSegmentPrefixLength().equals(segmentPrefixLength) : hasBits);\r\n\t}", "public Map<Integer, String> listProjects(InputStream is) throws MPXJException\n {\n try\n {\n m_tables = new HashMap<String, List<Row>>();\n processFile(is);\n\n Map<Integer, String> result = new HashMap<Integer, String>();\n\n List<Row> rows = getRows(\"project\", null, null);\n for (Row row : rows)\n {\n Integer id = row.getInteger(\"proj_id\");\n String name = row.getString(\"proj_short_name\");\n result.put(id, name);\n }\n\n return result;\n }\n\n finally\n {\n m_tables = null;\n m_currentTable = null;\n m_currentFieldNames = null;\n }\n }", "public static void checkFolderForFile(String fileName) throws IOException {\n\n\t\tif (fileName.lastIndexOf(File.separator) > 0) {\n\t\t\tString folder = fileName.substring(0, fileName.lastIndexOf(File.separator));\n\t\t\tdirectoryCheck(folder);\n\t\t}\n\t}", "private String getRequestBody(ServletRequest request) throws IOException {\n\n final StringBuilder sb = new StringBuilder();\n\n String line = request.getReader().readLine();\n while (null != line) {\n sb.append(line);\n line = request.getReader().readLine();\n }\n\n return sb.toString();\n }", "public static void convert(DMatrixD1 input , ZMatrixD1 output ) {\n if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n Arrays.fill(output.data, 0, output.getDataLength(), 0);\n\n final int length = output.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i] = input.data[i/2];\n }\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static short checkShort(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInShortRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), SHORT_MIN, SHORT_MAX);\n\t\t}\n\n\t\treturn number.shortValue();\n\t}", "private static void freeTempLOB(ClobWrapper clob, BlobWrapper blob)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (clob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the CLOB is open, close it\r\n\t\t\t\tif (clob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tclob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this CLOB\r\n\t\t\t\tclob.freeTemporary();\r\n\t\t\t}\r\n\r\n\t\t\tif (blob != null)\r\n\t\t\t{\r\n\t\t\t\t// If the BLOB is open, close it\r\n\t\t\t\tif (blob.isOpen())\r\n\t\t\t\t{\r\n\t\t\t\t\tblob.close();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Free the memory used by this BLOB\r\n\t\t\t\tblob.freeTemporary();\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n logger.error(\"Error during temporary LOB release\", e);\r\n\t\t}\r\n\t}", "public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }" ]
Copies file from a resource to a local temp file @param sourceResource @return Absolute filename of the temp file @throws Exception
[ "public static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception {\n try {\n Resource keystoreFile = new ClassPathResource(sourceResource);\n InputStream in = keystoreFile.getInputStream();\n\n File outKeyStoreFile = new File(destFileName);\n FileOutputStream fop = new FileOutputStream(outKeyStoreFile);\n byte[] buf = new byte[512];\n int num;\n while ((num = in.read(buf)) != -1) {\n fop.write(buf, 0, num);\n }\n fop.flush();\n fop.close();\n in.close();\n return outKeyStoreFile;\n } catch (IOException ioe) {\n throw new Exception(\"Could not copy keystore file: \" + ioe.getMessage());\n }\n }" ]
[ "public String getAttributeValue(String attributeName)\n throws JMException, UnsupportedEncodingException {\n String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding);\n return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName));\n }", "@Override\n public Response toResponse(ErrorDto e)\n {\n // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType();\n return Response.status(e.httpStatus).entity(e).type(MediaType.APPLICATION_JSON).build();\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 ItemRequest<CustomField> updateEnumOption(String enumOption) {\n \n String path = String.format(\"/enum_options/%s\", enumOption);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"PUT\");\n }", "synchronized void start(final ManagedServerBootCmdFactory factory) {\n final InternalState required = this.requiredState;\n // Ignore if the server is already started\n if(required == InternalState.SERVER_STARTED) {\n return;\n }\n // In case the server failed to start, try to start it again\n if(required != InternalState.FAILED) {\n final InternalState current = this.internalState;\n if(current != required) {\n // TODO this perhaps should wait?\n throw new IllegalStateException();\n }\n }\n operationID = CurrentOperationIdHolder.getCurrentOperationID();\n bootConfiguration = factory.createConfiguration();\n requiredState = InternalState.SERVER_STARTED;\n ROOT_LOGGER.startingServer(serverName);\n transition();\n }", "public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent,\n boolean logMessageContentOverride) {\n\n /*\n * If controlling of logging behavior is not allowed externally\n * then log according to global property value\n */\n if (!logMessageContentOverride) {\n return logMessageContent;\n }\n\n Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME);\n\n if (null == logMessageContentExtObj) {\n\n return logMessageContent;\n\n } else if (logMessageContentExtObj instanceof Boolean) {\n\n return ((Boolean) logMessageContentExtObj).booleanValue();\n\n } else if (logMessageContentExtObj instanceof String) {\n\n String logMessageContentExtVal = (String) logMessageContentExtObj;\n\n if (logMessageContentExtVal.equalsIgnoreCase(\"true\")) {\n\n return true;\n\n } else if (logMessageContentExtVal.equalsIgnoreCase(\"false\")) {\n\n return false;\n\n } else {\n\n return logMessageContent;\n }\n } else {\n\n return logMessageContent;\n }\n }", "@SuppressWarnings(\"unchecked\")\n public HttpMethodInfo handle(HttpRequest request,\n HttpResponder responder, Map<String, String> groupValues) throws Exception {\n //TODO: Refactor group values.\n try {\n if (httpMethods.contains(request.method())) {\n //Setup args for reflection call\n Object [] args = new Object[paramsInfo.size()];\n\n int idx = 0;\n for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {\n if (info.containsKey(PathParam.class)) {\n args[idx] = getPathParamValue(info, groupValues);\n }\n if (info.containsKey(QueryParam.class)) {\n args[idx] = getQueryParamValue(info, request.uri());\n }\n if (info.containsKey(HeaderParam.class)) {\n args[idx] = getHeaderParamValue(info, request);\n }\n idx++;\n }\n\n return new HttpMethodInfo(method, handler, responder, args, exceptionHandler);\n } else {\n //Found a matching resource but could not find the right HttpMethod so return 405\n throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format\n (\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n }\n } catch (Throwable e) {\n throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Error in executing request: %s %s\", request.method(),\n request.uri()), e);\n }\n }", "public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }", "public static Iterable<BoxRetentionPolicy.Info> getAll(final BoxAPIConnection api, String ... fields) {\r\n return getAll(null, null, null, DEFAULT_LIMIT, api, fields);\r\n }" ]
Get the property of the given object. @param object which to be got @return the property of the given object @throws RuntimeException if the property could not be evaluated
[ "public Object getProperty(Object object) {\n MetaMethod getter = getGetter();\n if (getter == null) {\n if (field != null) return field.getProperty(object);\n //TODO: create a WriteOnlyException class?\n throw new GroovyRuntimeException(\"Cannot read write-only property: \" + name);\n }\n return getter.invoke(object, MetaClassHelper.EMPTY_ARRAY);\n }" ]
[ "private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes,\tComponent component) {\n Long currentTimeOfComponent = 0L;\n String key = component.getComponentType();\n if (mapComponentTimes.containsKey(key)) {\n currentTimeOfComponent = mapComponentTimes.get(key);\n }\n //when transactions are run in parallel, we should log the longest transaction only to avoid that \n //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms \n Long maxTime = Math.max(component.getTime(), currentTimeOfComponent);\n mapComponentTimes.put(key, maxTime);\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}", "@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }", "protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public Set<RateType> getRateTypes() {\n Set<RateType> result = get(KEY_RATE_TYPES, Set.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "public void close() {\n logger.info(\"Closing all sync producers\");\n if (sync) {\n for (SyncProducer p : syncProducers.values()) {\n p.close();\n }\n } else {\n for (AsyncProducer<V> p : asyncProducers.values()) {\n p.close();\n }\n }\n\n }", "@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null == baseTmsUrl) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"baseTmsUrl\");\n\t\t}\n\n\t\t// Make sure we have a base URL we can work with:\n\t\tif ((baseTmsUrl.startsWith(\"http://\") || baseTmsUrl.startsWith(\"https://\")) && !baseTmsUrl.endsWith(\"/\")) {\n\t\t\tbaseTmsUrl += \"/\";\n\t\t}\n\n\t\t// Make sure there is a correct RasterLayerInfo object:\n\t\tif (layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO) {\n\t\t\ttry {\n\t\t\t\ttileMap = configurationService.getCapabilities(this);\n\t\t\t\tversion = tileMap.getVersion();\n\t\t\t\textension = tileMap.getTileFormat().getExtension();\n\t\t\t\tlayerInfo = configurationService.asLayerInfo(tileMap);\n\t\t\t\tusable = true;\n\t\t\t} catch (TmsLayerException e) {\n\t\t\t\t// a layer needs an info object to keep the DtoConfigurationPostProcessor happy !\n\t\t\t\tlayerInfo = UNUSABLE_LAYER_INFO;\n\t\t\t\tusable = false;\n\t\t\t\tlog.warn(\"The layer could not be correctly initialized: \" + getId(), e);\n\t\t\t}\n\t\t} else if (extension == null) {\n\t\t\tthrow new GeomajasException(ExceptionCode.PARAMETER_MISSING, \"extension\");\n\t\t}\n\n\t\tif (layerInfo != null) {\n\t\t\t// Finally prepare some often needed values:\n\t\t\tstate = new TileServiceState(geoService, layerInfo);\n\t\t\t// when proxying the real url will be resolved later on, just use a simple one for now\n\t\t\tboolean proxying = useCache || useProxy || null != authentication;\n\t\t\tif (tileMap != null && !proxying) {\n\t\t\t\turlBuilder = new TileMapUrlBuilder(tileMap);\n\t\t\t} else {\n\t\t\t\turlBuilder = new SimpleTmsUrlBuilder(extension);\n\t\t\t}\n\t\t}\n\t}", "void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {\n assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;\n\n final PatchingHistory history = context.getHistory();\n for (final PatchElement element : patch.getElements()) {\n\n final PatchElementProvider provider = element.getProvider();\n final String name = provider.getName();\n final boolean addOn = provider.isAddOn();\n\n final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);\n final String cumulativePatchID = target.getCumulativePatchID();\n if (Constants.BASE.equals(cumulativePatchID)) {\n reenableRolledBackInBase(target);\n continue;\n }\n\n boolean found = false;\n final PatchingHistory.Iterator iterator = history.iterator();\n while (iterator.hasNextCP()) {\n final PatchingHistory.Entry entry = iterator.nextCP();\n final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);\n\n if (patchId != null && patchId.equals(cumulativePatchID)) {\n final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);\n for (final PatchElement originalElement : original.getElements()) {\n if (name.equals(originalElement.getProvider().getName())\n && addOn == originalElement.getProvider().isAddOn()) {\n PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);\n }\n }\n // Record a loader to have access to the current modules\n final DirectoryStructure structure = target.getDirectoryStructure();\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);\n context.recordContentLoader(patchId, loader);\n found = true;\n break;\n }\n }\n if (!found) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);\n }\n\n reenableRolledBackInBase(target);\n }\n }", "public static int cudnnLRNCrossChannelBackward(\n cudnnHandle handle, \n cudnnLRNDescriptor normDesc, \n int lrnMode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }" ]
Designate the vertex attribute and shader variable for the texture coordinates associated with the named texture. @param texName name of texture @param texCoordAttr name of vertex attribute with texture coordinates. @param shaderVarName name of shader variable to get texture coordinates.
[ "public void setTexCoord(String texName, String texCoordAttr, String shaderVarName)\n {\n synchronized (textures)\n {\n GVRTexture tex = textures.get(texName);\n\n if (tex != null)\n {\n tex.setTexCoord(texCoordAttr, shaderVarName);\n }\n else\n {\n throw new UnsupportedOperationException(\"Texture must be set before updating texture coordinate information\");\n }\n }\n }" ]
[ "public static int getXPathLocation(String dom, String xpath) {\n\t\tString dom_lower = dom.toLowerCase();\n\t\tString xpath_lower = xpath.toLowerCase();\n\t\tString[] elements = xpath_lower.split(\"/\");\n\t\tint pos = 0;\n\t\tint temp;\n\t\tint number;\n\t\tfor (String element : elements) {\n\t\t\tif (!element.isEmpty() && !element.startsWith(\"@\") && !element.contains(\"()\")) {\n\t\t\t\tif (element.contains(\"[\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnumber =\n\t\t\t\t\t\t\t\tInteger.parseInt(element.substring(element.indexOf(\"[\") + 1,\n\t\t\t\t\t\t\t\t\t\telement.indexOf(\"]\")));\n\t\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnumber = 1;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < number; i++) {\n\t\t\t\t\t// find new open element\n\t\t\t\t\ttemp = dom_lower.indexOf(\"<\" + stripEndSquareBrackets(element), pos);\n\n\t\t\t\t\tif (temp > -1) {\n\t\t\t\t\t\tpos = temp + 1;\n\n\t\t\t\t\t\t// if depth>1 then goto end of current element\n\t\t\t\t\t\tif (number > 1 && i < number - 1) {\n\t\t\t\t\t\t\tpos =\n\t\t\t\t\t\t\t\t\tgetCloseElementLocation(dom_lower, pos,\n\t\t\t\t\t\t\t\t\t\t\tstripEndSquareBrackets(element));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pos - 1;\n\t}", "public static <T> T flattenOption(scala.Option<T> option) {\n if (option.isEmpty()) {\n return null;\n } else {\n return option.get();\n }\n }", "public static int getActionBarHeight(Context context) {\n int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);\n if (actionBarHeight == 0) {\n actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);\n }\n return actionBarHeight;\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 }", "@Override\n public void setBody(String body) {\n super.setBody(body);\n this.jsonValue = JsonValue.readFrom(body);\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 static base_response update(nitro_service client, autoscaleaction resource) throws Exception {\n\t\tautoscaleaction updateresource = new autoscaleaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.parameters = resource.parameters;\n\t\tupdateresource.vmdestroygraceperiod = resource.vmdestroygraceperiod;\n\t\tupdateresource.quiettime = resource.quiettime;\n\t\tupdateresource.vserver = resource.vserver;\n\t\treturn updateresource.update_resource(client);\n\t}", "public boolean isEUI64(boolean partial) {\n\t\tint segmentCount = getSegmentCount();\n\t\tint endIndex = addressSegmentIndex + segmentCount;\n\t\tif(addressSegmentIndex <= 5) {\n\t\t\tif(endIndex > 6) {\n\t\t\t\tint index3 = 5 - addressSegmentIndex;\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(index3);\n\t\t\t\tIPv6AddressSegment seg4 = getSegment(index3 + 1);\n\t\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00) && seg3.matchesWithMask(0xff, 0xff);\n\t\t\t} else if(partial && endIndex == 6) {\n\t\t\t\tIPv6AddressSegment seg3 = getSegment(5 - addressSegmentIndex);\n\t\t\t\treturn seg3.matchesWithMask(0xff, 0xff);\n\t\t\t}\n\t\t} else if(partial && addressSegmentIndex == 6 && endIndex > 6) {\n\t\t\tIPv6AddressSegment seg4 = getSegment(6 - addressSegmentIndex);\n\t\t\treturn seg4.matchesWithMask(0xfe00, 0xff00);\n\t\t}\n\t\treturn partial;\n\t}", "synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }" ]
Returns the value of a property of the current object on the specified level. @param attributes The attributes of the tag @return The property value @exception XDocletException If an error occurs @doc.tag type="content" @doc.param name="level" optional="false" description="The level for the current object" values="class,field,reference,collection" @doc.param name="name" optional="false" description="The name of the property" @doc.param name="default" optional="true" description="A default value to use if the property is not defined"
[ "public String propertyValue(Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n return value;\r\n }" ]
[ "public Object getJavaDefaultValueDefault() {\n\t\tif (field.getType() == boolean.class) {\n\t\t\treturn DEFAULT_VALUE_BOOLEAN;\n\t\t} else if (field.getType() == byte.class || field.getType() == Byte.class) {\n\t\t\treturn DEFAULT_VALUE_BYTE;\n\t\t} else if (field.getType() == char.class || field.getType() == Character.class) {\n\t\t\treturn DEFAULT_VALUE_CHAR;\n\t\t} else if (field.getType() == short.class || field.getType() == Short.class) {\n\t\t\treturn DEFAULT_VALUE_SHORT;\n\t\t} else if (field.getType() == int.class || field.getType() == Integer.class) {\n\t\t\treturn DEFAULT_VALUE_INT;\n\t\t} else if (field.getType() == long.class || field.getType() == Long.class) {\n\t\t\treturn DEFAULT_VALUE_LONG;\n\t\t} else if (field.getType() == float.class || field.getType() == Float.class) {\n\t\t\treturn DEFAULT_VALUE_FLOAT;\n\t\t} else if (field.getType() == double.class || field.getType() == Double.class) {\n\t\t\treturn DEFAULT_VALUE_DOUBLE;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}", "private void processQueue()\r\n {\r\n CacheEntry sv;\r\n while((sv = (CacheEntry) queue.poll()) != null)\r\n {\r\n sessionCache.remove(sv.oid);\r\n }\r\n }", "<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) {\n return handlers.get(artifact);\n }", "public void setResource(Resource resource)\n {\n m_resource = resource;\n String name = m_resource.getName();\n if (name == null || name.length() == 0)\n {\n name = \"Unnamed Resource\";\n }\n setName(name);\n }", "public String addClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY,\n \"enterprise\", metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "public void updatePathOrder(int profileId, int[] pathOrder) {\n for (int i = 0; i < pathOrder.length; i++) {\n EditService.updatePathTable(Constants.PATH_PROFILE_PATH_ORDER, (i + 1), pathOrder[i]);\n }\n }", "public static byte[] addContentToExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {\n final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);\n ModelNode contentItem = getContentItem(deploymentResource);\n byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItem).asBytes();\n List<ModelNode> contents = CONTENT_PARAM_ALL_EXPLODED.resolveModelAttribute(context, operation).asList();\n final List<ExplodedContent> addedFiles = new ArrayList<>(contents.size());\n\n final ModelNode slave = operation.clone();\n ModelNode slaveAddedfiles = slave.get(UPDATED_PATHS.getName()).setEmptyList();\n for(ModelNode content : contents) {\n InputStream in;\n if(hasValidContentAdditionParameterDefined(content)) {\n in = getInputStream(context, content);\n } else {\n in = null;\n }\n String path = TARGET_PATH.resolveModelAttribute(context, content).asString();\n addedFiles.add(new ExplodedContent(path, in));\n slaveAddedfiles.add(path);\n }\n final boolean overwrite = OVERWRITE.resolveModelAttribute(context, operation).asBoolean(true);\n final byte[] hash = contentRepository.addContentToExploded(oldHash, addedFiles, overwrite);\n\n // Clear the contents and update with the hash\n ModelNode addedContent = new ModelNode().setEmptyObject();\n addedContent.get(HASH).set(hash);\n addedContent.get(TARGET_PATH.getName()).set(\".\");\n slave.get(CONTENT).setEmptyList().add(addedContent);\n // Add the domain op transformer\n List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);\n if (transformers == null) {\n context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());\n }\n transformers.add(new CompositeOperationAwareTransmuter(slave));\n return hash;\n }", "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 void setStructuredAppendMessageId(String messageId) {\r\n if (messageId != null && !messageId.matches(\"^[\\\\x21-\\\\x7F]+$\")) {\r\n throw new IllegalArgumentException(\"Invalid Aztec Code structured append message ID: \" + messageId);\r\n }\r\n this.structuredAppendMessageId = messageId;\r\n }" ]