query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Write the document object to a file. @param document the document object. @param filePathname the path name of the file to be written to. @param method the output method: for instance html, xml, text @param indent amount of indentation. -1 to use the default. @throws TransformerException if an exception occurs. @throws IOException if an IO exception occurs.
[ "public static void writeDocumentToFile(Document document,\n String filePathname, String method, int indent)\n throws TransformerException, IOException {\n\n Transformer transformer = TransformerFactory.newInstance()\n .newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, method);\n\n transformer.transform(new DOMSource(document), new StreamResult(\n new FileOutputStream(filePathname)));\n }" ]
[ "public static int getMemberDimension() throws XDocletException\r\n {\r\n if (getCurrentField() != null) {\r\n return getCurrentField().getDimension();\r\n }\r\n else if (getCurrentMethod() != null) {\r\n XMethod method = getCurrentMethod();\r\n\r\n if (MethodTagsHandler.isGetterMethod(method)) {\r\n return method.getReturnType().getDimension();\r\n }\r\n else if (MethodTagsHandler.isSetterMethod(method)) {\r\n XParameter param = (XParameter)method.getParameters().iterator().next();\r\n\r\n return param.getDimension();\r\n }\r\n }\r\n return 0;\r\n }", "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 }", "protected boolean shouldApplyThisRuleTo(ClassNode classNode) {\r\n // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r\n boolean shouldApply = true;\r\n\r\n String applyTo = getApplyToClassNames();\r\n String doNotApplyTo = getDoNotApplyToClassNames();\r\n\r\n if (applyTo != null && applyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(applyTo, true);\r\n shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());\r\n }\r\n\r\n if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {\r\n WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);\r\n shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());\r\n }\r\n\r\n return shouldApply;\r\n }", "private static void registerCommonClasses(Class<?>... commonClasses) {\n\t\tfor (Class<?> clazz : commonClasses) {\n\t\t\tcommonClassCache.put(clazz.getName(), clazz);\n\t\t}\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 }", "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 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 }", "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 void updateIntegerBelief(String name, int value) {\n introspector.storeBeliefValue(this, name, getIntegerBelief(name) + value);\n }" ]
Finds "Y" coordinate value in which more elements could be added in the band @param band @return
[ "public static int findVerticalOffset(JRDesignBand band) {\n\t\tint finalHeight = 0;\n\t\tif (band != null) {\n\t\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\t\tJRDesignElement element = (JRDesignElement) jrChild;\n\t\t\t\tint currentHeight = element.getY() + element.getHeight();\n\t\t\t\tif (currentHeight > finalHeight) finalHeight = currentHeight;\n\t\t\t}\n\t\t\treturn finalHeight;\n\t\t}\n\t\treturn finalHeight;\n\t}" ]
[ "public static Collection<Field> getAttributes(\n final Class<?> classToInspect, final Predicate<Field> filter) {\n Set<Field> allFields = new HashSet<>();\n getAllAttributes(classToInspect, allFields, Function.identity(), filter);\n return allFields;\n }", "public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {\n if (!ignoreUnaffectedServerGroups) {\n return model;\n }\n model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);\n addServerGroupsToModel(hostModel, model);\n return model;\n }", "public static void main(final String[] args) throws IOException\n {\n // This is just a _hack_ ...\n BufferedReader reader = null;\n if (args.length == 0)\n {\n System.err.println(\"No input file specified.\");\n System.exit(-1);\n }\n if (args.length > 1)\n {\n reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[1]), \"UTF-8\"));\n String line = reader.readLine();\n while (line != null && !line.startsWith(\"<!-- ###\"))\n {\n System.out.println(line);\n line = reader.readLine();\n }\n }\n System.out.println(Processor.process(new File(args[0])));\n if (args.length > 1 && reader != null)\n {\n String line = reader.readLine();\n while (line != null)\n {\n System.out.println(line);\n line = reader.readLine();\n }\n reader.close();\n }\n }", "protected synchronized void registerOpenDatabase(DatabaseImpl newDB)\r\n {\r\n DatabaseImpl old_db = getCurrentDatabase();\r\n if (old_db != null)\r\n {\r\n try\r\n {\r\n if (old_db.isOpen())\r\n {\r\n log.warn(\"## There is still an opened database, close old one ##\");\r\n old_db.close();\r\n }\r\n }\r\n catch (Throwable t)\r\n {\r\n //ignore\r\n }\r\n }\r\n if (log.isDebugEnabled()) log.debug(\"Set current database \" + newDB + \" PBKey was \" + newDB.getPBKey());\r\n setCurrentDatabase(newDB);\r\n// usedDatabases.add(newDB.getPBKey());\r\n }", "public int getHotCueCount() {\n if (rawMessage != null) {\n return (int) ((NumberField) rawMessage.arguments.get(5)).getValue();\n }\n int total = 0;\n for (Entry entry : entries) {\n if (entry.hotCueNumber > 0) {\n ++total;\n }\n }\n return total;\n }", "public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }", "void writeSomeValueRestriction(String propertyUri, String rangeUri,\n\t\t\tResource bnode) throws RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(bnode, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.OWL_RESTRICTION);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_ON_PROPERTY,\n\t\t\t\tpropertyUri);\n\t\tthis.rdfWriter.writeTripleUriObject(bnode,\n\t\t\t\tRdfWriter.OWL_SOME_VALUES_FROM, rangeUri);\n\t}", "public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }", "public static void finishThread(){\r\n //--Create Task\r\n final long threadId = Thread.currentThread().getId();\r\n Runnable finish = new Runnable(){\r\n public void run(){\r\n releaseThreadControl(threadId);\r\n }\r\n };\r\n //--Run Task\r\n if(isThreaded){\r\n //(case: multithreaded)\r\n attemptThreadControl( threadId, finish );\r\n } else {\r\n //(case: no threading)\r\n throw new IllegalStateException(\"finishThreads() called outside of threaded environment\");\r\n }\r\n }" ]
Builds the table for the database results. @param results the database results @return the table
[ "private Table buildTable(CmsSqlConsoleResults results) {\n\n IndexedContainer container = new IndexedContainer();\n int numCols = results.getColumns().size();\n for (int c = 0; c < numCols; c++) {\n container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null);\n }\n int r = 0;\n for (List<Object> row : results.getData()) {\n Item item = container.addItem(Integer.valueOf(r));\n for (int c = 0; c < numCols; c++) {\n item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c));\n }\n r += 1;\n }\n Table table = new Table();\n table.setContainerDataSource(container);\n for (int c = 0; c < numCols; c++) {\n String col = (results.getColumns().get(c));\n table.setColumnHeader(Integer.valueOf(c), col);\n }\n table.setWidth(\"100%\");\n table.setHeight(\"100%\");\n table.setColumnCollapsingAllowed(true);\n return table;\n }" ]
[ "private String getPropertyLabel(PropertyIdValue propertyIdValue) {\n\t\tPropertyRecord propertyRecord = this.propertyRecords\n\t\t\t\t.get(propertyIdValue);\n\t\tif (propertyRecord == null || propertyRecord.propertyDocument == null) {\n\t\t\treturn propertyIdValue.getId();\n\t\t} else {\n\t\t\treturn getLabel(propertyIdValue, propertyRecord.propertyDocument);\n\t\t}\n\t}", "static Path resolvePath(final Path base, final String... paths) {\n return Paths.get(base.toString(), paths);\n }", "private List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }", "public static void acceptsZone(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_Z, OPT_ZONE), \"zone id\")\n .withRequiredArg()\n .describedAs(\"zone-id\")\n .ofType(Integer.class);\n }", "public static void zeroTriangle( boolean upper , DMatrixRBlock A )\n {\n int blockLength = A.blockLength;\n\n if( upper ) {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = i; j < A.numCols; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n for( int l = k+1; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n } else {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = 0; j <= i; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n int z = Math.min(k,w);\n for( int l = 0; l < z; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n }\n }", "protected FluentModelTImpl find(String key) {\n for (Map.Entry<String, FluentModelTImpl> entry : this.childCollection.entrySet()) {\n if (entry.getKey().equalsIgnoreCase(key)) {\n return entry.getValue();\n }\n }\n return null;\n }", "public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException {\n MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry();\n MetaClass meta = metaRegistry.getMetaClass(theClass);\n return new ProxyMetaClass(metaRegistry, theClass, meta);\n }", "private static void listTasks(ProjectFile file)\n {\n SimpleDateFormat df = new SimpleDateFormat(\"dd/MM/yyyy HH:mm z\");\n\n for (Task task : file.getTasks())\n {\n Date date = task.getStart();\n String text = task.getStartText();\n String startDate = text != null ? text : (date != null ? df.format(date) : \"(no start date supplied)\");\n\n date = task.getFinish();\n text = task.getFinishText();\n String finishDate = text != null ? text : (date != null ? df.format(date) : \"(no finish date supplied)\");\n\n Duration dur = task.getDuration();\n text = task.getDurationText();\n String duration = text != null ? text : (dur != null ? dur.toString() : \"(no duration supplied)\");\n\n dur = task.getActualDuration();\n String actualDuration = dur != null ? dur.toString() : \"(no actual duration supplied)\";\n\n String baselineDuration = task.getBaselineDurationText();\n if (baselineDuration == null)\n {\n dur = task.getBaselineDuration();\n if (dur != null)\n {\n baselineDuration = dur.toString();\n }\n else\n {\n baselineDuration = \"(no duration supplied)\";\n }\n }\n\n System.out.println(\"Task: \" + task.getName() + \" ID=\" + task.getID() + \" Unique ID=\" + task.getUniqueID() + \" (Start Date=\" + startDate + \" Finish Date=\" + finishDate + \" Duration=\" + duration + \" Actual Duration\" + actualDuration + \" Baseline Duration=\" + baselineDuration + \" Outline Level=\" + task.getOutlineLevel() + \" Outline Number=\" + task.getOutlineNumber() + \" Recurring=\" + task.getRecurring() + \")\");\n }\n System.out.println();\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 }" ]
Use this API to fetch rewritepolicy_csvserver_binding resources of given name .
[ "public static rewritepolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\trewritepolicy_csvserver_binding obj = new rewritepolicy_csvserver_binding();\n\t\tobj.set_name(name);\n\t\trewritepolicy_csvserver_binding response[] = (rewritepolicy_csvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our previews, on the proper thread, and outside our lock.\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(hotCache.keySet());\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n if (deck.hotCue == 0) {\n deliverBeatGridUpdate(deck.player, null);\n }\n }\n }\n });\n hotCache.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "public static String getOffsetCodeFromCurveName(String curveName) {\r\n\t\tif(curveName == null || curveName.length() == 0) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tString[] splits = curveName.split(\"(?<=\\\\D)(?=\\\\d)\");\r\n\t\tString offsetCode = splits[splits.length-1];\r\n\t\tif(!Character.isDigit(offsetCode.charAt(0))) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\toffsetCode = offsetCode.split(\"(?<=[A-Za-z])(?=.)\", 2)[0];\r\n\t\toffsetCode = offsetCode.replaceAll( \"[\\\\W_]\", \"\" );\r\n\t\treturn offsetCode;\r\n\t}", "public void addEmailStats(final InternetAddress[] recipients, final boolean storageUsed) {\n this.storageUsed = storageUsed;\n for (InternetAddress recipient: recipients) {\n emailDests.add(recipient.getAddress());\n }\n }", "public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }", "private void processStages() {\n\n // Locate the next step to execute.\n ModelNode primaryResponse = null;\n Step step;\n do {\n step = steps.get(currentStage).pollFirst();\n if (step == null) {\n\n if (currentStage == Stage.MODEL && addModelValidationSteps()) {\n continue;\n }\n // No steps remain in this stage; give subclasses a chance to check status\n // and approve moving to the next stage\n if (!tryStageCompleted(currentStage)) {\n // Can't continue\n resultAction = ResultAction.ROLLBACK;\n executeResultHandlerPhase(null);\n return;\n }\n // Proceed to the next stage\n if (currentStage.hasNext()) {\n currentStage = currentStage.next();\n if (currentStage == Stage.VERIFY) {\n // a change was made to the runtime. Thus, we must wait\n // for stability before resuming in to verify.\n try {\n awaitServiceContainerStability();\n } catch (InterruptedException e) {\n cancelled = true;\n handleContainerStabilityFailure(primaryResponse, e);\n executeResultHandlerPhase(null);\n return;\n } catch (TimeoutException te) {\n // The service container is in an unknown state; but we don't require restart\n // because rollback may allow the container to stabilize. We force require-restart\n // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)\n //processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback\n handleContainerStabilityFailure(primaryResponse, te);\n executeResultHandlerPhase(null);\n return;\n }\n }\n }\n } else {\n // The response to the first step is what goes to the outside caller\n if (primaryResponse == null) {\n primaryResponse = step.response;\n }\n // Execute the step, but make sure we always finalize any steps\n Throwable toThrow = null;\n // Whether to return after try/finally\n boolean exit = false;\n try {\n CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step);\n if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) {\n executeStep(step);\n } else {\n String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED\n ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD;\n step.response.get(RESPONSE_HEADERS, header).set(true);\n }\n } catch (RuntimeException | Error re) {\n resultAction = ResultAction.ROLLBACK;\n toThrow = re;\n } finally {\n // See if executeStep put us in a state where we shouldn't do any more\n if (toThrow != null || !canContinueProcessing()) {\n // We're done.\n executeResultHandlerPhase(toThrow);\n exit = true; // we're on the return path\n }\n }\n if (exit) {\n return;\n }\n }\n } while (currentStage != Stage.DONE);\n\n assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps\n\n // All steps ran and canContinueProcessing returned true for the last one, so...\n executeDoneStage(primaryResponse);\n }", "private byte[] receiveBytes(InputStream is) throws IOException {\n byte[] buffer = new byte[8192];\n int len = (is.read(buffer));\n if (len < 1) {\n throw new IOException(\"receiveBytes read \" + len + \" bytes.\");\n }\n return Arrays.copyOf(buffer, len);\n }", "public PeriodicEvent runEvery(Runnable task, float delay, float period) {\n return runEvery(task, delay, period, null);\n }", "public boolean isPartOf(GetVectorTileRequest request) {\n\t\tif (Math.abs(request.scale - scale) > EQUALS_DELTA) { return false; }\n\t\tif (code != null ? !code.equals(request.code) : request.code != null) { return false; }\n\t\tif (crs != null ? !crs.equals(request.crs) : request.crs != null) { return false; }\n\t\tif (filter != null ? !filter.equals(request.filter) : request.filter != null) { return false; }\n\t\tif (panOrigin != null ? !panOrigin.equals(request.panOrigin) : request.panOrigin != null) { return false; }\n\t\tif (renderer != null ? !renderer.equals(request.renderer) : request.renderer != null) { return false; }\n\t\tif (styleInfo != null ? !styleInfo.equals(request.styleInfo) : request.styleInfo != null) { return false; }\n\t\tif (paintGeometries && !request.paintGeometries) { return false; }\n\t\tif (paintLabels && !request.paintLabels) { return false; }\n\t\treturn true;\n\t}", "private FieldDescriptorDef cloneField(FieldDescriptorDef fieldDef, String prefix)\r\n {\r\n FieldDescriptorDef copyFieldDef = new FieldDescriptorDef(fieldDef, prefix);\r\n\r\n copyFieldDef.setOwner(this);\r\n // we remove properties that are only relevant to the class the features are declared in\r\n copyFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_IGNORE, null);\r\n\r\n Properties mod = getModification(copyFieldDef.getName());\r\n\r\n if (mod != null)\r\n {\r\n if (!PropertyHelper.toBoolean(mod.getProperty(PropertyHelper.OJB_PROPERTY_IGNORE), false) &&\r\n hasFeature(copyFieldDef.getName()))\r\n {\r\n LogHelper.warn(true,\r\n ClassDescriptorDef.class,\r\n \"process\",\r\n \"Class \"+getName()+\" has a feature that has the same name as its included field \"+\r\n copyFieldDef.getName()+\" from class \"+fieldDef.getOwner().getName()); \r\n }\r\n copyFieldDef.applyModifications(mod);\r\n }\r\n return copyFieldDef;\r\n }" ]
Use this API to fetch all the nd6ravariables resources that are configured on netscaler.
[ "public static nd6ravariables[] get(nitro_service service, options option) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tnd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option);\n\t\treturn response;\n\t}" ]
[ "public static long directorySize(File self) throws IOException, IllegalArgumentException\n {\n final long[] size = {0L};\n\n eachFileRecurse(self, FileType.FILES, new Closure<Void>(null) {\n public void doCall(Object[] args) {\n size[0] += ((File) args[0]).length();\n }\n });\n\n return size[0];\n }", "public Envelope getMaxExtent() {\n final int minX = 0;\n final int maxX = 1;\n final int minY = 2;\n final int maxY = 3;\n return new Envelope(this.maxExtent[minX], this.maxExtent[minY], this.maxExtent[maxX],\n this.maxExtent[maxY]);\n }", "public static void main(String[] args) throws Exception {\r\n StringUtils.printErrInvocationString(\"CRFClassifier\", args);\r\n\r\n Properties props = StringUtils.argsToProperties(args);\r\n CRFClassifier<CoreLabel> crf = new CRFClassifier<CoreLabel>(props);\r\n String testFile = crf.flags.testFile;\r\n String textFile = crf.flags.textFile;\r\n String loadPath = crf.flags.loadClassifier;\r\n String loadTextPath = crf.flags.loadTextClassifier;\r\n String serializeTo = crf.flags.serializeTo;\r\n String serializeToText = crf.flags.serializeToText;\r\n\r\n if (loadPath != null) {\r\n crf.loadClassifierNoExceptions(loadPath, props);\r\n } else if (loadTextPath != null) {\r\n System.err.println(\"Warning: this is now only tested for Chinese Segmenter\");\r\n System.err.println(\"(Sun Dec 23 00:59:39 2007) (pichuan)\");\r\n try {\r\n crf.loadTextClassifier(loadTextPath, props);\r\n // System.err.println(\"DEBUG: out from crf.loadTextClassifier\");\r\n } catch (Exception e) {\r\n throw new RuntimeException(\"error loading \" + loadTextPath, e);\r\n }\r\n } else if (crf.flags.loadJarClassifier != null) {\r\n crf.loadJarClassifier(crf.flags.loadJarClassifier, props);\r\n } else if (crf.flags.trainFile != null || crf.flags.trainFileList != null) {\r\n crf.train();\r\n } else {\r\n crf.loadDefaultClassifier();\r\n }\r\n\r\n // System.err.println(\"Using \" + crf.flags.featureFactory);\r\n // System.err.println(\"Using \" +\r\n // StringUtils.getShortClassName(crf.readerAndWriter));\r\n\r\n if (serializeTo != null) {\r\n crf.serializeClassifier(serializeTo);\r\n }\r\n\r\n if (serializeToText != null) {\r\n crf.serializeTextClassifier(serializeToText);\r\n }\r\n\r\n if (testFile != null) {\r\n DocumentReaderAndWriter<CoreLabel> readerAndWriter = crf.makeReaderAndWriter();\r\n if (crf.flags.searchGraphPrefix != null) {\r\n crf.classifyAndWriteViterbiSearchGraph(testFile, crf.flags.searchGraphPrefix, crf.makeReaderAndWriter());\r\n } else if (crf.flags.printFirstOrderProbs) {\r\n crf.printFirstOrderProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.printProbs) {\r\n crf.printProbs(testFile, readerAndWriter);\r\n } else if (crf.flags.useKBest) {\r\n int k = crf.flags.kBest;\r\n crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter);\r\n } else if (crf.flags.printLabelValue) {\r\n crf.printLabelInformation(testFile, readerAndWriter);\r\n } else {\r\n crf.classifyAndWriteAnswers(testFile, readerAndWriter);\r\n }\r\n }\r\n\r\n if (textFile != null) {\r\n crf.classifyAndWriteAnswers(textFile);\r\n }\r\n\r\n if (crf.flags.readStdin) {\r\n crf.classifyStdin();\r\n }\r\n }", "public void forAllIndexColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curIndexDef.getColumns(); it.hasNext(); )\r\n {\r\n _curColumnDef = _curTableDef.getColumn((String)it.next());\r\n generate(template);\r\n }\r\n _curColumnDef = null;\r\n }", "@Override\n public PaxDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public final void notifyHeaderItemRangeChanged(int positionStart, int itemCount) {\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemRangeChanged(positionStart, itemCount);\n }", "private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException {\n if (shouldWriteDecoratorAndElements(model)) {\n writer.writeStartElement(decoratorElement);\n persistChildren(writer, model);\n writer.writeEndElement();\n }\n }", "public Deployment setServerGroups(final Collection<String> serverGroups) {\n this.serverGroups.clear();\n this.serverGroups.addAll(serverGroups);\n return this;\n }", "public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\tf.set(receiver, value);\n\t}" ]
invoked from the jelly file @throws Exception Any exception
[ "@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 static int longestCommonContiguousSubstring(String s, String t) {\r\n if (s.length() == 0 || t.length() == 0) {\r\n return 0;\r\n }\r\n int M = s.length();\r\n int N = t.length();\r\n int[][] d = new int[M + 1][N + 1];\r\n for (int j = 0; j <= N; j++) {\r\n d[0][j] = 0;\r\n }\r\n for (int i = 0; i <= M; i++) {\r\n d[i][0] = 0;\r\n }\r\n\r\n int max = 0;\r\n for (int i = 1; i <= M; i++) {\r\n for (int j = 1; j <= N; j++) {\r\n if (s.charAt(i - 1) == t.charAt(j - 1)) {\r\n d[i][j] = d[i - 1][j - 1] + 1;\r\n } else {\r\n d[i][j] = 0;\r\n }\r\n\r\n if (d[i][j] > max) {\r\n max = d[i][j];\r\n }\r\n }\r\n }\r\n // System.err.println(\"LCCS(\" + s + \",\" + t + \") = \" + max);\r\n return max;\r\n }", "public Boolean getBoolean(int field, String falseText)\n {\n Boolean result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = ((m_fields[field].equalsIgnoreCase(falseText) == true) ? Boolean.FALSE : Boolean.TRUE);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "private void addToInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.addNavigationalInformationForInverseSide();\n\t}", "public static String minus(CharSequence self, Object target) {\n String s = self.toString();\n String text = DefaultGroovyMethods.toString(target);\n int index = s.indexOf(text);\n if (index == -1) return s;\n int end = index + text.length();\n if (s.length() > end) {\n return s.substring(0, index) + s.substring(end);\n }\n return s.substring(0, index);\n }", "private void animateIndicatorInvalidate() {\n if (mIndicatorScroller.computeScrollOffset()) {\n mIndicatorOffset = mIndicatorScroller.getCurr();\n invalidate();\n\n if (!mIndicatorScroller.isFinished()) {\n postOnAnimation(mIndicatorRunnable);\n return;\n }\n }\n\n completeAnimatingIndicator();\n }", "private Object tryConvert(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final Object rowValue) throws URISyntaxException, IOException {\n if (this.converters.isEmpty()) {\n return rowValue;\n }\n\n String value = String.valueOf(rowValue);\n for (TableColumnConverter<?> converter: this.converters) {\n if (converter.canConvert(value)) {\n return converter.resolve(clientHttpRequestFactory, value);\n }\n }\n\n return rowValue;\n }", "public static String replaceHtmlEntities(String content, Map<String, Character> map) {\n \n for (Entry<String, Character> entry : escapeStrings.entrySet()) {\n \n if (content.indexOf(entry.getKey()) != -1) {\n content = content.replace(entry.getKey(), String.valueOf(entry.getValue()));\n }\n \n }\n \n return content;\n }", "public void setPermissions(Permissions permissions) {\n if (this.permissions == permissions) {\n return;\n }\n\n this.removeChildObject(\"permissions\");\n this.permissions = permissions;\n this.addChildObject(\"permissions\", permissions);\n }", "public static int ptb2Text(Reader ptbText, Writer w) throws IOException {\r\n int numTokens = 0;\r\n PTB2TextLexer lexer = new PTB2TextLexer(ptbText);\r\n for (String token; (token = lexer.next()) != null; ) {\r\n numTokens++;\r\n w.write(token);\r\n }\r\n return numTokens;\r\n }" ]
Un-serialize a Json into Organization @param organization String @return Organization @throws IOException
[ "public static Organization unserializeOrganization(final String organization) throws IOException {\n final ObjectMapper mapper = new ObjectMapper();\n mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);\n return mapper.readValue(organization, Organization.class);\n }" ]
[ "public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\n }", "public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException {\n\t\tString[] split = signedRequest.split(\"\\\\.\");\n\t\tString encodedSignature = split[0];\n\t\tString payload = split[1];\t\t\n\t\tString decoded = base64DecodeToString(payload);\t\t\n\t\tbyte[] signature = base64DecodeToBytes(encodedSignature);\n\t\ttry {\n\t\t\tT data = objectMapper.readValue(decoded, type);\t\t\t\n\t\t\tString algorithm = objectMapper.readTree(decoded).get(\"algorithm\").textValue();\n\t\t\tif (algorithm == null || !algorithm.equals(\"HMAC-SHA256\")) {\n\t\t\t\tthrow new SignedRequestException(\"Unknown encryption algorithm: \" + algorithm);\n\t\t\t}\t\t\t\n\t\t\tbyte[] expectedSignature = encrypt(payload, secret);\n\t\t\tif (!Arrays.equals(expectedSignature, signature)) {\n\t\t\t\tthrow new SignedRequestException(\"Invalid signature.\");\n\t\t\t}\t\t\t\n\t\t\treturn data;\n\t\t} catch (IOException e) {\n\t\t\tthrow new SignedRequestException(\"Error parsing payload.\", e);\n\t\t}\n\t}", "private Object filterValue(Object value)\n {\n if (value instanceof Boolean && !((Boolean) value).booleanValue())\n {\n value = null;\n }\n if (value instanceof String && ((String) value).isEmpty())\n {\n value = null;\n }\n if (value instanceof Double && ((Double) value).doubleValue() == 0.0)\n {\n value = null;\n }\n if (value instanceof Integer && ((Integer) value).intValue() == 0)\n {\n value = null;\n }\n if (value instanceof Duration && ((Duration) value).getDuration() == 0.0)\n {\n value = null;\n }\n\n return value;\n }", "public void insert(Platform platform, Database model, int batchSize) throws SQLException\r\n {\r\n if (batchSize <= 1)\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n platform.insert(model, (DynaBean)it.next());\r\n }\r\n }\r\n else\r\n {\r\n for (int startIdx = 0; startIdx < _beans.size(); startIdx += batchSize)\r\n {\r\n platform.insert(model, _beans.subList(startIdx, startIdx + batchSize));\r\n }\r\n }\r\n }", "private void readResourceAssignments(Project gpProject)\n {\n Allocations allocations = gpProject.getAllocations();\n if (allocations != null)\n {\n for (Allocation allocation : allocations.getAllocation())\n {\n readResourceAssignment(allocation);\n }\n }\n }", "private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {\n\n int i, j;\n QrMode currentMode;\n int inputLength = inputModeUnoptimized.length;\n int count = 0;\n int alphaLength;\n int percent = 0;\n\n // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave\n // the original array alone so that subsequent binary length checks don't irrevocably\n // optimize the mode array for the wrong QR Code version\n QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);\n\n currentMode = QrMode.NULL;\n\n if (gs1) {\n count += 4;\n }\n\n if (eciMode != 3) {\n count += 12;\n }\n\n for (i = 0; i < inputLength; i++) {\n if (inputMode[i] != currentMode) {\n count += 4;\n switch (inputMode[i]) {\n case KANJI:\n count += tribus(version, 8, 10, 12);\n count += (blockLength(i, inputMode) * 13);\n break;\n case BINARY:\n count += tribus(version, 8, 16, 16);\n for (j = i; j < (i + blockLength(i, inputMode)); j++) {\n if (inputData[j] > 0xff) {\n count += 16;\n } else {\n count += 8;\n }\n }\n break;\n case ALPHANUM:\n count += tribus(version, 9, 11, 13);\n alphaLength = blockLength(i, inputMode);\n // In alphanumeric mode % becomes %%\n if (gs1) {\n for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b\n if (inputData[j] == '%') {\n percent++;\n }\n }\n }\n alphaLength += percent;\n switch (alphaLength % 2) {\n case 0:\n count += (alphaLength / 2) * 11;\n break;\n case 1:\n count += ((alphaLength - 1) / 2) * 11;\n count += 6;\n break;\n }\n break;\n case NUMERIC:\n count += tribus(version, 10, 12, 14);\n switch (blockLength(i, inputMode) % 3) {\n case 0:\n count += (blockLength(i, inputMode) / 3) * 10;\n break;\n case 1:\n count += ((blockLength(i, inputMode) - 1) / 3) * 10;\n count += 4;\n break;\n case 2:\n count += ((blockLength(i, inputMode) - 2) / 3) * 10;\n count += 7;\n break;\n }\n break;\n }\n currentMode = inputMode[i];\n }\n }\n\n return count;\n }", "protected synchronized Object materializeSubject() throws PersistenceBrokerException\r\n\t{\r\n\t\tTemporaryBrokerWrapper tmp = getBroker();\r\n try\r\n\t\t{\r\n\t\t\tObject realSubject = tmp.broker.getObjectByIdentity(_id);\r\n\t\t\tif (realSubject == null)\r\n\t\t\t{\r\n\t\t\t\tLoggerFactory.getLogger(IndirectionHandler.class).warn(\r\n\t\t\t\t\t\t\"Can not materialize object for Identity \" + _id + \" - using PBKey \" + getBrokerKey());\r\n\t\t\t}\r\n\t\t\treturn realSubject;\r\n\t\t} catch (Exception ex)\r\n\t\t{\r\n\t\t\tthrow new PersistenceBrokerException(ex);\r\n\t\t} finally\r\n\t\t{\r\n\t\t\ttmp.close();\r\n\t\t}\r\n\t}", "public static int cudnnConvolutionForward(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n cudnnFilterDescriptor wDesc, \n Pointer w, \n cudnnConvolutionDescriptor convDesc, \n int algo, \n Pointer workSpace, \n long workSpaceSizeInBytes, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnConvolutionForwardNative(handle, alpha, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, beta, yDesc, y));\n }", "public Collection<DataSource> getDataSources(int groupno) {\n if (groupno == 1)\n return group1;\n else if (groupno == 2)\n return group2;\n else\n throw new DukeConfigException(\"Invalid group number: \" + groupno);\n }" ]
get the type erasure signature
[ "public FullTypeSignature getTypeErasureSignature() {\r\n\t\tif (typeErasureSignature == null) {\r\n\t\t\ttypeErasureSignature = new ClassTypeSignature(binaryName,\r\n\t\t\t\t\tnew TypeArgSignature[0], ownerTypeSignature == null ? null\r\n\t\t\t\t\t\t\t: (ClassTypeSignature) ownerTypeSignature\r\n\t\t\t\t\t\t\t\t\t.getTypeErasureSignature());\r\n\t\t}\r\n\t\treturn typeErasureSignature;\r\n\t}" ]
[ "private static void writeUtf16Bom(OutputStream stream, boolean bigEndian) throws IOException {\n if (bigEndian) {\n stream.write(-2);\n stream.write(-1);\n } else {\n stream.write(-1);\n stream.write(-2);\n }\n }", "public void setConnectTimeout(int millis) {\n\t\tClientHttpRequestFactory f = getRequestFactory();\n\t\tif (f instanceof SimpleClientHttpRequestFactory) {\n\t\t\t((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t\telse {\n\t\t\t((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);\n\t\t}\n\t}", "public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {\n Set<String> orderedChildTypes = resource.getOrderedChildTypes();\n if (orderedChildTypes.size() > 0) {\n orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());\n }\n }", "public static Object getFieldValue(Object object, String fieldName) {\n try {\n return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }", "public void forceApply(String conflictResolution) {\n\n URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n JsonObject requestJSON = new JsonObject()\n .add(\"conflict_resolution\", conflictResolution);\n request.setBody(requestJSON.toString());\n request.send();\n }", "public static base_responses update(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy updateresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new dospolicy();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].qdepth = resources[i].qdepth;\n\t\t\t\tupdateresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "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 boolean clearParameters() {\n this.query = null;\n this.fields = null;\n this.scope = null;\n this.fileExtensions = null;\n this.createdRange = null;\n this.updatedRange = null;\n this.sizeRange = null;\n this.ownerUserIds = null;\n this.ancestorFolderIds = null;\n this.contentTypes = null;\n this.type = null;\n this.trashContent = null;\n this.metadataFilter = null;\n this.sort = null;\n this.direction = null;\n return true;\n }", "private void verifyXopResponse(XopBean xopOriginal, XopBean xopResponse) {\n if (!Arrays.equals(xopResponse.getBytes(), xopOriginal.getBytes())) {\n throw new RuntimeException(\"Received XOP attachment is corrupted\");\n }\n System.out.println();\n System.out.println(\"XOP attachment has been successfully received\");\n }" ]
This filter changes the amount of color in each of the three channels. @param r The amount of redness in the picture. Can range from -100 to 100 in percentage. @param g The amount of greenness in the picture. Can range from -100 to 100 in percentage. @param b The amount of blueness in the picture. Can range from -100 to 100 in percentage. @throws IllegalArgumentException if {@code r}, {@code g}, or {@code b} are outside of bounds.
[ "public static String rgb(int r, int g, int b) {\n if (r < -100 || r > 100) {\n throw new IllegalArgumentException(\"Red value must be between -100 and 100, inclusive.\");\n }\n if (g < -100 || g > 100) {\n throw new IllegalArgumentException(\"Green value must be between -100 and 100, inclusive.\");\n }\n if (b < -100 || b > 100) {\n throw new IllegalArgumentException(\"Blue value must be between -100 and 100, inclusive.\");\n }\n return FILTER_RGB + \"(\" + r + \",\" + g + \",\" + b + \")\";\n }" ]
[ "public static final void decodeBuffer(byte[] data, byte encryptionCode)\n {\n for (int i = 0; i < data.length; i++)\n {\n data[i] = (byte) (data[i] ^ encryptionCode);\n }\n }", "public static int getChunkId(String fileName) {\n Pattern pattern = Pattern.compile(\"_[\\\\d]+\\\\.\");\n Matcher matcher = pattern.matcher(fileName);\n\n if(matcher.find()) {\n return new Integer(fileName.substring(matcher.start() + 1, matcher.end() - 1));\n } else {\n throw new VoldemortException(\"Could not extract out chunk id from \" + fileName);\n }\n }", "private static int resolveDomainTimeoutAdder() {\n String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);\n if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {\n // First call or the system property changed\n sysPropDomainValue = propValue;\n int number = -1;\n try {\n number = Integer.valueOf(sysPropDomainValue);\n } catch (NumberFormatException nfe) {\n // ignored\n }\n\n if (number > 0) {\n defaultDomainValue = number; // this one is in ms\n } else {\n ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);\n defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;\n }\n }\n return defaultDomainValue;\n }", "public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }", "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 }", "public static final String getString(InputStream is) throws IOException\n {\n int type = is.read();\n if (type != 1)\n {\n throw new IllegalArgumentException(\"Unexpected string format\");\n }\n\n Charset charset = CharsetHelper.UTF8;\n \n int length = is.read();\n if (length == 0xFF)\n {\n length = getShort(is);\n if (length == 0xFFFE)\n {\n charset = CharsetHelper.UTF16LE;\n length = (is.read() * 2);\n }\n }\n\n String result;\n if (length == 0)\n {\n result = null;\n }\n else\n {\n byte[] stringData = new byte[length]; \n is.read(stringData);\n result = new String(stringData, charset);\n }\n return result;\n }", "public static lbsipparameters get(nitro_service service) throws Exception{\n\t\tlbsipparameters obj = new lbsipparameters();\n\t\tlbsipparameters[] response = (lbsipparameters[])obj.get_resources(service);\n\t\treturn response[0];\n\t}", "protected void generateFile(File file,\n String templateName,\n VelocityContext context) throws Exception\n {\n Writer writer = new BufferedWriter(new FileWriter(file));\n try\n {\n Velocity.mergeTemplate(classpathPrefix + templateName,\n ENCODING,\n context,\n writer);\n writer.flush();\n }\n finally\n {\n writer.close();\n }\n }", "public boolean matchesWithMask(IPAddress other, IPAddress mask) {\n\t\treturn getSection().matchesWithMask(other.getSection(), mask.getSection());\n\t}" ]
Lookup the group for the specified URL. @param url The url @return The group @throws FlickrException
[ "public Group lookupGroup(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_GROUP);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Group group = new Group();\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"groupname\").item(0);\r\n group.setId(payload.getAttribute(\"id\"));\r\n group.setName(((Text) groupnameElement.getFirstChild()).getData());\r\n return group;\r\n }" ]
[ "protected Object getTypedValue(int type, byte[] value)\n {\n Object result;\n\n switch (type)\n {\n case 4: // Date\n {\n result = MPPUtility.getTimestamp(value, 0);\n break;\n }\n\n case 6: // Duration\n {\n TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(value, 4), m_properties.getDefaultDurationUnits());\n result = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(value, 0), units);\n break;\n }\n\n case 9: // Cost\n {\n result = Double.valueOf(MPPUtility.getDouble(value, 0) / 100);\n break;\n }\n\n case 15: // Number\n {\n result = Double.valueOf(MPPUtility.getDouble(value, 0));\n break;\n }\n\n case 36058:\n case 21: // Text\n {\n result = MPPUtility.getUnicodeString(value, 0);\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n return result;\n }", "synchronized boolean doReConnect() throws IOException {\n\n // In case we are still connected, test the connection and see if we can reuse it\n if(connectionManager.isConnected()) {\n try {\n final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();\n result.get(15, TimeUnit.SECONDS); // Hmm, perhaps 15 is already too much\n return true;\n } catch (Exception e) {\n ServerLogger.AS_ROOT_LOGGER.debugf(e, \"failed to ping the host-controller, going to reconnect\");\n }\n // Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect\n final Connection connection = connectionManager.getConnection();\n StreamUtils.safeClose(connection);\n if(connection != null) {\n try {\n // Wait for the connection to be closed\n connection.awaitClosed();\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n }\n }\n\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n // Reconnect to the host-controller\n final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);\n try {\n boolean inSync = result.getResult().get();\n ok = true;\n reconnectRunner = null;\n return inSync;\n } catch (ExecutionException e) {\n throw new IOException(e);\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n } finally {\n if(!ok) {\n StreamUtils.safeClose(connection);\n }\n }\n }", "@Override\n public final PObject getObject(final String key) {\n PObject result = optObject(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "public static base_response add(nitro_service client, responderpolicy resource) throws Exception {\n\t\tresponderpolicy addresource = new responderpolicy();\n\t\taddresource.name = resource.name;\n\t\taddresource.rule = resource.rule;\n\t\taddresource.action = resource.action;\n\t\taddresource.undefaction = resource.undefaction;\n\t\taddresource.comment = resource.comment;\n\t\taddresource.logaction = resource.logaction;\n\t\taddresource.appflowaction = resource.appflowaction;\n\t\treturn addresource.add_resource(client);\n\t}", "public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }", "public static base_response unset(nitro_service client, nsspparams resource, String[] args) throws Exception{\n\t\tnsspparams unsetresource = new nsspparams();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {\n HttpHeaders headers = request.getHeaders();\n headers.set(HOST, destination.getUri().getAuthority());\n headers.remove(TE);\n }", "public static cachecontentgroup get(nitro_service service, String name) throws Exception{\n\t\tcachecontentgroup obj = new cachecontentgroup();\n\t\tobj.set_name(name);\n\t\tcachecontentgroup response = (cachecontentgroup) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setMonth(String monthStr) {\n\n final Month month = Month.valueOf(monthStr);\n if ((m_model.getMonth() == null) || !m_model.getMonth().equals(monthStr)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setMonth(month);\n onValueChange();\n\n }\n });\n }\n }" ]
Given a layer ID, search for the WMS layer. @param layerId layer id @return WMS layer or null if layer is not a WMS layer
[ "private WmsLayer getLayer(String layerId) {\n\t\tRasterLayer layer = configurationService.getRasterLayer(layerId);\n\t\tif (layer instanceof WmsLayer) {\n\t\t\treturn (WmsLayer) layer;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "public void setConnection(JdbcConnectionDescriptor jcd) throws PlatformException\r\n {\r\n _jcd = jcd;\r\n\r\n String targetDatabase = (String)_dbmsToTorqueDb.get(_jcd.getDbms().toLowerCase());\r\n\r\n if (targetDatabase == null)\r\n {\r\n throw new PlatformException(\"Database \"+_jcd.getDbms()+\" is not supported by torque\");\r\n }\r\n if (!targetDatabase.equals(_targetDatabase))\r\n {\r\n _targetDatabase = targetDatabase;\r\n _creationScript = null;\r\n _initScripts.clear();\r\n }\r\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 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 static void inner_reorder_lower(DMatrix1Row A , DMatrix1Row B )\n {\n final int cols = A.numCols;\n B.reshape(cols,cols);\n\n Arrays.fill(B.data,0);\n for (int i = 0; i <cols; i++) {\n for (int j = 0; j <=i; j++) {\n B.data[i*cols+j] += A.data[i]*A.data[j];\n }\n\n for (int k = 1; k < A.numRows; k++) {\n int indexRow = k*cols;\n double valI = A.data[i+indexRow];\n int indexB = i*cols;\n for (int j = 0; j <= i; j++) {\n B.data[indexB++] += valI*A.data[indexRow++];\n }\n }\n }\n }", "public int removeChildObjectsByName(final String name) {\n int removed = 0;\n\n if (null != name && !name.isEmpty()) {\n removed = removeChildObjectsByNameImpl(name);\n }\n\n return removed;\n }", "private int read() {\n int curByte = 0;\n try {\n curByte = rawData.get() & 0xFF;\n } catch (Exception e) {\n header.status = GifDecoder.STATUS_FORMAT_ERROR;\n }\n return curByte;\n }", "public Set<String> rangeByLexReverse(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (lexRange.hasLimit()) {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse(), lexRange.offset(), lexRange.count());\n } else {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse());\n }\n }\n });\n }", "public void setDatesWithCheckState(Collection<CmsPair<Date, Boolean>> datesWithCheckInfo) {\n\n SortedSet<Date> dates = new TreeSet<>();\n m_checkBoxes.clear();\n for (CmsPair<Date, Boolean> p : datesWithCheckInfo) {\n addCheckBox(p.getFirst(), p.getSecond().booleanValue());\n dates.add(p.getFirst());\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }", "public static int distance(String s1, String s2) {\n if (s1.length() == 0)\n return s2.length();\n if (s2.length() == 0)\n return s1.length();\n\n int s1len = s1.length();\n // we use a flat array for better performance. we address it by\n // s1ix + s1len * s2ix. this modification improves performance\n // by about 30%, which is definitely worth the extra complexity.\n int[] matrix = new int[(s1len + 1) * (s2.length() + 1)];\n for (int col = 0; col <= s2.length(); col++)\n matrix[col * s1len] = col;\n for (int row = 0; row <= s1len; row++)\n matrix[row] = row;\n\n for (int ix1 = 0; ix1 < s1len; ix1++) {\n char ch1 = s1.charAt(ix1);\n for (int ix2 = 0; ix2 < s2.length(); ix2++) {\n int cost;\n if (ch1 == s2.charAt(ix2))\n cost = 0;\n else\n cost = 1;\n\n int left = matrix[ix1 + ((ix2 + 1) * s1len)] + 1;\n int above = matrix[ix1 + 1 + (ix2 * s1len)] + 1;\n int aboveleft = matrix[ix1 + (ix2 * s1len)] + cost;\n matrix[ix1 + 1 + ((ix2 + 1) * s1len)] =\n Math.min(left, Math.min(above, aboveleft));\n }\n }\n\n // for (int ix1 = 0; ix1 <= s1len; ix1++) {\n // for (int ix2 = 0; ix2 <= s2.length(); ix2++) {\n // System.out.print(matrix[ix1 + (ix2 * s1len)] + \" \");\n // }\n // System.out.println();\n // }\n \n return matrix[s1len + (s2.length() * s1len)];\n }" ]
The number of bytes required to hold the given number @param number The number being checked. @return The required number of bytes (must be 8 or less)
[ "public static byte numberOfBytesRequired(long number) {\n if(number < 0)\n number = -number;\n for(byte i = 1; i <= SIZE_OF_LONG; i++)\n if(number < (1L << (8 * i)))\n return i;\n throw new IllegalStateException(\"Should never happen.\");\n }" ]
[ "public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }", "private void lockOnChange(Object propertyId) throws CmsException {\n\n if (isDescriptorProperty(propertyId)) {\n lockDescriptor();\n } else {\n Locale l = m_bundleType.equals(BundleType.PROPERTY) ? m_locale : null;\n lockLocalization(l);\n }\n\n }", "public int getJdbcType(String ojbType) throws SQLException\r\n {\r\n int result;\r\n if(ojbType == null) ojbType = \"\";\r\n\t\tojbType = ojbType.toLowerCase();\r\n if (ojbType.equals(\"bit\"))\r\n result = Types.BIT;\r\n else if (ojbType.equals(\"tinyint\"))\r\n result = Types.TINYINT;\r\n else if (ojbType.equals(\"smallint\"))\r\n result = Types.SMALLINT;\r\n else if (ojbType.equals(\"integer\"))\r\n result = Types.INTEGER;\r\n else if (ojbType.equals(\"bigint\"))\r\n result = Types.BIGINT;\r\n\r\n else if (ojbType.equals(\"float\"))\r\n result = Types.FLOAT;\r\n else if (ojbType.equals(\"real\"))\r\n result = Types.REAL;\r\n else if (ojbType.equals(\"double\"))\r\n result = Types.DOUBLE;\r\n\r\n else if (ojbType.equals(\"numeric\"))\r\n result = Types.NUMERIC;\r\n else if (ojbType.equals(\"decimal\"))\r\n result = Types.DECIMAL;\r\n\r\n else if (ojbType.equals(\"char\"))\r\n result = Types.CHAR;\r\n else if (ojbType.equals(\"varchar\"))\r\n result = Types.VARCHAR;\r\n else if (ojbType.equals(\"longvarchar\"))\r\n result = Types.LONGVARCHAR;\r\n\r\n else if (ojbType.equals(\"date\"))\r\n result = Types.DATE;\r\n else if (ojbType.equals(\"time\"))\r\n result = Types.TIME;\r\n else if (ojbType.equals(\"timestamp\"))\r\n result = Types.TIMESTAMP;\r\n\r\n else if (ojbType.equals(\"binary\"))\r\n result = Types.BINARY;\r\n else if (ojbType.equals(\"varbinary\"))\r\n result = Types.VARBINARY;\r\n else if (ojbType.equals(\"longvarbinary\"))\r\n result = Types.LONGVARBINARY;\r\n\r\n\t\telse if (ojbType.equals(\"clob\"))\r\n \t\tresult = Types.CLOB;\r\n\t\telse if (ojbType.equals(\"blob\"))\r\n\t\t\tresult = Types.BLOB;\r\n else\r\n throw new SQLException(\r\n \"The type '\"+ ojbType + \"' is not a valid jdbc type.\");\r\n return result;\r\n }", "private void resetCalendar() {\n _calendar = getCalendar();\n if (_defaultTimeZone != null) {\n _calendar.setTimeZone(_defaultTimeZone);\n }\n _currentYear = _calendar.get(Calendar.YEAR);\n }", "public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{\n\t\t// Check if the LMM uses a discount curve which is created from a forward curve\n\t\tif(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains(\"DiscountCurveFromForwardCurve\".toLowerCase())){\n\t\t\treturn new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime));\n\t\t}\n\t\telse {\n\t\t\t// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.\n\t\t\t// Only at startTime 0!\n\t\t\treturn (DiscountCurveInterface) model.getModel().getDiscountCurve();\n\t\t}\n\n\t}", "static void export(String path, String queueName, DbConn cnx) throws JqmXmlException\n {\n // Argument tests\n if (queueName == null)\n {\n throw new IllegalArgumentException(\"queue name cannot be null\");\n }\n if (cnx == null)\n {\n throw new IllegalArgumentException(\"database connection cannot be null\");\n }\n Queue q = CommonXml.findQueue(queueName, cnx);\n if (q == null)\n {\n throw new IllegalArgumentException(\"there is no queue named \" + queueName);\n }\n\n List<Queue> l = new ArrayList<>();\n l.add(q);\n export(path, l, cnx);\n }", "public void update(StoreDefinition storeDef) {\n if(!useOneEnvPerStore)\n throw new VoldemortException(\"Memory foot print can be set only when using different environments per store\");\n\n String storeName = storeDef.getName();\n Environment environment = environments.get(storeName);\n // change reservation amount of reserved store\n if(!unreservedStores.contains(environment) && storeDef.hasMemoryFootprint()) {\n EnvironmentMutableConfig mConfig = environment.getMutableConfig();\n long currentCacheSize = mConfig.getCacheSize();\n long newCacheSize = storeDef.getMemoryFootprintMB() * ByteUtils.BYTES_PER_MB;\n if(currentCacheSize != newCacheSize) {\n long newReservedCacheSize = this.reservedCacheSize - currentCacheSize\n + newCacheSize;\n\n // check that we leave a 'minimum' shared cache\n if((voldemortConfig.getBdbCacheSize() - newReservedCacheSize) < voldemortConfig.getBdbMinimumSharedCache()) {\n throw new StorageInitializationException(\"Reservation of \"\n + storeDef.getMemoryFootprintMB()\n + \" MB for store \"\n + storeName\n + \" violates minimum shared cache size of \"\n + voldemortConfig.getBdbMinimumSharedCache());\n }\n\n this.reservedCacheSize = newReservedCacheSize;\n adjustCacheSizes();\n mConfig.setCacheSize(newCacheSize);\n environment.setMutableConfig(mConfig);\n logger.info(\"Setting private cache for store \" + storeDef.getName() + \" to \"\n + newCacheSize);\n }\n } else {\n // we cannot support changing a reserved store to unreserved or vice\n // versa since the sharedCache param is not mutable\n throw new VoldemortException(\"Cannot switch between shared and private cache dynamically\");\n }\n }", "public Matrix4f getFinalTransformMatrix()\n {\n final FloatBuffer fb = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();\n NativeBone.getFinalTransformMatrix(getNative(), fb);\n return new Matrix4f(fb);\n }", "public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) {\n dest.clear();\n\n if (key != null) {\n dest.key = new Key(key);\n }\n\n for (int i = 0; i < timeStamps.size(); i++) {\n long time = timeStamps.get(i);\n if (timestampTest.test(time)) {\n dest.add(time, values.get(i));\n }\n }\n }" ]
Create an embedded host controller. @param jbossHomePath the location of the root of the host controller installation. Cannot be {@code null} or empty. @param modulePath the location of the root of the module repository. May be {@code null} if the standard location under {@code jbossHomePath} should be used @param systemPackages names of any packages that must be treated as system packages, with the same classes visible to the caller's classloader visible to host-controller-side classes loaded from the server's modular classloader @param cmdargs any additional arguments to pass to the embedded host controller (e.g. -b=192.168.100.10) @return the server. Will not be {@code null}
[ "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 Set<TupleOperation> getOperations() {\n\t\tif ( currentState == null ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\treturn new SetFromCollection<TupleOperation>( currentState.values() );\n\t\t}\n\t}", "public void setIssueTrackerInfo(BuildInfoBuilder builder) {\n Issues issues = new Issues();\n issues.setAggregateBuildIssues(aggregateBuildIssues);\n issues.setAggregationBuildStatus(aggregationBuildStatus);\n issues.setTracker(new IssueTracker(\"JIRA\", issueTrackerVersion));\n Set<Issue> affectedIssuesSet = IssuesTrackerUtils.getAffectedIssuesSet(affectedIssues);\n if (!affectedIssuesSet.isEmpty()) {\n issues.setAffectedIssues(affectedIssuesSet);\n }\n builder.issues(issues);\n }", "@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }", "protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){\n\t\tJRDesignExpression exp = new JRDesignExpression();\n\t\texp.setText(\"$V{\" + var.getName() + \"}\");\n\t\texp.setValueClass(var.getValueClass());\n\t\treturn exp;\n\t}", "private 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 }", "@Override\n public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {\n\n List<InstalledIdentity> installedIdentities;\n\n final File metadataDir = installedImage.getInstallationMetadata();\n if(!metadataDir.exists()) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;\n final File[] identityConfs = metadataDir.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.isFile() &&\n pathname.getName().endsWith(Constants.DOT_CONF) &&\n !pathname.getName().equals(defaultConf);\n }\n });\n if(identityConfs == null || identityConfs.length == 0) {\n installedIdentities = Collections.singletonList(defaultIdentity);\n } else {\n installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);\n installedIdentities.add(defaultIdentity);\n for(File conf : identityConfs) {\n final Properties props = loadProductConf(conf);\n String productName = conf.getName();\n productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());\n final String productVersion = props.getProperty(Constants.CURRENT_VERSION);\n\n InstalledIdentity identity;\n try {\n identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);\n } catch (IOException e) {\n throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);\n }\n installedIdentities.add(identity);\n }\n }\n }\n return installedIdentities;\n }", "public void build(Point3d[] points, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (points.length < nump) {\n throw new IllegalArgumentException(\"Point array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(points, nump);\n buildHull();\n }", "public static InterceptorFactory getInstance()\r\n\t{\r\n\t\tif (instance == null)\r\n\t\t{\r\n\t\t\tinstance = new InterceptorFactory();\r\n\t\t\tOjbConfigurator.getInstance().configure(instance);\r\n\t\t}\r\n\t\treturn instance;\r\n\t}", "private boolean isSingleMultiDay() {\n\n long duration = getEnd().getTime() - getStart().getTime();\n if (duration > I_CmsSerialDateValue.DAY_IN_MILLIS) {\n return true;\n }\n if (isWholeDay() && (duration <= I_CmsSerialDateValue.DAY_IN_MILLIS)) {\n return false;\n }\n Calendar start = new GregorianCalendar();\n start.setTime(getStart());\n Calendar end = new GregorianCalendar();\n end.setTime(getEnd());\n if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)) {\n return false;\n }\n return true;\n\n }" ]
Use this API to clear route6 resources.
[ "public static base_responses clear(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {\n\t\tCheck.notNull(code, \"code\");\n\t\tfinal ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, \"settings\"));\n\n\t\tfinal InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);\n\t\tfinal Clazz clazz = scaffoldClazz(analysis, settings);\n\n\t\t// immutable settings\n\t\tsettingsBuilder.fields(clazz.getFields());\n\t\tsettingsBuilder.immutableName(clazz.getName());\n\t\tsettingsBuilder.imports(clazz.getImports());\n\t\tfinal Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));\n\t\tsettingsBuilder.mainInterface(definition);\n\t\tsettingsBuilder.interfaces(clazz.getInterfaces());\n\t\tsettingsBuilder.packageDeclaration(clazz.getPackage());\n\n\t\tfinal String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));\n\t\tfinal String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));\n\t\treturn new Result(implementationCode, testCode);\n\t}", "public static boolean isTypesProxyable(Iterable<? extends Type> types, ServiceRegistry services) {\n return getUnproxyableTypesException(types, services) == null;\n }", "public static int[] convertBytesToInts(byte[] bytes)\n {\n if (bytes.length % 4 != 0)\n {\n throw new IllegalArgumentException(\"Number of input bytes must be a multiple of 4.\");\n }\n int[] ints = new int[bytes.length / 4];\n for (int i = 0; i < ints.length; i++)\n {\n ints[i] = convertBytesToInt(bytes, i * 4);\n }\n return ints;\n }", "public String buildRadio(String propName) throws CmsException {\n\n String propVal = readProperty(propName);\n StringBuffer result = new StringBuffer(\"<table border=\\\"0\\\"><tr>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"true\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_TRUE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"false\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(Boolean.valueOf(propVal).booleanValue() ? \"\" : \"checked=\\\"checked\\\"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(key(Messages.GUI_LABEL_FALSE_0)).append(\"</td>\");\n result.append(\"<td><input type=\\\"radio\\\" value=\\\"\\\" onClick=\\\"checkNoIntern()\\\" name=\\\"\").append(\n propName).append(\"\\\" \").append(CmsStringUtil.isEmpty(propVal) ? \"checked=\\\"checked\\\"\" : \"\").append(\n \"/></td><td id=\\\"tablelabel\\\">\").append(getPropertyInheritanceInfo(propName)).append(\n \"</td></tr></table>\");\n return result.toString();\n }", "public static boolean isAssignableFrom(TypeReference<?> from, TypeReference<?> to) {\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (to.getType() instanceof Class) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType());\n\t\t} else if (to.getType() instanceof ParameterizedType) {\n\t\t\treturn isAssignableFrom(from.getType(), (ParameterizedType) to\n\t\t\t\t\t.getType(), new HashMap<String, Type>());\n\t\t} else if (to.getType() instanceof GenericArrayType) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType())\n\t\t\t\t\t&& isAssignableFrom(from.getType(), (GenericArrayType) to\n\t\t\t\t\t\t\t.getType());\n\t\t} else {\n\t\t\tthrow new AssertionError(\"Unexpected Type : \" + to);\n\t\t}\n\t}", "public static Transformers.ResourceIgnoredTransformationRegistry createServerIgnoredRegistry(final RequiredConfigurationHolder rc, final Transformers.ResourceIgnoredTransformationRegistry delegate) {\n return new Transformers.ResourceIgnoredTransformationRegistry() {\n @Override\n public boolean isResourceTransformationIgnored(PathAddress address) {\n final int length = address.size();\n if (length == 0) {\n return false;\n } else if (length >= 1) {\n if (delegate.isResourceTransformationIgnored(address)) {\n return true;\n }\n\n final PathElement element = address.getElement(0);\n final String type = element.getKey();\n switch (type) {\n case ModelDescriptionConstants.EXTENSION:\n // Don't ignore extensions for now\n return false;\n// if (local) {\n// return false; // Always include all local extensions\n// } else if (rc.getExtensions().contains(element.getValue())) {\n// return false;\n// }\n// break;\n case ModelDescriptionConstants.PROFILE:\n if (rc.getProfiles().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SERVER_GROUP:\n if (rc.getServerGroups().contains(element.getValue())) {\n return false;\n }\n break;\n case ModelDescriptionConstants.SOCKET_BINDING_GROUP:\n if (rc.getSocketBindings().contains(element.getValue())) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n };\n }", "public static int cudnnBatchNormalizationBackward(\n cudnnHandle handle, \n int mode, \n Pointer alphaDataDiff, \n Pointer betaDataDiff, \n Pointer alphaParamDiff, \n Pointer betaParamDiff, \n cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */\n Pointer x, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor dxDesc, \n Pointer dx, \n /** Shared tensor desc for the 4 tensors below */\n cudnnTensorDescriptor dBnScaleBiasDesc, \n Pointer bnScale, /** bnBias doesn't affect backpropagation */\n /** scale and bias diff are not backpropagated below this layer */\n Pointer dBnScaleResult, \n Pointer dBnBiasResult, \n /** Same epsilon as forward pass */\n double epsilon, \n /** Optionally cached intermediate results from\n forward pass */\n Pointer savedMean, \n Pointer savedInvVariance)\n {\n return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));\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 Set<String> postProcessingFields() {\n Set<String> fields = new LinkedHashSet<>();\n query.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n sort.forEach(condition -> fields.addAll(condition.postProcessingFields()));\n return fields;\n }" ]
Use this API to save cachecontentgroup resources.
[ "public static base_responses save(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 saveresources[] = new cachecontentgroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cachecontentgroup();\n\t\t\t\tsaveresources[i].name = resources[i].name;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}" ]
[ "protected Object transformEntity(Entity entity) {\n\t\tPropertyColumn propertyColumn = (PropertyColumn) entity;\n\t\tJRDesignField field = new JRDesignField();\n\t\tColumnProperty columnProperty = propertyColumn.getColumnProperty();\n\t\tfield.setName(columnProperty.getProperty());\n\t\tfield.setValueClassName(columnProperty.getValueClassName());\n\t\t\n\t\tlog.debug(\"Transforming column: \" + propertyColumn.getName() + \", property: \" + columnProperty.getProperty() + \" (\" + columnProperty.getValueClassName() +\") \" );\n\n\t\tfield.setDescription(propertyColumn.getFieldDescription()); //hack for XML data source\n\t\tfor (String key : columnProperty.getFieldProperties().keySet()) {\n\t\t\tfield.getPropertiesMap().setProperty(key, columnProperty.getFieldProperties().get(key));\n\t\t}\n\t\treturn field;\n\t}", "public void updateIntegerBelief(String name, int value) {\n introspector.storeBeliefValue(this, name, getIntegerBelief(name) + value);\n }", "public ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }", "public static aaauser_auditsyslogpolicy_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_auditsyslogpolicy_binding obj = new aaauser_auditsyslogpolicy_binding();\n\t\tobj.set_username(username);\n\t\taaauser_auditsyslogpolicy_binding response[] = (aaauser_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public String haikunate() {\n if (tokenHex) {\n tokenChars = \"0123456789abcdef\";\n }\n\n String adjective = randomString(adjectives);\n String noun = randomString(nouns);\n\n StringBuilder token = new StringBuilder();\n if (tokenChars != null && tokenChars.length() > 0) {\n for (int i = 0; i < tokenLength; i++) {\n token.append(tokenChars.charAt(random.nextInt(tokenChars.length())));\n }\n }\n\n return Stream.of(adjective, noun, token.toString())\n .filter(s -> s != null && !s.isEmpty())\n .collect(joining(delimiter));\n }", "public T transitInt(int propertyId, int... vals) {\n String property = getPropertyName(propertyId);\n mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));\n mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));\n return self();\n }", "protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\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 Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }", "@JmxOperation(description = \"Forcefully invoke the log cleaning\")\n public void cleanLogs() {\n synchronized(lock) {\n try {\n for(Environment environment: environments.values()) {\n environment.cleanLog();\n }\n } catch(DatabaseException e) {\n throw new VoldemortException(e);\n }\n }\n }", "public final static int readMdLink(final StringBuilder out, final String in, final int start)\n {\n int pos = start;\n int counter = 1;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (ch == '\\\\' && pos + 1 < in.length())\n {\n pos = escape(out, in.charAt(pos + 1), pos);\n }\n else\n {\n boolean endReached = false;\n switch (ch)\n {\n case '(':\n counter++;\n break;\n case ' ':\n if (counter == 1)\n {\n endReached = true;\n }\n break;\n case ')':\n counter--;\n if (counter == 0)\n {\n endReached = true;\n }\n break;\n }\n if (endReached)\n {\n break;\n }\n out.append(ch);\n }\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }" ]
Removes a named property from the object. If the property is not found, no action is taken. @param name the name of the property
[ "public synchronized void delete(String name) {\n if (isEmpty(name)) {\n indexedProps.remove(name);\n } else {\n synchronized (context) {\n int scope = context.getAttributesScope(name);\n if (scope != -1) {\n context.removeAttribute(name, scope);\n }\n }\n }\n }" ]
[ "public String getFullContentType() {\n final String url = this.url.toExternalForm().substring(\"data:\".length());\n final int endIndex = url.indexOf(',');\n if (endIndex >= 0) {\n final String contentType = url.substring(0, endIndex);\n if (!contentType.isEmpty()) {\n return contentType;\n }\n }\n return \"text/plain;charset=US-ASCII\";\n }", "public void fireCalendarReadEvent(ProjectCalendar calendar)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.calendarRead(calendar);\n }\n }\n }", "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 Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }", "public static boolean isFileExist(String filePath) {\r\n if (StringUtils.isEmpty(filePath)) {\r\n return false;\r\n }\r\n\r\n File file = new File(filePath);\r\n return (file.exists() && file.isFile());\r\n }", "private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }", "private void applyAliases(Map<FieldType, String> aliases)\n {\n CustomFieldContainer fields = m_project.getCustomFields();\n for (Map.Entry<FieldType, String> entry : aliases.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }", "@Override\n protected void registerRequest(RestRequestValidator requestValidator,\n ChannelHandlerContext ctx,\n MessageEvent messageEvent) {\n\n // At this point we know the request is valid and we have a\n // error handler. So we construct the composite Voldemort\n // request object.\n CompositeVoldemortRequest<ByteArray, byte[]> requestObject = requestValidator.constructCompositeVoldemortRequestObject();\n\n if(requestObject != null) {\n\n DynamicTimeoutStoreClient<ByteArray, byte[]> storeClient = null;\n\n if(!requestValidator.getStoreName().equalsIgnoreCase(RestMessageHeaders.SCHEMATA_STORE)) {\n\n storeClient = this.fatClientMap.get(requestValidator.getStoreName());\n if(storeClient == null) {\n logger.error(\"Error when getting store. Non Existing store client.\");\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Non Existing store client. Critical error.\");\n return;\n }\n } else {\n requestObject.setOperationType(VoldemortOpCode.GET_METADATA_OP_CODE);\n }\n\n CoordinatorStoreClientRequest coordinatorRequest = new CoordinatorStoreClientRequest(requestObject,\n storeClient);\n Channels.fireMessageReceived(ctx, coordinatorRequest);\n\n }\n }", "@Override\n public double get( int row , int col ) {\n if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {\n throw new IllegalArgumentException(\"Specified element is out of bounds: \"+row+\" \"+col);\n }\n\n return data[ row * numCols + col ];\n }" ]
Reads GIF image from byte array. @param data containing GIF file. @return read status code (0 = no errors).
[ "synchronized int read(byte[] data) {\n this.header = getHeaderParser().setData(data).parseHeader();\n if (data != null) {\n setData(header, data);\n }\n\n return status;\n }" ]
[ "public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }", "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn Maps.filterEntries(left, new Predicate<Entry<K, V>>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(Entry<K, V> input) {\n\t\t\t\treturn !Objects.equal(input.getKey(), right.getKey()) || !Objects.equal(input.getValue(), right.getValue());\n\t\t\t}\n\t\t});\n\t}", "private static void loadFile(String filePath) {\n final Path path = FileSystems.getDefault().getPath(filePath);\n\n try {\n data.clear();\n data.load(Files.newBufferedReader(path));\n } catch(IOException e) {\n LOG.warn(\"Exception while loading \" + path.toString(), e);\n }\n }", "@Override\n public SuggestionsInterface getSuggestionsInterface() {\n if (suggestionsInterface == null) {\n suggestionsInterface = new SuggestionsInterface(apiKey, sharedSecret, transport);\n }\n return suggestionsInterface;\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 readResources(Document cdp)\n {\n for (Document.Resources.Resource resource : cdp.getResources().getResource())\n {\n readResource(resource);\n }\n }", "public Photoset create(String title, String description, String primaryPhotoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CREATE);\r\n\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\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 Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n photoset.setUrl(photosetElement.getAttribute(\"url\"));\r\n return photoset;\r\n }", "public List<CmsCategory> getLeafItems() {\n\n List<CmsCategory> result = new ArrayList<CmsCategory>();\n if (m_categories.isEmpty()) {\n return result;\n }\n Iterator<CmsCategory> it = m_categories.iterator();\n CmsCategory current = it.next();\n while (it.hasNext()) {\n CmsCategory next = it.next();\n if (!next.getPath().startsWith(current.getPath())) {\n result.add(current);\n }\n current = next;\n }\n result.add(current);\n return result;\n }", "private static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, double fWidth, double fHeight) {\n BufferedImage dbi = null;\n // Needed to create a new BufferedImage object\n int imageType = imageToScale.getType();\n if (imageToScale != null) {\n dbi = new BufferedImage(dWidth, dHeight, imageType);\n Graphics2D g = dbi.createGraphics();\n AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);\n g.drawRenderedImage(imageToScale, at);\n }\n return dbi;\n }" ]
Check that each emitted notification is properly described by its source.
[ "private void checkUndefinedNotification(Notification notification) {\n String type = notification.getType();\n PathAddress source = notification.getSource();\n Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);\n if (!descriptions.keySet().contains(type)) {\n missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));\n }\n }" ]
[ "public synchronized Widget measureChild(final int dataIndex, boolean calculateOffset) {\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"measureChild dataIndex = %d\", dataIndex);\n\n Widget widget = mContainer.get(dataIndex);\n if (widget != null) {\n synchronized (mMeasuredChildren) {\n mMeasuredChildren.add(dataIndex);\n }\n }\n return widget;\n }", "public ServerRedirect updateServerRedirectHost(int serverMappingId, String hostHeader) {\n ServerRedirect redirect = new ServerRedirect();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"hostHeader\", hostHeader),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVER + \"/\" + serverMappingId + \"/host\", params));\n redirect = getServerRedirectFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return redirect;\n }", "public int clear()\n {\n int n = 0;\n for (GVRCursorController c : controllers)\n {\n c.stopDrag();\n removeCursorController(c);\n ++n;\n }\n return n;\n }", "protected void queryTimerEnd(String sql, long queryStartTime) {\r\n\t\tif ((this.queryExecuteTimeLimit != 0) \r\n\t\t\t\t&& (this.connectionHook != null)){\r\n\t\t\tlong timeElapsed = (System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t\tif (timeElapsed > this.queryExecuteTimeLimit){\r\n\t\t\t\tthis.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (this.statisticsEnabled){\r\n\t\t\tthis.statistics.incrementStatementsExecuted();\r\n\t\t\tthis.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}", "public byte[] toArray() {\n if (size() > Integer.MAX_VALUE)\n throw new IllegalStateException(\"Cannot create byte array of more than 2GB\");\n\n int len = (int) size();\n ByteBuffer bb = toDirectByteBuffer(0L, len);\n byte[] b = new byte[len];\n // Copy data to the array\n bb.get(b, 0, len);\n return b;\n }", "public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) {\n ZkGroupDirs dirs = new ZkGroupDirs(group);\n List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir);\n //\n Map<String, List<String>> consumersPerTopicMap = new HashMap<String, List<String>>();\n for (String consumer : consumers) {\n TopicCount topicCount = getTopicCount(zkClient, group, consumer);\n for (Map.Entry<String, Set<String>> e : topicCount.getConsumerThreadIdsPerTopic().entrySet()) {\n final String topic = e.getKey();\n for (String consumerThreadId : e.getValue()) {\n List<String> list = consumersPerTopicMap.get(topic);\n if (list == null) {\n list = new ArrayList<String>();\n consumersPerTopicMap.put(topic, list);\n }\n //\n list.add(consumerThreadId);\n }\n }\n }\n //\n for (Map.Entry<String, List<String>> e : consumersPerTopicMap.entrySet()) {\n Collections.sort(e.getValue());\n }\n return consumersPerTopicMap;\n }", "public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) {\r\n\r\n\t\tif(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tthrow new IllegalArgumentException(\"SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL.\");\r\n\t\t}\r\n\r\n\t\t//Reverse sign of moneyness, if switching between payer and receiver convention.\r\n\t\tint reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1;\r\n\r\n\t\tList<Integer> maturities\t= new ArrayList<>();\r\n\t\tList<Integer> tenors\t\t= new ArrayList<>();\r\n\t\tList<Integer> moneynesss\t= new ArrayList<>();\r\n\t\tList<Double> values\t\t= new ArrayList<>();\r\n\r\n\t\tfor(DataKey key : entryMap.keySet()) {\r\n\t\t\tmaturities.add(key.maturity);\r\n\t\t\ttenors.add(key.tenor);\r\n\t\t\tmoneynesss.add(key.moneyness * reverse);\r\n\t\t\tvalues.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model));\r\n\t\t}\r\n\r\n\t\treturn new SwaptionDataLattice(referenceDate, targetConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule,\r\n\t\t\t\tmaturities.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\ttenors.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\tmoneynesss.stream().mapToInt(Integer::intValue).toArray(),\r\n\t\t\t\tvalues.stream().mapToDouble(Double::doubleValue).toArray());\r\n\t}", "@Pure\n\t@Inline(value = \"$3.union($1, $2)\", imported = MapExtensions.class)\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) {\n\t\treturn union(left, right);\n\t}", "protected List<String> splitLinesAndNewLines(String text) {\n\t\tif (text == null)\n\t\t\treturn Collections.emptyList();\n\t\tint idx = initialSegmentSize(text);\n\t\tif (idx == text.length()) {\n\t\t\treturn Collections.singletonList(text);\n\t\t}\n\n\t\treturn continueSplitting(text, idx);\n\t}" ]
Use this API to count dnszone_domain_binding resources configued on NetScaler.
[ "public static long count(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}" ]
[ "public 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 static ResourceKey key(Class<?> clazz, Enum<?> value) {\n return new ResourceKey(clazz.getName(), value.name());\n }", "public void schedule(BackoffTask task, long initialDelay, long fixedDelay) {\n \tsynchronized (queue) {\n\t \tstart();\n\t queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay));\n \t}\n }", "private void writeRelationList(String fieldName, Object value) throws IOException\n {\n @SuppressWarnings(\"unchecked\")\n List<Relation> list = (List<Relation>) value;\n if (!list.isEmpty())\n {\n m_writer.writeStartList(fieldName);\n for (Relation relation : list)\n {\n m_writer.writeStartObject(null);\n writeIntegerField(\"task_unique_id\", relation.getTargetTask().getUniqueID());\n writeDurationField(\"lag\", relation.getLag());\n writeStringField(\"type\", relation.getType());\n m_writer.writeEndObject();\n }\n m_writer.writeEndList();\n }\n }", "public static base_response update(nitro_service client, sslocspresponder resource) throws Exception {\n\t\tsslocspresponder updateresource = new sslocspresponder();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.url = resource.url;\n\t\tupdateresource.cache = resource.cache;\n\t\tupdateresource.cachetimeout = resource.cachetimeout;\n\t\tupdateresource.batchingdepth = resource.batchingdepth;\n\t\tupdateresource.batchingdelay = resource.batchingdelay;\n\t\tupdateresource.resptimeout = resource.resptimeout;\n\t\tupdateresource.respondercert = resource.respondercert;\n\t\tupdateresource.trustresponder = resource.trustresponder;\n\t\tupdateresource.producedattimeskew = resource.producedattimeskew;\n\t\tupdateresource.signingcert = resource.signingcert;\n\t\tupdateresource.usenonce = resource.usenonce;\n\t\tupdateresource.insertclientcert = resource.insertclientcert;\n\t\treturn updateresource.update_resource(client);\n\t}", "@SuppressWarnings(\"WeakerAccess\")\n public synchronized void stop() {\n if (isRunning()) {\n BeatFinder.getInstance().removeBeatListener(beatListener);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n running.set(false);\n positions.clear();\n updates.clear();\n deliverLifecycleAnnouncement(logger, false);\n }\n }", "@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 }", "public static base_responses add(nitro_service client, cmppolicylabel resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcmppolicylabel addresources[] = new cmppolicylabel[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new cmppolicylabel();\n\t\t\t\taddresources[i].labelname = resources[i].labelname;\n\t\t\t\taddresources[i].type = resources[i].type;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private List<Row> join(List<Row> leftRows, String leftColumn, String rightTable, List<Row> rightRows, String rightColumn)\n {\n List<Row> result = new LinkedList<Row>();\n\n RowComparator leftComparator = new RowComparator(new String[]\n {\n leftColumn\n });\n RowComparator rightComparator = new RowComparator(new String[]\n {\n rightColumn\n });\n Collections.sort(leftRows, leftComparator);\n Collections.sort(rightRows, rightComparator);\n\n ListIterator<Row> rightIterator = rightRows.listIterator();\n Row rightRow = rightIterator.hasNext() ? rightIterator.next() : null;\n\n for (Row leftRow : leftRows)\n {\n Integer leftValue = leftRow.getInteger(leftColumn);\n boolean match = false;\n\n while (rightRow != null)\n {\n Integer rightValue = rightRow.getInteger(rightColumn);\n int comparison = leftValue.compareTo(rightValue);\n if (comparison == 0)\n {\n match = true;\n break;\n }\n\n if (comparison < 0)\n {\n if (rightIterator.hasPrevious())\n {\n rightRow = rightIterator.previous();\n }\n break;\n }\n\n rightRow = rightIterator.next();\n }\n\n if (match && rightRow != null)\n {\n Map<String, Object> newMap = new HashMap<String, Object>(((MapRow) leftRow).getMap());\n\n for (Entry<String, Object> entry : ((MapRow) rightRow).getMap().entrySet())\n {\n String key = entry.getKey();\n if (newMap.containsKey(key))\n {\n key = rightTable + \".\" + key;\n }\n newMap.put(key, entry.getValue());\n }\n\n result.add(new MapRow(newMap));\n }\n }\n\n return result;\n }" ]
Given a class node, if this class node implements a trait, then generate all the appropriate code which delegates calls to the trait. It is safe to call this method on a class node which does not implement a trait. @param cNode a class node @param unit the source unit
[ "public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\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 final void notifyFooterItemChanged(int position) {\n if (position < 0 || position >= footerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position\n + \" is not within the position bounds for footer items [0 - \"\n + (footerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position + headerItemCount + contentItemCount);\n }", "public void setPlaying(boolean playing) {\n\n if (this.playing.get() == playing) {\n return;\n }\n\n this.playing.set(playing);\n\n if (playing) {\n metronome.jumpToBeat(whereStopped.get().getBeat());\n if (isSendingStatus()) { // Need to also start the beat sender.\n beatSender.set(new BeatSender(metronome));\n }\n } else {\n final BeatSender activeSender = beatSender.get();\n if (activeSender != null) { // We have a beat sender we need to stop.\n activeSender.shutDown();\n beatSender.set(null);\n }\n whereStopped.set(metronome.getSnapshot());\n }\n }", "public static final int findValueInListBox(ListBox list, String value) {\n\tfor (int i=0; i<list.getItemCount(); i++) {\n\t if (value.equals(list.getValue(i))) {\n\t\treturn i;\n\t }\n\t}\n\treturn -1;\n }", "public void setShortVec(CharBuffer data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (data.isDirect())\n {\n if (!NativeIndexBuffer.setShortVec(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input buffer is wrong size\");\n }\n }\n else if (data.hasArray())\n {\n if (!NativeIndexBuffer.setShortArray(getNative(), data.array()))\n {\n throw new UnsupportedOperationException(\"Input buffer is wrong size\");\n }\n }\n else\n {\n throw new UnsupportedOperationException(\n \"CharBuffer type not supported. Must be direct or have backing array\");\n }\n }", "public void setDiffuseIntensity(float r, float g, float b, float a) {\n setVec4(\"diffuse_intensity\", r, g, b, a);\n }", "public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }", "private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar)\n {\n DayTypes dayTypes = gpCalendar.getDayTypes();\n DefaultWeek defaultWeek = dayTypes.getDefaultWeek();\n if (defaultWeek == null)\n {\n mpxjCalendar.setWorkingDay(Day.SUNDAY, false);\n mpxjCalendar.setWorkingDay(Day.MONDAY, true);\n mpxjCalendar.setWorkingDay(Day.TUESDAY, true);\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true);\n mpxjCalendar.setWorkingDay(Day.THURSDAY, true);\n mpxjCalendar.setWorkingDay(Day.FRIDAY, true);\n mpxjCalendar.setWorkingDay(Day.SATURDAY, false);\n }\n else\n {\n mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon()));\n mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue()));\n mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed()));\n mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu()));\n mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri()));\n mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat()));\n mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun()));\n }\n\n for (Day day : Day.values())\n {\n if (mpxjCalendar.isWorkingDay(day))\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "@Override\n public Symmetry010Date dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }" ]
From the set of classes a new set is built containing all indexed subclasses, but removing then all subtypes of indexed entities. @param selection @return a new set of entities
[ "private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) {\n\t\tSet<Class<?>> entities = new HashSet<Class<?>>();\n\t\t//first build the \"entities\" set containing all indexed subtypes of \"selection\".\n\t\tfor ( Class<?> entityType : selection ) {\n\t\t\tIndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( IndexedTypeSets.fromClass( entityType ) );\n\t\t\tif ( targetedClasses.isEmpty() ) {\n\t\t\t\tString msg = entityType.getName() + \" is not an indexed entity or a subclass of an indexed entity\";\n\t\t\t\tthrow new IllegalArgumentException( msg );\n\t\t\t}\n\t\t\tentities.addAll( targetedClasses.toPojosSet() );\n\t\t}\n\t\tSet<Class<?>> cleaned = new HashSet<Class<?>>();\n\t\tSet<Class<?>> toRemove = new HashSet<Class<?>>();\n\t\t//now remove all repeated types to avoid duplicate loading by polymorphic query loading\n\t\tfor ( Class<?> type : entities ) {\n\t\t\tboolean typeIsOk = true;\n\t\t\tfor ( Class<?> existing : cleaned ) {\n\t\t\t\tif ( existing.isAssignableFrom( type ) ) {\n\t\t\t\t\ttypeIsOk = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( type.isAssignableFrom( existing ) ) {\n\t\t\t\t\ttoRemove.add( existing );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( typeIsOk ) {\n\t\t\t\tcleaned.add( type );\n\t\t\t}\n\t\t}\n\t\tcleaned.removeAll( toRemove );\n\t\tlog.debugf( \"Targets for indexing job: %s\", cleaned );\n\t\treturn IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) );\n\t}" ]
[ "public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }", "private long lastModified(Set<File> files) {\n long result = 0;\n for (File file : files) {\n if (file.lastModified() > result)\n result = file.lastModified();\n }\n return result;\n }", "private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {\n Map<String, Object> dataClone = new HashMap<String, Object>(data);\n dataClone.put(\"auth\", getAuthData());\n\n Map<String, String> payload = new HashMap<String, String>();\n payload.put(\"params\", jsonifyData(dataClone));\n\n if (transloadit.shouldSignRequest) {\n payload.put(\"signature\", getSignature(jsonifyData(dataClone)));\n }\n return payload;\n }", "public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, null, message, attributes));\n }", "@UiThread\n private int getFlatParentPosition(int parentPosition) {\n int parentCount = 0;\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i).isParent()) {\n parentCount++;\n\n if (parentCount > parentPosition) {\n return i;\n }\n }\n }\n\n return INVALID_FLAT_POSITION;\n }", "public <T> T handleResponse(Response response, Type returnType) throws ApiException {\n if (response.isSuccessful()) {\n if (returnType == null || response.code() == 204) {\n // returning null if the returnType is not defined,\n // or the status code is 204 (No Content)\n return null;\n } else {\n return deserialize(response, returnType);\n }\n } else {\n String respBody = null;\n if (response.body() != null) {\n try {\n respBody = response.body().string();\n } catch (IOException e) {\n throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());\n }\n }\n throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);\n }\n }", "public static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }", "private static String decode(String s) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (ch == '%') {\n baos.write(hexToInt(s.charAt(i + 1)) * 16 + hexToInt(s.charAt(i + 2)));\n i += 2;\n continue;\n }\n baos.write(ch);\n }\n try {\n return new String(baos.toByteArray(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }", "private void setFields(Map<String, FieldType> map, MapRow row, FieldContainer container)\n {\n if (row != null)\n {\n for (Map.Entry<String, FieldType> entry : map.entrySet())\n {\n container.set(entry.getValue(), row.getObject(entry.getKey()));\n }\n }\n }" ]
Start the StatsD reporter, if configured. @throws URISyntaxException
[ "@PostConstruct\n public final void init() throws URISyntaxException {\n final String address = getConfig(ADDRESS, null);\n if (address != null) {\n final URI uri = new URI(\"udp://\" + address);\n final String prefix = getConfig(PREFIX, \"mapfish-print\").replace(\"%h\", getHostname());\n final int period = Integer.parseInt(getConfig(PERIOD, \"10\"));\n LOGGER.info(\"Starting a StatsD reporter targeting {} with prefix {} and period {}s\",\n uri, prefix, period);\n this.reporter = StatsDReporter.forRegistry(this.metricRegistry)\n .prefixedWith(prefix)\n .build(uri.getHost(), uri.getPort());\n this.reporter.start(period, TimeUnit.SECONDS);\n }\n }" ]
[ "private void registerPackageInTypeInterestFactory(String pkg)\n {\n TypeInterestFactory.registerInterest(pkg + \"_pkg\", pkg.replace(\".\", \"\\\\.\"), pkg, TypeReferenceLocation.IMPORT);\n // TODO: Finish the implementation\n }", "private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }", "public static Attachment writeAttachmentWithErrorMessage(Throwable throwable, String title) {\n String message = throwable.getMessage();\n try {\n return writeAttachment(message.getBytes(CONFIG.getAttachmentsEncoding()), title);\n } catch (Exception e) {\n e.addSuppressed(throwable);\n LOGGER.error(String.format(\"Can't write attachment \\\"%s\\\"\", title), e);\n }\n return new Attachment();\n }", "public static authorizationpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tauthorizationpolicylabel_binding obj = new authorizationpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tauthorizationpolicylabel_binding response = (authorizationpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }", "private void userInfoInit() {\n\t\tboolean first = true;\n\t\tuserId = null;\n\t\tuserLocale = null;\n\t\tuserName = null;\n\t\tuserOrganization = null;\n\t\tuserDivision = null;\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tuserId = combine(userId, auth.getUserId());\n\t\t\t\tuserName = combine(userName, auth.getUserName());\n\t\t\t\tif (first) {\n\t\t\t\t\tuserLocale = auth.getUserLocale();\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tif (null != auth.getUserLocale() &&\n\t\t\t\t\t\t\t(null == userLocale || !userLocale.equals(auth.getUserLocale()))) {\n\t\t\t\t\t\tuserLocale = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tuserOrganization = combine(userOrganization, auth.getUserOrganization());\n\t\t\t\tuserDivision = combine(userDivision, auth.getUserDivision());\n\t\t\t}\n\t\t}\n\n\t\t// now calculate the \"id\" for this context, this should be independent of the data order, so sort\n\t\tMap<String, List<String>> idParts = new HashMap<String, List<String>>();\n\t\tif (null != authentications) {\n\t\t\tfor (Authentication auth : authentications) {\n\t\t\t\tList<String> auths = new ArrayList<String>();\n\t\t\t\tfor (BaseAuthorization ba : auth.getAuthorizations()) {\n\t\t\t\t\tauths.add(ba.getId());\n\t\t\t\t}\n\t\t\t\tCollections.sort(auths);\n\t\t\t\tidParts.put(auth.getSecurityServiceId(), auths);\n\t\t\t}\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\tList<String> sortedKeys = new ArrayList<String>(idParts.keySet());\n\t\tCollections.sort(sortedKeys);\n\t\tfor (String key : sortedKeys) {\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tsb.append('|');\n\t\t\t}\n\t\t\tList<String> auths = idParts.get(key);\n\t\t\tfirst = true;\n\t\t\tfor (String ak : auths) {\n\t\t\t\tif (first) {\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else {\n\t\t\t\t\tsb.append('|');\n\t\t\t\t}\n\t\t\t\tsb.append(ak);\n\t\t\t}\n\t\t\tsb.append('@');\n\t\t\tsb.append(key);\n\t\t}\n\t\tid = sb.toString();\n\t}", "public String format(String value) {\n StringBuilder s = new StringBuilder();\n\n if (value != null && value.trim().length() > 0) {\n boolean continuationLine = false;\n\n s.append(getName()).append(\":\");\n if (isFirstLineEmpty()) {\n s.append(\"\\n\");\n continuationLine = true;\n }\n\n try {\n BufferedReader reader = new BufferedReader(new StringReader(value));\n String line;\n while ((line = reader.readLine()) != null) {\n if (continuationLine && line.trim().length() == 0) {\n // put a dot on the empty continuation lines\n s.append(\" .\\n\");\n } else {\n s.append(\" \").append(line).append(\"\\n\");\n }\n\n continuationLine = true;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n return s.toString();\n }", "@Override\n public void onRotationSensor(long timeStamp, float rotationW, float rotationX, float rotationY, float rotationZ,\n float gyroX, float gyroY, float gyroZ) {\n GVRCameraRig cameraRig = null;\n if (mMainScene != null) {\n cameraRig = mMainScene.getMainCameraRig();\n }\n\n if (cameraRig != null) {\n cameraRig.setRotationSensorData(timeStamp, rotationW, rotationX, rotationY, rotationZ, gyroX, gyroY, gyroZ);\n updateSensoredScene();\n }\n }" ]
Only sets and gets that are by row and column are used.
[ "public static long access2d(DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c )\n {\n long timeBefore = System.currentTimeMillis();\n\n for( int i = 0; i < a.numRows; i++ ) {\n\n for( int j = 0; j < b.numCols; j++ ) {\n c.set(i,j,a.get(i,0)*b.get(0,j));\n }\n\n for( int k = 1; k < b.numRows; k++ ) {\n for( int j = 0; j < b.numCols; j++ ) {\n// c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j));\n c.data[i*b.numCols+j] +=a.get(i,k)*b.get(k,j);\n }\n }\n }\n\n return System.currentTimeMillis() - timeBefore;\n }" ]
[ "public static boolean nullSafeEquals(final Object obj1, final Object obj2) {\n return ((obj1 == null && obj2 == null)\n || (obj1 != null && obj2 != null && obj1.equals(obj2)));\n }", "public static Info eye( final Variable A , ManagerTempVariables manager) {\n Info ret = new Info();\n final VariableMatrix output = manager.createMatrix();\n ret.output = output;\n\n if( A instanceof VariableMatrix ) {\n ret.op = new Operation(\"eye-m\") {\n @Override\n public void process() {\n DMatrixRMaj mA = ((VariableMatrix)A).matrix;\n output.matrix.reshape(mA.numRows,mA.numCols);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else if( A instanceof VariableInteger ) {\n ret.op = new Operation(\"eye-i\") {\n @Override\n public void process() {\n int N = ((VariableInteger)A).value;\n output.matrix.reshape(N,N);\n CommonOps_DDRM.setIdentity(output.matrix);\n }\n };\n } else {\n throw new RuntimeException(\"Unsupported variable type \"+A);\n }\n\n return ret;\n }", "private void ensurePKsFromHierarchy(ClassDescriptorDef classDef) throws ConstraintException\r\n {\r\n SequencedHashMap pks = new SequencedHashMap();\r\n\r\n for (Iterator it = classDef.getAllExtentClasses(); it.hasNext();)\r\n {\r\n ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();\r\n\r\n ArrayList subPKs = subTypeDef.getPrimaryKeys();\r\n\r\n // check against already present PKs\r\n for (Iterator pkIt = subPKs.iterator(); pkIt.hasNext();)\r\n {\r\n FieldDescriptorDef fieldDef = (FieldDescriptorDef)pkIt.next();\r\n FieldDescriptorDef foundPKDef = (FieldDescriptorDef)pks.get(fieldDef.getName());\r\n\r\n if (foundPKDef != null)\r\n {\r\n if (!isEqual(fieldDef, foundPKDef))\r\n {\r\n throw new ConstraintException(\"Cannot pull up the declaration of the required primary key \"+fieldDef.getName()+\r\n \" because its definitions in \"+fieldDef.getOwner().getName()+\" and \"+\r\n foundPKDef.getOwner().getName()+\" differ\");\r\n }\r\n }\r\n else\r\n {\r\n pks.put(fieldDef.getName(), fieldDef);\r\n }\r\n }\r\n }\r\n\r\n ensureFields(classDef, pks.values());\r\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 }", "public void postProcess() {\n\t\tif (foreignColumnName != null) {\n\t\t\tforeignAutoRefresh = true;\n\t\t}\n\t\tif (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {\n\t\t\tmaxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;\n\t\t}\n\t}", "@Override\r\n @SuppressWarnings(\"unchecked\")\r\n public V put(K key, V value) {\r\n if (value == null) {\r\n return put(key, (V)nullValue);\r\n }\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n V result = deltaMap.put(key, value);\r\n if (result == null) {\r\n return originalMap.get(key);\r\n }\r\n if (result == nullValue) {\r\n return null;\r\n }\r\n if (result == removedValue) {\r\n return null;\r\n }\r\n return result;\r\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 }", "@Override\n public final long getLong(final String key) {\n Long result = optLong(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\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}" ]
Handler for month changes. @param event change event.
[ "@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 }" ]
[ "public static bridgegroup_nsip_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_nsip_binding obj = new bridgegroup_nsip_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_nsip_binding response[] = (bridgegroup_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n //\n // Retrieve the LHS value\n //\n FieldType field = m_leftValue;\n Object lhs;\n\n if (field == null)\n {\n lhs = null;\n }\n else\n {\n lhs = container.getCurrentValue(field);\n switch (field.getDataType())\n {\n case DATE:\n {\n if (lhs != null)\n {\n lhs = DateHelper.getDayStartDate((Date) lhs);\n }\n break;\n }\n\n case DURATION:\n {\n if (lhs != null)\n {\n Duration dur = (Duration) lhs;\n lhs = dur.convertUnits(TimeUnit.HOURS, m_properties);\n }\n else\n {\n lhs = Duration.getInstance(0, TimeUnit.HOURS);\n }\n break;\n }\n\n case STRING:\n {\n lhs = lhs == null ? \"\" : lhs;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n //\n // Retrieve the RHS values\n //\n Object[] rhs;\n if (m_symbolicValues == true)\n {\n rhs = processSymbolicValues(m_workingRightValues, container, promptValues);\n }\n else\n {\n rhs = m_workingRightValues;\n }\n\n //\n // Evaluate\n //\n boolean result;\n switch (m_operator)\n {\n case AND:\n case OR:\n {\n result = evaluateLogicalOperator(container, promptValues);\n break;\n }\n\n default:\n {\n result = m_operator.evaluate(lhs, rhs);\n break;\n }\n }\n\n return result;\n }", "public <U> CoreRemoteMongoIterable<U> map(final Function<ResultT, U> mapper) {\n return new CoreRemoteMappingIterable<>(this, mapper);\n }", "private void disableCertificateVerification()\n throws KeyManagementException, NoSuchAlgorithmException {\n // Create a trust manager that does not validate certificate chains\n final TrustManager[] trustAllCerts = new TrustManager[] { new CustomTrustManager() };\n\n // Install the all-trusting trust manager\n final SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new SecureRandom());\n final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();\n HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);\n final HostnameVerifier verifier = new HostnameVerifier() {\n @Override\n public boolean verify(final String hostname,\n final SSLSession session) {\n return true;\n }\n };\n\n HttpsURLConnection.setDefaultHostnameVerifier(verifier);\n }", "public static void assertValidNode(MetadataStore metadataStore, Integer nodeId) {\n if(!metadataStore.getCluster().hasNodeWithId(nodeId)) {\n throw new InvalidMetadataException(\"NodeId \" + nodeId + \" is not or no longer in this cluster\");\n }\n }", "public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {\n if (searchView != null) {\n searchView.setOnCloseListener(new SearchView.OnCloseListener() {\n @Override public boolean onClose() {\n return listener.onClose();\n }\n });\n } else if (supportView != null) {\n supportView.setOnCloseListener(listener);\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }", "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\n }", "public void pause()\n {\n if (mAudioListener != null)\n {\n int sourceId = getSourceId();\n if (sourceId != GvrAudioEngine.INVALID_ID)\n {\n mAudioListener.getAudioEngine().pauseSound(sourceId);\n }\n }\n }", "public static responderpolicylabel_responderpolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_responderpolicy_binding obj = new responderpolicylabel_responderpolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_responderpolicy_binding response[] = (responderpolicylabel_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
This method is called to format a duration. @param value duration value @return formatted duration value
[ "private String formatDuration(Object value)\n {\n String result = null;\n if (value instanceof Duration)\n {\n Duration duration = (Duration) value;\n result = m_formats.getDurationDecimalFormat().format(duration.getDuration()) + formatTimeUnit(duration.getUnits());\n }\n return result;\n }" ]
[ "public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));\n final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, \"true\")\n .queryParam(ServerAPI.SCOPE_TEST_PARAM, \"true\")\n .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())\n .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())\n .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"get module ancestors \", moduleName, moduleVersion);\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Dependency>>(){});\n }", "public static <T> Iterator<T> unique(Iterator<T> self) {\n return toList((Iterable<T>) unique(toList(self))).listIterator();\n }", "public static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode) {\n requireNonNull(source, \"source\");\n requireNonNull(target, \"target\");\n final DiffProcessor processor = new DiffProcessor(replaceMode, () -> unchangedValues(source, target));\n generateDiffs(processor, EMPTY_JSON_POINTER, source, target);\n return processor.getPatch();\n }", "private TrackSourceSlot findTrackSourceSlot() {\n TrackSourceSlot result = TRACK_SOURCE_SLOT_MAP.get(packetBytes[41]);\n if (result == null) {\n return TrackSourceSlot.UNKNOWN;\n }\n return result;\n }", "public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }", "public void adjustLinks(String sourceFolder, String targetFolder) throws CmsException {\n\n String rootSourceFolder = addSiteRoot(sourceFolder);\n String rootTargetFolder = addSiteRoot(targetFolder);\n String siteRoot = getRequestContext().getSiteRoot();\n getRequestContext().setSiteRoot(\"\");\n try {\n CmsLinkRewriter linkRewriter = new CmsLinkRewriter(this, rootSourceFolder, rootTargetFolder);\n linkRewriter.rewriteLinks();\n } finally {\n getRequestContext().setSiteRoot(siteRoot);\n }\n }", "private static BsonDocument withNewVersion(\n final BsonDocument document,\n final BsonDocument newVersion\n ) {\n final BsonDocument newDocument = BsonUtils.copyOfDocument(document);\n newDocument.put(DOCUMENT_VERSION_FIELD, newVersion);\n return newDocument;\n }", "private void applyAliases()\n {\n CustomFieldContainer fields = m_projectFile.getCustomFields();\n for (Map.Entry<FieldType, String> entry : ALIASES.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }", "public static base_responses export(nitro_service client, appfwlearningdata resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tappfwlearningdata exportresources[] = new appfwlearningdata[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\texportresources[i] = new appfwlearningdata();\n\t\t\t\texportresources[i].profilename = resources[i].profilename;\n\t\t\t\texportresources[i].securitycheck = resources[i].securitycheck;\n\t\t\t\texportresources[i].target = resources[i].target;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, exportresources,\"export\");\n\t\t}\n\t\treturn result;\n\t}" ]
Sets all Fluo properties to their default in the given configuration. NOTE - some properties do not have defaults and will not be set.
[ "public static void setDefaultConfiguration(SimpleConfiguration config) {\n config.setProperty(CONNECTION_ZOOKEEPERS_PROP, CONNECTION_ZOOKEEPERS_DEFAULT);\n config.setProperty(CONNECTION_ZOOKEEPER_TIMEOUT_PROP, CONNECTION_ZOOKEEPER_TIMEOUT_DEFAULT);\n config.setProperty(DFS_ROOT_PROP, DFS_ROOT_DEFAULT);\n config.setProperty(ACCUMULO_ZOOKEEPERS_PROP, ACCUMULO_ZOOKEEPERS_DEFAULT);\n config.setProperty(WORKER_NUM_THREADS_PROP, WORKER_NUM_THREADS_DEFAULT);\n config.setProperty(TRANSACTION_ROLLBACK_TIME_PROP, TRANSACTION_ROLLBACK_TIME_DEFAULT);\n config.setProperty(LOADER_NUM_THREADS_PROP, LOADER_NUM_THREADS_DEFAULT);\n config.setProperty(LOADER_QUEUE_SIZE_PROP, LOADER_QUEUE_SIZE_DEFAULT);\n config.setProperty(MINI_START_ACCUMULO_PROP, MINI_START_ACCUMULO_DEFAULT);\n config.setProperty(MINI_DATA_DIR_PROP, MINI_DATA_DIR_DEFAULT);\n }" ]
[ "public static Object objectify(ObjectMapper mapper, Object source) {\n return objectify(mapper, source, Object.class);\n }", "protected void runScript(File script) {\n if (!script.exists()) {\n JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + \" does not exist.\",\n \"Unable to run script.\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n\n int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), \"Run CLI script \" + script.getName() + \"?\",\n \"Confirm run script\", JOptionPane.YES_NO_OPTION);\n if (choice != JOptionPane.YES_OPTION) return;\n\n menu.addScript(script);\n\n cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output\n output.post(\"\\n\");\n\n SwingWorker scriptRunner = new ScriptRunner(script);\n scriptRunner.execute();\n }", "public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) {\n\t\tList<MwDumpFile> dumps = findAllDumps(dumpContentType);\n\n\t\tfor (MwDumpFile dump : dumps) {\n\t\t\tif (dump.isAvailable()) {\n\t\t\t\treturn dump;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "protected List<String> extractWords() throws IOException\n {\n while( true ) {\n lineNumber++;\n String line = in.readLine();\n if( line == null ) {\n return null;\n }\n\n // skip comment lines\n if( hasComment ) {\n if( line.charAt(0) == comment )\n continue;\n }\n\n // extract the words, which are the variables encoded\n return parseWords(line);\n }\n }", "private long getTime(Date start, Date end, long target, boolean after)\n {\n long total = 0;\n if (start != null && end != null)\n {\n Date startTime = DateHelper.getCanonicalTime(start);\n Date endTime = DateHelper.getCanonicalTime(end);\n\n Date startDay = DateHelper.getDayStartDate(start);\n Date finishDay = DateHelper.getDayStartDate(end);\n\n //\n // Handle the case where the end of the range is at midnight -\n // this will show up as the start and end days not matching\n //\n if (startDay.getTime() != finishDay.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n int diff = DateHelper.compare(startTime, endTime, target);\n if (diff == 0)\n {\n if (after == true)\n {\n total = (endTime.getTime() - target);\n }\n else\n {\n total = (target - startTime.getTime());\n }\n }\n else\n {\n if ((after == true && diff < 0) || (after == false && diff > 0))\n {\n total = (endTime.getTime() - startTime.getTime());\n }\n }\n }\n return (total);\n }", "public static Value.Builder makeValue(Date date) {\n return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L));\n }", "public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) {\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n possibleState.put(action.getName(), action.getExpr());\r\n }\n\r\n return possibleStateList;\r\n }", "public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) {\n return find(project, type) != null;\n }", "public Set<ConstraintViolation> validate(int record) {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int ds = 0; ds < 250; ++ds) {\r\n\t\t\ttry {\r\n\t\t\t\tDataSetInfo dataSetInfo = dsiFactory.create(IIM.DS(record, ds));\r\n\t\t\t\terrors.addAll(validate(dataSetInfo));\r\n\t\t\t} catch (InvalidDataSetException ignored) {\r\n\t\t\t\t// DataSetFactory doesn't know about this ds, so will skip it\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn errors;\r\n\t}" ]
Gets an iterable of all the assignments of this task. @param fields the fields to retrieve. @return an iterable containing info about all the assignments.
[ "public Iterable<BoxTaskAssignment.Info> getAllAssignments(String ... fields) {\n final QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields);\n }\n return new Iterable<BoxTaskAssignment.Info>() {\n public Iterator<BoxTaskAssignment.Info> iterator() {\n URL url = GET_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(\n BoxTask.this.getAPI().getBaseURL(), builder.toString(), BoxTask.this.getID());\n return new BoxTaskAssignmentIterator(BoxTask.this.getAPI(), url);\n }\n };\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 }", "public List<TableProperty> getEditableColumns(CmsMessageBundleEditorTypes.EditMode mode) {\n\n return m_editorState.get(mode).getEditableColumns();\n }", "public static final PatchOperationTarget createHost(final String hostName, final ModelControllerClient client) {\n final PathElement host = PathElement.pathElement(HOST, hostName);\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(host, CORE_SERVICES);\n return new RemotePatchOperationTarget(address, client);\n }", "public static double huntKennedyCMSFloorValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}", "protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }", "public static String convertToFileSystemChar(String name) {\n String erg = \"\";\n Matcher m = Pattern.compile(\"[a-z0-9 _#&@\\\\[\\\\(\\\\)\\\\]\\\\-\\\\.]\", Pattern.CASE_INSENSITIVE).matcher(name);\n while (m.find()) {\n erg += name.substring(m.start(), m.end());\n }\n if (erg.length() > 200) {\n erg = erg.substring(0, 200);\n System.out.println(\"cut filename: \" + erg);\n }\n return erg;\n }", "public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)\n throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setFollowRedirects(true);\n \n if (parameters != null) {\n for (Entry<String, String> entry : parameters.entrySet()) {\n conn.addRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n\n boolean redirect = false;\n\n // normally, 3xx is redirect\n int status = conn.getResponseCode();\n if (status != HttpURLConnection.HTTP_OK) {\n if (status == HttpURLConnection.HTTP_MOVED_TEMP\n || status == HttpURLConnection.HTTP_MOVED_PERM\n || status == HttpURLConnection.HTTP_SEE_OTHER)\n redirect = true;\n }\n\n if (redirect) {\n\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(\"Location\");\n\n // get the cookie if need, for login\n String cookies = conn.getHeaderField(\"Set-Cookie\");\n\n // open the new connnection again\n conn = (HttpURLConnection) new URL(newUrl).openConnection();\n conn.setRequestProperty(\"Cookie\", cookies);\n\n }\n \n byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());\n FileOutputStream fos = new FileOutputStream(fileToSave);\n fos.write(data);\n fos.close();\n }", "public static ActorSystem createAndGetActorSystem() {\n if (actorSystem == null || actorSystem.isTerminated()) {\n actorSystem = ActorSystem.create(PcConstants.ACTOR_SYSTEM, conf);\n }\n return actorSystem;\n }", "public static void doMetaClearRebalance(AdminClient adminClient, List<Integer> nodeIds) {\n AdminToolUtils.assertServerNotInOfflineState(adminClient, nodeIds);\n System.out.println(\"Setting \" + MetadataStore.SERVER_STATE_KEY + \" to \"\n + MetadataStore.VoldemortState.NORMAL_SERVER);\n doMetaSet(adminClient,\n nodeIds,\n MetadataStore.SERVER_STATE_KEY,\n MetadataStore.VoldemortState.NORMAL_SERVER.toString());\n RebalancerState state = RebalancerState.create(\"[]\");\n System.out.println(\"Cleaning up \" + MetadataStore.REBALANCING_STEAL_INFO + \" to \"\n + state.toJsonString());\n doMetaSet(adminClient,\n nodeIds,\n MetadataStore.REBALANCING_STEAL_INFO,\n state.toJsonString());\n System.out.println(\"Cleaning up \" + MetadataStore.REBALANCING_SOURCE_CLUSTER_XML\n + \" to empty string\");\n doMetaSet(adminClient, nodeIds, MetadataStore.REBALANCING_SOURCE_CLUSTER_XML, \"\");\n }" ]
Helper method to add a parameter without having to create it explicitely. The created parameter should be persisted afterwards. @param key name of the parameter to add @param value value of the parameter to create @return the newly created parameter
[ "public RuntimeParameter addParameter(String key, String value)\n {\n RuntimeParameter jp = new RuntimeParameter();\n jp.setJi(this.getId());\n jp.setKey(key);\n jp.setValue(value);\n return jp;\n }" ]
[ "public MACAddressSection toEUI(boolean extended) {\n\t\tMACAddressSegment[] segs = toEUISegments(extended);\n\t\tif(segs == null) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\treturn createSectionInternal(creator, segs, Math.max(0, addressSegmentIndex - 4) << 1, extended);\n\t}", "@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n private void cleanupSessions(List<String> storeNamesToCleanUp) {\n\n logger.info(\"Performing cleanup\");\n for(String store: storeNamesToCleanUp) {\n\n for(Node node: nodesToStream) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store,\n node.getId()));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n node.getId()));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n\n }\n\n cleanedUp = true;\n\n }", "public void spawnThread(DukeController controller, int check_interval) {\n this.controller = controller;\n timer = mgr.schedule(this, 0, check_interval * 1000); // convert to ms\n }", "private void populateCalendarException(Record record, ProjectCalendar calendar) throws MPXJException\n {\n Date fromDate = record.getDate(0);\n Date toDate = record.getDate(1);\n boolean working = record.getNumericBoolean(2);\n\n // I have found an example MPX file where a single day exception is expressed with just the start date set.\n // If we find this for we assume that the end date is the same as the start date.\n if (fromDate != null && toDate == null)\n {\n toDate = fromDate;\n }\n\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n addExceptionRange(exception, record.getTime(3), record.getTime(4));\n addExceptionRange(exception, record.getTime(5), record.getTime(6));\n addExceptionRange(exception, record.getTime(7), record.getTime(8));\n }\n }", "@Override\n public ModelNode resolveValue(ExpressionResolver resolver, ModelNode value) throws OperationFailedException {\n\n // Pass non-LIST values through the superclass so it can reject weird values and, in the odd chance\n // that's how this object is set up, turn undefined into a default list value.\n ModelNode superResult = value.getType() == ModelType.LIST ? value : super.resolveValue(resolver, value);\n\n // If it's not a LIST (almost certainly UNDEFINED), then nothing more we can do\n if (superResult.getType() != ModelType.LIST) {\n return superResult;\n }\n // Resolve each element.\n // Don't mess with the original value\n ModelNode clone = superResult == value ? value.clone() : superResult;\n ModelNode result = new ModelNode();\n result.setEmptyList();\n for (ModelNode element : clone.asList()) {\n result.add(valueType.resolveValue(resolver, element));\n }\n // Validate the entire list\n getValidator().validateParameter(getName(), result);\n return result;\n }", "public static ResourceKey key(Enum<?> value) {\n return new ResourceKey(value.getClass().getName(), value.name());\n }", "public static DMatrixRMaj extractRow(DMatrixRMaj a , int row , DMatrixRMaj out ) {\n if( out == null)\n out = new DMatrixRMaj(1,a.numCols);\n else if( !MatrixFeatures_DDRM.isVector(out) || out.getNumElements() != a.numCols )\n throw new MatrixDimensionException(\"Output must be a vector of length \"+a.numCols);\n\n System.arraycopy(a.data,a.getIndex(row,0),out.data,0,a.numCols);\n\n return out;\n }", "public void refresh() {\n this.getRefreshLock().writeLock().lock();\n\n try {\n this.authenticate();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n this.getRefreshLock().writeLock().unlock();\n throw e;\n }\n\n this.notifyRefresh();\n this.getRefreshLock().writeLock().unlock();\n }", "public GVRComponent detachComponent(long type) {\n NativeSceneObject.detachComponent(getNative(), type);\n synchronized (mComponents) {\n GVRComponent component = mComponents.remove(type);\n if (component != null) {\n component.setOwnerObject(null);\n }\n return component;\n }\n }" ]
Checks if the path leads to an embedded property or association. @param targetTypeName the entity with the property @param namesWithoutAlias the path to the property with all the aliases resolved @return {@code true} if the property is an embedded, {@code false} otherwise.
[ "public boolean isEmbeddedProperty(String targetTypeName, List<String> namesWithoutAlias) {\n\t\tOgmEntityPersister persister = getPersister( targetTypeName );\n\t\tType propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );\n\t\tif ( propertyType.isComponentType() ) {\n\t\t\t// Embedded\n\t\t\treturn true;\n\t\t}\n\t\telse if ( propertyType.isAssociationType() ) {\n\t\t\tJoinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );\n\t\t\tif ( associatedJoinable.isCollection() ) {\n\t\t\t\tOgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;\n\t\t\t\treturn collectionPersister.getType().isComponentType();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}" ]
[ "public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }", "public String lookupUser(String url) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LOOKUP_USER);\r\n\r\n parameters.put(\"url\", url);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element payload = response.getPayload();\r\n Element groupnameElement = (Element) payload.getElementsByTagName(\"username\").item(0);\r\n return ((Text) groupnameElement.getFirstChild()).getData();\r\n }", "@Override\n public synchronized void start() {\n if (!started.getAndSet(true)) {\n finished.set(false);\n thread.start();\n }\n }", "public static tmtrafficaction[] get(nitro_service service) throws Exception{\n\t\ttmtrafficaction obj = new tmtrafficaction();\n\t\ttmtrafficaction[] response = (tmtrafficaction[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "private static void checkPreconditions(final Set<Object> possibleValues) {\n\t\tif( possibleValues == null ) {\n\t\t\tthrow new NullPointerException(\"possibleValues Set should not be null\");\n\t\t} else if( possibleValues.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"possibleValues Set should not be empty\");\n\t\t}\n\t}", "protected void addPropertiesStart(String type) {\n putProperty(PropertyKey.Host.name(), IpUtils.getHostName());\n putProperty(PropertyKey.Type.name(), type);\n putProperty(PropertyKey.Status.name(), Status.Start.name());\n }", "public void run(Configuration configuration, InjectableStepsFactory stepsFactory, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n RunContext context = new RunContext(configuration, stepsFactory, story.getPath(), filter);\n if (beforeStories != null) {\n context.stateIs(beforeStories);\n }\n Map<String, String> storyParameters = new HashMap<>();\n run(context, story, storyParameters);\n }", "public double getDurationMs() {\n double durationMs = 0;\n for (Duration duration : durations) {\n if (duration.taskFinished()) {\n durationMs += duration.getDurationMS();\n }\n }\n return durationMs;\n }" ]
Use this API to delete ntpserver.
[ "public static base_response delete(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = resource.serverip;\n\t\tdeleteresource.servername = resource.servername;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
[ "public Set<Annotation> getPropertyAnnotations()\n\t{\n\t\tif (accessor instanceof PropertyAwareAccessor)\n\t\t{\n\t\t\treturn unmodifiableSet(((PropertyAwareAccessor) accessor).getReadMethodAnnotations());\n\t\t}\n\t\treturn unmodifiableSet(Collections.<Annotation>emptySet());\n\t}", "public String clean(String value) {\n String orig = value;\n \n // check if there's a + before the first digit\n boolean initialplus = findPlus(value);\n \n // remove everything but digits\n value = sub.clean(value);\n if (value == null)\n return null;\n\n // check for initial '00'\n boolean zerozero = !initialplus && value.startsWith(\"00\");\n if (zerozero)\n value = value.substring(2); // strip off the zeros\n\n // look for country code\n CountryCode ccode = findCountryCode(value);\n if (ccode == null) {\n // no country code, let's do what little we can\n if (initialplus || zerozero)\n return orig; // this number is messed up. dare not touch\n return value;\n\n } else {\n value = value.substring(ccode.getPrefix().length()); // strip off ccode\n if (ccode.getStripZero() && value.startsWith(\"0\"))\n value = value.substring(1); // strip the zero\n\n if (ccode.isRightFormat(value))\n return \"+\" + ccode.getPrefix() + \" \" + value;\n else\n return orig; // don't dare touch this\n }\n }", "public CurrencyQueryBuilder setCurrencyCodes(String... codes) {\n return set(CurrencyQuery.KEY_QUERY_CURRENCY_CODES, Arrays.asList(codes));\n }", "protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item,\n BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) {\n\n\n String queryString = \"\";\n if (notify != null) {\n queryString = new QueryStringBuilder().appendParam(\"notify\", notify.toString()).toString();\n }\n URL url;\n if (queryString.length() > 0) {\n url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString);\n } else {\n url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL());\n }\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", item);\n requestJSON.add(\"accessible_by\", accessibleBy);\n requestJSON.add(\"role\", role.toJSONString());\n if (canViewPath != null) {\n requestJSON.add(\"can_view_path\", canViewPath.booleanValue());\n }\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get(\"id\").asString());\n return newCollaboration.new Info(responseJSON);\n }", "public String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\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 }", "public <T> T cached(String key) {\n H.Session sess = session();\n if (null != sess) {\n return sess.cached(key);\n } else {\n return app().cache().get(key);\n }\n }", "private static RemoteWebDriver buildRemoteWebDriver(String hubUrl) {\n\t\tDesiredCapabilities capabilities = new DesiredCapabilities();\n\t\tcapabilities.setPlatform(Platform.ANY);\n\t\tURL url;\n\t\ttry {\n\t\t\turl = new URL(hubUrl);\n\t\t} catch (MalformedURLException e) {\n\t\t\tLOGGER.error(\"The given hub url of the remote server is malformed can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\tHttpCommandExecutor executor = null;\n\t\ttry {\n\t\t\texecutor = new HttpCommandExecutor(url);\n\t\t} catch (Exception e) {\n\t\t\t// TODO Stefan; refactor this catch, this will definitely result in\n\t\t\t// NullPointers, why\n\t\t\t// not throw RuntimeException direct?\n\t\t\tLOGGER.error(\n\t\t\t\t\t\"Received unknown exception while creating the \"\n\t\t\t\t\t\t\t+ \"HttpCommandExecutor, can not continue!\",\n\t\t\t\t\te);\n\t\t\treturn null;\n\t\t}\n\t\treturn new RemoteWebDriver(executor, capabilities);\n\t}", "public AbstractSqlCreator setParameter(String name, Object value) {\n ppsc.setParameter(name, value);\n return this;\n }" ]
Use this API to Reboot reboot.
[ "public static base_response Reboot(nitro_service client, reboot resource) throws Exception {\n\t\treboot Rebootresource = new reboot();\n\t\tRebootresource.warm = resource.warm;\n\t\treturn Rebootresource.perform_operation(client);\n\t}" ]
[ "public static final Path resolveSecurely(Path rootPath, String path) {\n Path resolvedPath;\n if(path == null || path.isEmpty()) {\n resolvedPath = rootPath.normalize();\n } else {\n String relativePath = removeSuperflousSlashes(path);\n resolvedPath = rootPath.resolve(relativePath).normalize();\n }\n if(!resolvedPath.startsWith(rootPath)) {\n throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path);\n }\n return resolvedPath;\n }", "static void showWarning(final String caption, final String description) {\n\n Notification warning = new Notification(caption, description, Type.WARNING_MESSAGE, true);\n warning.setDelayMsec(-1);\n warning.show(UI.getCurrent().getPage());\n\n }", "@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 static base_response restart(nitro_service client) throws Exception {\n\t\tdbsmonitors restartresource = new dbsmonitors();\n\t\treturn restartresource.perform_operation(client,\"restart\");\n\t}", "public static String changeFirstLetterToCapital(String word) {\n char[] letras = word.toCharArray();\n char a = letras[0];\n letras[0] = Character.toUpperCase(a);\n return new String(letras);\n }", "protected ExpectState prepareClosure(int pairIndex, MatchResult result) {\n /* TODO: potentially remove this?\n {\n System.out.println( \"Begin: \" + result.beginOffset(0) );\n System.out.println( \"Length: \" + result.length() );\n System.out.println( \"Current: \" + input.getCurrentOffset() );\n System.out.println( \"Begin: \" + input.getMatchBeginOffset() );\n System.out.println( \"End: \" + input.getMatchEndOffset() );\n //System.out.println( \"Match: \" + input.match() );\n //System.out.println( \"Pre: >\" + input.preMatch() + \"<\");\n //System.out.println( \"Post: \" + input.postMatch() );\n }\n */\n\n // Prepare Closure environment\n ExpectState state;\n Map<String, Object> prevMap = null;\n if (g_state != null) {\n prevMap = g_state.getVars();\n }\n\n int matchedWhere = result.beginOffset(0);\n String matchedText = result.toString(); // expect_out(0,string)\n\n // Unmatched upto end of match\n // expect_out(buffer)\n char[] chBuffer = input.getBuffer();\n String copyBuffer = new String(chBuffer, 0, result.endOffset(0) );\n\n List<String> groups = new ArrayList<>();\n for (int j = 1; j <= result.groups(); j++) {\n String group = result.group(j);\n groups.add( group );\n }\n state = new ExpectState(copyBuffer.toString(), matchedWhere, matchedText, pairIndex, groups, prevMap);\n\n return state;\n }", "public void okResponse(String responseCode, String message) {\r\n untagged();\r\n message(OK);\r\n responseCode(responseCode);\r\n message(message);\r\n end();\r\n }", "public static CredentialsConfig getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) {\n if (deployerOverrider.isOverridingDefaultDeployer()) {\n CredentialsConfig deployerCredentialsConfig = deployerOverrider.getDeployerCredentialsConfig();\n if (deployerCredentialsConfig != null) {\n return deployerCredentialsConfig;\n }\n }\n\n if (server != null) {\n CredentialsConfig deployerCredentials = server.getDeployerCredentialsConfig();\n if (deployerCredentials != null) {\n return deployerCredentials;\n }\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }", "public boolean getBoxBound(float[] corners)\n {\n int rc;\n if ((corners == null) || (corners.length != 6) ||\n ((rc = NativeVertexBuffer.getBoundingVolume(getNative(), corners)) < 0))\n {\n throw new IllegalArgumentException(\"Cannot copy box bound into array provided\");\n }\n return rc != 0;\n }" ]
Creates a spin wrapper for a data input of a given data format. @param input the input to wrap @param format the data format of the input @return the spin wrapper for the input @throws IllegalArgumentException in case an argument of illegal type is provided (such as 'null')
[ "public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }" ]
[ "public static boolean isFloat(CharSequence self) {\n try {\n Float.valueOf(self.toString().trim());\n return true;\n } catch (NumberFormatException nfe) {\n return false;\n }\n }", "public ThumborUrlBuilder crop(int top, int left, int bottom, int right) {\n if (top < 0) {\n throw new IllegalArgumentException(\"Top must be greater or equal to zero.\");\n }\n if (left < 0) {\n throw new IllegalArgumentException(\"Left must be greater or equal to zero.\");\n }\n if (bottom < 1 || bottom <= top) {\n throw new IllegalArgumentException(\"Bottom must be greater than zero and top.\");\n }\n if (right < 1 || right <= left) {\n throw new IllegalArgumentException(\"Right must be greater than zero and left.\");\n }\n hasCrop = true;\n cropTop = top;\n cropLeft = left;\n cropBottom = bottom;\n cropRight = right;\n return this;\n }", "public static List<String> splitAndTrimAsList(String text, String sep) {\n ArrayList<String> answer = new ArrayList<>();\n if (text != null && text.length() > 0) {\n for (String v : text.split(sep)) {\n String trim = v.trim();\n if (trim.length() > 0) {\n answer.add(trim);\n }\n }\n }\n return answer;\n }", "private String jsonifyData(Map<String, ? extends Object> data) {\n JSONObject jsonData = new JSONObject(data);\n\n return jsonData.toString();\n }", "@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }", "public boolean isDuplicateName(String name) {\n if (name == null || name.trim().isEmpty()) {\n return false;\n }\n List<AssignmentRow> as = view.getAssignmentRows();\n if (as != null && !as.isEmpty()) {\n int nameCount = 0;\n for (AssignmentRow row : as) {\n if (name.trim().compareTo(row.getName()) == 0) {\n nameCount++;\n if (nameCount > 1) {\n return true;\n }\n }\n }\n }\n return false;\n }", "public final void printClientConfig(final JSONWriter json) throws JSONException {\n json.key(\"layouts\");\n json.array();\n final Map<String, Template> accessibleTemplates = getTemplates();\n accessibleTemplates.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))\n .forEach(entry -> {\n json.object();\n json.key(\"name\").value(entry.getKey());\n entry.getValue().printClientConfig(json);\n json.endObject();\n });\n json.endArray();\n json.key(\"smtp\").object();\n json.key(\"enabled\").value(smtp != null);\n if (smtp != null) {\n json.key(\"storage\").object();\n json.key(\"enabled\").value(smtp.getStorage() != null);\n json.endObject();\n }\n json.endObject();\n }", "protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }", "public static <T> T splitEachLine(File self, String regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure<T> closure) throws IOException {\n return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);\n }" ]
Notifies that a header item is changed. @param position the position.
[ "public final void notifyHeaderItemChanged(int position) {\n if (position < 0 || position >= headerItemCount) {\n throw new IndexOutOfBoundsException(\"The given position \" + position + \" is not within the position bounds for header items [0 - \" + (headerItemCount - 1) + \"].\");\n }\n notifyItemChanged(position);\n }" ]
[ "public static RgbaColor fromHsl(float H, float S, float L) {\n\n // convert to [0-1]\n H /= 360f;\n S /= 100f;\n L /= 100f;\n\n float R, G, B;\n\n if (S == 0) {\n // grey\n R = G = B = L;\n }\n else {\n float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S;\n float m1 = 2f * L - m2;\n R = hue2rgb(m1, m2, H + 1 / 3f);\n G = hue2rgb(m1, m2, H);\n B = hue2rgb(m1, m2, H - 1 / 3f);\n }\n\n // convert [0-1] to [0-255]\n int r = Math.round(R * 255f);\n int g = Math.round(G * 255f);\n int b = Math.round(B * 255f);\n\n return new RgbaColor(r, g, b, 1);\n }", "public static vpnvserver_authenticationsamlpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_authenticationsamlpolicy_binding obj = new vpnvserver_authenticationsamlpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_authenticationsamlpolicy_binding response[] = (vpnvserver_authenticationsamlpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void initialize() {\n\t\tif (dataClass == null) {\n\t\t\tthrow new IllegalStateException(\"dataClass was never set on \" + getClass().getSimpleName());\n\t\t}\n\t\tif (tableName == null) {\n\t\t\ttableName = extractTableName(databaseType, dataClass);\n\t\t}\n\t}", "@Programmatic\n public <T> Blob toExcelPivot(\n final List<T> domainObjects,\n final Class<T> cls,\n final String fileName) throws ExcelService.Exception {\n return toExcelPivot(domainObjects, cls, null, fileName);\n }", "private String formatCurrency(Number value)\n {\n return (value == null ? null : m_formats.getCurrencyFormat().format(value));\n }", "public static base_responses unset(nitro_service client, String sitename[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (sitename != null && sitename.length > 0) {\n\t\t\tgslbsite unsetresources[] = new gslbsite[sitename.length];\n\t\t\tfor (int i=0;i<sitename.length;i++){\n\t\t\t\tunsetresources[i] = new gslbsite();\n\t\t\t\tunsetresources[i].sitename = sitename[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 base_responses enable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 enableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tenableresources[i] = new nsacl6();\n\t\t\t\tenableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}", "void endOfRunDb()\n {\n DbConn cnx = null;\n\n try\n {\n cnx = Helpers.getNewDbSession();\n\n // Done: put inside history & remove instance from queue.\n History.create(cnx, this.ji, this.resultStatus, endDate);\n jqmlogger.trace(\"An History was just created for job instance \" + this.ji.getId());\n cnx.runUpdate(\"ji_delete_by_id\", this.ji.getId());\n cnx.commit();\n }\n catch (RuntimeException e)\n {\n endBlockDbFailureAnalysis(e);\n }\n finally\n {\n Helpers.closeQuietly(cnx);\n }\n }", "private Project.Tasks.Task.PredecessorLink writePredecessor(Integer taskID, RelationType type, Duration lag)\n {\n Project.Tasks.Task.PredecessorLink link = m_factory.createProjectTasksTaskPredecessorLink();\n\n link.setPredecessorUID(NumberHelper.getBigInteger(taskID));\n link.setType(BigInteger.valueOf(type.getValue()));\n link.setCrossProject(Boolean.FALSE); // SF-300: required to keep P6 happy when importing MSPDI files\n\n if (lag != null && lag.getDuration() != 0)\n {\n double linkLag = lag.getDuration();\n if (lag.getUnits() != TimeUnit.PERCENT && lag.getUnits() != TimeUnit.ELAPSED_PERCENT)\n {\n linkLag = 10.0 * Duration.convertUnits(linkLag, lag.getUnits(), TimeUnit.MINUTES, m_projectFile.getProjectProperties()).getDuration();\n }\n link.setLinkLag(BigInteger.valueOf((long) linkLag));\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(lag.getUnits(), false));\n }\n else\n {\n // SF-329: default required to keep Powerproject happy when importing MSPDI files\n link.setLinkLag(BIGINTEGER_ZERO);\n link.setLagFormat(DatatypeConverter.printDurationTimeUnits(m_projectFile.getProjectProperties().getDefaultDurationUnits(), false));\n }\n\n return (link);\n }" ]
Creates a solver for symmetric positive definite matrices. @return A new solver for symmetric positive definite matrices.
[ "public static LinearSolverDense<DMatrixRMaj> symmPosDef(int matrixWidth ) {\n if(matrixWidth < EjmlParameters.SWITCH_BLOCK64_CHOLESKY ) {\n CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true);\n return new LinearSolverChol_DDRM(decomp);\n } else {\n if( EjmlParameters.MEMORY == EjmlParameters.MemoryUsage.FASTER )\n return new LinearSolverChol_DDRB();\n else {\n CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true);\n return new LinearSolverChol_DDRM(decomp);\n }\n }\n }" ]
[ "protected int getRequestTypeFromString(String requestType) {\n if (\"GET\".equals(requestType)) {\n return REQUEST_TYPE_GET;\n }\n if (\"POST\".equals(requestType)) {\n return REQUEST_TYPE_POST;\n }\n if (\"PUT\".equals(requestType)) {\n return REQUEST_TYPE_PUT;\n }\n if (\"DELETE\".equals(requestType)) {\n return REQUEST_TYPE_DELETE;\n }\n return REQUEST_TYPE_ALL;\n }", "protected GVRPickedObject findCollider(GVRPickedObject[] pickList, GVRCollider findme)\n {\n if (pickList == null)\n {\n return null;\n }\n for (GVRPickedObject hit : pickList)\n {\n if ((hit != null) && (hit.hitCollider == findme))\n {\n return hit;\n }\n }\n return null;\n }", "public void actionPerformed(java.awt.event.ActionEvent actionEvent)\r\n {\r\n new Thread()\r\n {\r\n public void run()\r\n {\r\n final java.sql.Connection conn = new JDlgDBConnection(containingFrame, false).showAndReturnConnection();\r\n if (conn != null)\r\n {\r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n JIFrmDatabase frm = new JIFrmDatabase(conn);\r\n containingFrame.getContentPane().add(frm);\r\n frm.setVisible(true);\r\n }\r\n });\r\n }\r\n }\r\n }.start();\r\n }", "private void sortFileList() {\n if (this.size() > 1) {\n Collections.sort(this.fileList, new Comparator() {\n\n public final int compare(final Object o1, final Object o2) {\n final File f1 = (File) o1;\n final File f2 = (File) o2;\n final Object[] f1TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f1.getName(), baseFile);\n final Object[] f2TimeAndCount = backupSuffixHelper\n .backupTimeAndCount(f2.getName(), baseFile);\n final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();\n final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();\n if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {\n final long f1Time = f1.lastModified();\n final long f2Time = f2.lastModified();\n if (f1Time < f2Time) {\n return -1;\n }\n if (f1Time > f2Time) {\n return 1;\n }\n return 0;\n }\n if (f1TimeSuffix < f2TimeSuffix) {\n return -1;\n }\n if (f1TimeSuffix > f2TimeSuffix) {\n return 1;\n }\n final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();\n final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();\n if (f1Count < f2Count) {\n return -1;\n }\n if (f1Count > f2Count) {\n return 1;\n }\n if (f1Count == f2Count) {\n if (fileHelper.isCompressed(f1)) {\n return -1;\n }\n if (fileHelper.isCompressed(f2)) {\n return 1;\n }\n }\n return 0;\n }\n });\n }\n }", "public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }", "public static Multimap<String, String> convertToMultiMap(final PObject objectParams) {\n Multimap<String, String> params = HashMultimap.create();\n if (objectParams != null) {\n Iterator<String> customParamsIter = objectParams.keys();\n while (customParamsIter.hasNext()) {\n String key = customParamsIter.next();\n if (objectParams.isArray(key)) {\n final PArray array = objectParams.optArray(key);\n for (int i = 0; i < array.size(); i++) {\n params.put(key, array.getString(i));\n }\n } else {\n params.put(key, objectParams.optString(key, \"\"));\n }\n }\n }\n\n return params;\n }", "public Metadata add(String path, String value) {\n this.values.add(this.pathToProperty(path), value);\n this.addOp(\"add\", path, value);\n return this;\n }", "protected List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory) throws IOException {\n return getRecursiveThriftFiles(project, outputDirectory, new ArrayList<File>());\n }", "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 }" ]
Returns the vertex points in this hull. @return array of vertex points @see QuickHull3D#getVertices(double[]) @see QuickHull3D#getFaces()
[ "public Point3d[] getVertices() {\n Point3d[] vtxs = new Point3d[numVertices];\n for (int i = 0; i < numVertices; i++) {\n vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt;\n }\n return vtxs;\n }" ]
[ "public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name,\n CreateUserParams params) {\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"login\", login);\n requestJSON.add(\"name\", name);\n\n if (params != null) {\n if (params.getRole() != null) {\n requestJSON.add(\"role\", params.getRole().toJSONValue());\n }\n\n if (params.getStatus() != null) {\n requestJSON.add(\"status\", params.getStatus().toJSONValue());\n }\n\n requestJSON.add(\"language\", params.getLanguage());\n requestJSON.add(\"is_sync_enabled\", params.getIsSyncEnabled());\n requestJSON.add(\"job_title\", params.getJobTitle());\n requestJSON.add(\"phone\", params.getPhone());\n requestJSON.add(\"address\", params.getAddress());\n requestJSON.add(\"space_amount\", params.getSpaceAmount());\n requestJSON.add(\"can_see_managed_users\", params.getCanSeeManagedUsers());\n requestJSON.add(\"timezone\", params.getTimezone());\n requestJSON.add(\"is_exempt_from_device_limits\", params.getIsExemptFromDeviceLimits());\n requestJSON.add(\"is_exempt_from_login_verification\", params.getIsExemptFromLoginVerification());\n requestJSON.add(\"is_platform_access_only\", params.getIsPlatformAccessOnly());\n requestJSON.add(\"external_app_user_id\", params.getExternalAppUserId());\n }\n\n URL url = USERS_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxUser createdUser = new BoxUser(api, responseJSON.get(\"id\").asString());\n return createdUser.new Info(responseJSON);\n }", "public static final PatchOperationTarget createStandalone(final ModelControllerClient controllerClient) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(CORE_SERVICES);\n return new RemotePatchOperationTarget(address, controllerClient);\n }", "protected String pauseMsg() throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setPaused(isPaused());\n return ObjectMapperFactory.get().writeValueAsString(status);\n }", "public static void zeroTriangle( boolean upper , DMatrixRBlock A )\n {\n int blockLength = A.blockLength;\n\n if( upper ) {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = i; j < A.numCols; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n for( int l = k+1; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n } else {\n for( int i = 0; i < A.numRows; i += blockLength ) {\n int h = Math.min(blockLength,A.numRows-i);\n\n for( int j = 0; j <= i; j += blockLength ) {\n int w = Math.min(blockLength,A.numCols-j);\n\n int index = i*A.numCols + h*j;\n\n if( j == i ) {\n for( int k = 0; k < h; k++ ) {\n int z = Math.min(k,w);\n for( int l = 0; l < z; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n } else {\n for( int k = 0; k < h; k++ ) {\n for( int l = 0; l < w; l++ ) {\n A.data[index + w*k+l ] = 0;\n }\n }\n }\n }\n }\n }\n }", "@Override\n public void setExpectedMaxSize( int numRows , int numCols ) {\n super.setExpectedMaxSize(numRows,numCols);\n\n // if the matrix that is being decomposed is smaller than the block we really don't\n // see the B matrix.\n if( numRows < blockWidth)\n B = new DMatrixRMaj(0,0);\n else\n B = new DMatrixRMaj(blockWidth,maxWidth);\n\n chol = new CholeskyBlockHelper_DDRM(blockWidth);\n }", "public static vlan get(nitro_service service, Long id) throws Exception{\n\t\tvlan obj = new vlan();\n\t\tobj.set_id(id);\n\t\tvlan response = (vlan) obj.get_resource(service);\n\t\treturn response;\n\t}", "public boolean changeState(StateVertex nextState) {\n\t\tif (nextState == null) {\n\t\t\tLOGGER.info(\"nextState given is null\");\n\t\t\treturn false;\n\t\t}\n\t\tLOGGER.debug(\"Trying to change to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\tcurrentState.getName());\n\n\t\tif (stateFlowGraph.canGoTo(currentState, nextState)) {\n\n\t\t\tLOGGER.debug(\"Changed to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\t\tcurrentState.getName());\n\n\t\t\tsetCurrentState(nextState);\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\tLOGGER.info(\"Cannot go to state: '{}' from: '{}'\", nextState.getName(),\n\t\t\t\t\tcurrentState.getName());\n\t\t\treturn false;\n\t\t}\n\t}", "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 }", "@PreDestroy\n public void disconnectLocator() throws InterruptedException,\n ServiceLocatorException {\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Destroy Locator client\");\n }\n\n if (endpointCollector != null) {\n endpointCollector.stopScheduledCollection();\n }\n \n if (locatorClient != null) {\n locatorClient.disconnect();\n locatorClient = null;\n }\n }" ]
Parses a tag formatted as defined by the HTTP standard. @param httpTag The HTTP tag string; if it starts with 'W/' the tag will be marked as weak and the data following the 'W/' used as the tag; otherwise it should be surrounded with quotes (e.g., "sometag"). @return A new tag instance. @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11">HTTP Entity Tags</a>
[ "public static Optional<Tag> parse(final String httpTag) {\r\n Tag result = null;\r\n boolean weak = false;\r\n String internal = httpTag;\r\n\r\n if (internal.startsWith(\"W/\")) {\r\n weak = true;\r\n internal = internal.substring(2);\r\n }\r\n\r\n if (internal.startsWith(\"\\\"\") && internal.endsWith(\"\\\"\")) {\r\n result = new Tag(\r\n internal.substring(1, internal.length() - 1), weak);\r\n }\r\n else if (internal.equals(\"*\")) {\r\n result = new Tag(\"*\", weak);\r\n }\r\n\r\n return Optional.ofNullable(result);\r\n }" ]
[ "public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }", "@SuppressWarnings(\"deprecation\")\n @RequestMapping(value = \"/api/backup\", method = RequestMethod.GET)\n public\n @ResponseBody\n String getBackup(Model model, HttpServletResponse response) throws Exception {\n response.addHeader(\"Content-Disposition\", \"attachment; filename=backup.json\");\n response.setContentType(\"application/json\");\n\n Backup backup = BackupService.getInstance().getBackupData();\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();\n\n return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);\n }", "public void addPostEffect(GVRMaterial postEffectData) {\n GVRContext ctx = getGVRContext();\n\n if (mPostEffects == null)\n {\n mPostEffects = new GVRRenderData(ctx, postEffectData);\n GVRMesh dummyMesh = new GVRMesh(getGVRContext(),\"float3 a_position float2 a_texcoord\");\n mPostEffects.setMesh(dummyMesh);\n NativeCamera.setPostEffect(getNative(), mPostEffects.getNative());\n mPostEffects.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n }\n else\n {\n GVRRenderPass rpass = new GVRRenderPass(ctx, postEffectData);\n rpass.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n mPostEffects.addPass(rpass);\n }\n }", "private void processCalendars() throws Exception\n {\n List<Row> rows = getRows(\"select * from zcalendar where zproject=?\", m_projectID);\n for (Row row : rows)\n {\n ProjectCalendar calendar = m_project.addCalendar();\n calendar.setUniqueID(row.getInteger(\"Z_PK\"));\n calendar.setName(row.getString(\"ZTITLE\"));\n processDays(calendar);\n processExceptions(calendar);\n m_eventManager.fireCalendarReadEvent(calendar);\n }\n }", "public void loadModel(GVRAndroidResource avatarResource, String attachBone)\n {\n EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettingsWith(EnumSet.of(GVRImportSettings.OPTIMIZE_GRAPH, GVRImportSettings.NO_ANIMATION));\n GVRContext ctx = mAvatarRoot.getGVRContext();\n GVRResourceVolume volume = new GVRResourceVolume(ctx, avatarResource);\n GVRSceneObject modelRoot = new GVRSceneObject(ctx);\n GVRSceneObject boneObject;\n int boneIndex;\n\n if (mSkeleton == null)\n {\n throw new IllegalArgumentException(\"Cannot attach model to avatar - there is no skeleton\");\n }\n boneIndex = mSkeleton.getBoneIndex(attachBone);\n if (boneIndex < 0)\n {\n throw new IllegalArgumentException(attachBone + \" is not a bone in the avatar skeleton\");\n }\n boneObject = mSkeleton.getBone(boneIndex);\n if (boneObject == null)\n {\n throw new IllegalArgumentException(attachBone +\n \" does not have a bone object in the avatar skeleton\");\n }\n boneObject.addChildObject(modelRoot);\n ctx.getAssetLoader().loadModel(volume, modelRoot, settings, false, mLoadModelHandler);\n }", "private String getResponseString(boolean async, UploaderResponse response) {\r\n return async ? response.getTicketId() : response.getPhotoId();\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}", "private Number calculateUnitsPercentComplete(Row row)\n {\n double result = 0;\n\n double actualWorkQuantity = NumberHelper.getDouble(row.getDouble(\"act_work_qty\"));\n double actualEquipmentQuantity = NumberHelper.getDouble(row.getDouble(\"act_equip_qty\"));\n double numerator = actualWorkQuantity + actualEquipmentQuantity;\n\n if (numerator != 0)\n {\n double remainingWorkQuantity = NumberHelper.getDouble(row.getDouble(\"remain_work_qty\"));\n double remainingEquipmentQuantity = NumberHelper.getDouble(row.getDouble(\"remain_equip_qty\"));\n double denominator = remainingWorkQuantity + actualWorkQuantity + remainingEquipmentQuantity + actualEquipmentQuantity;\n result = denominator == 0 ? 0 : ((numerator * 100) / denominator);\n }\n\n return NumberHelper.getDouble(result);\n }", "public void remove(RowKey key) {\n\t\tcurrentState.put( key, new AssociationOperation( key, null, REMOVE ) );\n\t}" ]
Performs a get all operation with the specified composite request object @param requestWrapper Composite request object containing a reference to the Iterable keys @return Map of the keys to the corresponding versioned values
[ "public Map<K, List<Versioned<V>>> getAllWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n Map<K, List<Versioned<V>>> items = null;\n for(int attempts = 0;; attempts++) {\n if(attempts >= this.metadataRefreshAttempts)\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n try {\n String KeysHexString = \"\";\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n Iterable<ByteArray> keys = (Iterable<ByteArray>) requestWrapper.getIterableKeys();\n KeysHexString = getKeysHexString(keys);\n debugLogStart(\"GET_ALL\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n KeysHexString);\n }\n items = store.getAll(requestWrapper);\n if(logger.isDebugEnabled()) {\n int vcEntrySize = 0;\n\n for(List<Versioned<V>> item: items.values()) {\n for(Versioned<V> vc: item) {\n vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size();\n }\n }\n\n debugLogEnd(\"GET_ALL\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n KeysHexString,\n vcEntrySize);\n }\n return items;\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during getAll [ \"\n + e.getMessage() + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n }" ]
[ "public long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }", "public static base_responses update(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice updateresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbservice();\n\t\t\t\tupdateresources[i].servicename = resources[i].servicename;\n\t\t\t\tupdateresources[i].ipaddress = resources[i].ipaddress;\n\t\t\t\tupdateresources[i].publicip = resources[i].publicip;\n\t\t\t\tupdateresources[i].publicport = resources[i].publicport;\n\t\t\t\tupdateresources[i].cip = resources[i].cip;\n\t\t\t\tupdateresources[i].cipheader = resources[i].cipheader;\n\t\t\t\tupdateresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\tupdateresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\tupdateresources[i].maxclient = resources[i].maxclient;\n\t\t\t\tupdateresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\tupdateresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\tupdateresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\tupdateresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\tupdateresources[i].viewname = resources[i].viewname;\n\t\t\t\tupdateresources[i].viewip = resources[i].viewip;\n\t\t\t\tupdateresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].monitor_name_svc = resources[i].monitor_name_svc;\n\t\t\t\tupdateresources[i].hashid = resources[i].hashid;\n\t\t\t\tupdateresources[i].comment = resources[i].comment;\n\t\t\t\tupdateresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "@Override\n\tpublic EmbeddedBrowser get() {\n\t\tLOGGER.debug(\"Setting up a Browser\");\n\t\t// Retrieve the config values used\n\t\tImmutableSortedSet<String> filterAttributes =\n\t\t\t\tconfiguration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();\n\t\tlong crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();\n\t\tlong crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();\n\n\t\t// Determine the requested browser type\n\t\tEmbeddedBrowser browser = null;\n\t\tEmbeddedBrowser.BrowserType browserType =\n\t\t\t\tconfiguration.getBrowserConfig().getBrowserType();\n\t\ttry {\n\t\t\tswitch (browserType) {\n\t\t\t\tcase CHROME:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHROME_HEADLESS:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload,\n\t\t\t\t\t\t\tcrawlWaitEvent, true);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX_HEADLESS:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOTE:\n\t\t\t\t\tbrowser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(\n\t\t\t\t\t\t\tconfiguration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,\n\t\t\t\t\t\t\tcrawlWaitEvent, crawlWaitReload);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHANTOMJS:\n\t\t\t\t\tbrowser =\n\t\t\t\t\t\t\tnewPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unrecognized browser type \"\n\t\t\t\t\t\t\t+ configuration.getBrowserConfig().getBrowserType());\n\t\t\t}\n\t\t} catch (IllegalStateException e) {\n\t\t\tLOGGER.error(\"Crawling with {} failed: \" + e.getMessage(), browserType.toString());\n\t\t\tthrow e;\n\t\t}\n\n\t\t/* for Retina display. */\n\t\tif (browser instanceof WebDriverBackedEmbeddedBrowser) {\n\t\t\tint pixelDensity =\n\t\t\t\t\tthis.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();\n\t\t\tif (pixelDensity != -1)\n\t\t\t\t((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);\n\t\t}\n\n\t\tplugins.runOnBrowserCreatedPlugins(browser);\n\t\treturn browser;\n\t}", "public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public void add(Vector3d v1) {\n x += v1.x;\n y += v1.y;\n z += v1.z;\n }", "private void purgeDeadJobInstances(DbConn cnx, Node node)\n {\n for (JobInstance ji : JobInstance.select(cnx, \"ji_select_by_node\", node.getId()))\n {\n try\n {\n cnx.runSelectSingle(\"history_select_state_by_id\", String.class, ji.getId());\n }\n catch (NoResultException e)\n {\n History.create(cnx, ji, State.CRASHED, Calendar.getInstance());\n Message.create(cnx,\n \"Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash\",\n ji.getId());\n }\n\n cnx.runUpdate(\"ji_delete_by_id\", ji.getId());\n }\n cnx.commit();\n }", "public String[] init(String[] argv, int min, int max,\n Collection<CommandLineParser.Option> options)\n throws IOException, SAXException {\n // parse command line\n parser = new CommandLineParser();\n parser.setMinimumArguments(min);\n parser.setMaximumArguments(max);\n parser.registerOption(new CommandLineParser.BooleanOption(\"reindex\", 'I'));\n if (options != null)\n for (CommandLineParser.Option option : options)\n parser.registerOption(option);\n\n try {\n argv = parser.parse(argv);\n } catch (CommandLineParser.CommandLineParserException e) {\n System.err.println(\"ERROR: \" + e.getMessage());\n usage();\n System.exit(1);\n }\n\n // do we need to reindex?\n boolean reindex = parser.getOptionState(\"reindex\");\n\n // load configuration\n config = ConfigLoader.load(argv[0]);\n database = config.getDatabase(reindex); // overwrite iff reindex\n if (database.isInMemory())\n reindex = true; // no other way to do it in this case\n\n // reindex, if requested\n if (reindex)\n reindex(config, database);\n\n return argv;\n }", "void stop() {\n try {\n dm.stop(getBundleContext());\n } catch (DirectoryMonitoringException e) {\n LOG.error(\"Failed to stop \" + DirectoryMonitor.class.getName() + \" for the directory \" + monitoredDirectory, e);\n }\n declarationsFiles.clear();\n declarationRegistrationManager.unregisterAll();\n }", "public void setEnterpriseCost(int index, Number value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_COST, index), value);\n }" ]
we only use the registrationList map if the object is not a proxy. During the reference locking, we will materialize objects and they will enter the registered for lock map.
[ "private void lockAndRegisterReferences(ClassDescriptor cld, Object sourceObject, int lockMode, List registeredObjects) throws LockNotGrantedException\r\n {\r\n if (implicitLocking)\r\n {\r\n Iterator i = cld.getObjectReferenceDescriptors(true).iterator();\r\n while (i.hasNext())\r\n {\r\n ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) i.next();\r\n Object refObj = rds.getPersistentField().get(sourceObject);\r\n if (refObj != null)\r\n {\r\n boolean isProxy = ProxyHelper.isProxy(refObj);\r\n RuntimeObject rt = isProxy ? new RuntimeObject(refObj, this, false) : new RuntimeObject(refObj, this);\r\n if (!registrationList.contains(rt.getIdentity()))\r\n {\r\n lockAndRegister(rt, lockMode, registeredObjects);\r\n }\r\n }\r\n }\r\n }\r\n }" ]
[ "public final Object getValue(final String id, final String property) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);\n final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);\n criteria.select(root.get(property));\n criteria.where(builder.equal(root.get(\"referenceId\"), id));\n return getSession().createQuery(criteria).uniqueResult();\n }", "public void processDefaultCurrency(Row row)\n {\n ProjectProperties properties = m_project.getProjectProperties();\n properties.setCurrencySymbol(row.getString(\"curr_symbol\"));\n properties.setSymbolPosition(CURRENCY_SYMBOL_POSITION_MAP.get(row.getString(\"pos_curr_fmt_type\")));\n properties.setCurrencyDigits(row.getInteger(\"decimal_digit_cnt\"));\n properties.setThousandsSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n properties.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n }", "public static int restrictRange(int value, int min, int max)\n {\n return Math.min((Math.max(value, min)), max);\n }", "public void promoteModule(final String moduleId) {\n final DbModule module = getModule(moduleId);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n final DbArtifact artifact = repositoryHandler.getArtifact(gavc);\n artifact.setPromoted(true);\n repositoryHandler.store(artifact);\n }\n\n repositoryHandler.promoteModule(module);\n }", "private void readProjectProperties(Settings phoenixSettings, Storepoint storepoint)\n {\n ProjectProperties mpxjProperties = m_projectFile.getProjectProperties();\n mpxjProperties.setName(phoenixSettings.getTitle());\n mpxjProperties.setDefaultDurationUnits(phoenixSettings.getBaseunit());\n mpxjProperties.setStatusDate(storepoint.getDataDate());\n }", "public static double[][] diag(double[] vector){\n\n\t\t// Note: According to the Java Language spec, an array is initialized with the default value, here 0.\n\t\tdouble[][] diagonalMatrix = new double[vector.length][vector.length];\n\n\t\tfor(int index = 0; index < vector.length; index++) {\n\t\t\tdiagonalMatrix[index][index] = vector[index];\n\t\t}\n\n\t\treturn diagonalMatrix;\n\t}", "public String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }", "public static autoscaleaction get(nitro_service service, String name) throws Exception{\n\t\tautoscaleaction obj = new autoscaleaction();\n\t\tobj.set_name(name);\n\t\tautoscaleaction response = (autoscaleaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }" ]
Gets whether this registration has an alternative wildcard registration
[ "boolean hasNoAlternativeWildcardRegistration() {\n return parent == null || PathElement.WILDCARD_VALUE.equals(valueString) || !parent.getChildNames().contains(PathElement.WILDCARD_VALUE);\n }" ]
[ "OTMConnection getConnection()\r\n {\r\n if (m_connection == null)\r\n {\r\n OTMConnectionRuntimeException ex = new OTMConnectionRuntimeException(\"Connection is null.\");\r\n sendEvents(ConnectionEvent.CONNECTION_ERROR_OCCURRED, ex, null);\r\n }\r\n return m_connection;\r\n }", "public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }", "public base_response enable_features(String[] features) throws Exception\n\t{\n\t\tbase_response result = null;\n\t\tnsfeature resource = new nsfeature();\n\t\tresource.set_feature(features);\n\t\toptions option = new options();\n\t\toption.set_action(\"enable\");\n\t\tresult = resource.perform_operation(this, option);\n\t\treturn result;\n\t}", "public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }", "public EventBus emitSync(String event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }", "private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)\r\n {\r\n IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());\r\n\r\n if (indexDef == null)\r\n {\r\n indexDef = new IndexDef(indexDescDef.getName(),\r\n indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));\r\n tableDef.addIndex(indexDef);\r\n }\r\n\r\n try\r\n {\r\n String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n }\r\n catch (NoSuchFieldException ex)\r\n {\r\n // won't happen if we already checked the constraints\r\n }\r\n }", "@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\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 void setCycleInterval(float newCycleInterval) {\n if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) {\n for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) {\n //TODO Cannot easily change the GVRAnimation's GVRChannel once set.\n }\n this.cycleInterval = newCycleInterval;\n }\n }" ]
Prepare a model JSON for analyze, resolves the hierarchical structure creates a HashMap which contains all resourceIds as keys and for each key the JSONObject, all id are keys of this map @param object @return a HashMap keys: all ressourceIds values: all child JSONObjects @throws org.json.JSONException
[ "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 }" ]
[ "@SuppressWarnings(\"unused\")\n public boolean isValid() {\n Phonenumber.PhoneNumber phoneNumber = getPhoneNumber();\n return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber);\n }", "private void saveToXmlVfsBundle() throws CmsException {\n\n if (m_lockedBundleFiles.get(null) != null) { // If the file was not locked, no changes were made, i.e., storing is not necessary.\n for (Locale l : m_locales) {\n SortedProperties props = m_localizations.get(l);\n if (null != props) {\n if (m_xmlBundle.hasLocale(l)) {\n m_xmlBundle.removeLocale(l);\n }\n m_xmlBundle.addLocale(m_cms, l);\n int i = 0;\n List<Object> keys = new ArrayList<Object>(props.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n String value = props.getProperty(key.toString());\n if (!value.isEmpty()) {\n m_xmlBundle.addValue(m_cms, \"Message\", l, i);\n i++;\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Key\", l).setStringValue(m_cms, key.toString());\n m_xmlBundle.getValue(\"Message[\" + i + \"]/Value\", l).setStringValue(m_cms, value);\n }\n }\n }\n }\n CmsFile bundleFile = m_lockedBundleFiles.get(null).getFile();\n bundleFile.setContents(m_xmlBundle.marshal());\n m_cms.writeFile(bundleFile);\n }\n }\n }", "private void handleChange(Object propertyId) {\n\n if (!m_saveBtn.isEnabled()) {\n m_saveBtn.setEnabled(true);\n m_saveExitBtn.setEnabled(true);\n }\n m_model.handleChange(propertyId);\n\n }", "public int compareTo(WordTag wordTag) { \r\n int first = (word != null ? word().compareTo(wordTag.word()) : 0);\r\n if(first != 0)\r\n return first;\r\n else {\r\n if (tag() == null) {\r\n if (wordTag.tag() == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return tag().compareTo(wordTag.tag());\r\n }\r\n }", "private static long daysBetween(Date date1, Date date2) {\n long diff;\n if (date2.after(date1)) {\n diff = date2.getTime() - date1.getTime();\n } else {\n diff = date1.getTime() - date2.getTime();\n }\n return diff / (24 * 60 * 60 * 1000);\n }", "private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException {\n\t\t//cannot batch fetch by unique key (property-ref associations)\n\t\tif ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) {\n\t\t\tEntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() );\n\t\t\tEntityKey entityKey = session.generateEntityKey( id, persister );\n\t\t\tif ( !session.getPersistenceContext().containsEntity( entityKey ) ) {\n\t\t\t\tsession.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );\n\t\t\t}\n\t\t}\n\t}", "public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;\n\n switch (NumberHelper.getInt(value))\n {\n case 0:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n }\n\n return (result);\n }", "public void startAnimation()\n {\n Date time = new Date();\n this.beginAnimation = time.getTime();\n this.endAnimation = beginAnimation + (long) (animationTime * 1000);\n this.animate = true;\n }", "protected String findPath(String start, String end) {\n if (start.equals(end)) {\n return start;\n } else {\n return findPath(start, parent.get(end)) + \" -> \" + end;\n }\n }" ]
Executes an operation on the controller latching onto an existing transaction @param operation the operation @param handler the handler @param control the transaction control @param prepareStep the prepare step to be executed before any other steps @param operationId the id of the current transaction @return the result of the operation
[ "@SuppressWarnings(\"deprecation\")\n protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) {\n final AbstractOperationContext delegateContext = getDelegateContext(operationId);\n CurrentOperationIdHolder.setCurrentOperationID(operationId);\n try {\n return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext);\n } finally {\n CurrentOperationIdHolder.setCurrentOperationID(null);\n }\n }" ]
[ "public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }", "@Override\n\tpublic String toCanonicalString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.canonicalString) == null) {\n\t\t\tstringCache.canonicalString = result = toNormalizedString(IPv6StringCache.canonicalParams);\n\t\t}\n\t\treturn result;\n\t}", "static void produceInputStreamWithEntry( final DataConsumer consumer,\n final InputStream inputStream,\n final TarArchiveEntry entry ) throws IOException {\n try {\n consumer.onEachFile(inputStream, entry);\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n }", "public Object get(int dataSet) throws SerializationException {\r\n\t\tObject result = null;\r\n\t\tfor (Iterator<DataSet> i = dataSets.iterator(); i.hasNext();) {\r\n\t\t\tDataSet ds = i.next();\r\n\t\t\tDataSetInfo info = ds.getInfo();\r\n\t\t\tif (info.getDataSetNumber() == dataSet) {\r\n\t\t\t\tresult = getData(ds);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "protected void processTaskBaseline(Row row)\n {\n Integer id = row.getInteger(\"TASK_UID\");\n Task task = m_project.getTaskByUniqueID(id);\n if (task != null)\n {\n int index = row.getInt(\"TB_BASE_NUM\");\n\n task.setBaselineDuration(index, MPDUtility.getAdjustedDuration(m_project, row.getInt(\"TB_BASE_DUR\"), MPDUtility.getDurationTimeUnits(row.getInt(\"TB_BASE_DUR_FMT\"))));\n task.setBaselineStart(index, row.getDate(\"TB_BASE_START\"));\n task.setBaselineFinish(index, row.getDate(\"TB_BASE_FINISH\"));\n task.setBaselineWork(index, row.getDuration(\"TB_BASE_WORK\"));\n task.setBaselineCost(index, row.getCurrency(\"TB_BASE_COST\"));\n }\n }", "public void showToast(final String message, float duration) {\n final float quadWidth = 1.2f;\n final GVRTextViewSceneObject toastSceneObject = new GVRTextViewSceneObject(this, quadWidth, quadWidth / 5,\n message);\n\n toastSceneObject.setTextSize(6);\n toastSceneObject.setTextColor(Color.WHITE);\n toastSceneObject.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);\n toastSceneObject.setBackgroundColor(Color.DKGRAY);\n toastSceneObject.setRefreshFrequency(GVRTextViewSceneObject.IntervalFrequency.REALTIME);\n\n final GVRTransform t = toastSceneObject.getTransform();\n t.setPositionZ(-1.5f);\n\n final GVRRenderData rd = toastSceneObject.getRenderData();\n final float finalOpacity = 0.7f;\n rd.getMaterial().setOpacity(0);\n rd.setRenderingOrder(2 * GVRRenderData.GVRRenderingOrder.OVERLAY);\n rd.setDepthTest(false);\n\n final GVRCameraRig rig = getMainScene().getMainCameraRig();\n rig.addChildObject(toastSceneObject);\n\n final GVRMaterialAnimation fadeOut = new GVRMaterialAnimation(rd.getMaterial(), duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(finalOpacity - ratio * finalOpacity);\n }\n };\n fadeOut.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n rig.removeChildObject(toastSceneObject);\n }\n });\n\n final GVRMaterialAnimation fadeIn = new GVRMaterialAnimation(rd.getMaterial(), 3.0f * duration / 4.0f) {\n @Override\n protected void animate(GVRHybridObject target, float ratio) {\n final GVRMaterial material = (GVRMaterial) target;\n material.setOpacity(ratio * finalOpacity);\n }\n };\n fadeIn.setOnFinish(new GVROnFinish() {\n @Override\n public void finished(GVRAnimation animation) {\n getAnimationEngine().start(fadeOut);\n }\n });\n\n getAnimationEngine().start(fadeIn);\n }", "private void purgeDeadJobInstances(DbConn cnx, Node node)\n {\n for (JobInstance ji : JobInstance.select(cnx, \"ji_select_by_node\", node.getId()))\n {\n try\n {\n cnx.runSelectSingle(\"history_select_state_by_id\", String.class, ji.getId());\n }\n catch (NoResultException e)\n {\n History.create(cnx, ji, State.CRASHED, Calendar.getInstance());\n Message.create(cnx,\n \"Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash\",\n ji.getId());\n }\n\n cnx.runUpdate(\"ji_delete_by_id\", ji.getId());\n }\n cnx.commit();\n }", "public void deleteRebalancingState(RebalanceTaskInfo stealInfo) {\n // acquire write lock\n writeLock.lock();\n try {\n RebalancerState rebalancerState = getRebalancerState();\n\n if(!rebalancerState.remove(stealInfo))\n throw new IllegalArgumentException(\"Couldn't find \" + stealInfo + \" in \"\n + rebalancerState + \" while deleting\");\n\n if(rebalancerState.isEmpty()) {\n logger.debug(\"Cleaning all rebalancing state\");\n cleanAllRebalancingState();\n } else {\n put(REBALANCING_STEAL_INFO, rebalancerState);\n initCache(REBALANCING_STEAL_INFO);\n }\n } finally {\n writeLock.unlock();\n }\n }", "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 }" ]
Copy a single named file to the output directory. @param outputDirectory The destination directory for the copied resource. @param sourceFile The path of the file to copy. @param targetFileName The name of the file created in {@literal outputDirectory}. @throws IOException If the file cannot be copied.
[ "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 }" ]
[ "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 }", "public void handleEvent(Event event) {\n LOG.fine(\"ContentLengthHandler called\");\n\n //if maximum length is shorter then <cut><![CDATA[ ]]></cut> it's not possible to cut the content\n if(CUT_START_TAG.length() + CUT_END_TAG.length() > length) {\n LOG.warning(\"Trying to cut content. But length is shorter then needed for \"\n + CUT_START_TAG + CUT_END_TAG + \". So content is skipped.\");\n event.setContent(\"\");\n return;\n }\n\n int currentLength = length - CUT_START_TAG.length() - CUT_END_TAG.length();\n\n if (event.getContent() != null && event.getContent().length() > length) {\n LOG.fine(\"cutting content to \" + currentLength\n + \" characters. Original length was \"\n + event.getContent().length());\n LOG.fine(\"Content before cutting: \" + event.getContent());\n event.setContent(CUT_START_TAG\n + event.getContent().substring(0, currentLength) + CUT_END_TAG);\n LOG.fine(\"Content after cutting: \" + event.getContent());\n }\n }", "protected String getUniqueString(FieldDescriptor field) throws SequenceManagerException\r\n {\r\n ResultSetAndStatement rsStmt = null;\r\n String returnValue = null;\r\n try\r\n {\r\n rsStmt = getBrokerForClass().serviceJdbcAccess().executeSQL(\r\n \"select newid()\", field.getClassDescriptor(), Query.NOT_SCROLLABLE);\r\n if (rsStmt.m_rs.next())\r\n {\r\n returnValue = rsStmt.m_rs.getString(1);\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass()\r\n + \": Can't lookup new oid for field \" + field);\r\n }\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new SequenceManagerException(e);\r\n }\r\n\r\n finally\r\n {\r\n // close the used resources\r\n if (rsStmt != null) rsStmt.close();\r\n }\r\n return returnValue;\r\n }", "public static CmsResource getDescriptor(CmsObject cms, String basename) {\n\n CmsSolrQuery query = new CmsSolrQuery();\n query.setResourceTypes(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR.toString());\n query.setFilterQueries(\"filename:\\\"\" + basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX + \"\\\"\");\n query.add(\"fl\", \"path\");\n CmsSolrResultList results;\n try {\n boolean isOnlineProject = cms.getRequestContext().getCurrentProject().isOnlineProject();\n String indexName = isOnlineProject\n ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE\n : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE;\n results = OpenCms.getSearchManager().getIndexSolr(indexName).search(cms, query, true, null, true, null);\n } catch (CmsSearchException e) {\n LOG.error(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_SEARCH_ERROR_0), e);\n return null;\n }\n\n switch (results.size()) {\n case 0:\n return null;\n case 1:\n return results.get(0);\n default:\n String files = \"\";\n for (CmsResource res : results) {\n files += \" \" + res.getRootPath();\n }\n LOG.warn(Messages.get().getBundle().key(Messages.ERR_BUNDLE_DESCRIPTOR_NOT_UNIQUE_1, files));\n return results.get(0);\n }\n }", "private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n for (Relation relation : relationList)\n {\n if (relation.getTargetTask() == targetTask)\n {\n if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)\n {\n matchFound = relationList.remove(relation);\n break;\n }\n }\n }\n return matchFound;\n }", "public EventBus emit(String event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "private void setW() {\n if( saveW ) {\n W.col0 = Y.col0;\n W.col1 = Y.col1;\n W.row0 = Y.row0;\n W.row1 = Y.row1;\n } else {\n W.col1 = Y.col1 - Y.col0;\n W.row0 = Y.row0;\n }\n }", "public static String toXml(DeploymentDescriptor descriptor) {\n try {\n\n Marshaller marshaller = getContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, \"http://www.jboss.org/jbpm deployment-descriptor.xsd\");\n marshaller.setSchema(schema);\n StringWriter stringWriter = new StringWriter();\n\n // clone the object and cleanup transients\n DeploymentDescriptor clone = ((DeploymentDescriptorImpl) descriptor).clearClone();\n\n marshaller.marshal(clone, stringWriter);\n String output = stringWriter.toString();\n\n return output;\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to generate xml from deployment descriptor\", e);\n }\n }", "@SuppressForbidden(\"legitimate sysstreams.\")\n private Execute forkProcess(ForkedJvmInfo slaveInfo, EventBus eventBus, \n CommandlineJava commandline, \n TailInputStream eventStream, OutputStream sysout, OutputStream syserr, RandomAccessFile streamsBuffer) {\n try {\n String tempDir = commandline.getSystemProperties().getVariablesVector().stream()\n .filter(v -> v.getKey().equals(\"java.io.tmpdir\"))\n .map(v -> v.getValue())\n .findAny()\n .orElse(null);\n\n final LocalSlaveStreamHandler streamHandler = \n new LocalSlaveStreamHandler(\n eventBus, testsClassLoader, System.err, eventStream, \n sysout, syserr, heartbeat, streamsBuffer);\n\n // Add certain properties to allow identification of the forked JVM from within\n // the subprocess. This can be used for policy files etc.\n final Path cwd = getWorkingDirectory(slaveInfo, tempDir);\n\n Variable v = new Variable();\n v.setKey(CHILDVM_SYSPROP_CWD);\n v.setFile(cwd.toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SYSPROP_TEMPDIR);\n v.setFile(getTempDir().toAbsolutePath().normalize().toFile());\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_ID);\n v.setValue(Integer.toString(slaveInfo.id));\n commandline.addSysproperty(v);\n\n v = new Variable();\n v.setKey(SysGlobals.CHILDVM_SYSPROP_JVM_COUNT);\n v.setValue(Integer.toString(slaveInfo.slaves));\n commandline.addSysproperty(v);\n\n // Emit command line before -stdin to avoid confusion.\n slaveInfo.slaveCommandLine = escapeAndJoin(commandline.getCommandline());\n log(\"Forked child JVM at '\" + cwd.toAbsolutePath().normalize() + \n \"', command (may need escape sequences for your shell):\\n\" + \n slaveInfo.slaveCommandLine, Project.MSG_VERBOSE);\n\n final Execute execute = new Execute();\n execute.setCommandline(commandline.getCommandline());\n execute.setVMLauncher(true);\n execute.setWorkingDirectory(cwd.toFile());\n execute.setStreamHandler(streamHandler);\n execute.setNewenvironment(newEnvironment);\n if (env.getVariables() != null)\n execute.setEnvironment(env.getVariables());\n log(\"Starting JVM J\" + slaveInfo.id, Project.MSG_DEBUG);\n execute.execute();\n return execute;\n } catch (IOException e) {\n throw new BuildException(\"Could not start the child process. Run ant with -verbose to get\" +\n \t\t\" the execution details.\", e);\n }\n }" ]
Inserts a new instance but references via the outIdentifier, which is returned as part of the ExecutionResults The outIdentifier can be null. The entryPoint, which can also be null, specifies the entrypoint the object is inserted into. @param object @param outIdentifier @param entryPoint @return
[ "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 Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }", "private void getMultipleValues(Method method, Object object, Map<String, String> map)\n {\n try\n {\n int index = 1;\n while (true)\n {\n Object value = filterValue(method.invoke(object, Integer.valueOf(index)));\n if (value != null)\n {\n map.put(getPropertyName(method, index), String.valueOf(value));\n }\n ++index;\n }\n }\n catch (Exception ex)\n {\n // Reached the end of the valid indexes\n }\n }", "public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception {\n int currentOrdinal = 0;\n List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters);\n for (EnabledEndpoint enabledEndpoint : enabledEndpoints) {\n if (enabledEndpoint.getOverrideId() == overrideId) {\n currentOrdinal++;\n }\n }\n return currentOrdinal;\n }", "public RowColumn following() {\n if (row.equals(Bytes.EMPTY)) {\n return RowColumn.EMPTY;\n } else if (col.equals(Column.EMPTY)) {\n return new RowColumn(followingBytes(row));\n } else if (!col.isQualifierSet()) {\n return new RowColumn(row, new Column(followingBytes(col.getFamily())));\n } else if (!col.isVisibilitySet()) {\n return new RowColumn(row, new Column(col.getFamily(), followingBytes(col.getQualifier())));\n } else {\n return new RowColumn(row,\n new Column(col.getFamily(), col.getQualifier(), followingBytes(col.getVisibility())));\n }\n }", "public void set1Value(int index, String newValue) {\n try {\n value.set( index, newValue );\n }\n catch (IndexOutOfBoundsException e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) out of bounds.\" + e);\n }\n catch (Exception e) {\n Log.e(TAG, \"X3D MFString set1Value(int index, ...) exception \" + e);\n }\n }", "public void set_protocol(String protocol) throws nitro_exception\n\t{\n\t\tif (protocol == null || !(protocol.equalsIgnoreCase(\"http\") ||protocol.equalsIgnoreCase(\"https\"))) {\n\t\t\tthrow new nitro_exception(\"error: protocol value \" + protocol + \" is not supported\");\n\t\t}\n\t\tthis.protocol = protocol;\n\t}", "private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException {\n\n String title = \"\";\n String subtitle = \"\";\n CmsFavInfo result = new CmsFavInfo(entry);\n CmsObject cms = A_CmsUI.getCmsObject();\n String project = getProject(cms, entry);\n String site = getSite(cms, entry);\n try {\n CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId();\n CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n CmsResourceUtil resutil = new CmsResourceUtil(cms, resource);\n switch (entry.getType()) {\n case explorerFolder:\n title = CmsStringUtil.isEmpty(resutil.getTitle())\n ? CmsResource.getName(resource.getRootPath())\n : resutil.getTitle();\n break;\n case page:\n title = resutil.getTitle();\n break;\n }\n subtitle = resource.getRootPath();\n CmsResourceIcon icon = result.getResourceIcon();\n icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n result.getTopLine().setValue(title);\n result.getBottomLine().setValue(subtitle);\n result.getProjectLabel().setValue(project);\n result.getSiteLabel().setValue(site);\n\n return result;\n\n }", "public static java.sql.Time getTime(Object value) {\n try {\n return toTime(value);\n } catch (ParseException pe) {\n pe.printStackTrace();\n return null;\n }\n }", "public static void inner_reorder_lower(DMatrix1Row A , DMatrix1Row B )\n {\n final int cols = A.numCols;\n B.reshape(cols,cols);\n\n Arrays.fill(B.data,0);\n for (int i = 0; i <cols; i++) {\n for (int j = 0; j <=i; j++) {\n B.data[i*cols+j] += A.data[i]*A.data[j];\n }\n\n for (int k = 1; k < A.numRows; k++) {\n int indexRow = k*cols;\n double valI = A.data[i+indexRow];\n int indexB = i*cols;\n for (int j = 0; j <= i; j++) {\n B.data[indexB++] += valI*A.data[indexRow++];\n }\n }\n }\n }" ]
Compute the A matrix from the Q and R matrices. @return The A matrix.
[ "@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }" ]
[ "@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Iterables.contains(keys, input);\n\t\t\t}\n\t\t});\n\t}", "public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }", "synchronized void removeServerProcess() {\n this.requiredState = InternalState.STOPPED;\n internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);\n }", "public void setClasspathRef(Reference r)\r\n {\r\n createClasspath().setRefid(r);\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }", "@SuppressWarnings(\"deprecation\")\n @RequestMapping(value = \"/api/backup\", method = RequestMethod.GET)\n public\n @ResponseBody\n String getBackup(Model model, HttpServletResponse response) throws Exception {\n response.addHeader(\"Content-Disposition\", \"attachment; filename=backup.json\");\n response.setContentType(\"application/json\");\n\n Backup backup = BackupService.getInstance().getBackupData();\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();\n\n return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);\n }", "public void visitMethodInsn(int opcode, String owner, String name,\n String desc, boolean itf) {\n if (mv != null) {\n mv.visitMethodInsn(opcode, owner, name, desc, itf);\n }\n }", "public static 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 }", "public static <T> T callConstructor(Class<T> klass) {\n return callConstructor(klass, new Class<?>[0], new Object[0]);\n }", "public static List<Dependency> getAllDependencies(final Module module) {\n final Set<Dependency> dependencies = new HashSet<Dependency>();\n final List<String> producedArtifacts = new ArrayList<String>();\n for(final Artifact artifact: getAllArtifacts(module)){\n producedArtifacts.add(artifact.getGavc());\n }\n\n dependencies.addAll(getAllDependencies(module, producedArtifacts));\n\n return new ArrayList<Dependency>(dependencies);\n }" ]
Read a text file from assets into a single string @param context A non-null Android Context @param asset The asset file to read @return The contents or null on error.
[ "public static String readTextFile(Context context, String asset) {\n try {\n InputStream inputStream = context.getAssets().open(asset);\n return org.gearvrf.utility.TextFile.readTextFile(inputStream);\n } catch (FileNotFoundException f) {\n Log.w(TAG, \"readTextFile(): asset file '%s' doesn't exist\", asset);\n } catch (IOException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"readTextFile()\");\n }\n return null;\n }" ]
[ "public static void writeShortString(ByteBuffer buffer, String s) {\n if (s == null) {\n buffer.putShort((short) -1);\n } else if (s.length() > Short.MAX_VALUE) {\n throw new IllegalArgumentException(\"String exceeds the maximum size of \" + Short.MAX_VALUE + \".\");\n } else {\n byte[] data = getBytes(s); //topic support non-ascii character\n buffer.putShort((short) data.length);\n buffer.put(data);\n }\n }", "public static void writeInt(byte[] bytes, int value, int offset) {\n bytes[offset] = (byte) (0xFF & (value >> 24));\n bytes[offset + 1] = (byte) (0xFF & (value >> 16));\n bytes[offset + 2] = (byte) (0xFF & (value >> 8));\n bytes[offset + 3] = (byte) (0xFF & value);\n }", "public void setChildren(List<PrintComponent<?>> children) {\n\t\tthis.children = children;\n\t\t// needed for Json unmarshall !!!!\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.setParent(this);\n\t\t}\n\t}", "private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }", "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 void useNewSOAPService(boolean direct) throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerServiceNew.wsdl\");\n org.customer.service.CustomerServiceService service = \n new org.customer.service.CustomerServiceService(wsdlURL);\n \n org.customer.service.CustomerService customerService = \n direct ? service.getCustomerServicePort() : service.getCustomerServiceNewPort();\n\n System.out.println(\"Using new SOAP CustomerService with new client\");\n \n customer.v2.Customer customer = createNewCustomer(\"Barry New SOAP\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry New SOAP\");\n printNewCustomerDetails(customer);\n }", "@PostConstruct\n public final void addMetricsAppenderToLogback() {\n final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();\n final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);\n\n final InstrumentedAppender metrics = new InstrumentedAppender(this.metricRegistry);\n metrics.setContext(root.getLoggerContext());\n metrics.start();\n root.addAppender(metrics);\n }", "public void resetResendCount() {\n\t\tthis.resendCount = 0;\n\t\tif (this.initializationComplete)\n\t\t\tthis.nodeStage = NodeStage.NODEBUILDINFO_DONE;\n\t\tthis.lastUpdated = Calendar.getInstance().getTime();\n\t}", "private void validateAttributes() {\n if (content == null) {\n throw new NullContentException(\"RendererBuilder needs content to create Renderer instances\");\n }\n\n if (parent == null) {\n throw new NullParentException(\"RendererBuilder needs a parent to inflate Renderer instances\");\n }\n\n if (layoutInflater == null) {\n throw new NullLayoutInflaterException(\n \"RendererBuilder needs a LayoutInflater to inflate Renderer instances\");\n }\n }" ]
A simple helper method that creates a pool of connections to Redis using the supplied configurations. @param jesqueConfig the config used to create the pooled Jedis connections @param poolConfig the config used to create the pool @return a configured Pool of Jedis connections
[ "public static Pool<Jedis> createJedisPool(final Config jesqueConfig, final GenericObjectPoolConfig poolConfig) {\n if (jesqueConfig == null) {\n throw new IllegalArgumentException(\"jesqueConfig must not be null\");\n }\n if (poolConfig == null) {\n throw new IllegalArgumentException(\"poolConfig must not be null\");\n }\n if (jesqueConfig.getMasterName() != null && !\"\".equals(jesqueConfig.getMasterName()) \n && jesqueConfig.getSentinels() != null && jesqueConfig.getSentinels().size() > 0) {\n return new JedisSentinelPool(jesqueConfig.getMasterName(), jesqueConfig.getSentinels(), poolConfig, \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n } else {\n return new JedisPool(poolConfig, jesqueConfig.getHost(), jesqueConfig.getPort(), \n jesqueConfig.getTimeout(), jesqueConfig.getPassword(), jesqueConfig.getDatabase());\n }\n }" ]
[ "public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }", "private void initialize(Handler callbackHandler, int threadPoolSize) {\n\t\tmDownloadDispatchers = new DownloadDispatcher[threadPoolSize];\n\t\tmDelivery = new CallBackDelivery(callbackHandler);\n\t}", "public static final UUID parseUUID(String value)\n {\n UUID result = null;\n if (value != null && !value.isEmpty())\n {\n if (value.charAt(0) == '{')\n {\n // PMXML representation: <GUID>{0AB9133E-A09A-9648-B98A-B2384894AC44}</GUID>\n result = UUID.fromString(value.substring(1, value.length() - 1));\n }\n else\n {\n // XER representation: CrkTPqCalki5irI4SJSsRA\n byte[] data = javax.xml.bind.DatatypeConverter.parseBase64Binary(value + \"==\");\n long msb = 0;\n long lsb = 0;\n\n for (int i = 0; i < 8; i++)\n {\n msb = (msb << 8) | (data[i] & 0xff);\n }\n\n for (int i = 8; i < 16; i++)\n {\n lsb = (lsb << 8) | (data[i] & 0xff);\n }\n\n result = new UUID(msb, lsb);\n }\n }\n return result;\n }", "public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath)\n {\n String extension = StringUtils.substringAfterLast(filePath, \".\");\n\n if (!StringUtils.equalsIgnoreCase(extension, \"jar\"))\n return false;\n\n ZipFile archive;\n try\n {\n archive = new ZipFile(filePath);\n } catch (IOException e)\n {\n return false;\n }\n\n WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext());\n WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext());\n\n // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything)\n boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext();\n\n // this should only be true if:\n // 1) the package does not contain *any* customer packages.\n // 2) the package contains \"known\" vendor packages.\n boolean exclusivelyKnown = false;\n\n String organization = null;\n Enumeration<?> e = archive.entries();\n\n // go through all entries...\n ZipEntry entry;\n while (e.hasMoreElements())\n {\n entry = (ZipEntry) e.nextElement();\n String entryName = entry.getName();\n\n if (entry.isDirectory() || !StringUtils.endsWith(entryName, \".class\"))\n continue;\n\n String classname = PathUtil.classFilePathToClassname(entryName);\n // if the package isn't current \"known\", try to match against known packages for this entry.\n if (!exclusivelyKnown)\n {\n organization = getOrganizationForPackage(event, classname);\n if (organization != null)\n {\n exclusivelyKnown = true;\n } else\n {\n // we couldn't find a package definitively, so ignore the archive\n exclusivelyKnown = false;\n break;\n }\n }\n\n // If the user specified package names and this is in those package names, then scan it anyway\n if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname))\n {\n return false;\n }\n }\n\n if (exclusivelyKnown)\n LOG.info(\"Known Package: \" + archive.getName() + \"; Organization: \" + organization);\n\n // Return the evaluated exclusively known value.\n return exclusivelyKnown;\n }", "public static <T> List<List<T>> getNGrams(List<T> items, int minSize, int maxSize) {\r\n List<List<T>> ngrams = new ArrayList<List<T>>();\r\n int listSize = items.size();\r\n for (int i = 0; i < listSize; ++i) {\r\n for (int ngramSize = minSize; ngramSize <= maxSize; ++ngramSize) {\r\n if (i + ngramSize <= listSize) {\r\n List<T> ngram = new ArrayList<T>();\r\n for (int j = i; j < i + ngramSize; ++j) {\r\n ngram.add(items.get(j));\r\n }\r\n ngrams.add(ngram);\r\n }\r\n }\r\n }\r\n return ngrams;\r\n }", "private static MonolingualTextValue toTerm(MonolingualTextValue term) {\n\t\treturn term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText());\n\t}", "public String getDefaultTableName()\r\n {\r\n String name = getName();\r\n int lastDotPos = name.lastIndexOf('.');\r\n int lastDollarPos = name.lastIndexOf('$');\r\n\r\n return lastDollarPos > lastDotPos ? name.substring(lastDollarPos + 1) : name.substring(lastDotPos + 1);\r\n }", "private synchronized Constructor getIndirectionHandlerConstructor()\r\n {\r\n if(_indirectionHandlerConstructor == null)\r\n {\r\n Class[] paramType = {PBKey.class, Identity.class};\r\n\r\n try\r\n {\r\n _indirectionHandlerConstructor = getIndirectionHandlerClass().getConstructor(paramType);\r\n }\r\n catch(NoSuchMethodException ex)\r\n {\r\n throw new MetadataException(\"The class \"\r\n + _indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass\"\r\n + \" is required to have a public constructor with signature (\"\r\n + PBKey.class.getName()\r\n + \", \"\r\n + Identity.class.getName()\r\n + \").\");\r\n }\r\n }\r\n return _indirectionHandlerConstructor;\r\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 }" ]
Creates a template node for the given templateString and appends it to the given parent node. Templates are translated to generator node trees and expressions in templates can be of type IGeneratorNode. @return the given parent node
[ "public CompositeGeneratorNode appendTemplate(final CompositeGeneratorNode parent, final StringConcatenationClient templateString) {\n final TemplateNode proc = new TemplateNode(templateString, this);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(proc);\n return parent;\n }" ]
[ "public Date getStartDate()\n {\n Date result = (Date) getCachedValue(ProjectField.START_DATE);\n if (result == null)\n {\n result = getParentFile().getStartDate();\n }\n return (result);\n }", "public synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }", "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 boolean shouldBeInReport(final DbDependency dependency) {\n if(dependency == null){\n return false;\n }\n if(dependency.getTarget() == null){\n return false;\n }\n if(corporateFilter != null){\n if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){\n return false;\n }\n if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){\n return false;\n }\n }\n\n if(!scopeHandler.filter(dependency)){\n return false;\n }\n\n return true;\n }", "public static Command newInsert(Object object,\n String outIdentifier) {\n return getCommandFactoryProvider().newInsert( object,\n outIdentifier );\n }", "public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\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 }", "public static cmpglobal_cmppolicy_binding[] get(nitro_service service) throws Exception{\n\t\tcmpglobal_cmppolicy_binding obj = new cmpglobal_cmppolicy_binding();\n\t\tcmpglobal_cmppolicy_binding response[] = (cmpglobal_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void each(int offset, int maxRows, Closure closure) throws SQLException {\n eachRow(getSql(), getParameters(), offset, maxRows, closure);\n }" ]
Given a DocumentVersionInfo, returns a BSON document representing the next version. This means and incremented version count for a non-empty version, or a fresh version document for an empty version. @return a BsonDocument representing a synchronization version
[ "BsonDocument getNextVersion() {\n if (!this.hasVersion() || this.getVersionDoc() == null) {\n return getFreshVersionDocument();\n }\n final BsonDocument nextVersion = BsonUtils.copyOfDocument(this.getVersionDoc());\n nextVersion.put(\n Fields.VERSION_COUNTER_FIELD,\n new BsonInt64(this.getVersion().getVersionCounter() + 1));\n return nextVersion;\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 base_response disable(nitro_service client, String trapname) throws Exception {\n\t\tsnmpalarm disableresource = new snmpalarm();\n\t\tdisableresource.trapname = trapname;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}", "public static Type getCanonicalType(Class<?> clazz) {\n if (clazz.isArray()) {\n Class<?> componentType = clazz.getComponentType();\n Type resolvedComponentType = getCanonicalType(componentType);\n if (componentType != resolvedComponentType) {\n // identity check intentional\n // a different identity means that we actually replaced the component Class with a ParameterizedType\n return new GenericArrayTypeImpl(resolvedComponentType);\n }\n }\n if (clazz.getTypeParameters().length > 0) {\n Type[] actualTypeParameters = clazz.getTypeParameters();\n return new ParameterizedTypeImpl(clazz, actualTypeParameters, clazz.getDeclaringClass());\n }\n return clazz;\n }", "protected void processCalendarData(ProjectCalendar calendar, Row row)\n {\n int dayIndex = row.getInt(\"CD_DAY_OR_EXCEPTION\");\n if (dayIndex == 0)\n {\n processCalendarException(calendar, row);\n }\n else\n {\n processCalendarHours(calendar, row, dayIndex);\n }\n }", "public static systemglobal_authenticationldappolicy_binding[] get(nitro_service service) throws Exception{\n\t\tsystemglobal_authenticationldappolicy_binding obj = new systemglobal_authenticationldappolicy_binding();\n\t\tsystemglobal_authenticationldappolicy_binding response[] = (systemglobal_authenticationldappolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void scaleRow( double alpha , DMatrixRMaj A , int row ) {\n int idx = row*A.numCols;\n for (int col = 0; col < A.numCols; col++) {\n A.data[idx++] *= alpha;\n }\n }", "public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Value> valuesList = new NamespacesList<Value>();\r\n parameters.put(\"method\", METHOD_GET_VALUES);\r\n\r\n if (namespace != null) {\r\n parameters.put(\"namespace\", namespace);\r\n }\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"value\");\r\n valuesList.setPage(nsElement.getAttribute(\"page\"));\r\n valuesList.setPages(nsElement.getAttribute(\"pages\"));\r\n valuesList.setPerPage(nsElement.getAttribute(\"perPage\"));\r\n valuesList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n Value value = parseValue(element);\r\n value.setNamespace(namespace);\r\n value.setPredicate(predicate);\r\n valuesList.add(value);\r\n }\r\n return valuesList;\r\n }", "public static boolean check(String passwd, String hashed) {\n try {\n String[] parts = hashed.split(\"\\\\$\");\n\n if (parts.length != 5 || !parts[1].equals(\"s0\")) {\n throw new IllegalArgumentException(\"Invalid hashed value\");\n }\n\n long params = Long.parseLong(parts[2], 16);\n byte[] salt = decode(parts[3].toCharArray());\n byte[] derived0 = decode(parts[4].toCharArray());\n\n int N = (int) Math.pow(2, params >> 16 & 0xffff);\n int r = (int) params >> 8 & 0xff;\n int p = (int) params & 0xff;\n\n byte[] derived1 = SCrypt.scrypt(passwd.getBytes(\"UTF-8\"), salt, N, r, p, 32);\n\n if (derived0.length != derived1.length) return false;\n\n int result = 0;\n for (int i = 0; i < derived0.length; i++) {\n result |= derived0[i] ^ derived1[i];\n }\n return result == 0;\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"JVM doesn't support UTF-8?\");\n } catch (GeneralSecurityException e) {\n throw new IllegalStateException(\"JVM doesn't support SHA1PRNG or HMAC_SHA256?\");\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 }" ]
should not be public
[ "public void release(Contextual<T> contextual, T instance) {\n synchronized (dependentInstances) {\n for (ContextualInstance<?> dependentInstance : dependentInstances) {\n // do not destroy contextual again, since it's just being destroyed\n if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) {\n destroy(dependentInstance);\n }\n }\n }\n if (resourceReferences != null) {\n for (ResourceReference<?> reference : resourceReferences) {\n reference.release();\n }\n }\n }" ]
[ "public static Double getDistanceWithinThresholdOfCoordinates(\r\n Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {\r\n throw new NotImplementedError();\r\n }", "protected void ensureColumns(List columns, List existingColumns)\r\n {\r\n if (columns == null || columns.isEmpty())\r\n {\r\n return;\r\n }\r\n \r\n Iterator iter = columns.iterator();\r\n\r\n while (iter.hasNext())\r\n {\r\n FieldHelper cf = (FieldHelper) iter.next();\r\n if (!existingColumns.contains(cf.name))\r\n {\r\n getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());\r\n }\r\n }\r\n }", "@PostConstruct\n public void loadTagDefinitions()\n {\n Map<Addon, List<URL>> addonToResourcesMap = scanner.scanForAddonMap(new FileExtensionFilter(\"tags.xml\"));\n for (Map.Entry<Addon, List<URL>> entry : addonToResourcesMap.entrySet())\n {\n for (URL resource : entry.getValue())\n {\n log.info(\"Reading tags definitions from: \" + resource.toString() + \" from addon \" + entry.getKey().getId());\n try(InputStream is = resource.openStream())\n {\n tagService.readTags(is);\n }\n catch( Exception ex )\n {\n throw new WindupException(\"Failed reading tags definition: \" + resource.toString() + \" from addon \" + entry.getKey().getId() + \":\\n\" + ex.getMessage(), ex);\n }\n }\n }\n }", "public int[] argb(int x, int y) {\n Pixel p = pixel(x, y);\n return new int[]{p.alpha(), p.red(), p.green(), p.blue()};\n }", "public static final long getLong6(byte[] data, int offset)\n {\n long result = 0;\n int i = offset;\n for (int shiftBy = 0; shiftBy < 48; shiftBy += 8)\n {\n result |= ((long) (data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }", "protected String extractHeaderComment( File xmlFile )\n throws MojoExecutionException\n {\n\n try\n {\n SAXParser parser = SAXParserFactory.newInstance().newSAXParser();\n SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler();\n parser.setProperty( \"http://xml.org/sax/properties/lexical-handler\", handler );\n parser.parse( xmlFile, handler );\n return handler.getHeaderComment();\n }\n catch ( Exception e )\n {\n throw new MojoExecutionException( \"Failed to parse XML from \" + xmlFile, e );\n }\n }", "public static String get(String url, Map<String, String> customHeaders, Map<String, String> params) throws URISyntaxException, IOException, HTTPException {\n LOGGER.log(Level.INFO, \"Sending GET request to the url {0}\", url);\n\n URIBuilder uriBuilder = new URIBuilder(url);\n\n if (params != null && params.size() > 0) {\n for (Map.Entry<String, String> param : params.entrySet()) {\n uriBuilder.setParameter(param.getKey(), param.getValue());\n }\n }\n\n HttpGet httpGet = new HttpGet(uriBuilder.build());\n\n populateHeaders(httpGet, customHeaders);\n\n HttpClient httpClient = HttpClientBuilder.create().build();\n\n HttpResponse httpResponse = httpClient.execute(httpGet);\n\n int statusCode = httpResponse.getStatusLine().getStatusCode();\n if (isErrorStatus(statusCode)) {\n String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);\n }\n\n return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n }", "public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)\n {\n if (cleanBaseFileName)\n {\n baseFileName = PathUtil.cleanFileName(baseFileName);\n }\n\n if (ancestorFolders != null)\n {\n Path pathToFile = Paths.get(\"\", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);\n baseFileName = pathToFile.toString();\n }\n String filename = baseFileName + \".\" + extension;\n\n // FIXME this looks nasty\n while (usedFilenames.contains(filename))\n {\n filename = baseFileName + \".\" + index.getAndIncrement() + \".\" + extension;\n }\n usedFilenames.add(filename);\n\n return filename;\n }", "private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel)\r\n {\r\n if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))\r\n {\r\n classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, \"false\");\r\n }\r\n }" ]
Look up a shaper by a short String name. @param name Shaper name. Known names have patterns along the lines of: dan[12](bio)?(UseLC)?, jenny1(useLC)?, chris[1234](useLC)?. @return An integer constant for the shaper
[ "public static int lookupShaper(String name) {\r\n if (name == null) {\r\n return NOWORDSHAPE;\r\n } else if (name.equalsIgnoreCase(\"dan1\")) {\r\n return WORDSHAPEDAN1;\r\n } else if (name.equalsIgnoreCase(\"chris1\")) {\r\n return WORDSHAPECHRIS1;\r\n } else if (name.equalsIgnoreCase(\"dan2\")) {\r\n return WORDSHAPEDAN2;\r\n } else if (name.equalsIgnoreCase(\"dan2useLC\")) {\r\n return WORDSHAPEDAN2USELC;\r\n } else if (name.equalsIgnoreCase(\"dan2bio\")) {\r\n return WORDSHAPEDAN2BIO;\r\n } else if (name.equalsIgnoreCase(\"dan2bioUseLC\")) {\r\n return WORDSHAPEDAN2BIOUSELC;\r\n } else if (name.equalsIgnoreCase(\"jenny1\")) {\r\n return WORDSHAPEJENNY1;\r\n } else if (name.equalsIgnoreCase(\"jenny1useLC\")) {\r\n return WORDSHAPEJENNY1USELC;\r\n } else if (name.equalsIgnoreCase(\"chris2\")) {\r\n return WORDSHAPECHRIS2;\r\n } else if (name.equalsIgnoreCase(\"chris2useLC\")) {\r\n return WORDSHAPECHRIS2USELC;\r\n } else if (name.equalsIgnoreCase(\"chris3\")) {\r\n return WORDSHAPECHRIS3;\r\n } else if (name.equalsIgnoreCase(\"chris3useLC\")) {\r\n return WORDSHAPECHRIS3USELC;\r\n } else if (name.equalsIgnoreCase(\"chris4\")) {\r\n return WORDSHAPECHRIS4;\r\n } else if (name.equalsIgnoreCase(\"digits\")) {\r\n return WORDSHAPEDIGITS;\r\n } else {\r\n return NOWORDSHAPE;\r\n }\r\n }" ]
[ "private String getResourceField(int key)\n {\n String result = null;\n\n if (key > 0 && key < m_resourceNames.length)\n {\n result = m_resourceNames[key];\n }\n\n return (result);\n }", "@RequestMapping(value = \"group\", method = RequestMethod.GET)\n public String newGroupGet(Model model) {\n model.addAttribute(\"groups\",\n pathOverrideService.findAllGroups());\n return \"groups\";\n }", "public void getKey(int keyIndex, float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n System.arraycopy(mKeys, index + 1, values, 0, values.length);\n }", "private ClassDescriptor getRealClassDescriptor(ClassDescriptor aCld, Object anObj)\r\n {\r\n ClassDescriptor result;\r\n\r\n if(aCld.getClassOfObject() == ProxyHelper.getRealClass(anObj))\r\n {\r\n result = aCld;\r\n }\r\n else\r\n {\r\n result = aCld.getRepository().getDescriptorFor(anObj.getClass());\r\n }\r\n\r\n return result;\r\n }", "private void processCalendars() throws SQLException\n {\n for (ResultSetRow row : getRows(\"SELECT * FROM MSP_CALENDARS WHERE PROJ_ID=?\", m_projectID))\n {\n processCalendar(row);\n }\n\n updateBaseCalendarNames();\n\n processCalendarData(m_project.getCalendars());\n }", "public void endRecord_() {\n // this is where we actually update the link database. basically,\n // all we need to do is to retract those links which weren't seen\n // this time around, and that can be done via assertLink, since it\n // can override existing links.\n\n // get all the existing links\n Collection<Link> oldlinks = linkdb.getAllLinksFor(getIdentity(current));\n\n // build a hashmap so we can look up corresponding old links from\n // new links\n if (oldlinks != null) {\n Map<String, Link> oldmap = new HashMap(oldlinks.size());\n for (Link l : oldlinks)\n oldmap.put(makeKey(l), l);\n\n // removing all the links we found this time around from the set of\n // old links. any links remaining after this will be stale, and need\n // to be retracted\n for (Link newl : new ArrayList<Link>(curlinks)) {\n String key = makeKey(newl);\n Link oldl = oldmap.get(key);\n if (oldl == null)\n continue;\n\n if (oldl.overrides(newl))\n // previous information overrides this link, so ignore\n curlinks.remove(newl);\n else if (sameAs(oldl, newl)) {\n // there's no new information here, so just ignore this\n curlinks.remove(newl);\n oldmap.remove(key); // we don't want to retract the old one\n } else\n // the link is out of date, but will be overwritten, so remove\n oldmap.remove(key);\n }\n\n // all the inferred links left in oldmap are now old links we\n // didn't find on this pass. there is no longer any evidence\n // supporting them, and so we can retract them.\n for (Link oldl : oldmap.values())\n if (oldl.getStatus() == LinkStatus.INFERRED) {\n oldl.retract(); // changes to retracted, updates timestamp\n curlinks.add(oldl);\n }\n }\n\n // okay, now we write it all to the database\n for (Link l : curlinks)\n linkdb.assertLink(l);\n }", "private static String wordShapeChris4(String s, boolean omitIfInBoundary, Collection<String> knownLCWords) {\r\n int len = s.length();\r\n if (len <= BOUNDARY_SIZE * 2) {\r\n return wordShapeChris4Short(s, len, knownLCWords);\r\n } else {\r\n return wordShapeChris4Long(s, omitIfInBoundary, len, knownLCWords);\r\n }\r\n }", "public static BufferedImage createImage(ImageProducer producer) {\n\t\tPixelGrabber pg = new PixelGrabber(producer, 0, 0, -1, -1, null, 0, 0);\n\t\ttry {\n\t\t\tpg.grabPixels();\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(\"Image fetch interrupted\");\n\t\t}\n\t\tif ((pg.status() & ImageObserver.ABORT) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch aborted\");\n\t\tif ((pg.status() & ImageObserver.ERROR) != 0)\n\t\t\tthrow new RuntimeException(\"Image fetch error\");\n\t\tBufferedImage p = new BufferedImage(pg.getWidth(), pg.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\t\tp.setRGB(0, 0, pg.getWidth(), pg.getHeight(), (int[])pg.getPixels(), 0, pg.getWidth());\n\t\treturn p;\n\t}", "public void setBooleanAttribute(String name, Boolean value) {\n\t\tensureValue();\n\t\tAttribute attribute = new BooleanAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}" ]
Parses command-line and removes metadata related to rebalancing. @param args Command-line input @param printHelp Tells whether to print help only or execute command actually @throws IOException
[ "@SuppressWarnings(\"unchecked\")\n public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n\n // declare parameters\n String url = null;\n List<Integer> nodeIds = null;\n Boolean allNodes = true;\n Boolean confirm = false;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n // check required options and/or conflicting options\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n AdminParserUtils.checkOptional(options,\n AdminParserUtils.OPT_NODE,\n AdminParserUtils.OPT_ALL_NODES);\n\n // load parameters\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_NODE)) {\n nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);\n allNodes = false;\n }\n if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Remove metadata related to rebalancing\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n if(allNodes) {\n System.out.println(\" node = all nodes\");\n } else {\n System.out.println(\" node = \" + Joiner.on(\", \").join(nodeIds));\n }\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm, \"remove metadata related to rebalancing\")) {\n return;\n }\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n if(allNodes) {\n nodeIds = AdminToolUtils.getAllNodeIds(adminClient);\n }\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds);\n\n doMetaClearRebalance(adminClient, nodeIds);\n }" ]
[ "@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }", "private ProjectCalendar deriveResourceCalendar(Integer parentCalendarID)\n {\n ProjectCalendar calendar = m_project.addDefaultDerivedCalendar();\n calendar.setUniqueID(Integer.valueOf(m_project.getProjectConfig().getNextCalendarUniqueID()));\n calendar.setParent(m_project.getCalendarByUniqueID(parentCalendarID));\n return calendar;\n }", "public void init( double diag[] ,\n double off[],\n int numCols ) {\n reset(numCols);\n\n this.diag = diag;\n this.off = off;\n }", "protected void aliasGeneric( Object variable , String name ) {\n if( variable.getClass() == Integer.class ) {\n alias(((Integer)variable).intValue(),name);\n } else if( variable.getClass() == Double.class ) {\n alias(((Double)variable).doubleValue(),name);\n } else if( variable.getClass() == DMatrixRMaj.class ) {\n alias((DMatrixRMaj)variable,name);\n } else if( variable.getClass() == FMatrixRMaj.class ) {\n alias((FMatrixRMaj)variable,name);\n } else if( variable.getClass() == DMatrixSparseCSC.class ) {\n alias((DMatrixSparseCSC)variable,name);\n } else if( variable.getClass() == SimpleMatrix.class ) {\n alias((SimpleMatrix) variable, name);\n } else if( variable instanceof DMatrixFixed ) {\n DMatrixRMaj M = new DMatrixRMaj(1,1);\n ConvertDMatrixStruct.convert((DMatrixFixed)variable,M);\n alias(M,name);\n } else if( variable instanceof FMatrixFixed ) {\n FMatrixRMaj M = new FMatrixRMaj(1,1);\n ConvertFMatrixStruct.convert((FMatrixFixed)variable,M);\n alias(M,name);\n } else {\n throw new RuntimeException(\"Unknown value type of \"+\n (variable.getClass().getSimpleName())+\" for variable \"+name);\n }\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 String getRepoKey() {\n String repoKey;\n if (isDynamicMode()) {\n repoKey = keyFromText;\n } else {\n repoKey = keyFromSelect;\n }\n return repoKey;\n }", "private Expression correctClassClassChain(PropertyExpression pe) {\n LinkedList<Expression> stack = new LinkedList<Expression>();\n ClassExpression found = null;\n for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) {\n if (it instanceof ClassExpression) {\n found = (ClassExpression) it;\n break;\n } else if (!(it.getClass() == PropertyExpression.class)) {\n return pe;\n }\n stack.addFirst(it);\n }\n if (found == null) return pe;\n\n if (stack.isEmpty()) return pe;\n Object stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpression = (PropertyExpression) stackElement;\n String propertyNamePart = classPropertyExpression.getPropertyAsString();\n if (propertyNamePart == null || !propertyNamePart.equals(\"class\")) return pe;\n\n found.setSourcePosition(classPropertyExpression);\n if (stack.isEmpty()) return found;\n stackElement = stack.removeFirst();\n if (!(stackElement.getClass() == PropertyExpression.class)) return pe;\n PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement;\n\n classPropertyExpressionContainer.setObjectExpression(found);\n return pe;\n }", "@SuppressWarnings(\"deprecation\")\n public BUILDER addAccessConstraint(final AccessConstraintDefinition accessConstraint) {\n if (accessConstraints == null) {\n accessConstraints = new AccessConstraintDefinition[] {accessConstraint};\n } else {\n accessConstraints = Arrays.copyOf(accessConstraints, accessConstraints.length + 1);\n accessConstraints[accessConstraints.length - 1] = accessConstraint;\n }\n return (BUILDER) this;\n }", "public void mergeSubsystem(final GlobalTransformerRegistry registry, String subsystemName, ModelVersion version) {\n final PathElement element = PathElement.pathElement(SUBSYSTEM, subsystemName);\n registry.mergeSubtree(this, PathAddress.EMPTY_ADDRESS.append(element), version);\n }" ]
Count some stats on what occurs in a file.
[ "public static void main(String[] args) throws IOException, ClassNotFoundException {\r\n CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter();\r\n f.init(new SeqClassifierFlags());\r\n int numDocs = 0;\r\n int numTokens = 0;\r\n int numEntities = 0;\r\n String lastAnsBase = \"\";\r\n for (Iterator<List<CoreLabel>> it = f.getIterator(new FileReader(args[0])); it.hasNext(); ) {\r\n List<CoreLabel> doc = it.next();\r\n numDocs++;\r\n for (CoreLabel fl : doc) {\r\n // System.out.println(\"FL \" + (++i) + \" was \" + fl);\r\n if (fl.word().equals(BOUNDARY)) {\r\n continue;\r\n }\r\n String ans = fl.get(AnswerAnnotation.class);\r\n String ansBase;\r\n String ansPrefix;\r\n String[] bits = ans.split(\"-\");\r\n if (bits.length == 1) {\r\n ansBase = bits[0];\r\n ansPrefix = \"\";\r\n } else {\r\n ansBase = bits[1];\r\n ansPrefix = bits[0];\r\n }\r\n numTokens++;\r\n if (ansBase.equals(\"O\")) {\r\n } else if (ansBase.equals(lastAnsBase)) {\r\n if (ansPrefix.equals(\"B\")) {\r\n numEntities++;\r\n }\r\n } else {\r\n numEntities++;\r\n }\r\n }\r\n }\r\n System.out.println(\"File \" + args[0] + \" has \" + numDocs + \" documents, \" +\r\n numTokens + \" (non-blank line) tokens and \" +\r\n numEntities + \" entities.\");\r\n }" ]
[ "public String nstring(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n switch (next) {\n case '\"':\n return consumeQuoted(request);\n case '{':\n return consumeLiteral(request);\n default:\n String value = atom(request);\n if (\"NIL\".equals(value)) {\n return null;\n } else {\n throw new ProtocolException(\"Invalid nstring value: valid values are '\\\"...\\\"', '{12} CRLF *CHAR8', and 'NIL'.\");\n }\n }\n }", "private boolean checkAndSetManifestAndImagePathCandidates(String manifestPath, String candidateImagePath, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateManifest = getManifestFromArtifactory(dependenciesClient, manifestPath);\n if (candidateManifest == null) {\n return false;\n }\n\n String imageDigest = DockerUtils.getConfigDigest(candidateManifest);\n if (imageDigest.equals(imageId)) {\n manifest = candidateManifest;\n imagePath = candidateImagePath;\n return true;\n }\n\n listener.getLogger().println(String.format(\"Found incorrect manifest.json file in Artifactory in the following path: %s\\nExpecting: %s got: %s\", manifestPath, imageId, imageDigest));\n return false;\n }", "public List<StepCandidate> prioritise(String stepAsText, List<StepCandidate> candidates) {\n return prioritisingStrategy.prioritise(stepAsText, candidates);\n }", "public static cmppolicy_stats[] get(nitro_service service) throws Exception{\n\t\tcmppolicy_stats obj = new cmppolicy_stats();\n\t\tcmppolicy_stats[] response = (cmppolicy_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public void createResourceFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RESOURCE_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultResourceData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }", "public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void main(String[] args) {\r\n TreebankLanguagePack tlp = new PennTreebankLanguagePack();\r\n System.out.println(\"Start symbol: \" + tlp.startSymbol());\r\n String start = tlp.startSymbol();\r\n System.out.println(\"Should be true: \" + (tlp.isStartSymbol(start)));\r\n String[] strs = {\"-\", \"-LLB-\", \"NP-2\", \"NP=3\", \"NP-LGS\", \"NP-TMP=3\"};\r\n for (String str : strs) {\r\n System.out.println(\"String: \" + str + \" basic: \" + tlp.basicCategory(str) + \" basicAndFunc: \" + tlp.categoryAndFunction(str));\r\n }\r\n }", "public static clusterinstance[] get(nitro_service service, Long clid[]) throws Exception{\n\t\tif (clid !=null && clid.length>0) {\n\t\t\tclusterinstance response[] = new clusterinstance[clid.length];\n\t\t\tclusterinstance obj[] = new clusterinstance[clid.length];\n\t\t\tfor (int i=0;i<clid.length;i++) {\n\t\t\t\tobj[i] = new clusterinstance();\n\t\t\t\tobj[i].set_clid(clid[i]);\n\t\t\t\tresponse[i] = (clusterinstance) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private static Interval parseStartExtended(CharSequence startStr, CharSequence endStr) {\n Instant start = Instant.parse(startStr);\n if (endStr.length() > 0) {\n char c = endStr.charAt(0);\n if (c == 'P' || c == 'p') {\n PeriodDuration amount = PeriodDuration.parse(endStr);\n // addition of PeriodDuration only supported by OffsetDateTime,\n // but to make that work need to move point being added to closer to EPOCH\n long move = start.isBefore(Instant.EPOCH) ? 1000 * 86400 : -1000 * 86400;\n Instant end = start.plusSeconds(move).atOffset(ZoneOffset.UTC).plus(amount).toInstant().minusSeconds(move);\n return Interval.of(start, end);\n }\n }\n // infer offset from start if not specified by end\n return parseEndDateTime(start, ZoneOffset.UTC, endStr);\n }" ]
Count the number of non-zero elements in R
[ "void countNonZeroInR( int[] parent ) {\n TriangularSolver_DSCC.postorder(parent,n,post,gwork);\n columnCounts.process(A,parent,post,countsR);\n nz_in_R = 0;\n for (int k = 0; k < n; k++) {\n nz_in_R += countsR[k];\n }\n if( nz_in_R < 0)\n throw new RuntimeException(\"Too many elements. Numerical overflow in R counts\");\n }" ]
[ "public static void addLoadInstruction(CodeAttribute code, String type, int variable) {\n char tp = type.charAt(0);\n if (tp != 'L' && tp != '[') {\n // we have a primitive type\n switch (tp) {\n case 'J':\n code.lload(variable);\n break;\n case 'D':\n code.dload(variable);\n break;\n case 'F':\n code.fload(variable);\n break;\n default:\n code.iload(variable);\n }\n } else {\n code.aload(variable);\n }\n }", "protected void appendList(StringBuilder sql, List<?> list, String init, String sep) {\n\n boolean first = true;\n\n for (Object s : list) {\n if (first) {\n sql.append(init);\n } else {\n sql.append(sep);\n }\n sql.append(s);\n first = false;\n }\n }", "public void append(LogSegment segment) {\n while (true) {\n List<LogSegment> curr = contents.get();\n List<LogSegment> updated = new ArrayList<LogSegment>(curr);\n updated.add(segment);\n if (contents.compareAndSet(curr, updated)) {\n return;\n }\n }\n }", "public static DMatrixRMaj wrap(int numRows , int numCols , double []data ) {\n DMatrixRMaj s = new DMatrixRMaj();\n s.data = data;\n s.numRows = numRows;\n s.numCols = numCols;\n\n return s;\n }", "protected void progressInfoMessage(final String tag) {\n if(logger.isInfoEnabled()) {\n long totalTimeS = (System.currentTimeMillis() - startTimeMs) / Time.MS_PER_SECOND;\n\n logger.info(tag + \" : scanned \" + scanned + \" and fetched \" + fetched + \" for store '\"\n + storageEngine.getName() + \"' partitionIds:\" + partitionIds + \" in \"\n + totalTimeS + \" s\");\n }\n }", "public void reportCompletion(NodeT completed) {\n completed.setPreparer(true);\n String dependency = completed.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onSuccessfulResolution(dependency);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }", "public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }", "public void setPatternScheme(final boolean isWeekDayBased) {\n\n if (isWeekDayBased ^ (null != m_model.getWeekDay())) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n if (isWeekDayBased) {\n m_model.setWeekDay(getPatternDefaultValues().getWeekDay());\n m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth());\n } else {\n m_model.setWeekDay(null);\n m_model.setWeekOfMonth(null);\n }\n m_model.setMonth(getPatternDefaultValues().getMonth());\n m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth());\n m_model.setInterval(getPatternDefaultValues().getInterval());\n onValueChange();\n }\n });\n }\n }", "public static BoxRetentionPolicy.Info createFinitePolicy(BoxAPIConnection api, String name, int length,\r\n String action, RetentionPolicyParams optionalParams) {\r\n return createRetentionPolicy(api, name, TYPE_FINITE, length, action, optionalParams);\r\n }" ]
Read the work weeks. @param data calendar data @param offset current offset into data @param cal parent calendar
[ "private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }" ]
[ "private J2EETransactionImpl newInternTransaction()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"obtain new intern odmg-transaction\");\r\n J2EETransactionImpl tx = new J2EETransactionImpl(this);\r\n try\r\n {\r\n getConfigurator().configure(tx);\r\n }\r\n catch (ConfigurationException e)\r\n {\r\n throw new OJBRuntimeException(\"Cannot create new intern odmg transaction\", e);\r\n }\r\n return tx;\r\n }", "@PrefMetadata(type = CmsTimeWarpPreference.class)\n public String getTimeWarp() {\n\n long warp = m_settings.getTimeWarp();\n return warp < 0 ? \"\" : \"\" + warp; // if timewarp < 0 (i.e. time warp is not set), use the empty string because we don't want the date selector widget to interpret the negative value\n }", "public static base_response update(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup updateresource = new cachecontentgroup();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\tupdateresource.heurexpiryparam = resource.heurexpiryparam;\n\t\tupdateresource.relexpiry = resource.relexpiry;\n\t\tupdateresource.relexpirymillisec = resource.relexpirymillisec;\n\t\tupdateresource.absexpiry = resource.absexpiry;\n\t\tupdateresource.absexpirygmt = resource.absexpirygmt;\n\t\tupdateresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\tupdateresource.hitparams = resource.hitparams;\n\t\tupdateresource.invalparams = resource.invalparams;\n\t\tupdateresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\tupdateresource.matchcookies = resource.matchcookies;\n\t\tupdateresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\tupdateresource.polleverytime = resource.polleverytime;\n\t\tupdateresource.ignorereloadreq = resource.ignorereloadreq;\n\t\tupdateresource.removecookies = resource.removecookies;\n\t\tupdateresource.prefetch = resource.prefetch;\n\t\tupdateresource.prefetchperiod = resource.prefetchperiod;\n\t\tupdateresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\tupdateresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\tupdateresource.flashcache = resource.flashcache;\n\t\tupdateresource.expireatlastbyte = resource.expireatlastbyte;\n\t\tupdateresource.insertvia = resource.insertvia;\n\t\tupdateresource.insertage = resource.insertage;\n\t\tupdateresource.insertetag = resource.insertetag;\n\t\tupdateresource.cachecontrol = resource.cachecontrol;\n\t\tupdateresource.quickabortsize = resource.quickabortsize;\n\t\tupdateresource.minressize = resource.minressize;\n\t\tupdateresource.maxressize = resource.maxressize;\n\t\tupdateresource.memlimit = resource.memlimit;\n\t\tupdateresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\tupdateresource.minhits = resource.minhits;\n\t\tupdateresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\tupdateresource.persist = resource.persist;\n\t\tupdateresource.pinned = resource.pinned;\n\t\tupdateresource.lazydnsresolve = resource.lazydnsresolve;\n\t\tupdateresource.hitselector = resource.hitselector;\n\t\tupdateresource.invalselector = resource.invalselector;\n\t\treturn updateresource.update_resource(client);\n\t}", "@Nullable\n public static LocationEngineResult extractResult(Intent intent) {\n LocationEngineResult result = null;\n if (isOnClasspath(GOOGLE_PLAY_LOCATION_RESULT)) {\n result = extractGooglePlayResult(intent);\n }\n return result == null ? extractAndroidResult(intent) : result;\n }", "public static <T> String extractTableName(DatabaseType databaseType, Class<T> clazz) {\n\t\tDatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class);\n\t\tString name = null;\n\t\tif (databaseTable != null && databaseTable.tableName() != null && databaseTable.tableName().length() > 0) {\n\t\t\tname = databaseTable.tableName();\n\t\t}\n\t\tif (name == null && javaxPersistenceConfigurer != null) {\n\t\t\tname = javaxPersistenceConfigurer.getEntityName(clazz);\n\t\t}\n\t\tif (name == null) {\n\t\t\t// if the name isn't specified, it is the class name lowercased\n\t\t\tif (databaseType == null) {\n\t\t\t\t// database-type is optional so if it is not specified we just use english\n\t\t\t\tname = clazz.getSimpleName().toLowerCase(Locale.ENGLISH);\n\t\t\t} else {\n\t\t\t\tname = databaseType.downCaseString(clazz.getSimpleName(), true);\n\t\t\t}\n\t\t}\n\t\treturn name;\n\t}", "public static dbdbprofile get(nitro_service service, String name) throws Exception{\n\t\tdbdbprofile obj = new dbdbprofile();\n\t\tobj.set_name(name);\n\t\tdbdbprofile response = (dbdbprofile) obj.get_resource(service);\n\t\treturn response;\n\t}", "private InputStream connect(String url) throws IOException {\n\t\tURLConnection conn = new URL(URL_BASE + url).openConnection();\n\t\tconn.setConnectTimeout(CONNECT_TIMEOUT);\n\t\tconn.setReadTimeout(READ_TIMEOUT);\n\t\tconn.setRequestProperty(\"User-Agent\", USER_AGENT);\n\t\treturn conn.getInputStream();\n\t}", "public static String readFileContentToString(String filePath)\n throws IOException {\n String content = \"\";\n content = Files.toString(new File(filePath), Charsets.UTF_8);\n return content;\n }", "public Object lookup(Identity oid)\r\n {\r\n Object ret = null;\r\n if (oid != null)\r\n {\r\n ObjectCache cache = getCache(oid, null, METHOD_LOOKUP);\r\n if (cache != null)\r\n {\r\n ret = cache.lookup(oid);\r\n }\r\n }\r\n return ret;\r\n }" ]
Gets the type to use for the Vaadin table column corresponding to the c-th column in this result. @param c the column index @return the class to use for the c-th Vaadin table column
[ "public Class<?> getColumnType(int c) {\n\n for (int r = 0; r < m_data.size(); r++) {\n Object val = m_data.get(r).get(c);\n if (val != null) {\n return val.getClass();\n }\n }\n return Object.class;\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 addDefaultCalendarHours(Day day)\n {\n ProjectCalendarHours hours = addCalendarHours(day);\n\n if (day != Day.SATURDAY && day != Day.SUNDAY)\n {\n hours.addRange(DEFAULT_WORKING_MORNING);\n hours.addRange(DEFAULT_WORKING_AFTERNOON);\n }\n }", "public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n return client;\n }", "@Override\n public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) {\n return DiscordianDate.of(prolepticYear, month, dayOfMonth);\n }", "public void begin(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n data = new TimingData(key);\n executionInfo.put(key, data);\n }\n data.begin();\n }", "private synchronized JsonSchema getInputPathJsonSchema() throws IOException {\n if (inputPathJsonSchema == null) {\n // No need to query Hadoop more than once as this shouldn't change mid-run,\n // thus, we can lazily initialize and cache the result.\n inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath());\n }\n return inputPathJsonSchema;\n }", "public void fatal(String msg) {\n\t\tlogIfEnabled(Level.FATAL, null, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, null);\n\t}", "public static void clear() {\n JobContext ctx = current_.get();\n if (null != ctx) {\n ctx.bag_.clear();\n JobContext parent = ctx.parent;\n if (null != parent) {\n current_.set(parent);\n ctx.parent = null;\n } else {\n current_.remove();\n Act.eventBus().trigger(new JobContextDestroyed(ctx));\n }\n }\n }", "protected ClassDescriptor getClassDescriptor()\r\n {\r\n ClassDescriptor cld = (ClassDescriptor) m_classDescriptor.get();\r\n if(cld == null)\r\n {\r\n throw new OJBRuntimeException(\"Requested ClassDescriptor instance was already GC by JVM\");\r\n }\r\n return cld;\r\n }" ]
Upload a file and attach it to a task @param task Globally unique identifier for the task. @param fileContent Content of the file to be uploaded @param fileName Name of the file to be uploaded @param fileType MIME type of the file to be uploaded @return Request object
[ "public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {\n MultipartContent.Part part = new MultipartContent.Part()\n .setContent(new InputStreamContent(fileType, fileContent))\n .setHeaders(new HttpHeaders().set(\n \"Content-Disposition\",\n String.format(\"form-data; name=\\\"file\\\"; filename=\\\"%s\\\"\", fileName) // TODO: escape fileName?\n ));\n MultipartContent content = new MultipartContent()\n .setMediaType(new HttpMediaType(\"multipart/form-data\").setParameter(\"boundary\", UUID.randomUUID().toString()))\n .addPart(part);\n\n String path = String.format(\"/tasks/%s/attachments\", task);\n return new ItemRequest<Attachment>(this, Attachment.class, path, \"POST\")\n .data(content);\n }" ]
[ "public double determinant() {\n if (m != n) {\n throw new IllegalArgumentException(\"Matrix must be square.\");\n }\n double d = (double) pivsign;\n for (int j = 0; j < n; j++) {\n d *= LU[j][j];\n }\n return d;\n }", "public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) {\n checkArgument(!variableName.isEmpty());\n return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine));\n }", "protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) {\n routingFor(routable1)\n .routees()\n .forEach(routee -> routee.receiveCommand(action, routable1));\n }", "private static String quoteSort(Sort[] sort) {\n LinkedList<String> sorts = new LinkedList<String>();\n for (Sort pair : sort) {\n sorts.add(String.format(\"{%s: %s}\", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));\n }\n return sorts.toString();\n }", "public static onlinkipv6prefix get(nitro_service service, String ipv6prefix) throws Exception{\n\t\tonlinkipv6prefix obj = new onlinkipv6prefix();\n\t\tobj.set_ipv6prefix(ipv6prefix);\n\t\tonlinkipv6prefix response = (onlinkipv6prefix) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroupbindings obj = new servicegroupbindings();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroupbindings response = (servicegroupbindings) obj.get_resource(service);\n\t\treturn response;\n\t}", "public void setIssueTrackerInfo(BuildInfoBuilder builder) {\n Issues issues = new Issues();\n issues.setAggregateBuildIssues(aggregateBuildIssues);\n issues.setAggregationBuildStatus(aggregationBuildStatus);\n issues.setTracker(new IssueTracker(\"JIRA\", issueTrackerVersion));\n Set<Issue> affectedIssuesSet = IssuesTrackerUtils.getAffectedIssuesSet(affectedIssues);\n if (!affectedIssuesSet.isEmpty()) {\n issues.setAffectedIssues(affectedIssuesSet);\n }\n builder.issues(issues);\n }", "@UiThread\n public void collapseParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n collapseParent(i);\n }\n }", "public static void permutationVector( DMatrixSparseCSC P , int[] vector) {\n if( P.numCols != P.numRows ) {\n throw new MatrixDimensionException(\"Expected a square matrix\");\n } else if( P.nz_length != P.numCols ) {\n throw new IllegalArgumentException(\"Expected N non-zero elements in permutation matrix\");\n } else if( vector.length < P.numCols ) {\n throw new IllegalArgumentException(\"vector is too short\");\n }\n\n int M = P.numCols;\n\n for (int i = 0; i < M; i++) {\n if( P.col_idx[i+1] != i+1 )\n throw new IllegalArgumentException(\"Unexpected number of elements in a column\");\n\n vector[P.nz_rows[i]] = i;\n }\n }" ]
Grab random holiday from the equivalence class that falls between the two dates @param earliest the earliest date parameter as defined in the model @param latest the latest date parameter as defined in the model @return a holiday that falls between the dates
[ "public String getRandomHoliday(String earliest, String latest) {\n String dateString = \"\";\n DateTimeFormatter parser = ISODateTimeFormat.date();\n DateTime earlyDate = parser.parseDateTime(earliest);\n DateTime lateDate = parser.parseDateTime(latest);\n List<Holiday> holidays = new LinkedList<>();\n\n int min = Integer.parseInt(earlyDate.toString().substring(0, 4));\n int max = Integer.parseInt(lateDate.toString().substring(0, 4));\n int range = max - min + 1;\n int randomYear = (int) (Math.random() * range) + min;\n\n for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {\n holidays.add(s);\n }\n Collections.shuffle(holidays);\n\n for (Holiday holiday : holidays) {\n dateString = convertToReadableDate(holiday.forYear(randomYear));\n if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {\n break;\n }\n }\n return dateString;\n }" ]
[ "private String getPropertyName(Expression expression) {\n\t\tif (!(expression instanceof PropertyName)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a PropertyName.\");\n\t\t}\n\t\tString name = ((PropertyName) expression).getPropertyName();\n\t\tif (name.endsWith(FilterService.ATTRIBUTE_ID)) {\n\t\t\t// replace by Hibernate id property, always refers to the id, even if named differently\n\t\t\tname = name.substring(0, name.length() - FilterService.ATTRIBUTE_ID.length()) + HIBERNATE_ID;\n\t\t}\n\t\treturn name;\n\t}", "public void createInsertionSql(Database model, Platform platform, Writer writer) throws IOException\r\n {\r\n for (Iterator it = _beans.iterator(); it.hasNext();)\r\n {\r\n writer.write(platform.getInsertSql(model, (DynaBean)it.next()));\r\n if (it.hasNext())\r\n {\r\n writer.write(\"\\n\");\r\n }\r\n }\r\n }", "public static ClientBuilder account(String account) {\n logger.config(\"Account: \" + account);\n return ClientBuilder.url(\n convertStringToURL(String.format(\"https://%s.cloudant.com\", account)));\n }", "public static void validateClusterPartitionCounts(final Cluster lhs, final Cluster rhs) {\n if(lhs.getNumberOfPartitions() != rhs.getNumberOfPartitions())\n throw new VoldemortException(\"Total number of partitions should be equal [ lhs cluster (\"\n + lhs.getNumberOfPartitions()\n + \") not equal to rhs cluster (\"\n + rhs.getNumberOfPartitions() + \") ]\");\n }", "protected Class<?> classForName(String name) {\n try {\n return resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_CLASS;\n }\n }", "private Object mapToId(Object tmp) {\n if (tmp instanceof Double) {\n return new Integer(((Double)tmp).intValue());\n } else {\n return Context.toString(tmp);\n }\n }", "public static void extract( DMatrixRMaj src,\n int rows[] , int rowsSize ,\n int cols[] , int colsSize , DMatrixRMaj dst ) {\n if( rowsSize != dst.numRows || colsSize != dst.numCols )\n throw new MatrixDimensionException(\"Unexpected number of rows and/or columns in dst matrix\");\n\n int indexDst = 0;\n for (int i = 0; i < rowsSize; i++) {\n int indexSrcRow = src.numCols*rows[i];\n for (int j = 0; j < colsSize; j++) {\n dst.data[indexDst++] = src.data[indexSrcRow + cols[j]];\n }\n }\n }", "public static boolean distributeAndCheckResponse(DistributionBuilder distributionBuilder, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber, boolean dryRun) throws IOException {\n // do a dry run first\n listener.getLogger().println(\"Performing dry run distribution (no changes are made during dry run) ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, true)) {\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully\");\n if (!dryRun) {\n listener.getLogger().println(\"Performing distribution ...\");\n if (!distribute(distributionBuilder, client, listener, buildName, buildNumber, false)) {\n return false;\n }\n listener.getLogger().println(\"Distribution completed successfully!\");\n }\n return true;\n }", "public void wireSteps( CanWire canWire ) {\n for( StageState steps : stages.values() ) {\n canWire.wire( steps.instance );\n }\n }" ]
Execute the transactional flow - catch all exceptions @param input Initial data input @return Try that represents either success (with result) or failure (with errors)
[ "public Try<R,Throwable> execute(T input){\n\t\treturn Try.withCatch( ()->transactionTemplate.execute(status-> transaction.apply(input)));\n\t\t \n\t}" ]
[ "@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) 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 List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }", "public static ServiceName moduleServiceName(ModuleIdentifier identifier) {\n if (!identifier.getName().startsWith(MODULE_PREFIX)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }", "public int addServerRedirectToProfile(String region, String srcUrl, String destUrl, String hostHeader,\n int profileId, int clientId) throws Exception {\n int serverId = -1;\n\n try {\n Client client = ClientService.getInstance().getClient(clientId);\n serverId = addServerRedirect(region, srcUrl, destUrl, hostHeader, profileId, client.getActiveServerGroup());\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return serverId;\n }", "static void initSingleParam(String key, String initValue, DbConn cnx)\n {\n try\n {\n cnx.runSelectSingle(\"globalprm_select_by_key\", 2, String.class, key);\n return;\n }\n catch (NoResultException e)\n {\n GlobalParameter.create(cnx, key, initValue);\n }\n catch (NonUniqueResultException e)\n {\n // It exists! Nothing to do...\n }\n }", "private File buildDirPath(final String serverConfigUserDirPropertyName, final String suppliedConfigDir,\n final String serverConfigDirPropertyName, final String serverBaseDirPropertyName, final String defaultBaseDir) {\n String propertyDir = System.getProperty(serverConfigUserDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n if (suppliedConfigDir != null) {\n return new File(suppliedConfigDir);\n }\n propertyDir = System.getProperty(serverConfigDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n\n propertyDir = System.getProperty(serverBaseDirPropertyName);\n if (propertyDir != null) {\n return new File(propertyDir);\n }\n\n return new File(new File(stateValues.getOptions().getJBossHome(), defaultBaseDir), \"configuration\");\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 Thumbor create(String host, String key) {\n if (key == null || key.length() == 0) {\n throw new IllegalArgumentException(\"Key must not be blank.\");\n }\n return new Thumbor(host, key);\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 }", "public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }" ]
Destroy the proxy & update the map containing the registration ref. @param importDeclaration
[ "@Override\n protected void denyImportDeclaration(ImportDeclaration importDeclaration) {\n LOG.debug(\"CXFImporter destroy a proxy for \" + importDeclaration);\n ServiceRegistration serviceRegistration = map.get(importDeclaration);\n serviceRegistration.unregister();\n\n // set the importDeclaration has unhandled\n super.unhandleImportDeclaration(importDeclaration);\n\n map.remove(importDeclaration);\n }" ]
[ "public double stdev() {\n double m = mean();\n\n double total = 0;\n\n final int N = getNumElements();\n if( N <= 1 )\n throw new IllegalArgumentException(\"There must be more than one element to compute stdev\");\n\n\n for( int i = 0; i < N; i++ ) {\n double x = get(i);\n\n total += (x - m)*(x - m);\n }\n\n total /= (N-1);\n\n return Math.sqrt(total);\n }", "public void save() throws CmsException {\n\n if (hasChanges()) {\n switch (m_bundleType) {\n case PROPERTY:\n saveLocalization();\n saveToPropertyVfsBundle();\n break;\n\n case XML:\n saveLocalization();\n saveToXmlVfsBundle();\n\n break;\n\n case DESCRIPTOR:\n break;\n default:\n throw new IllegalArgumentException();\n }\n if (null != m_descFile) {\n saveToBundleDescriptor();\n }\n\n resetChanges();\n }\n\n }", "protected void _format(EObject obj, IFormattableDocument document) {\n\t\tfor (EObject child : obj.eContents())\n\t\t\tdocument.format(child);\n\t}", "public void addDataSource(int groupno, DataSource datasource) {\n // the loader takes care of validation\n if (groupno == 0)\n datasources.add(datasource);\n else if (groupno == 1)\n group1.add(datasource);\n else if (groupno == 2)\n group2.add(datasource);\n }", "public void process(SearchDistributor distributor) {\r\n List<PossibleState> bootStrap;\r\n try {\r\n bootStrap = bfs(bootStrapMin);\r\n } catch (ModelException e) {\r\n bootStrap = new LinkedList<>();\r\n }\n\r\n List<Frontier> frontiers = new LinkedList<>();\r\n for (PossibleState p : bootStrap) {\r\n SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList);\r\n frontiers.add(dge);\r\n }\n\r\n distributor.distribute(frontiers);\r\n }", "@Override\n public final int getInt(final String key) {\n Integer result = optInt(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }", "private GraphicalIndicatorCriteria processCriteria(FieldType type)\n {\n GraphicalIndicatorCriteria criteria = new GraphicalIndicatorCriteria(m_properties);\n criteria.setLeftValue(type);\n\n int indicatorType = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n criteria.setIndicator(indicatorType);\n\n if (m_dataOffset + 4 < m_data.length)\n {\n int operatorValue = MPPUtility.getInt(m_data, m_dataOffset);\n m_dataOffset += 4;\n TestOperator operator = (operatorValue == 0 ? TestOperator.IS_ANY_VALUE : TestOperator.getInstance(operatorValue - 0x3E7));\n criteria.setOperator(operator);\n\n if (operator != TestOperator.IS_ANY_VALUE)\n {\n processOperandValue(0, type, criteria);\n\n if (operator == TestOperator.IS_WITHIN || operator == TestOperator.IS_NOT_WITHIN)\n {\n processOperandValue(1, type, criteria);\n }\n }\n }\n\n return (criteria);\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 }", "public static boolean invertSPD(DMatrixRMaj mat, DMatrixRMaj result ) {\n if( mat.numRows != mat.numCols )\n throw new IllegalArgumentException(\"Must be a square matrix\");\n result.reshape(mat.numRows,mat.numRows);\n\n if( mat.numRows <= UnrolledCholesky_DDRM.MAX ) {\n // L*L' = A\n if( !UnrolledCholesky_DDRM.lower(mat,result) )\n return false;\n // L = inv(L)\n TriangularSolver_DDRM.invertLower(result.data,result.numCols);\n // inv(A) = inv(L')*inv(L)\n SpecializedOps_DDRM.multLowerTranA(result);\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.chol(mat.numCols);\n if( solver.modifiesA() )\n mat = mat.copy();\n\n if( !solver.setA(mat))\n return false;\n solver.invert(result);\n }\n\n return true;\n }" ]
Do the set-up that's needed to access Amazon S3.
[ "private void init() {\n validatePreSignedUrls();\n\n try {\n conn = new AWSAuthConnection(access_key, secret_access_key);\n // Determine the bucket name if prefix is set or if pre-signed URLs are being used\n if (prefix != null && prefix.length() > 0) {\n ListAllMyBucketsResponse bucket_list = conn.listAllMyBuckets(null);\n List buckets = bucket_list.entries;\n if (buckets != null) {\n boolean found = false;\n for (Object tmp : buckets) {\n if (tmp instanceof Bucket) {\n Bucket bucket = (Bucket) tmp;\n if (bucket.name.startsWith(prefix)) {\n location = bucket.name;\n found = true;\n }\n }\n }\n if (!found) {\n location = prefix + \"-\" + java.util.UUID.randomUUID().toString();\n }\n }\n }\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n location = parsedPut.getBucket();\n }\n if (!conn.checkBucketExists(location)) {\n conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage();\n }\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3Bucket(location, e.getLocalizedMessage());\n }\n }" ]
[ "private FieldConversion[] getPkFieldConversion(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pks = cld.getPkFields();\r\n FieldConversion[] fc = new FieldConversion[pks.length]; \r\n \r\n for (int i= 0; i < pks.length; i++)\r\n {\r\n fc[i] = pks[i].getFieldConversion();\r\n }\r\n \r\n return fc;\r\n }", "public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {\n return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());\n }", "public void validate(final List<Throwable> validationErrors) {\n if (this.matchers == null) {\n validationErrors.add(new IllegalArgumentException(\n \"Matchers cannot be null. There should be at least a !acceptAll matcher\"));\n }\n if (this.matchers != null && this.matchers.isEmpty()) {\n validationErrors.add(new IllegalArgumentException(\n \"There are no url matchers defined. There should be at least a \" +\n \"!acceptAll matcher\"));\n }\n }", "public <T extends CoreLabel> Datum<String, String> makeDatum(List<IN> info, int loc, FeatureFactory featureFactory) {\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n Collection<String> features = new ArrayList<String>();\r\n List<Clique> cliques = featureFactory.getCliques();\r\n for (Clique c : cliques) {\r\n Collection<String> feats = featureFactory.getCliqueFeatures(pInfo, loc, c);\r\n feats = addOtherClasses(feats, pInfo, loc, c);\r\n features.addAll(feats);\r\n }\r\n\r\n printFeatures(pInfo.get(loc), features);\r\n CoreLabel c = info.get(loc);\r\n return new BasicDatum<String, String>(features, c.get(AnswerAnnotation.class));\r\n }", "private synchronized void finishTransition(final InternalState current, final InternalState next) {\n internalSetState(getTransitionTask(next), current, next);\n transition();\n }", "protected void deleteConflictingResources(CmsObject cms, CmsModule module, Map<CmsUUID, CmsUUID> conflictingIds)\n throws CmsException, Exception {\n\n CmsProject conflictProject = cms.createProject(\n \"Deletion of conflicting resources for \" + module.getName(),\n \"Deletion of conflicting resources for \" + module.getName(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n CmsObject deleteCms = OpenCms.initCmsObject(cms);\n deleteCms.getRequestContext().setCurrentProject(conflictProject);\n for (CmsUUID vfsId : conflictingIds.values()) {\n CmsResource toDelete = deleteCms.readResource(vfsId, CmsResourceFilter.ALL);\n lock(deleteCms, toDelete);\n deleteCms.deleteResource(toDelete, CmsResource.DELETE_PRESERVE_SIBLINGS);\n }\n OpenCms.getPublishManager().publishProject(deleteCms);\n OpenCms.getPublishManager().waitWhileRunning();\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 }", "@Override public void setModel(TableModel model)\n {\n super.setModel(model);\n int columns = model.getColumnCount();\n TableColumnModel tableColumnModel = getColumnModel();\n for (int index = 0; index < columns; index++)\n {\n tableColumnModel.getColumn(index).setPreferredWidth(m_columnWidth);\n }\n }", "public ProgressBar stop() {\n target.kill();\n try {\n thread.join();\n target.consoleStream.print(\"\\n\");\n target.consoleStream.flush();\n }\n catch (InterruptedException ex) { }\n return this;\n }" ]
Renames the current base log file to the roll file name. @param from The current base log file. @param to The backup file.
[ "private void doFileRoll(final File from, final File to) {\n final FileHelper fileHelper = FileHelper.getInstance();\n if (!fileHelper.deleteExisting(to)) {\n this.getAppender().getErrorHandler()\n .error(\"Unable to delete existing \" + to + \" for rename\");\n }\n final String original = from.toString();\n if (fileHelper.rename(from, to)) {\n LogLog.debug(\"Renamed \" + original + \" to \" + to);\n } else {\n this.getAppender().getErrorHandler()\n .error(\"Unable to rename \" + original + \" to \" + to);\n }\n }" ]
[ "public void register(Delta delta) {\n\t\tfinal IResourceDescription newDesc = delta.getNew();\n\t\tif (newDesc == null) {\n\t\t\tremoveDescription(delta.getUri());\n\t\t} else {\n\t\t\taddDescription(delta.getUri(), newDesc);\n\t\t}\n\t}", "void apply() {\n final FlushLog log = new FlushLog();\n store.logOperations(txn, log);\n final BlobVault blobVault = store.getBlobVault();\n if (blobVault.requiresTxn()) {\n try {\n blobVault.flushBlobs(blobStreams, blobFiles, deferredBlobsToDelete, txn);\n } catch (Exception e) {\n // out of disk space not expected there\n throw ExodusException.toEntityStoreException(e);\n }\n }\n txn.setCommitHook(new Runnable() {\n @Override\n public void run() {\n log.flushed();\n final EntityIterableCacheAdapterMutable cache = PersistentStoreTransaction.this.mutableCache;\n if (cache != null) { // mutableCache can be null if only blobs are modified\n applyAtomicCaches(cache);\n }\n }\n });\n }", "public void clearHandlers() {\r\n\r\n for (Map<String, CmsAttributeHandler> handlers : m_handlers) {\r\n for (CmsAttributeHandler handler : handlers.values()) {\r\n handler.clearHandlers();\r\n }\r\n handlers.clear();\r\n }\r\n m_handlers.clear();\r\n m_handlers.add(new HashMap<String, CmsAttributeHandler>());\r\n m_handlerById.clear();\r\n }", "private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) {\r\n\r\n // Validate.\r\n if ((scrollbar == m_scrollbar) || (scrollbar == null)) {\r\n return;\r\n }\r\n // Detach new child.\r\n\r\n scrollbar.asWidget().removeFromParent();\r\n // Remove old child.\r\n if (m_scrollbar != null) {\r\n if (m_verticalScrollbarHandlerRegistration != null) {\r\n m_verticalScrollbarHandlerRegistration.removeHandler();\r\n m_verticalScrollbarHandlerRegistration = null;\r\n }\r\n remove(m_scrollbar);\r\n }\r\n m_scrollLayer.appendChild(scrollbar.asWidget().getElement());\r\n adopt(scrollbar.asWidget());\r\n\r\n // Logical attach.\r\n m_scrollbar = scrollbar;\r\n m_verticalScrollbarWidth = width;\r\n\r\n // Initialize the new scrollbar.\r\n m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Integer> event) {\r\n\r\n int vPos = scrollbar.getVerticalScrollPosition();\r\n int v = getVerticalScrollPosition();\r\n if (v != vPos) {\r\n setVerticalScrollPosition(vPos);\r\n }\r\n\r\n }\r\n });\r\n maybeUpdateScrollbars();\r\n }", "public static Class getClass(String name) throws ClassNotFoundException\r\n {\r\n try\r\n {\r\n return Class.forName(name);\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ClassNotFoundException(name);\r\n }\r\n }", "public static InetAddress getLocalHost() throws UnknownHostException {\n InetAddress addr;\n try {\n addr = InetAddress.getLocalHost();\n } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404\n addr = InetAddress.getByName(null);\n }\n return addr;\n }", "private void checkAndAddLengths(final int... requiredLengths) {\n\t\tfor( final int length : requiredLengths ) {\n\t\t\tif( length < 0 ) {\n\t\t\t\tthrow new IllegalArgumentException(String.format(\"required length cannot be negative but was %d\",\n\t\t\t\t\tlength));\n\t\t\t}\n\t\t\tthis.requiredLengths.add(length);\n\t\t}\n\t}", "void backup() throws ConfigurationPersistenceException {\n if (!doneBootup.get()) {\n return;\n }\n try {\n if (!interactionPolicy.isReadOnly()) {\n //Move the main file to the versioned history\n moveFile(mainFile, getVersionedFile(mainFile));\n } else {\n //Copy the Last file to the versioned history\n moveFile(lastFile, getVersionedFile(mainFile));\n }\n int seq = sequence.get();\n // delete unwanted backup files\n int currentHistoryLength = getInteger(CURRENT_HISTORY_LENGTH_PROPERTY, CURRENT_HISTORY_LENGTH, 0);\n if (seq > currentHistoryLength) {\n for (int k = seq - currentHistoryLength; k > 0; k--) {\n File delete = getVersionedFile(mainFile, k);\n if (! delete.exists()) {\n break;\n }\n delete.delete();\n }\n }\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }", "public void setInRGB(IntRange inRGB) {\r\n this.inRed = inRGB;\r\n this.inGreen = inRGB;\r\n this.inBlue = inRGB;\r\n\r\n CalculateMap(inRGB, outRed, mapRed);\r\n CalculateMap(inRGB, outGreen, mapGreen);\r\n CalculateMap(inRGB, outBlue, mapBlue);\r\n }" ]
Use this API to fetch a vpnglobal_auditnslogpolicy_binding resources.
[ "public static vpnglobal_auditnslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_auditnslogpolicy_binding obj = new vpnglobal_auditnslogpolicy_binding();\n\t\tvpnglobal_auditnslogpolicy_binding response[] = (vpnglobal_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public int getIgnoredCount() {\n int count = 0;\n for (AggregatedTestResultEvent t : getTests()) {\n if (t.getStatus() == TestStatus.IGNORED ||\n t.getStatus() == TestStatus.IGNORED_ASSUMPTION) {\n count++;\n }\n }\n return count;\n }", "boolean applyDomainModel(ModelNode result) {\n if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {\n return false;\n }\n final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();\n return callback.applyDomainModel(bootOperations);\n }", "public byte[] join(Map<Integer, byte[]> parts) {\n checkArgument(parts.size() > 0, \"No parts provided\");\n final int[] lengths = parts.values().stream().mapToInt(v -> v.length).distinct().toArray();\n checkArgument(lengths.length == 1, \"Varying lengths of part values\");\n final byte[] secret = new byte[lengths[0]];\n for (int i = 0; i < secret.length; i++) {\n final byte[][] points = new byte[parts.size()][2];\n int j = 0;\n for (Map.Entry<Integer, byte[]> part : parts.entrySet()) {\n points[j][0] = part.getKey().byteValue();\n points[j][1] = part.getValue()[i];\n j++;\n }\n secret[i] = GF256.interpolate(points);\n }\n return secret;\n }", "void registerAlias(FieldType type, String alias)\n {\n m_aliasMap.put(new Pair<FieldTypeClass, String>(type.getFieldTypeClass(), alias), type);\n }", "protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }", "@Api\n\tpublic void setNamedRoles(Map<String, List<NamedRoleInfo>> namedRoles) {\n\t\tthis.namedRoles = namedRoles;\n\t\tldapRoleMapping = new HashMap<String, Set<String>>();\n\t\tfor (String roleName : namedRoles.keySet()) {\n\t\t\tif (!ldapRoleMapping.containsKey(roleName)) {\n\t\t\t\tldapRoleMapping.put(roleName, new HashSet<String>());\n\t\t\t}\n\t\t\tfor (NamedRoleInfo role : namedRoles.get(roleName)) {\n\t\t\t\tldapRoleMapping.get(roleName).add(role.getName());\n\t\t\t}\n\t\t}\n\t}", "protected void postConnection(ConnectionHandle handle, long statsObtainTime){\r\n\r\n\t\thandle.renewConnection(); // mark it as being logically \"open\"\r\n\r\n\t\t// Give an application a chance to do something with it.\r\n\t\tif (handle.getConnectionHook() != null){\r\n\t\t\thandle.getConnectionHook().onCheckOut(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.closeConnectionWatch){ // a debugging tool\r\n\t\t\tthis.pool.watchConnection(handle);\r\n\t\t}\r\n\r\n\t\tif (this.pool.statisticsEnabled){\r\n\t\t\tthis.pool.statistics.addCumulativeConnectionWaitTime(System.nanoTime()-statsObtainTime);\r\n\t\t}\r\n\t}", "protected String consumeQuoted(ImapRequestLineReader request)\n throws ProtocolException {\n // The 1st character must be '\"'\n consumeChar(request, '\"');\n\n StringBuilder quoted = new StringBuilder();\n char next = request.nextChar();\n while (next != '\"') {\n if (next == '\\\\') {\n request.consume();\n next = request.nextChar();\n if (!isQuotedSpecial(next)) {\n throw new ProtocolException(\"Invalid escaped character in quote: '\" +\n next + '\\'');\n }\n }\n quoted.append(next);\n request.consume();\n next = request.nextChar();\n }\n\n consumeChar(request, '\"');\n\n return quoted.toString();\n }", "private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }" ]
Make a string with the shader layout for a uniform block with a given descriptor. The format of the descriptor is the same as for a @{link GVRShaderData} - a string of types and names of each field. <p> This function will return a Vulkan shader layout if the Vulkan renderer is being used. Otherwise, it returns an OpenGL layout. @param descriptor string with types and names of each field @param blockName name of uniform block @param useUBO true to output uniform buffer layout, false for push constants @return string with shader declaration
[ "static String makeLayout(String descriptor, String blockName, boolean useUBO)\n {\n return NativeShaderManager.makeLayout(descriptor, blockName, useUBO);\n }" ]
[ "public void applyPattern(String primaryPattern, String[] alternativePatterns, char decimalSeparator, char groupingSeparator)\n {\n m_symbols.setDecimalSeparator(decimalSeparator);\n m_symbols.setGroupingSeparator(groupingSeparator);\n\n setDecimalFormatSymbols(m_symbols);\n applyPattern(primaryPattern);\n\n if (alternativePatterns != null && alternativePatterns.length != 0)\n {\n int loop;\n if (m_alternativeFormats == null || m_alternativeFormats.length != alternativePatterns.length)\n {\n m_alternativeFormats = new DecimalFormat[alternativePatterns.length];\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop] = new DecimalFormat();\n }\n }\n\n for (loop = 0; loop < alternativePatterns.length; loop++)\n {\n m_alternativeFormats[loop].setDecimalFormatSymbols(m_symbols);\n m_alternativeFormats[loop].applyPattern(alternativePatterns[loop]);\n }\n }\n }", "public String invokeOperation(String operationName, Map<String, String[]> parameterMap)\n throws JMException, UnsupportedEncodingException {\n MBeanOperationInfo operationInfo = getOperationInfo(operationName);\n MBeanOperationInvoker invoker = createMBeanOperationInvoker(mBeanServer, objectName, operationInfo);\n return sanitizer.escapeValue(invoker.invokeOperation(parameterMap));\n }", "public static Object objectify(ObjectMapper mapper, Object source) {\n return objectify(mapper, source, Object.class);\n }", "@Override\n public void close() throws VoldemortException {\n logger.debug(\"Close called for read-only store.\");\n this.fileModificationLock.writeLock().lock();\n\n try {\n if(isOpen) {\n this.isOpen = false;\n fileSet.close();\n } else {\n logger.debug(\"Attempt to close already closed store \" + getName());\n }\n } finally {\n this.fileModificationLock.writeLock().unlock();\n }\n }", "public static PredicateExpression nin(Object... rhs) {\n PredicateExpression ex = new PredicateExpression(\"$nin\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\n }", "public static nstrafficdomain_binding[] get(nitro_service service, Long td[]) throws Exception{\n\t\tif (td !=null && td.length>0) {\n\t\t\tnstrafficdomain_binding response[] = new nstrafficdomain_binding[td.length];\n\t\t\tnstrafficdomain_binding obj[] = new nstrafficdomain_binding[td.length];\n\t\t\tfor (int i=0;i<td.length;i++) {\n\t\t\t\tobj[i] = new nstrafficdomain_binding();\n\t\t\t\tobj[i].set_td(td[i]);\n\t\t\t\tresponse[i] = (nstrafficdomain_binding) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}", "private Object runWithPossibleProxySwap(Method method, Object target, Object[] args)\n\t\t\tthrows IllegalAccessException, InvocationTargetException {\n\t\tObject result;\n\t\t// swap with proxies to these too.\n\t\tif (method.getName().equals(\"createStatement\")){\n\t\t\tresult = memorize((Statement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareStatement\")){\n\t\t\tresult = memorize((PreparedStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse if (method.getName().equals(\"prepareCall\")){\n\t\t\tresult = memorize((CallableStatement)method.invoke(target, args), this.connectionHandle.get());\n\t\t}\n\t\telse result = method.invoke(target, args);\n\t\treturn result;\n\t}", "public static int colorSpline(int x, int numKnots, int[] xknots, int[] yknots) {\n\t\tint span;\n\t\tint numSpans = numKnots - 3;\n\t\tfloat k0, k1, k2, k3;\n\t\tfloat c0, c1, c2, c3;\n\t\t\n\t\tif (numSpans < 1)\n\t\t\tthrow new IllegalArgumentException(\"Too few knots in spline\");\n\t\t\n\t\tfor (span = 0; span < numSpans; span++)\n\t\t\tif (xknots[span+1] > x)\n\t\t\t\tbreak;\n\t\tif (span > numKnots-3)\n\t\t\tspan = numKnots-3;\n\t\tfloat t = (float)(x-xknots[span]) / (xknots[span+1]-xknots[span]);\n\t\tspan--;\n\t\tif (span < 0) {\n\t\t\tspan = 0;\n\t\t\tt = 0;\n\t\t}\n\n\t\tint v = 0;\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint shift = i * 8;\n\t\t\t\n\t\t\tk0 = (yknots[span] >> shift) & 0xff;\n\t\t\tk1 = (yknots[span+1] >> shift) & 0xff;\n\t\t\tk2 = (yknots[span+2] >> shift) & 0xff;\n\t\t\tk3 = (yknots[span+3] >> shift) & 0xff;\n\t\t\t\n\t\t\tc3 = m00*k0 + m01*k1 + m02*k2 + m03*k3;\n\t\t\tc2 = m10*k0 + m11*k1 + m12*k2 + m13*k3;\n\t\t\tc1 = m20*k0 + m21*k1 + m22*k2 + m23*k3;\n\t\t\tc0 = m30*k0 + m31*k1 + m32*k2 + m33*k3;\n\t\t\tint n = (int)(((c3*t + c2)*t + c1)*t + c0);\n\t\t\tif (n < 0)\n\t\t\t\tn = 0;\n\t\t\telse if (n > 255)\n\t\t\t\tn = 255;\n\t\t\tv |= n << shift;\n\t\t}\n\t\t\n\t\treturn v;\n\t}", "private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }" ]
Removes a value from the list box. Nothing is done if the value isn't on the list box. @param value the value to be removed from the list @param reload perform a 'material select' reload to update the DOM.
[ "public void removeValue(T value, boolean reload) {\n int idx = getIndex(value);\n if (idx >= 0) {\n removeItemInternal(idx, reload);\n }\n }" ]
[ "public static final char getChar(Locale locale, String key)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);\n return (bundle.getString(key).charAt(0));\n }", "public static Polygon calculateBounds(final MapfishMapContext context) {\n double rotation = context.getRootContext().getRotation();\n ReferencedEnvelope env = context.getRootContext().toReferencedEnvelope();\n\n Coordinate centre = env.centre();\n AffineTransform rotateInstance = AffineTransform.getRotateInstance(rotation, centre.x, centre.y);\n\n double[] dstPts = new double[8];\n double[] srcPts = {\n env.getMinX(), env.getMinY(), env.getMinX(), env.getMaxY(),\n env.getMaxX(), env.getMaxY(), env.getMaxX(), env.getMinY()\n };\n\n rotateInstance.transform(srcPts, 0, dstPts, 0, 4);\n\n return new GeometryFactory().createPolygon(new Coordinate[]{\n new Coordinate(dstPts[0], dstPts[1]), new Coordinate(dstPts[2], dstPts[3]),\n new Coordinate(dstPts[4], dstPts[5]), new Coordinate(dstPts[6], dstPts[7]),\n new Coordinate(dstPts[0], dstPts[1])\n });\n }", "protected List<CRFDatum> extractDatumSequence(int[][][] allData, int beginPosition, int endPosition,\r\n List<IN> labeledWordInfos) {\r\n List<CRFDatum> result = new ArrayList<CRFDatum>();\r\n int beginContext = beginPosition - windowSize + 1;\r\n if (beginContext < 0) {\r\n beginContext = 0;\r\n }\r\n // for the beginning context, add some dummy datums with no features!\r\n // TODO: is there any better way to do this?\r\n for (int position = beginContext; position < beginPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n cliqueFeatures.add(Collections.<String>emptyList());\r\n }\r\n CRFDatum<Collection<String>, String> datum = new CRFDatum<Collection<String>, String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n // now add the real datums\r\n for (int position = beginPosition; position <= endPosition; position++) {\r\n List<Collection<String>> cliqueFeatures = new ArrayList<Collection<String>>();\r\n for (int i = 0; i < windowSize; i++) {\r\n // create a feature list\r\n Collection<String> features = new ArrayList<String>();\r\n for (int j = 0; j < allData[position][i].length; j++) {\r\n features.add(featureIndex.get(allData[position][i][j]));\r\n }\r\n cliqueFeatures.add(features);\r\n }\r\n CRFDatum<Collection<String>,String> datum = new CRFDatum<Collection<String>,String>(cliqueFeatures,\r\n labeledWordInfos.get(position).get(AnswerAnnotation.class));\r\n result.add(datum);\r\n }\r\n return result;\r\n }", "public void recordGetAllTime(long timeNS,\n int requested,\n int returned,\n long totalValueBytes,\n long totalKeyBytes) {\n recordTime(Tracked.GET_ALL,\n timeNS,\n requested - returned,\n totalValueBytes,\n totalKeyBytes,\n requested);\n }", "@Override\r\n public boolean containsKey(Object key) {\r\n // key could be not in original or in deltaMap\r\n // key could be not in original but in deltaMap\r\n // key could be in original but removed from deltaMap\r\n // key could be in original but mapped to something else in deltaMap\r\n Object value = deltaMap.get(key);\r\n if (value == null) {\r\n return originalMap.containsKey(key);\r\n }\r\n if (value == removedValue) {\r\n return false;\r\n }\r\n return true;\r\n }", "public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K, ? extends V> self) {\n return Collections.unmodifiableSortedMap(self);\n }", "protected void update(float scale) {\n GVRSceneObject owner = getOwnerObject();\n if (isEnabled() && (owner != null) && owner.isEnabled())\n {\n float w = getWidth();\n float h = getHeight();\n mPose.update(mARPlane.getCenterPose(), scale);\n Matrix4f m = new Matrix4f();\n m.set(mPose.getPoseMatrix());\n m.scaleLocal(w * 0.95f, h * 0.95f, 1.0f);\n owner.getTransform().setModelMatrix(m);\n }\n }", "public List<com.groupon.odo.proxylib.models.Method> getMethodsNotInGroup(int groupId) throws Exception {\n List<com.groupon.odo.proxylib.models.Method> allMethods = getAllMethods();\n List<com.groupon.odo.proxylib.models.Method> methodsNotInGroup = new ArrayList<com.groupon.odo.proxylib.models.Method>();\n List<com.groupon.odo.proxylib.models.Method> methodsInGroup = editService.getMethodsFromGroupId(groupId, null);\n\n for (int i = 0; i < allMethods.size(); i++) {\n boolean add = true;\n String methodName = allMethods.get(i).getMethodName();\n String className = allMethods.get(i).getClassName();\n\n for (int j = 0; j < methodsInGroup.size(); j++) {\n if ((methodName.equals(methodsInGroup.get(j).getMethodName())) &&\n (className.equals(methodsInGroup.get(j).getClassName()))) {\n add = false;\n }\n }\n if (add) {\n methodsNotInGroup.add(allMethods.get(i));\n }\n }\n return methodsNotInGroup;\n }", "public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }" ]
Finds out which dump files of the given type are available for download. The result is a list of objects that describe the available dump files, in descending order by their date. Not all of the dumps included might be actually available. @return list of objects that provide information on available full dumps
[ "List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) {\n\t\tList<String> dumpFileDates = findDumpDatesOnline(dumpContentType);\n\n\t\tList<MwDumpFile> result = new ArrayList<>();\n\n\t\tfor (String dateStamp : dumpFileDates) {\n\t\t\tif (dumpContentType == DumpContentType.DAILY) {\n\t\t\t\tresult.add(new WmfOnlineDailyDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager));\n\t\t\t} else if (dumpContentType == DumpContentType.JSON) {\n\t\t\t\tresult.add(new JsonOnlineDumpFile(dateStamp, this.projectName,\n\t\t\t\t\t\tthis.webResourceFetcher, this.dumpfileDirectoryManager));\n\t\t\t} else {\n\t\t\t\tresult.add(new WmfOnlineStandardDumpFile(dateStamp,\n\t\t\t\t\t\tthis.projectName, this.webResourceFetcher,\n\t\t\t\t\t\tthis.dumpfileDirectoryManager, dumpContentType));\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(\"Found \" + result.size() + \" online dumps of type \"\n\t\t\t\t+ dumpContentType + \": \" + result);\n\n\t\treturn result;\n\t}" ]
[ "public static void pow(ComplexPolar_F64 a , int N , ComplexPolar_F64 result )\n {\n result.r = Math.pow(a.r,N);\n result.theta = N*a.theta;\n }", "public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\n }", "public static ComplexNumber Function2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) {\n\n double X = x * Math.cos(orientation) + y * Math.sin(orientation);\n double Y = -x * Math.sin(orientation) + y * Math.cos(orientation);\n\n double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance)));\n double real = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset);\n double imaginary = Math.sin(2 * Math.PI * (X / wavelength) + phaseOffset);\n\n return new ComplexNumber(envelope * real, envelope * imaginary);\n }", "public void addCommandClass(ZWaveCommandClass commandClass) {\r\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\r\n\t\tif (!supportedCommandClasses.containsKey(key)) {\r\n\t\t\tsupportedCommandClasses.put(key, commandClass);\r\n\t\t}\r\n\t}", "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 List<Response> bulk(List<?> objects, boolean allOrNothing) {\n assertNotEmpty(objects, \"objects\");\n InputStream responseStream = null;\n HttpConnection connection;\n try {\n final JsonObject jsonObject = new JsonObject();\n if(allOrNothing) {\n jsonObject.addProperty(\"all_or_nothing\", true);\n }\n final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri();\n jsonObject.add(\"docs\", getGson().toJsonTree(objects));\n connection = Http.POST(uri, \"application/json\");\n if (jsonObject.toString().length() != 0) {\n connection.setRequestBody(jsonObject.toString());\n }\n couchDbClient.execute(connection);\n responseStream = connection.responseAsInputStream();\n List<Response> bulkResponses = getResponseList(responseStream, getGson(),\n DeserializationTypes.LC_RESPONSES);\n for(Response response : bulkResponses) {\n response.setStatusCode(connection.getConnection().getResponseCode());\n }\n return bulkResponses;\n }\n catch (IOException e) {\n throw new CouchDbException(\"Error retrieving response input stream.\", e);\n } finally {\n close(responseStream);\n }\n }", "private void registerPerformanceMonitor(String beanName,\n BeanDefinitionRegistry registry) {\n\n String perfMonitorName = beanName + \"PerformanceMonitor\";\n if (!registry.containsBeanDefinition(perfMonitorName)) {\n BeanDefinitionBuilder initializer =\n BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);\n registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());\n }\n }", "public void end(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n LOG.info(\"Called end with key: \" + key + \" without ever calling begin\");\n return;\n }\n data.end();\n }", "public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }" ]
Read an unsigned integer from the given byte array @param bytes The bytes to read from @param offset The offset to begin reading at @return The integer as a long
[ "public static long readUnsignedInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xffL) << 24) | ((bytes[offset + 1] & 0xffL) << 16)\n | ((bytes[offset + 2] & 0xffL) << 8) | (bytes[offset + 3] & 0xffL));\n }" ]
[ "public static String parseString(String value)\n {\n if (value != null)\n {\n // Strip angle brackets if present\n if (!value.isEmpty() && value.charAt(0) == '<')\n {\n value = value.substring(1, value.length() - 1);\n }\n\n // Strip quotes if present\n if (!value.isEmpty() && value.charAt(0) == '\"')\n {\n value = value.substring(1, value.length() - 1);\n }\n }\n return value;\n }", "private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }", "protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }", "public static void launchPermissionSettings(Activity activity) {\n Intent intent = new Intent();\n intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n intent.setData(Uri.fromParts(\"package\", activity.getPackageName(), null));\n activity.startActivity(intent);\n }", "private Query getReportQueryByCriteriaCount(ReportQueryByCriteria aQuery)\r\n {\r\n ReportQueryByCriteria countQuery = (ReportQueryByCriteria) getQueryByCriteriaCount(aQuery);\r\n\r\n // BRJ: keep the original columns to build the Join\r\n countQuery.setJoinAttributes(aQuery.getAttributes());\r\n\r\n // BRJ: we have to preserve groupby information\r\n Iterator iter = aQuery.getGroupBy().iterator();\r\n while(iter.hasNext())\r\n {\r\n countQuery.addGroupBy((FieldHelper) iter.next());\r\n }\r\n\r\n return countQuery;\r\n }", "public synchronized void stop() {\r\n\r\n if (m_thread != null) {\r\n long timeBeforeShutdownWasCalled = System.currentTimeMillis();\r\n JLANServer.shutdownServer(new String[] {});\r\n while (m_thread.isAlive()\r\n && ((System.currentTimeMillis() - timeBeforeShutdownWasCalled) < MAX_SHUTDOWN_WAIT_MILLIS)) {\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException e) {\r\n // ignore\r\n }\r\n }\r\n }\r\n\r\n }", "private static Class<?> getGenericReturnType(Method method, Class<?> source, int typeIndex, int nestingLevel) {\n\t\treturn extractType(method.getGenericReturnType(), source, typeIndex, null, null, nestingLevel, 1);\n\t}", "@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }", "protected Element createLineElement(float x1, float y1, float x2, float y2)\n {\n HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2);\n String color = colorString(getGraphicsState().getStrokingColor());\n\n StringBuilder pstyle = new StringBuilder(50);\n pstyle.append(\"left:\").append(style.formatLength(line.getLeft())).append(';');\n pstyle.append(\"top:\").append(style.formatLength(line.getTop())).append(';');\n pstyle.append(\"width:\").append(style.formatLength(line.getWidth())).append(';');\n pstyle.append(\"height:\").append(style.formatLength(line.getHeight())).append(';');\n pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(\" solid \").append(color).append(';');\n if (line.getAngleDegrees() != 0)\n pstyle.append(\"transform:\").append(\"rotate(\").append(line.getAngleDegrees()).append(\"deg);\");\n\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }" ]
read broker info for watching topics @param zkClient the zookeeper client @param topics topic names @return topic-&gt;(brokerid-0,brokerid-1...brokerid2-0,brokerid2-1...)
[ "public static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) {\n Map<String, List<String>> ret = new HashMap<String, List<String>>();\n for (String topic : topics) {\n List<String> partList = new ArrayList<String>();\n List<String> brokers = getChildrenParentMayNotExist(zkClient, BrokerTopicsPath + \"/\" + topic);\n if (brokers != null) {\n for (String broker : brokers) {\n final String parts = readData(zkClient, BrokerTopicsPath + \"/\" + topic + \"/\" + broker);\n int nParts = Integer.parseInt(parts);\n for (int i = 0; i < nParts; i++) {\n partList.add(broker + \"-\" + i);\n }\n }\n }\n Collections.sort(partList);\n ret.put(topic, partList);\n }\n return ret;\n }" ]
[ "public static Searcher get(String variant) {\n final Searcher searcher = instances.get(variant);\n if (searcher == null) {\n throw new IllegalStateException(Errors.SEARCHER_GET_BEFORE_CREATE);\n }\n return searcher;\n }", "public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeInsert: \" + obj);\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n PreparedStatement stmt = null;\r\n try\r\n {\r\n stmt = sm.getInsertStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getInsertStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getInsertStatement returned a null statement\");\r\n }\r\n // before bind values perform autoincrement sequence columns\r\n assignAutoincrementSequences(cld, obj);\r\n sm.bindInsert(stmt, cld, obj);\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeInsert: \" + stmt);\r\n stmt.executeUpdate();\r\n // after insert read and assign identity columns\r\n assignAutoincrementIdentityColumns(cld, obj);\r\n\r\n // Harvest any return values.\r\n harvestReturnValues(cld.getInsertProcedure(), obj, stmt);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n logger.error(\"PersistenceBrokerException during the execution of the insert: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch(SequenceManagerException e)\r\n {\r\n throw new PersistenceBrokerException(\"Error while try to assign identity value\", e);\r\n }\r\n catch (SQLException e)\r\n {\r\n final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();\r\n throw ExceptionHelper.generateException(e, sql, cld, logger, obj);\r\n }\r\n finally\r\n {\r\n sm.closeResources(stmt, null);\r\n }\r\n }", "public static Set<Annotation> filterInterceptorBindings(BeanManagerImpl beanManager, Collection<Annotation> annotations) {\n Set<Annotation> interceptorBindings = new InterceptorBindingSet(beanManager);\n for (Annotation annotation : annotations) {\n if (beanManager.isInterceptorBinding(annotation.annotationType())) {\n interceptorBindings.add(annotation);\n }\n }\n return interceptorBindings;\n }", "public static BoxRetentionPolicyAssignment.Info createAssignmentToEnterprise(BoxAPIConnection api,\r\n String policyID) {\r\n return createAssignment(api, policyID, new JsonObject().add(\"type\", TYPE_ENTERPRISE), null);\r\n }", "public int getNumWeights() {\r\n if (weights == null) return 0;\r\n int numWeights = 0;\r\n for (double[] wts : weights) {\r\n numWeights += wts.length;\r\n }\r\n return numWeights;\r\n }", "public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {\n\t\tMap<Double, RandomVariable> sum = new HashMap<>();\n\n\t\tfor(double time: timeDiscretization) {\n\t\t\tsum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));\n\t\t}\n\n\t\treturn new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);\n\t}", "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 }", "public List<Integer> getPathOrder(int profileId) {\n ArrayList<Integer> pathOrder = new ArrayList<Integer>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \"\n + Constants.DB_TABLE_PATH + \" WHERE \"\n + Constants.GENERIC_PROFILE_ID + \" = ? \"\n + \" ORDER BY \" + Constants.PATH_PROFILE_PATH_ORDER + \" ASC\"\n );\n queryStatement.setInt(1, profileId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n pathOrder.add(results.getInt(Constants.GENERIC_ID));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n logger.info(\"pathOrder = {}\", pathOrder);\n return pathOrder;\n }", "public void removeExpiration() {\n\n if (getFilterQueries() != null) {\n for (String fq : getFilterQueries()) {\n if (fq.startsWith(CmsSearchField.FIELD_DATE_EXPIRED + \":\")\n || fq.startsWith(CmsSearchField.FIELD_DATE_RELEASED + \":\")) {\n removeFilterQuery(fq);\n }\n }\n }\n m_ignoreExpiration = true;\n }" ]
Evaluates the animation with the given index at the specified time. @param animIndex 0-based index of {@link GVRAnimator} to start @param timeInSec time to evaluate the animation at @see GVRAvatar#stop() @see #start(String)
[ "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 synchronized Object[] getIds() {\n String[] keys = getAllKeys();\n int size = keys.length + indexedProps.size();\n Object[] res = new Object[size];\n System.arraycopy(keys, 0, res, 0, keys.length);\n int i = keys.length;\n // now add all indexed properties\n for (Object index : indexedProps.keySet()) {\n res[i++] = index;\n }\n return res;\n }", "private YearQuarter with(int newYear, Quarter newQuarter) {\n if (year == newYear && quarter == newQuarter) {\n return this;\n }\n return new YearQuarter(newYear, newQuarter);\n }", "public static CustomInfo getOrCreateCustomInfo(Message message) {\n CustomInfo customInfo = message.get(CustomInfo.class);\n if (customInfo == null) {\n customInfo = new CustomInfo();\n message.put(CustomInfo.class, customInfo);\n }\n return customInfo;\n }", "public List<RoutableDestination<T>> getDestinations(String path) {\n\n String cleanPath = (path.endsWith(\"/\") && path.length() > 1)\n ? path.substring(0, path.length() - 1) : path;\n\n List<RoutableDestination<T>> result = new ArrayList<>();\n\n for (ImmutablePair<Pattern, RouteDestinationWithGroups> patternRoute : patternRouteList) {\n Map<String, String> groupNameValuesBuilder = new HashMap<>();\n Matcher matcher = patternRoute.getFirst().matcher(cleanPath);\n if (matcher.matches()) {\n int matchIndex = 1;\n for (String name : patternRoute.getSecond().getGroupNames()) {\n String value = matcher.group(matchIndex);\n groupNameValuesBuilder.put(name, value);\n matchIndex++;\n }\n result.add(new RoutableDestination<>(patternRoute.getSecond().getDestination(), groupNameValuesBuilder));\n }\n }\n return result;\n }", "@Override\n\tpublic Result getResult() throws Exception {\n\t\tResult returnResult = result;\n\n\t\t// If we've chained to other Actions, we need to find the last result\n\t\twhile (returnResult instanceof ActionChainResult) {\n\t\t\tActionProxy aProxy = ((ActionChainResult) returnResult).getProxy();\n\n\t\t\tif (aProxy != null) {\n\t\t\t\tResult proxyResult = aProxy.getInvocation().getResult();\n\n\t\t\t\tif ((proxyResult != null) && (aProxy.getExecuteResult())) {\n\t\t\t\t\treturnResult = proxyResult;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn returnResult;\n\t}", "public Map<String, MBeanAttributeInfo> getAttributeMetadata() {\n\n MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes();\n\n Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>();\n for (MBeanAttributeInfo attribute: attributeList) {\n attributeMap.put(attribute.getName(), attribute);\n }\n return attributeMap;\n }", "public static void validateClusterPartitionState(final Cluster subsetCluster,\n final Cluster supersetCluster) {\n if(!supersetCluster.getNodeIds().containsAll(subsetCluster.getNodeIds())) {\n throw new VoldemortException(\"Superset cluster does not contain all nodes from subset cluster[ subset cluster node ids (\"\n + subsetCluster.getNodeIds()\n + \") are not a subset of superset cluster node ids (\"\n + supersetCluster.getNodeIds() + \") ]\");\n\n }\n for(int nodeId: subsetCluster.getNodeIds()) {\n Node supersetNode = supersetCluster.getNodeById(nodeId);\n Node subsetNode = subsetCluster.getNodeById(nodeId);\n if(!supersetNode.getPartitionIds().equals(subsetNode.getPartitionIds())) {\n throw new VoldemortRebalancingException(\"Partition IDs do not match between clusters for nodes with id \"\n + nodeId\n + \" : subset cluster has \"\n + subsetNode.getPartitionIds()\n + \" and superset cluster has \"\n + supersetNode.getPartitionIds());\n }\n }\n Set<Integer> nodeIds = supersetCluster.getNodeIds();\n nodeIds.removeAll(subsetCluster.getNodeIds());\n for(int nodeId: nodeIds) {\n Node supersetNode = supersetCluster.getNodeById(nodeId);\n if(!supersetNode.getPartitionIds().isEmpty()) {\n throw new VoldemortRebalancingException(\"New node \"\n + nodeId\n + \" in superset cluster already has partitions: \"\n + supersetNode.getPartitionIds());\n }\n }\n }", "public void commit() {\n if (directory == null)\n return;\n\n try {\n if (reader != null)\n reader.close();\n\n // it turns out that IndexWriter.optimize actually slows\n // searches down, because it invalidates the cache. therefore\n // not calling it any more.\n // http://www.searchworkings.org/blog/-/blogs/uwe-says%3A-is-your-reader-atomic\n // iwriter.optimize();\n\n iwriter.commit();\n openSearchers();\n } catch (IOException e) {\n throw new DukeException(e);\n }\n }", "static void cleanup(final Resource resource) {\n synchronized (resource) {\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBSYSTEM)) {\n resource.removeChild(entry.getPathElement());\n }\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBDEPLOYMENT)) {\n resource.removeChild(entry.getPathElement());\n }\n }\n }" ]
Merges information from the resource root into this resource root @param additionalResourceRoot The root to merge
[ "public void merge(final ResourceRoot additionalResourceRoot) {\n if(!additionalResourceRoot.getRoot().equals(root)) {\n throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot());\n }\n usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource;\n if(additionalResourceRoot.getExportFilters().isEmpty()) {\n //new root has no filters, so we don't want our existing filters to break anything\n //see WFLY-1527\n this.exportFilters.clear();\n } else {\n this.exportFilters.addAll(additionalResourceRoot.getExportFilters());\n }\n }" ]
[ "@Nonnull\n private ReferencedEnvelope getFeatureBounds(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final MapAttributeValues mapValues, final ExecutionContext context) {\n final MapfishMapContext mapContext = createMapContext(mapValues);\n\n String layerName = mapValues.zoomToFeatures.layer;\n ReferencedEnvelope bounds = new ReferencedEnvelope();\n for (MapLayer layer: mapValues.getLayers()) {\n context.stopIfCanceled();\n\n if ((!StringUtils.isEmpty(layerName) && layerName.equals(layer.getName())) ||\n (StringUtils.isEmpty(layerName) && layer instanceof AbstractFeatureSourceLayer)) {\n AbstractFeatureSourceLayer featureLayer = (AbstractFeatureSourceLayer) layer;\n FeatureSource<?, ?> featureSource =\n featureLayer.getFeatureSource(clientHttpRequestFactory, mapContext);\n FeatureCollection<?, ?> features;\n try {\n features = featureSource.getFeatures();\n } catch (IOException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n\n if (!features.isEmpty()) {\n final ReferencedEnvelope curBounds = features.getBounds();\n bounds.expandToInclude(curBounds);\n }\n }\n }\n\n return bounds;\n }", "private static Map<String, ServerGroupDeploymentPlanResult> buildServerGroupResults(Map<UUID, DeploymentActionResult> deploymentActionResults) {\n Map<String, ServerGroupDeploymentPlanResult> serverGroupResults = new HashMap<String, ServerGroupDeploymentPlanResult>();\n\n for (Map.Entry<UUID, DeploymentActionResult> entry : deploymentActionResults.entrySet()) {\n\n UUID actionId = entry.getKey();\n DeploymentActionResult actionResult = entry.getValue();\n\n Map<String, ServerGroupDeploymentActionResult> actionResultsByServerGroup = actionResult.getResultsByServerGroup();\n for (ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup.values()) {\n String serverGroupName = serverGroupActionResult.getServerGroupName();\n\n ServerGroupDeploymentPlanResultImpl sgdpr = (ServerGroupDeploymentPlanResultImpl) serverGroupResults.get(serverGroupName);\n if (sgdpr == null) {\n sgdpr = new ServerGroupDeploymentPlanResultImpl(serverGroupName);\n serverGroupResults.put(serverGroupName, sgdpr);\n }\n\n for (Map.Entry<String, ServerUpdateResult> serverEntry : serverGroupActionResult.getResultByServer().entrySet()) {\n String serverName = serverEntry.getKey();\n ServerUpdateResult sud = serverEntry.getValue();\n ServerDeploymentPlanResultImpl sdpr = (ServerDeploymentPlanResultImpl) sgdpr.getServerResult(serverName);\n if (sdpr == null) {\n sdpr = new ServerDeploymentPlanResultImpl(serverName);\n sgdpr.storeServerResult(serverName, sdpr);\n }\n sdpr.storeServerUpdateResult(actionId, sud);\n }\n }\n }\n return serverGroupResults;\n }", "public static 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 Set<PlaybackState> getPlaybackState() {\n Set<PlaybackState> result = new HashSet<PlaybackState>(playbackStateMap.values());\n return Collections.unmodifiableSet(result);\n }", "public void registerCollectionSizeGauge(\n\t\t\tCollectionSizeGauge collectionSizeGauge) {\n\t\tString name = createMetricName(LocalTaskExecutorService.class,\n\t\t\t\t\"queue-size\");\n\t\tmetrics.register(name, collectionSizeGauge);\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 }", "private void updateCursorsInScene(GVRScene scene, boolean add) {\n synchronized (mCursors) {\n for (Cursor cursor : mCursors) {\n if (cursor.isActive()) {\n if (add) {\n addCursorToScene(cursor);\n } else {\n removeCursorFromScene(cursor);\n }\n }\n }\n }\n }", "private void writeNotes(int recordNumber, String text) throws IOException\n {\n m_buffer.setLength(0);\n\n m_buffer.append(recordNumber);\n m_buffer.append(m_delimiter);\n\n if (text != null)\n {\n String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);\n boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('\"') != -1);\n int length = note.length();\n char c;\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n\n for (int loop = 0; loop < length; loop++)\n {\n c = note.charAt(loop);\n\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\"\\\"\");\n break;\n }\n\n default:\n {\n m_buffer.append(c);\n break;\n }\n }\n }\n\n if (quote == true)\n {\n m_buffer.append('\"');\n }\n }\n\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }", "String getRangeUri(PropertyIdValue propertyIdValue) {\n\t\tString datatype = this.propertyRegister\n\t\t\t\t.getPropertyType(propertyIdValue);\n\n\t\tif (datatype == null)\n\t\t\treturn null;\n\n\t\tswitch (datatype) {\n\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.RDF_LANG_STRING;\n\t\tcase DatatypeIdValue.DT_STRING:\n\t\tcase DatatypeIdValue.DT_EXTERNAL_ID:\n\t\tcase DatatypeIdValue.DT_MATH:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.XSD_STRING;\n\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\tcase DatatypeIdValue.DT_ITEM:\n\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\tcase DatatypeIdValue.DT_LEXEME:\n\t\tcase DatatypeIdValue.DT_FORM:\n\t\tcase DatatypeIdValue.DT_SENSE:\n\t\tcase DatatypeIdValue.DT_TIME:\n\t\tcase DatatypeIdValue.DT_URL:\n\t\tcase DatatypeIdValue.DT_GEO_SHAPE:\n\t\tcase DatatypeIdValue.DT_TABULAR_DATA:\n\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\tthis.rdfConversionBuffer.addObjectProperty(propertyIdValue);\n\t\t\treturn Vocabulary.OWL_THING;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}" ]
Gets the element at the given index. @param index the index @return the element @throws IndexOutOfBoundsException if the index is out of range (<tt>index &lt; 0 || index &gt;= size()</tt>)
[ "public PathElement getElement(int index) {\n final List<PathElement> list = pathAddressList;\n return list.get(index);\n }" ]
[ "private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {\n if (eventType != null) {\n return EventTypeEnum.valueOf(eventType.name());\n }\n return EventTypeEnum.UNKNOWN;\n }", "public static base_response add(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey addresource = new sslcertkey();\n\t\taddresource.certkey = resource.certkey;\n\t\taddresource.cert = resource.cert;\n\t\taddresource.key = resource.key;\n\t\taddresource.password = resource.password;\n\t\taddresource.fipskey = resource.fipskey;\n\t\taddresource.inform = resource.inform;\n\t\taddresource.passplain = resource.passplain;\n\t\taddresource.expirymonitor = resource.expirymonitor;\n\t\taddresource.notificationperiod = resource.notificationperiod;\n\t\taddresource.bundle = resource.bundle;\n\t\treturn addresource.add_resource(client);\n\t}", "public MapBounds getRotatedBoundsAdjustedForPreciseRotatedMapSize() {\n Rectangle2D.Double paintAreaPrecise = getRotatedMapSizePrecise();\n Rectangle paintArea = new Rectangle(MapfishMapContext.rectangleDoubleToDimension(paintAreaPrecise));\n return getRotatedBounds(paintAreaPrecise, paintArea);\n }", "public static Result get(XmlFileModel key)\n {\n String cacheKey = getKey(key);\n\n Result result = null;\n CacheDocument reference = map.get(cacheKey);\n\n if (reference == null)\n return new Result(false, null);\n\n if (reference.parseFailure)\n return new Result(true, null);\n\n Document document = reference.getDocument();\n if (document == null)\n LOG.info(\"Cache miss on XML document: \" + cacheKey);\n\n return new Result(false, document);\n }", "public Record findRecordById(String id) {\n if (directory == null)\n init();\n\n Property idprop = config.getIdentityProperties().iterator().next();\n for (Record r : lookup(idprop, id))\n if (r.getValue(idprop.getName()).equals(id))\n return r;\n\n return null; // not found\n }", "private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }", "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 static GridLabelFormat fromConfig(final GridParam param) {\n if (param.labelFormat != null) {\n return new GridLabelFormat.Simple(param.labelFormat);\n } else if (param.valueFormat != null) {\n return new GridLabelFormat.Detailed(\n param.valueFormat, param.unitFormat,\n param.formatDecimalSeparator, param.formatGroupingSeparator);\n }\n return null;\n }", "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 }" ]
Call when you are done with the client @throws Exception
[ "public void destroy() throws Exception {\n if (_clientId == null) {\n return;\n }\n\n // delete the clientId here\n String uri = BASE_PROFILE + uriEncode(_profileName) + \"/\" + BASE_CLIENTS + \"/\" + _clientId;\n try {\n doDelete(uri, null);\n } catch (Exception e) {\n // some sort of error\n throw new Exception(\"Could not delete a proxy client\");\n }\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}", "protected void clearStatementCaches(boolean internalClose) {\r\n\r\n\t\tif (this.statementCachingEnabled){ // safety\r\n\r\n\t\t\tif (internalClose){\r\n\t\t\t\tthis.callableStatementCache.clear();\r\n\t\t\t\tthis.preparedStatementCache.clear();\r\n\t\t\t} else {\r\n\t\t\t\tif (this.pool.closeConnectionWatch){ // debugging enabled?\r\n\t\t\t\t\tthis.callableStatementCache.checkForProperClosure();\r\n\t\t\t\t\tthis.preparedStatementCache.checkForProperClosure();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public void bootstrap() throws Exception {\n final HostRunningModeControl runningModeControl = environment.getRunningModeControl();\n final ControlledProcessState processState = new ControlledProcessState(true);\n shutdownHook.setControlledProcessState(processState);\n ServiceTarget target = serviceContainer.subTarget();\n ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService.addService(target, processState).getValue();\n RunningStateJmx.registerMBean(controlledProcessStateService, null, runningModeControl, false);\n final HostControllerService hcs = new HostControllerService(environment, runningModeControl, authCode, processState);\n target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install();\n }", "public void warn(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.WARNING, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "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 getCompleteThrough()\n {\n Date value = (Date) getCachedValue(TaskField.COMPLETE_THROUGH);\n if (value == null)\n {\n int percentComplete = NumberHelper.getInt(getPercentageComplete());\n switch (percentComplete)\n {\n case 0:\n {\n break;\n }\n\n case 100:\n {\n value = getActualFinish();\n break;\n }\n\n default:\n {\n Date actualStart = getActualStart();\n Duration duration = getDuration();\n if (actualStart != null && duration != null)\n {\n double durationValue = (duration.getDuration() * percentComplete) / 100d;\n duration = Duration.getInstance(durationValue, duration.getUnits());\n ProjectCalendar calendar = getEffectiveCalendar();\n value = calendar.getDate(actualStart, duration, true);\n }\n break;\n }\n }\n\n set(TaskField.COMPLETE_THROUGH, value);\n }\n return value;\n }", "public 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 }", "@JmxGetter(name = \"avgFetchEntriesNetworkTimeMs\", description = \"average time spent on network, for streaming operations\")\n public double getAvgFetchEntriesNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_ENTRIES).getAvgEventValue()\n / Time.NS_PER_MS;\n }", "public void addExportedPackages(Set<String> packages) {\n\t\tString s = (String) getMainAttributes().get(EXPORT_PACKAGE);\n\t\tWrapper<Boolean> modified = Wrapper.wrap(this.modified);\n\t\tString result = mergeIntoCommaSeparatedList(s, packages, modified, lineDelimiter);\n\t\tthis.modified = modified.get();\n\t\tgetMainAttributes().put(EXPORT_PACKAGE, result);\n\t}" ]
Check if the object has a property with the key. @param key key to check for.
[ "@Override\n public final boolean has(final String key) {\n String result = this.obj.optString(key, null);\n return result != null;\n }" ]
[ "public static void printResults(Counter<String> entityTP, Counter<String> entityFP,\r\n Counter<String> entityFN) {\r\n Set<String> entities = new TreeSet<String>();\r\n entities.addAll(entityTP.keySet());\r\n entities.addAll(entityFP.keySet());\r\n entities.addAll(entityFN.keySet());\r\n boolean printedHeader = false;\r\n for (String entity : entities) {\r\n double tp = entityTP.getCount(entity);\r\n double fp = entityFP.getCount(entity);\r\n double fn = entityFN.getCount(entity);\r\n printedHeader = printPRLine(entity, tp, fp, fn, printedHeader);\r\n }\r\n double tp = entityTP.totalCount();\r\n double fp = entityFP.totalCount();\r\n double fn = entityFN.totalCount();\r\n printedHeader = printPRLine(\"Totals\", tp, fp, fn, printedHeader);\r\n }", "public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) {\n dest.clear();\n\n if (key != null) {\n dest.key = new Key(key);\n }\n\n for (int i = 0; i < timeStamps.size(); i++) {\n long time = timeStamps.get(i);\n if (timestampTest.test(time)) {\n dest.add(time, values.get(i));\n }\n }\n }", "public static ipset_nsip_binding[] get(nitro_service service, String name) throws Exception{\n\t\tipset_nsip_binding obj = new ipset_nsip_binding();\n\t\tobj.set_name(name);\n\t\tipset_nsip_binding response[] = (ipset_nsip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static ManagementProtocolHeader parse(DataInput input) throws IOException {\n validateSignature(input);\n expectHeader(input, ManagementProtocol.VERSION_FIELD);\n int version = input.readInt();\n expectHeader(input, ManagementProtocol.TYPE);\n byte type = input.readByte();\n switch (type) {\n case ManagementProtocol.TYPE_REQUEST:\n return new ManagementRequestHeader(version, input);\n case ManagementProtocol.TYPE_RESPONSE:\n return new ManagementResponseHeader(version, input);\n case ManagementProtocol.TYPE_BYE_BYE:\n return new ManagementByeByeHeader(version);\n case ManagementProtocol.TYPE_PING:\n return new ManagementPingHeader(version);\n case ManagementProtocol.TYPE_PONG:\n return new ManagementPongHeader(version);\n default:\n throw ProtocolLogger.ROOT_LOGGER.invalidType(\"0x\" + Integer.toHexString(type));\n }\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}", "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 SimplifySpanBuild append(String text) {\n if (TextUtils.isEmpty(text)) return this;\n\n mNormalSizeText.append(text);\n mStringBuilder.append(text);\n return this;\n }", "public List<Integer> getTrackIds() {\n ArrayList<Integer> results = new ArrayList<Integer>(trackCount);\n Enumeration<? extends ZipEntry> entries = zipFile.entries();\n while (entries.hasMoreElements()) {\n ZipEntry entry = entries.nextElement();\n if (entry.getName().startsWith(CACHE_METADATA_ENTRY_PREFIX)) {\n String idPart = entry.getName().substring(CACHE_METADATA_ENTRY_PREFIX.length());\n if (idPart.length() > 0) {\n results.add(Integer.valueOf(idPart));\n }\n }\n }\n\n return Collections.unmodifiableList(results);\n }", "public void setMat4(String key, float x1, float y1, float z1, float w1,\n float x2, float y2, float z2, float w2, float x3, float y3,\n float z3, float w3, float x4, float y4, float z4, float w4)\n {\n checkKeyIsUniform(key);\n NativeLight.setMat4(getNative(), key, x1, y1, z1, w1, x2, y2,\n z2, w2, x3, y3, z3, w3, x4, y4, z4, w4);\n }" ]
Prepare a parallel HTTP GET Task. @param url the UrlPostfix: e.g. in http://localhost:8080/index.html.,the url is "/index.html" @return the parallel task builder
[ "public ParallelTaskBuilder prepareHttpGet(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n \n cb.getHttpMeta().setHttpMethod(HttpMethod.GET);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n \n return cb;\n }" ]
[ "public static String getParameter(DbConn cnx, String key, String defaultValue)\n {\n try\n {\n return cnx.runSelectSingle(\"globalprm_select_by_key\", 3, String.class, key);\n }\n catch (NoResultException e)\n {\n return defaultValue;\n }\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 }", "public String updateContextAndGetFavoriteUrl(CmsObject cms) throws CmsException {\n\n CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION;\n CmsProject project = null;\n switch (getType()) {\n case explorerFolder:\n CmsResource folder = cms.readResource(getStructureId(), filter);\n project = cms.readProject(getProjectId());\n cms.getRequestContext().setSiteRoot(getSiteRoot());\n cms.getRequestContext().setCurrentProject(project);\n String explorerLink = CmsVaadinUtils.getWorkplaceLink()\n + \"#!\"\n + CmsFileExplorerConfiguration.APP_ID\n + \"/\"\n + getProjectId()\n + \"!!\"\n + getSiteRoot()\n + \"!!\"\n + cms.getSitePath(folder);\n return explorerLink;\n case page:\n project = cms.readProject(getProjectId());\n CmsResource target = cms.readResource(getStructureId(), filter);\n CmsResource detailContent = null;\n String link = null;\n cms.getRequestContext().setCurrentProject(project);\n cms.getRequestContext().setSiteRoot(getSiteRoot());\n if (getDetailId() != null) {\n detailContent = cms.readResource(getDetailId());\n link = OpenCms.getLinkManager().substituteLinkForUnknownTarget(\n cms,\n cms.getSitePath(detailContent),\n cms.getSitePath(target),\n false);\n } else {\n link = OpenCms.getLinkManager().substituteLink(cms, target);\n }\n return link;\n default:\n return null;\n }\n }", "public void createEnterpriseCustomFieldMap(Props props, Class<?> c)\n {\n byte[] fieldMapData = null;\n for (Integer key : ENTERPRISE_CUSTOM_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData != null)\n {\n int index = 4;\n while (index < fieldMapData.length)\n {\n //Looks like the custom fields have varying types, it may be that the last byte of the four represents the type?\n //System.out.println(ByteArrayHelper.hexdump(fieldMapData, index, 4, false));\n int typeValue = MPPUtility.getInt(fieldMapData, index);\n FieldType type = getFieldType(typeValue);\n if (type != null && type.getClass() == c && type.toString().startsWith(\"Enterprise Custom Field\"))\n {\n int varDataKey = (typeValue & 0xFFFF);\n FieldItem item = new FieldItem(type, FieldLocation.VAR_DATA, 0, 0, varDataKey, 0, 0);\n m_map.put(type, item);\n //System.out.println(item);\n }\n //System.out.println((type == null ? \"?\" : type.getClass().getSimpleName() + \".\" + type) + \" \" + Integer.toHexString(typeValue));\n\n index += 4;\n }\n }\n }", "private void writeTasks() throws JAXBException\n {\n Tasks tasks = m_factory.createTasks();\n m_plannerProject.setTasks(tasks);\n List<net.sf.mpxj.planner.schema.Task> taskList = tasks.getTask();\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task, taskList);\n }\n }", "private static void initInstance(final TransactionLogger instance, final Logger logger, final Logger auditor) {\n instance.logger = logger;\n instance.auditor = auditor;\n instance.components = new LinkedHashMap<>();\n instance.properties = new LinkedHashMap<>();\n instance.total = new Component(TOTAL_COMPONENT);\n instance.total.startTimer();\n instance.componentsMultiThread = new ComponentsMultiThread();\n instance.flowContext = FlowContextFactory.serializeNativeFlowContext();\n }", "public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n //\n // Retrieve the LHS value\n //\n FieldType field = m_leftValue;\n Object lhs;\n\n if (field == null)\n {\n lhs = null;\n }\n else\n {\n lhs = container.getCurrentValue(field);\n switch (field.getDataType())\n {\n case DATE:\n {\n if (lhs != null)\n {\n lhs = DateHelper.getDayStartDate((Date) lhs);\n }\n break;\n }\n\n case DURATION:\n {\n if (lhs != null)\n {\n Duration dur = (Duration) lhs;\n lhs = dur.convertUnits(TimeUnit.HOURS, m_properties);\n }\n else\n {\n lhs = Duration.getInstance(0, TimeUnit.HOURS);\n }\n break;\n }\n\n case STRING:\n {\n lhs = lhs == null ? \"\" : lhs;\n break;\n }\n\n default:\n {\n break;\n }\n }\n }\n\n //\n // Retrieve the RHS values\n //\n Object[] rhs;\n if (m_symbolicValues == true)\n {\n rhs = processSymbolicValues(m_workingRightValues, container, promptValues);\n }\n else\n {\n rhs = m_workingRightValues;\n }\n\n //\n // Evaluate\n //\n boolean result;\n switch (m_operator)\n {\n case AND:\n case OR:\n {\n result = evaluateLogicalOperator(container, promptValues);\n break;\n }\n\n default:\n {\n result = m_operator.evaluate(lhs, rhs);\n break;\n }\n }\n\n return result;\n }", "private void rotatorPushRight( int m )\n {\n double b11 = off[m];\n double b21 = diag[m+1];\n\n computeRotator(b21,-b11);\n\n // apply rotator on the right\n off[m] = 0;\n diag[m+1] = b21*c-b11*s;\n\n if( m+2 < N) {\n double b22 = off[m+1];\n off[m+1] = b22*c;\n bulge = b22*s;\n } else {\n bulge = 0;\n }\n\n// SimpleMatrix Q = createQ(m,m+1, c, s, true);\n// B=Q.mult(B);\n//\n// B.print();\n// printMatrix();\n// System.out.println(\" bulge = \"+bulge);\n// System.out.println();\n\n if( Ut != null ) {\n updateRotator(Ut,m,m+1,c,s);\n\n// SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print();\n// printMatrix();\n// System.out.println(\"bulge = \"+bulge);\n// System.out.println();\n }\n }", "@Nullable\n public StitchUserT getUser() {\n authLock.readLock().lock();\n try {\n return activeUser;\n } finally {\n authLock.readLock().unlock();\n }\n }" ]
Gets the health memory. @return the health memory
[ "public String getHealthMemory() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"Logging JVM Stats\\n\");\n MonitorProvider mp = MonitorProvider.getInstance();\n PerformUsage perf = mp.getJVMMemoryUsage();\n sb.append(perf.toString());\n\n if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {\n sb.append(\"========= WARNING: MEM USAGE > \" + THRESHOLD_PERCENT\n + \"!!\");\n sb.append(\" !! Live Threads List=============\\n\");\n sb.append(mp.getThreadUsage().toString());\n sb.append(\"========================================\\n\");\n sb.append(\"========================JVM Thread Dump====================\\n\");\n ThreadInfo[] threadDump = mp.getThreadDump();\n for (ThreadInfo threadInfo : threadDump) {\n sb.append(threadInfo.toString() + \"\\n\");\n }\n sb.append(\"===========================================================\\n\");\n }\n sb.append(\"Logged JVM Stats\\n\");\n\n return sb.toString();\n }" ]
[ "public static ServiceName moduleResolvedServiceName(ModuleIdentifier identifier) {\n if (!isDynamicModule(identifier)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_RESOLVED_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }", "protected void appendWhereClause(StringBuffer where, Criteria crit, StringBuffer stmt)\r\n {\r\n if (where.length() == 0)\r\n {\r\n where = null;\r\n }\r\n\r\n if (where != null || (crit != null && !crit.isEmpty()))\r\n {\r\n stmt.append(\" WHERE \");\r\n appendClause(where, crit, stmt);\r\n }\r\n }", "public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }", "public double[] getScaleDenominators() {\n double[] dest = new double[this.scaleDenominators.length];\n System.arraycopy(this.scaleDenominators, 0, dest, 0, this.scaleDenominators.length);\n return dest;\n }", "protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {\n StringBuilder baseURL = new StringBuilder();\n if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {\n baseURL.append(httpServletRequest.getContextPath());\n }\n if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {\n baseURL.append(httpServletRequest.getServletPath());\n }\n return baseURL;\n }", "public ServerSetup[] build(Properties properties) {\n List<ServerSetup> serverSetups = new ArrayList<>();\n\n String hostname = properties.getProperty(\"greenmail.hostname\", ServerSetup.getLocalHostAddress());\n long serverStartupTimeout =\n Long.parseLong(properties.getProperty(\"greenmail.startup.timeout\", \"-1\"));\n\n // Default setups\n addDefaultSetups(hostname, properties, serverSetups);\n\n // Default setups for test\n addTestSetups(hostname, properties, serverSetups);\n\n // Default setups\n for (String protocol : ServerSetup.PROTOCOLS) {\n addSetup(hostname, protocol, properties, serverSetups);\n }\n\n for (ServerSetup setup : serverSetups) {\n if (properties.containsKey(GREENMAIL_VERBOSE)) {\n setup.setVerbose(true);\n }\n if (serverStartupTimeout >= 0L) {\n setup.setServerStartupTimeout(serverStartupTimeout);\n }\n }\n\n return serverSetups.toArray(new ServerSetup[serverSetups.size()]);\n }", "public static AnalysisResult fakeSuccess() {\n return new AnalysisResult(null, new Extensions(Collections.emptyMap(), Collections.emptyMap(),\n Collections.emptyMap(), Collections.emptyMap()));\n }", "public void recordConnectionEstablishmentTimeUs(SocketDestination dest, long connEstTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordConnectionEstablishmentTimeUs(null, connEstTimeUs);\n recordConnectionEstablishmentTimeUs(null, connEstTimeUs);\n } else {\n this.connectionEstablishmentRequestCounter.addRequest(connEstTimeUs * Time.NS_PER_US);\n }\n }", "static void cleanup(final Resource resource) {\n synchronized (resource) {\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBSYSTEM)) {\n resource.removeChild(entry.getPathElement());\n }\n for (final Resource.ResourceEntry entry : resource.getChildren(SUBDEPLOYMENT)) {\n resource.removeChild(entry.getPathElement());\n }\n }\n }" ]
will trigger workers to cancel then wait for it to report back.
[ "@SuppressWarnings(\"deprecation\")\n private final void operationTimeout() {\n\n /**\n * first kill async http worker; before suicide LESSON: MUST KILL AND\n * WAIT FOR CHILDREN to reply back before kill itself.\n */\n cancelCancellable();\n if (asyncWorker != null && !asyncWorker.isTerminated()) {\n asyncWorker\n .tell(RequestWorkerMsgType.PROCESS_ON_TIMEOUT, getSelf());\n\n } else {\n logger.info(\"asyncWorker has been killed or uninitialized (null). \"\n + \"Not send PROCESS ON TIMEOUT.\\nREQ: \"\n + request.toString());\n replyErrors(PcConstants.OPERATION_TIMEOUT,\n PcConstants.OPERATION_TIMEOUT, PcConstants.NA,\n PcConstants.NA_INT);\n }\n\n }" ]
[ "public void addComparator(Comparator<T> comparator, boolean ascending) {\n\t\tthis.comparators.add(new InvertibleComparator<T>(comparator, ascending));\n\t}", "public static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }", "public boolean classifySentenceStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n while ((line = is.readLine()) != null) {\r\n \t\r\n if (line.trim().equals(\"\")) {\r\n \t text += sentence + eol;\r\n \t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n classifyAndWriteAnswers(documents, readerWriter);\r\n text = \"\";\r\n } else {\r\n \t text += line + eol;\r\n }\r\n }\r\n if (text.trim().equals(\"\")) {\r\n \treturn false;\r\n }\r\n return true;\r\n }", "protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }", "public synchronized void setMonitoredPlayer(final int player) {\n if (player < 0) {\n throw new IllegalArgumentException(\"player cannot be negative\");\n }\n clearPlaybackState();\n monitoredPlayer.set(player);\n if (player > 0) { // Start monitoring the specified player\n setPlaybackState(player, 0, false); // Start with default values for required simple state.\n VirtualCdj.getInstance().addUpdateListener(updateListener);\n MetadataFinder.getInstance().addTrackMetadataListener(metadataListener);\n cueList.set(null); // Assume the worst, but see if we have one available next.\n if (MetadataFinder.getInstance().isRunning()) {\n TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(player);\n if (metadata != null) {\n cueList.set(metadata.getCueList());\n }\n }\n WaveformFinder.getInstance().addWaveformListener(waveformListener);\n if (WaveformFinder.getInstance().isRunning() && WaveformFinder.getInstance().isFindingDetails()) {\n waveform.set(WaveformFinder.getInstance().getLatestDetailFor(player));\n } else {\n waveform.set(null);\n }\n BeatGridFinder.getInstance().addBeatGridListener(beatGridListener);\n if (BeatGridFinder.getInstance().isRunning()) {\n beatGrid.set(BeatGridFinder.getInstance().getLatestBeatGridFor(player));\n } else {\n beatGrid.set(null);\n }\n try {\n TimeFinder.getInstance().start();\n if (!animating.getAndSet(true)) {\n // Create the thread to update our position smoothly as the track plays\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (animating.get()) {\n try {\n Thread.sleep(33); // Animate at 30 fps\n } catch (InterruptedException e) {\n logger.warn(\"Waveform animation thread interrupted; ending\");\n animating.set(false);\n }\n setPlaybackPosition(TimeFinder.getInstance().getTimeFor(getMonitoredPlayer()));\n }\n }\n }).start();\n }\n } catch (Exception e) {\n logger.error(\"Unable to start the TimeFinder to animate the waveform detail view\");\n animating.set(false);\n }\n } else { // Stop monitoring any player\n animating.set(false);\n VirtualCdj.getInstance().removeUpdateListener(updateListener);\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n cueList.set(null);\n waveform.set(null);\n beatGrid.set(null);\n }\n if (!autoScroll.get()) {\n invalidate();\n }\n repaint();\n }", "public static void mainInternal(String[] args) throws Exception {\n\n Options options = new Options();\n CmdLineParser parser = new CmdLineParser(options);\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n helpScreen(parser);\n return;\n }\n\n try {\n List<String> configs = new ArrayList<>();\n if (options.configs != null) {\n configs.addAll(Arrays.asList(options.configs.split(\",\")));\n }\n ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);\n } catch (ConfigException ex) {\n ConfigLogger.error(ex);\n throw ex;\n } catch (Throwable th) {\n ConfigLogger.error(th);\n throw th;\n }\n }", "public static long addressToLong(InetAddress address) {\n long result = 0;\n for (byte element : address.getAddress()) {\n result = (result << 8) + unsign(element);\n }\n return result;\n }", "@Override\n public ImageSource apply(ImageSource input) {\n final int[][] pixelMatrix = new int[3][3];\n\n int w = input.getWidth();\n int h = input.getHeight();\n\n int[][] output = new int[h][w];\n\n for (int j = 1; j < h - 1; j++) {\n for (int i = 1; i < w - 1; i++) {\n pixelMatrix[0][0] = input.getR(i - 1, j - 1);\n pixelMatrix[0][1] = input.getRGB(i - 1, j);\n pixelMatrix[0][2] = input.getRGB(i - 1, j + 1);\n pixelMatrix[1][0] = input.getRGB(i, j - 1);\n pixelMatrix[1][2] = input.getRGB(i, j + 1);\n pixelMatrix[2][0] = input.getRGB(i + 1, j - 1);\n pixelMatrix[2][1] = input.getRGB(i + 1, j);\n pixelMatrix[2][2] = input.getRGB(i + 1, j + 1);\n\n int edge = (int) convolution(pixelMatrix);\n int rgb = (edge << 16 | edge << 8 | edge);\n output[j][i] = rgb;\n }\n }\n\n MatrixSource source = new MatrixSource(output);\n return source;\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 }" ]
Get the value for a single attribute on an MBean by name. @param attributeName the attribute name (can be URL-encoded). @return the value as a String. @throws JMException Java Management Exception @throws UnsupportedEncodingException if the encoding is not supported.
[ "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 }" ]
[ "public static final Date getTimestamp(byte[] data, int offset)\n {\n Date result;\n\n long days = getShort(data, offset + 2);\n if (days < 100)\n {\n // We are seeing some files which have very small values for the number of days.\n // When the relevant field is shown in MS Project it appears as NA.\n // We try to mimic this behaviour here.\n days = 0;\n }\n\n if (days == 0 || days == 65535)\n {\n result = null;\n }\n else\n {\n long time = getShort(data, offset);\n if (time == 65535)\n {\n time = 0;\n }\n result = DateHelper.getTimestampFromLong((EPOCH + (days * DateHelper.MS_PER_DAY) + ((time * DateHelper.MS_PER_MINUTE) / 10)));\n }\n\n return (result);\n }", "private static void displayAvailableFilters(ProjectFile project)\n {\n System.out.println(\"Unknown filter name supplied.\");\n System.out.println(\"Available task filters:\");\n for (Filter filter : project.getFilters().getTaskFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\n System.out.println(\"Available resource filters:\");\n for (Filter filter : project.getFilters().getResourceFilters())\n {\n System.out.println(\" \" + filter.getName());\n }\n\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 ComplexNumber Subtract(ComplexNumber z1, double scalar) {\r\n return new ComplexNumber(z1.real - scalar, z1.imaginary);\r\n }", "private void updateCurrencyFormats(ProjectProperties properties, char decimalSeparator, char thousandsSeparator)\n {\n String prefix = \"\";\n String suffix = \"\";\n String currencySymbol = quoteFormatCharacters(properties.getCurrencySymbol());\n\n switch (properties.getSymbolPosition())\n {\n case AFTER:\n {\n suffix = currencySymbol;\n break;\n }\n\n case BEFORE:\n {\n prefix = currencySymbol;\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n suffix = \" \" + currencySymbol;\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n prefix = currencySymbol + \" \";\n break;\n }\n }\n\n StringBuilder pattern = new StringBuilder(prefix);\n pattern.append(\"#0\");\n\n int digits = properties.getCurrencyDigits().intValue();\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n pattern.append(suffix);\n\n String primaryPattern = pattern.toString();\n\n String[] alternativePatterns = new String[7];\n alternativePatterns[0] = primaryPattern + \";(\" + primaryPattern + \")\";\n pattern.insert(prefix.length(), \"#,#\");\n String secondaryPattern = pattern.toString();\n alternativePatterns[1] = secondaryPattern;\n alternativePatterns[2] = secondaryPattern + \";(\" + secondaryPattern + \")\";\n\n pattern.setLength(0);\n pattern.append(\"#0\");\n\n if (digits > 0)\n {\n pattern.append('.');\n for (int i = 0; i < digits; i++)\n {\n pattern.append(\"0\");\n }\n }\n\n String noSymbolPrimaryPattern = pattern.toString();\n alternativePatterns[3] = noSymbolPrimaryPattern;\n alternativePatterns[4] = noSymbolPrimaryPattern + \";(\" + noSymbolPrimaryPattern + \")\";\n pattern.insert(0, \"#,#\");\n String noSymbolSecondaryPattern = pattern.toString();\n alternativePatterns[5] = noSymbolSecondaryPattern;\n alternativePatterns[6] = noSymbolSecondaryPattern + \";(\" + noSymbolSecondaryPattern + \")\";\n\n m_currencyFormat.applyPattern(primaryPattern, alternativePatterns, decimalSeparator, thousandsSeparator);\n }", "public static void plotCharts(List<Chart> charts){\n\t\tint numRows =1;\n\t\tint numCols =1;\n\t\tif(charts.size()>1){\n\t\t\tnumRows = (int) Math.ceil(charts.size()/2.0);\n\t\t\tnumCols = 2;\n\t\t}\n\t\t\n\t final JFrame frame = new JFrame(\"\");\n\t frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);\n frame.getContentPane().setLayout(new GridLayout(numRows, numCols));\n\t for (Chart chart : charts) {\n\t if (chart != null) {\n\t JPanel chartPanel = new XChartPanel(chart);\n\t frame.add(chartPanel);\n\t }\n\t else {\n\t JPanel chartPanel = new JPanel();\n\t frame.getContentPane().add(chartPanel);\n\t }\n\n\t }\n\t // Display the window.\n frame.pack();\n frame.setVisible(true);\n\t}", "protected byte[] getUpperBytesInternal() {\n\t\tbyte cached[];\n\t\tif(hasNoValueCache()) {\n\t\t\tValueCache cache = valueCache;\n\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\tif(!isMultiple()) {\n\t\t\t\tcache.lowerBytes = cached;\n\t\t\t}\n\t\t} else {\n\t\t\tValueCache cache = valueCache;\n\t\t\tif((cached = cache.upperBytes) == null) {\n\t\t\t\tif(!isMultiple()) {\n\t\t\t\t\tif((cached = cache.lowerBytes) != null) {\n\t\t\t\t\t\tcache.upperBytes = cached;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache.lowerBytes = cache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcache.upperBytes = cached = getBytesImpl(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cached;\n\t}", "public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {\r\n\r\n\t\tSwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,\r\n\t\t\t\tforwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);\r\n\t\tcombined.entryMap.putAll(entryMap);\r\n\r\n\t\tif(quotingConvention == other.quotingConvention && displacement == other.displacement) {\r\n\t\t\tcombined.entryMap.putAll(other.entryMap);\r\n\t\t} else {\r\n\t\t\tSwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);\r\n\t\t\tcombined.entryMap.putAll(converted.entryMap);\r\n\t\t}\r\n\r\n\t\treturn combined;\r\n\t}", "@Override\n public AccountingDate date(int prolepticYear, int month, int dayOfMonth) {\n return AccountingDate.of(this, prolepticYear, month, dayOfMonth);\n }" ]
Use this API to add ipset.
[ "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}" ]
[ "public Label htmlLabel(String html) {\n\n Label label = new Label();\n label.setContentMode(ContentMode.HTML);\n label.setValue(html);\n return label;\n\n }", "public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }", "private Double getDouble(Number number)\n {\n Double result = null;\n\n if (number != null)\n {\n result = Double.valueOf(number.doubleValue());\n }\n\n return result;\n }", "private BasicCredentialsProvider getCredentialsProvider() {\n return new BasicCredentialsProvider() {\n private Set<AuthScope> authAlreadyTried = Sets.newHashSet();\n\n @Override\n public Credentials getCredentials(AuthScope authscope) {\n if (authAlreadyTried.contains(authscope)) {\n return null;\n }\n authAlreadyTried.add(authscope);\n return super.getCredentials(authscope);\n }\n };\n }", "private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"classes.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\t// Add direct subclass information:\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Integer superClass : classEntry.getValue().directSuperClasses) {\n\t\t\t\t\tthis.classRecords.get(superClass).nonemptyDirectSubclasses\n\t\t\t\t\t\t\t.add(classEntry.getKey().toString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tint countNoLabel = 0;\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (classEntry.getValue().label == null) {\n\t\t\t\t\tcountNoLabel++;\n\t\t\t\t}\n\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + classEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, classEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" class items.\");\n\t\t\tSystem.out.println(\" -- class items with missing label: \"\n\t\t\t\t\t+ countNoLabel);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "private void readResourceAssignments()\n {\n for (MapRow row : getTable(\"USGTAB\"))\n {\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n Resource resource = m_projectFile.getResourceByUniqueID(row.getInteger(\"RESOURCE_ID\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n m_eventManager.fireAssignmentReadEvent(assignment);\n }\n }\n }", "public Integer getBlockMaskPrefixLength(boolean network) {\n\t\tInteger prefixLen;\n\t\tif(network) {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.networkMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t} else {\n\t\t\tif(hasNoPrefixCache() || (prefixLen = prefixCache.hostMaskPrefixLen) == null) {\n\t\t\t\tprefixLen = setHostMaskPrefix(checkForPrefixMask(network));\n\t\t\t}\n\t\t}\n\t\tif(prefixLen < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn prefixLen;\n\t}", "private void copy(InputStream input, OutputStream output) throws IOException {\n try {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = input.read(buffer);\n while (bytesRead != -1) {\n output.write(buffer, 0, bytesRead);\n bytesRead = input.read(buffer);\n }\n } finally {\n input.close();\n output.close();\n }\n }", "public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}" ]
This method is called from Javascript, passing in the previously created callback key. It uses that to find the correct handler and then passes on the call. State events in the Google Maps API don't pass any parameters. @param callbackKey Key generated by the call to registerHandler.
[ "public void handleStateEvent(String callbackKey) {\n if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {\n ((StateEventHandler) handlers.get(callbackKey)).handle();\n } else {\n System.err.println(\"Error in handle: \" + callbackKey + \" for state handler \");\n }\n }" ]
[ "public 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 String convert(BufferedImage image, boolean favicon) {\n // Reset statistics before anything\n statsArray = new int[12];\n // Begin the timer\n dStart = System.nanoTime();\n // Scale the image\n image = scale(image, favicon);\n // The +1 is for the newline characters\n StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight());\n\n for (int y = 0; y < image.getHeight(); y++) {\n // At the end of each line, add a newline character\n if (sb.length() != 0) sb.append(\"\\n\");\n for (int x = 0; x < image.getWidth(); x++) {\n //\n Color pixelColor = new Color(image.getRGB(x, y), true);\n int alpha = pixelColor.getAlpha();\n boolean isTransient = alpha < 0.1;\n double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250);\n final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue);\n sb.append(s);\n }\n }\n imgArray = sb.toString().toCharArray();\n dEnd = System.nanoTime();\n return sb.toString();\n }", "public static vpnvserver_vpnnexthopserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_vpnnexthopserver_binding obj = new vpnvserver_vpnnexthopserver_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_vpnnexthopserver_binding response[] = (vpnvserver_vpnnexthopserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void RunScript(InteractiveObject interactiveObject, String functionName, Object[] parameters) {\n boolean complete = false;\n if ( V8JavaScriptEngine) {\n GVRJavascriptV8File gvrJavascriptV8File = interactiveObject.getScriptObject().getGVRJavascriptV8File();\n String paramString = \"var params =[\";\n for (int i = 0; i < parameters.length; i++ ) {\n paramString += (parameters[i] + \", \");\n }\n paramString = paramString.substring(0, (paramString.length()-2)) + \"];\";\n\n final GVRJavascriptV8File gvrJavascriptV8FileFinal = gvrJavascriptV8File;\n final InteractiveObject interactiveObjectFinal = interactiveObject;\n final String functionNameFinal = functionName;\n final Object[] parametersFinal = parameters;\n final String paramStringFinal = paramString;\n gvrContext.runOnGlThread(new Runnable() {\n @Override\n public void run() {\n RunScriptThread (gvrJavascriptV8FileFinal, interactiveObjectFinal, functionNameFinal, parametersFinal, paramStringFinal);\n }\n });\n } // end V8JavaScriptEngine\n else {\n // Mozilla Rhino engine\n GVRJavascriptScriptFile gvrJavascriptFile = interactiveObject.getScriptObject().getGVRJavascriptScriptFile();\n\n complete = gvrJavascriptFile.invokeFunction(functionName, parameters);\n if (complete) {\n // The JavaScript (JS) ran. Now get the return\n // values (saved as X3D data types such as SFColor)\n // stored in 'localBindings'.\n // Then call SetResultsFromScript() to set the GearVR values\n Bindings localBindings = gvrJavascriptFile.getLocalBindings();\n SetResultsFromScript(interactiveObject, localBindings);\n } else {\n Log.e(TAG, \"Error in SCRIPT node '\" + interactiveObject.getScriptObject().getName() +\n \"' running Rhino Engine JavaScript function '\" + functionName + \"'\");\n }\n }\n }", "public void updateUniqueCounters()\n {\n //\n // Update task unique IDs\n //\n for (Task task : m_parent.getTasks())\n {\n int uniqueID = NumberHelper.getInt(task.getUniqueID());\n if (uniqueID > m_taskUniqueID)\n {\n m_taskUniqueID = uniqueID;\n }\n }\n\n //\n // Update resource unique IDs\n //\n for (Resource resource : m_parent.getResources())\n {\n int uniqueID = NumberHelper.getInt(resource.getUniqueID());\n if (uniqueID > m_resourceUniqueID)\n {\n m_resourceUniqueID = uniqueID;\n }\n }\n\n //\n // Update calendar unique IDs\n //\n for (ProjectCalendar calendar : m_parent.getCalendars())\n {\n int uniqueID = NumberHelper.getInt(calendar.getUniqueID());\n if (uniqueID > m_calendarUniqueID)\n {\n m_calendarUniqueID = uniqueID;\n }\n }\n\n //\n // Update assignment unique IDs\n //\n for (ResourceAssignment assignment : m_parent.getResourceAssignments())\n {\n int uniqueID = NumberHelper.getInt(assignment.getUniqueID());\n if (uniqueID > m_assignmentUniqueID)\n {\n m_assignmentUniqueID = uniqueID;\n }\n }\n }", "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\n }", "public List<Index<Field>> allIndexes() {\n List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();\n indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));\n return indexesOfAnyType;\n }", "public void removeNodeMetaData(Object key) {\n if (key==null) throw new GroovyBugError(\"Tried to remove meta data with null key \"+this+\".\");\n if (metaDataMap == null) {\n return;\n }\n metaDataMap.remove(key);\n }" ]
Compares two vectors and determines if they are numeric equals, independent of its type. @param vector1 the first vector @param vector2 the second vector @return true if the vectors are numeric equals
[ "protected static boolean numericEquals(Field vector1, Field vector2) {\n\t\tif (vector1.size() != vector2.size())\n\t\t\treturn false;\n\t\tif (vector1.isEmpty())\n\t\t\treturn true;\n\n\t\tIterator<Object> it1 = vector1.iterator();\n\t\tIterator<Object> it2 = vector2.iterator();\n\n\t\twhile (it1.hasNext()) {\n\t\t\tObject obj1 = it1.next();\n\t\t\tObject obj2 = it2.next();\n\n\t\t\tif (!(obj1 instanceof Number && obj2 instanceof Number))\n\t\t\t\treturn false;\n\n\t\t\tif (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())\n\t\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}" ]
[ "public boolean merge(final PluginXmlAccess other) {\n boolean _xblockexpression = false;\n {\n String _path = this.getPath();\n String _path_1 = other.getPath();\n boolean _notEquals = (!Objects.equal(_path, _path_1));\n if (_notEquals) {\n String _path_2 = this.getPath();\n String _plus = (\"Merging plugin.xml files with different paths: \" + _path_2);\n String _plus_1 = (_plus + \", \");\n String _path_3 = other.getPath();\n String _plus_2 = (_plus_1 + _path_3);\n PluginXmlAccess.LOG.warn(_plus_2);\n }\n _xblockexpression = this.entries.addAll(other.entries);\n }\n return _xblockexpression;\n }", "public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }", "public static int[] convertBytesToInts(byte[] bytes)\n {\n if (bytes.length % 4 != 0)\n {\n throw new IllegalArgumentException(\"Number of input bytes must be a multiple of 4.\");\n }\n int[] ints = new int[bytes.length / 4];\n for (int i = 0; i < ints.length; i++)\n {\n ints[i] = convertBytesToInt(bytes, i * 4);\n }\n return ints;\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 }", "public static Double checkLatitude(String name, Double latitude) {\n if (latitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LATITUDE,\n MAX_LATITUDE,\n latitude);\n }\n return latitude;\n }", "static int lastArgMatchesVarg(Parameter[] params, ClassNode... args) {\n if (!isVargs(params)) return -1;\n // case length ==0 handled already\n // we have now two cases,\n // the argument is wrapped in the vargs array or\n // the argument is an array that can be used for the vargs part directly\n // we test only the wrapping part, since the non wrapping is done already\n ClassNode lastParamType = params[params.length - 1].getType();\n ClassNode ptype = lastParamType.getComponentType();\n ClassNode arg = args[args.length - 1];\n if (isNumberType(ptype) && isNumberType(arg) && !ptype.equals(arg)) return -1;\n return isAssignableTo(arg, ptype)?Math.min(getDistance(arg, lastParamType), getDistance(arg, ptype)):-1;\n }", "public static authenticationradiusaction[] get(nitro_service service) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tauthenticationradiusaction[] response = (authenticationradiusaction[])obj.get_resources(service);\n\t\treturn response;\n\t}", "public static Event map(EventType eventType) {\n Event event = new Event();\n event.setEventType(mapEventTypeEnum(eventType.getEventType()));\n Date date = (eventType.getTimestamp() == null)\n ? new Date() : eventType.getTimestamp().toGregorianCalendar().getTime();\n event.setTimestamp(date);\n event.setOriginator(mapOriginatorType(eventType.getOriginator()));\n MessageInfo messageInfo = mapMessageInfo(eventType.getMessageInfo());\n event.setMessageInfo(messageInfo);\n String content = mapContent(eventType.getContent());\n event.setContent(content);\n event.getCustomInfo().clear();\n event.getCustomInfo().putAll(mapCustomInfo(eventType.getCustomInfo()));\n return event;\n }", "@Deprecated\r\n public void setViews(String views) {\r\n if (views != null) {\r\n try {\r\n setViews(Integer.parseInt(views));\r\n } catch (NumberFormatException e) {\r\n setViews(-1);\r\n }\r\n }\r\n }" ]
Use this API to fetch autoscaleprofile resource of given name .
[ "public static autoscaleprofile get(nitro_service service, String name) throws Exception{\n\t\tautoscaleprofile obj = new autoscaleprofile();\n\t\tobj.set_name(name);\n\t\tautoscaleprofile response = (autoscaleprofile) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public void setFieldByAlias(String alias, Object value)\n {\n set(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias), value);\n }", "public final void setOrientation(int orientation) {\n mOrientation = orientation;\n mOrientationState = getOrientationStateFromParam(mOrientation);\n invalidate();\n if (mOuterAdapter != null) {\n mOuterAdapter.setOrientation(mOrientation);\n }\n\n }", "public static Envelope getTileBounds(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble[] layerSize = getTileLayerSize(code, maxExtent, scale);\n\t\tif (layerSize[0] == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tdouble cX = maxExtent.getMinX() + code.getX() * layerSize[0];\n\t\tdouble cY = maxExtent.getMinY() + code.getY() * layerSize[1];\n\t\treturn new Envelope(cX, cX + layerSize[0], cY, cY + layerSize[1]);\n\t}", "public static <T> Set<T> toSet(Iterable<T> items) {\r\n Set<T> set = new HashSet<T>();\r\n addAll(set, items);\r\n return set;\r\n }", "public <V> V attachIfAbsent(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.putIfAbsent(key, value));\n }", "public void setBorderWidth(int borderWidth) {\n\t\tthis.borderWidth = borderWidth;\n\t\tif(paintBorder != null)\n\t\t\tpaintBorder.setStrokeWidth(borderWidth);\n\t\trequestLayout();\n\t\tinvalidate();\n\t}", "public ParallelTaskBuilder setHttpPollerProcessor(\n HttpPollerProcessor httpPollerProcessor) {\n this.httpMeta.setHttpPollerProcessor(httpPollerProcessor);\n this.httpMeta.setPollable(true);\n return this;\n }", "public Stats getPhotosetStats(String photosetId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTOSET_STATS, \"photoset_id\", photosetId, date);\n }", "public static void setTranslucentStatusFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);\n }\n }" ]
Prints the plan to a file. @param outputDirName @param plan
[ "public static void dumpPlanToFile(String outputDirName, RebalancePlan plan) {\n if(outputDirName != null) {\n File outputDir = new File(outputDirName);\n if(!outputDir.exists()) {\n Utils.mkdirs(outputDir);\n }\n try {\n FileUtils.writeStringToFile(new File(outputDirName, \"plan.out\"), plan.toString());\n } catch(IOException e) {\n logger.error(\"IOException during dumpPlanToFile: \" + e);\n }\n }\n }" ]
[ "public 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 T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {\n return modifyFile(name, path, existingHash, newHash, isDirectory, null);\n }", "public static int cudnnActivationForward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnActivationForwardNative(handle, activationDesc, alpha, xDesc, x, beta, yDesc, y));\n }", "private String getInitials(String name)\n {\n String result = null;\n\n if (name != null && name.length() != 0)\n {\n StringBuilder sb = new StringBuilder();\n sb.append(name.charAt(0));\n int index = 1;\n while (true)\n {\n index = name.indexOf(' ', index);\n if (index == -1)\n {\n break;\n }\n\n ++index;\n if (index < name.length() && name.charAt(index) != ' ')\n {\n sb.append(name.charAt(index));\n }\n\n ++index;\n }\n\n result = sb.toString();\n }\n\n return result;\n }", "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}", "private void fillWeekPanel() {\r\n\r\n addCheckBox(WeekOfMonth.FIRST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_1_0);\r\n addCheckBox(WeekOfMonth.SECOND.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_2_0);\r\n addCheckBox(WeekOfMonth.THIRD.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_3_0);\r\n addCheckBox(WeekOfMonth.FOURTH.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_4_0);\r\n addCheckBox(WeekOfMonth.LAST.toString(), Messages.GUI_SERIALDATE_WEEKDAYNUMBER_5_0);\r\n }", "public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) {\n Pipeline pipelined = jedis.pipelined();\n pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue);\n for (String jobJson : jobJsons) {\n pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson);\n }\n pipelined.sync();\n }", "public static String implodeObjects(Iterable<?> objects) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tboolean first = true;\n\t\tfor (Object o : objects) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tbuilder.append(\"|\");\n\t\t\t}\n\t\t\tbuilder.append(o.toString());\n\t\t}\n\t\treturn builder.toString();\n\t}", "public synchronized void resumeDeployment(final String deployment) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getDeployment().equals(deployment)) {\n ep.resume();\n }\n }\n }" ]
Classify the tokens in a String. Each sentence becomes a separate document. @param str A String with tokens in one or more sentences of text to be classified. @return {@link List} of classified sentences (each a List of something that extends {@link CoreMap}).
[ "public List<List<IN>> classify(String str) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromString(str, plainTextReaderAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n // TaggedWord word = new TaggedWord(wi.word(), wi.answer());\r\n // sentence.add(word);\r\n sentence.add(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }" ]
[ "private boolean isAbandoned(final SubmittedPrintJob printJob) {\n final long duration = ThreadPoolJobManager.this.jobQueue.timeSinceLastStatusCheck(\n printJob.getEntry().getReferenceId());\n final boolean abandoned =\n duration > TimeUnit.SECONDS.toMillis(ThreadPoolJobManager.this.abandonedTimeout);\n if (abandoned) {\n LOGGER.info(\"Job {} is abandoned (no status check within the last {} seconds)\",\n printJob.getEntry().getReferenceId(), ThreadPoolJobManager.this.abandonedTimeout);\n }\n return abandoned;\n }", "public void setSourceUrl(String newUrl, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVERS +\n \" SET \" + Constants.SERVER_REDIRECT_SRC_URL + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newUrl);\n statement.setInt(2, id);\n statement.executeUpdate();\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 }", "protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }", "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public CrosstabBuilder setColumnStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {\r\n\t\tcrosstab.setColumnHeaderStyle(headerStyle);\r\n\t\tcrosstab.setColumnTotalheaderStyle(totalHeaderStyle);\r\n\t\tcrosstab.setColumnTotalStyle(totalStyle);\r\n\t\treturn this;\r\n\t}", "private void addColumns(MpxjTreeNode parentNode, Table table)\n {\n for (Column column : table.getColumns())\n {\n final Column c = column;\n MpxjTreeNode childNode = new MpxjTreeNode(column)\n {\n @Override public String toString()\n {\n return c.getTitle();\n }\n };\n parentNode.add(childNode);\n }\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 }", "private String escapeQuotes(String value)\n {\n StringBuilder sb = new StringBuilder();\n int length = value.length();\n char c;\n\n sb.append('\"');\n for (int index = 0; index < length; index++)\n {\n c = value.charAt(index);\n sb.append(c);\n\n if (c == '\"')\n {\n sb.append('\"');\n }\n }\n sb.append('\"');\n\n return (sb.toString());\n }" ]
This method extracts data for a single resource from a GanttProject file. @param gpResource resource data
[ "private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1));\n mpxjResource.setName(gpResource.getName());\n mpxjResource.setEmailAddress(gpResource.getContacts());\n mpxjResource.setText(1, gpResource.getPhone());\n mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction()));\n\n net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate();\n if (gpRate != null)\n {\n mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS));\n }\n readResourceCustomFields(gpResource, mpxjResource);\n m_eventManager.fireResourceReadEvent(mpxjResource);\n }" ]
[ "public void addFieldDescriptor(FieldDescriptor fld)\r\n {\r\n fld.setClassDescriptor(this); // BRJ\r\n if (m_FieldDescriptions == null)\r\n {\r\n m_FieldDescriptions = new FieldDescriptor[1];\r\n m_FieldDescriptions[0] = fld;\r\n }\r\n else\r\n {\r\n int size = m_FieldDescriptions.length;\r\n FieldDescriptor[] tmpArray = new FieldDescriptor[size + 1];\r\n System.arraycopy(m_FieldDescriptions, 0, tmpArray, 0, size);\r\n tmpArray[size] = fld;\r\n m_FieldDescriptions = tmpArray;\r\n // 2. Sort fields according to their getOrder() Property\r\n Arrays.sort(m_FieldDescriptions, FieldDescriptor.getComparator());\r\n }\r\n\r\n m_fieldDescriptorNameMap = null;\r\n m_PkFieldDescriptors = null;\r\n m_nonPkFieldDescriptors = null;\r\n m_lockingFieldDescriptors = null;\r\n m_RwFieldDescriptors = null;\r\n m_RwNonPkFieldDescriptors = null;\r\n }", "public static void createMetadataCache(SlotReference slot, int playlistId, File cache) throws Exception {\n createMetadataCache(slot, playlistId, cache, null);\n }", "public static String compressedListOfPartitionsInZone(final Cluster cluster, int zoneId) {\n Map<Integer, Integer> idToRunLength = PartitionBalanceUtils.getMapOfContiguousPartitions(cluster,\n zoneId);\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n boolean first = true;\n Set<Integer> sortedInitPartitionIds = new TreeSet<Integer>(idToRunLength.keySet());\n for(int initPartitionId: sortedInitPartitionIds) {\n if(!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n\n int runLength = idToRunLength.get(initPartitionId);\n if(runLength == 1) {\n sb.append(initPartitionId);\n } else {\n int endPartitionId = (initPartitionId + runLength - 1)\n % cluster.getNumberOfPartitions();\n sb.append(initPartitionId).append(\"-\").append(endPartitionId);\n }\n }\n sb.append(\"]\");\n\n return sb.toString();\n }", "public static <T extends Comparable<T>> int compareLists(List<T> list1, List<T> list2) {\r\n if (list1 == null && list2 == null)\r\n return 0;\r\n if (list1 == null || list2 == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n int size1 = list1.size();\r\n int size2 = list2.size();\r\n int size = Math.min(size1, size2);\r\n for (int i = 0; i < size; i++) {\r\n int c = list1.get(i).compareTo(list2.get(i));\r\n if (c != 0)\r\n return c;\r\n }\r\n if (size1 < size2)\r\n return -1;\r\n if (size1 > size2)\r\n return 1;\r\n return 0;\r\n }", "private static List< Block > createBlocks(int[] data, boolean debug) {\r\n\r\n List< Block > blocks = new ArrayList<>();\r\n Block current = null;\r\n\r\n for (int i = 0; i < data.length; i++) {\r\n EncodingMode mode = chooseMode(data[i]);\r\n if ((current != null && current.mode == mode) &&\r\n (mode != EncodingMode.NUM || current.length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {\r\n current.length++;\r\n } else {\r\n current = new Block(mode);\r\n blocks.add(current);\r\n }\r\n }\r\n\r\n if (debug) {\r\n System.out.println(\"Initial block pattern: \" + blocks);\r\n }\r\n\r\n smoothBlocks(blocks);\r\n\r\n if (debug) {\r\n System.out.println(\"Final block pattern: \" + blocks);\r\n }\r\n\r\n return blocks;\r\n }", "private void verifiedCopyFile(File sourceFile, File destFile) throws IOException {\n if(!destFile.exists()) {\n destFile.createNewFile();\n }\n\n FileInputStream source = null;\n FileOutputStream destination = null;\n LogVerificationInputStream verifyStream = null;\n try {\n source = new FileInputStream(sourceFile);\n destination = new FileOutputStream(destFile);\n verifyStream = new LogVerificationInputStream(env, source, sourceFile.getName());\n\n final byte[] buf = new byte[LOGVERIFY_BUFSIZE];\n\n while(true) {\n final int len = verifyStream.read(buf);\n if(len < 0) {\n break;\n }\n destination.write(buf, 0, len);\n }\n\n } finally {\n if(verifyStream != null) {\n verifyStream.close();\n }\n if(destination != null) {\n destination.close();\n }\n }\n }", "private static String[] readArgsFile(String argsFile) throws IOException {\n final ArrayList<String> lines = new ArrayList<String>();\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(\n new FileInputStream(argsFile), \"UTF-8\"));\n try {\n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (!line.isEmpty() && !line.startsWith(\"#\")) {\n lines.add(line);\n }\n }\n } finally {\n reader.close();\n }\n return lines.toArray(new String [lines.size()]);\n }", "public GVRRenderData setDrawMode(int drawMode) {\n if (drawMode != GL_POINTS && drawMode != GL_LINES\n && drawMode != GL_LINE_STRIP && drawMode != GL_LINE_LOOP\n && drawMode != GL_TRIANGLES && drawMode != GL_TRIANGLE_STRIP\n && drawMode != GL_TRIANGLE_FAN) {\n throw new IllegalArgumentException(\n \"drawMode must be one of GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP.\");\n }\n NativeRenderData.setDrawMode(getNative(), drawMode);\n return this;\n }", "synchronized void stop(Integer timeout) {\n final InternalState required = this.requiredState;\n if(required != InternalState.STOPPED) {\n this.requiredState = InternalState.STOPPED;\n ROOT_LOGGER.stoppingServer(serverName);\n // Only send the stop operation if the server is started\n if (internalState == InternalState.SERVER_STARTED) {\n internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);\n } else {\n transition(false);\n }\n }\n }" ]
Returns an Organization @param organizationId String @return DbOrganization
[ "public DbOrganization getOrganization(final String organizationId) {\n final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);\n\n if(dbOrganization == null){\n throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)\n .entity(\"Organization \" + organizationId + \" does not exist.\").build());\n }\n\n return dbOrganization;\n }" ]
[ "public void addAttribute(String attributeName, String attributeValue)\r\n {\r\n if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))\r\n {\r\n final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);\r\n jdbcProperties.setProperty(jdbcPropertyName, attributeValue);\r\n }\r\n else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))\r\n {\r\n final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);\r\n dbcpProperties.setProperty(dbcpPropertyName, attributeValue);\r\n }\r\n else\r\n {\r\n super.addAttribute(attributeName, attributeValue);\r\n }\r\n }", "public boolean setOverrideRepeatCount(String pathName, String methodName, Integer ordinal, Integer repeatCount) {\n try {\n String methodId = getOverrideIdForMethodName(methodName).toString();\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"profileIdentifier\", this._profileName),\n new BasicNameValuePair(\"ordinal\", ordinal.toString()),\n new BasicNameValuePair(\"repeatNumber\", repeatCount.toString())\n };\n\n JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + \"/\" + methodId, params));\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }", "public final void setWeekDays(SortedSet<WeekDay> weekDays) {\n\n m_weekDays.clear();\n if (null != weekDays) {\n m_weekDays.addAll(weekDays);\n }\n }", "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 }", "@SuppressWarnings(\"WeakerAccess\")\n public boolean isPlaying() {\n if (packetBytes.length >= 212) {\n return (packetBytes[STATUS_FLAGS] & PLAYING_FLAG) > 0;\n } else {\n final PlayState1 state = getPlayState1();\n return state == PlayState1.PLAYING || state == PlayState1.LOOPING ||\n (state == PlayState1.SEARCHING && getPlayState2() == PlayState2.MOVING);\n }\n }", "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 static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException {\n StringTokenizer tokenizer = new StringTokenizer(str, \",\");\n int n = tokenizer.countTokens();\n int[] list = new int[n];\n for (int i = 0; i < n; i++) {\n String token = tokenizer.nextToken();\n list[i] = Integer.parseInt(token);\n }\n return list;\n }", "public void ifDoesntHaveMemberTag(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean result = false;\r\n\r\n if (getCurrentField() != null) {\r\n if (!hasTag(attributes, FOR_FIELD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n else if (getCurrentMethod() != null) {\r\n if (!hasTag(attributes, FOR_METHOD)) {\r\n result = true;\r\n generate(template);\r\n }\r\n }\r\n if (!result) {\r\n String error = attributes.getProperty(\"error\");\r\n\r\n if (error != null) {\r\n getEngine().print(error);\r\n }\r\n }\r\n }", "public static void append(File file, Object text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file, true);\n if (!file.exists()) {\n writeUTF16BomIfRequired(charset, out);\n }\n writer = new OutputStreamWriter(out, charset);\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 }" ]
Remove a named object
[ "void unbind(String key)\r\n {\r\n NamedEntry entry = new NamedEntry(key, null, false);\r\n localUnbind(key);\r\n addForDeletion(entry);\r\n }" ]
[ "protected AbstractColumn buildSimpleImageColumn() {\n\t\tImageColumn column = new ImageColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\treturn column;\n\t}", "public Object lookup(Identity oid)\r\n {\r\n Object ret = null;\r\n if (oid != null)\r\n {\r\n ObjectCache cache = getCache(oid, null, METHOD_LOOKUP);\r\n if (cache != null)\r\n {\r\n ret = cache.lookup(oid);\r\n }\r\n }\r\n return ret;\r\n }", "public ItemRequest<CustomField> delete(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"DELETE\");\n }", "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 }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<CopticDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<CopticDate>) super.localDateTime(temporal);\n }", "public void addRegexRoute(String urlPattern, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {\n addRoute(new Route(urlPattern, true), actorClass);\n }", "public void unlinkFK(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds)\n {\n setFKField(targetObject, cld, rds, null);\n }", "public void abort()\r\n {\r\n /*\r\n do nothing if already rolledback\r\n */\r\n if (txStatus == Status.STATUS_NO_TRANSACTION\r\n || txStatus == Status.STATUS_UNKNOWN\r\n || txStatus == Status.STATUS_ROLLEDBACK)\r\n {\r\n log.info(\"Nothing to abort, tx is not active - status is \" + TxUtil.getStatusString(txStatus));\r\n return;\r\n }\r\n // check status of tx\r\n if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED &&\r\n txStatus != Status.STATUS_MARKED_ROLLBACK)\r\n {\r\n throw new IllegalStateException(\"Illegal state for abort call, state was '\" + TxUtil.getStatusString(txStatus) + \"'\");\r\n }\r\n if(log.isEnabledFor(Logger.INFO))\r\n {\r\n log.info(\"Abort transaction was called on tx \" + this);\r\n }\r\n try\r\n {\r\n try\r\n {\r\n doAbort();\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while abort transaction, will be skipped\", e);\r\n }\r\n\r\n // used in managed environments, ignored in non-managed\r\n this.implementation.getTxManager().abortExternalTx(this);\r\n\r\n try\r\n {\r\n if(hasBroker() && getBroker().isInTransaction())\r\n {\r\n getBroker().abortTransaction();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Error while do abort used broker instance, will be skipped\", e);\r\n }\r\n }\r\n finally\r\n {\r\n txStatus = Status.STATUS_ROLLEDBACK;\r\n // cleanup things, e.g. release all locks\r\n doClose();\r\n }\r\n }", "public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedCostContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedCost> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 16; // 16 byte header\n int blockSize = 20;\n double previousTotalCost = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n index += blockSize;\n\n while (index + blockSize <= data.length)\n {\n Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);\n double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;\n if (!costEquals(previousTotalCost, currentTotalCost))\n {\n TimephasedCost cost = new TimephasedCost();\n cost.setStart(blockStartDate);\n cost.setFinish(blockEndDate);\n cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));\n\n if (list == null)\n {\n list = new LinkedList<TimephasedCost>();\n }\n list.add(cost);\n //System.out.println(cost);\n\n previousTotalCost = currentTotalCost;\n }\n\n blockStartDate = blockEndDate;\n index += blockSize;\n }\n\n if (list != null)\n {\n result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }" ]
Creates the database. @throws PlatformException If some error occurred
[ "public void createDB() throws PlatformException\r\n {\r\n if (_creationScript == null)\r\n {\r\n createCreationScript();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueDataModelTask modelTask = new TorqueDataModelTask();\r\n File tmpDir = null;\r\n File scriptFile = null;\r\n \r\n try\r\n {\r\n tmpDir = new File(getWorkDir(), \"schemas\");\r\n tmpDir.mkdir();\r\n\r\n scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);\r\n\r\n writeCompressedText(scriptFile, _creationScript);\r\n\r\n project.setBasedir(tmpDir.getAbsolutePath());\r\n\r\n // we use the ant task 'sql' to perform the creation script\r\n\t SQLExec sqlTask = new SQLExec();\r\n\t SQLExec.OnError onError = new SQLExec.OnError();\r\n\t\r\n\t onError.setValue(\"continue\");\r\n\t sqlTask.setProject(project);\r\n\t sqlTask.setAutocommit(true);\r\n\t sqlTask.setDriver(_jcd.getDriver());\r\n\t sqlTask.setOnerror(onError);\r\n\t sqlTask.setUserid(_jcd.getUserName());\r\n\t sqlTask.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n\t sqlTask.setUrl(getDBCreationUrl());\r\n\t sqlTask.setSrc(scriptFile);\r\n\t sqlTask.execute();\r\n\r\n\t deleteDir(tmpDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if ((tmpDir != null) && tmpDir.exists())\r\n {\r\n try\r\n {\r\n scriptFile.delete();\r\n }\r\n catch (NullPointerException e) \r\n {\r\n LoggerFactory.getLogger(this.getClass()).error(\"NPE While deleting scriptFile [\" + scriptFile.getName() + \"]\", e);\r\n }\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }" ]
[ "public base_response login(String username, String password, Long timeout) throws Exception\n\t{\n\t\tthis.set_credential(username, password);\n\t\tthis.set_timeout(timeout);\n\t\treturn this.login();\n\t}", "public void addExtentClass(String newExtentClassName)\r\n {\r\n extentClassNames.add(newExtentClassName);\r\n if(m_repository != null) m_repository.addExtent(newExtentClassName, this);\r\n }", "public static int readInt(byte[] bytes, int offset) {\n return (((bytes[offset + 0] & 0xff) << 24) | ((bytes[offset + 1] & 0xff) << 16)\n | ((bytes[offset + 2] & 0xff) << 8) | (bytes[offset + 3] & 0xff));\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 void transformPose(Matrix4f trans)\n {\n Bone bone = mBones[0];\n\n bone.LocalMatrix.set(trans);\n bone.WorldMatrix.set(trans);\n bone.Changed = WORLD_POS | WORLD_ROT;\n mNeedSync = true;\n sync();\n }", "public static <T> T callConstructor(Class<T> klass, Object[] args) {\n Class<?>[] klasses = new Class[args.length];\n for(int i = 0; i < args.length; i++)\n klasses[i] = args[i].getClass();\n return callConstructor(klass, klasses, args);\n }", "public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) {\r\n Expression method = methodCall.getMethod();\r\n\r\n // !important: performance enhancement\r\n boolean IS_NAME_MATCH = false;\r\n if (method instanceof ConstantExpression) {\r\n if (((ConstantExpression) method).getValue() instanceof String) {\r\n IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern);\r\n }\r\n }\r\n\r\n if (IS_NAME_MATCH && numArguments != null) {\r\n return AstUtil.getMethodArguments(methodCall).size() == numArguments;\r\n }\r\n return IS_NAME_MATCH;\r\n }", "private String checkinScriptCommand() {\n\n String exportModules = \"\";\n if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {\n StringBuffer exportModulesParam = new StringBuffer();\n for (String moduleName : m_modulesToExport) {\n exportModulesParam.append(\" \").append(moduleName);\n }\n exportModulesParam.replace(0, 1, \" \\\"\");\n exportModulesParam.append(\"\\\" \");\n exportModules = \" --modules \" + exportModulesParam.toString();\n\n }\n String commitMessage = \"\";\n if (m_commitMessage != null) {\n commitMessage = \" -msg \\\"\" + m_commitMessage.replace(\"\\\"\", \"\\\\\\\"\") + \"\\\"\";\n }\n String gitUserName = \"\";\n if (m_gitUserName != null) {\n if (m_gitUserName.trim().isEmpty()) {\n gitUserName = \" --ignore-default-git-user-name\";\n } else {\n gitUserName = \" --git-user-name \\\"\" + m_gitUserName + \"\\\"\";\n }\n }\n String gitUserEmail = \"\";\n if (m_gitUserEmail != null) {\n if (m_gitUserEmail.trim().isEmpty()) {\n gitUserEmail = \" --ignore-default-git-user-email\";\n } else {\n gitUserEmail = \" --git-user-email \\\"\" + m_gitUserEmail + \"\\\"\";\n }\n }\n String autoPullBefore = \"\";\n if (m_autoPullBefore != null) {\n autoPullBefore = m_autoPullBefore.booleanValue() ? \" --pull-before \" : \" --no-pull-before\";\n }\n String autoPullAfter = \"\";\n if (m_autoPullAfter != null) {\n autoPullAfter = m_autoPullAfter.booleanValue() ? \" --pull-after \" : \" --no-pull-after\";\n }\n String autoPush = \"\";\n if (m_autoPush != null) {\n autoPush = m_autoPush.booleanValue() ? \" --push \" : \" --no-push\";\n }\n String exportFolder = \" --export-folder \\\"\" + m_currentConfiguration.getModuleExportPath() + \"\\\"\";\n String exportMode = \" --export-mode \" + m_currentConfiguration.getExportMode();\n String excludeLibs = \"\";\n if (m_excludeLibs != null) {\n excludeLibs = m_excludeLibs.booleanValue() ? \" --exclude-libs\" : \" --no-exclude-libs\";\n }\n String commitMode = \"\";\n if (m_commitMode != null) {\n commitMode = m_commitMode.booleanValue() ? \" --commit\" : \" --no-commit\";\n }\n String ignoreUncleanMode = \"\";\n if (m_ignoreUnclean != null) {\n ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? \" --ignore-unclean\" : \" --no-ignore-unclean\";\n }\n String copyAndUnzip = \"\";\n if (m_copyAndUnzip != null) {\n copyAndUnzip = m_copyAndUnzip.booleanValue() ? \" --copy-and-unzip\" : \" --no-copy-and-unzip\";\n }\n\n String configFilePath = m_currentConfiguration.getFilePath();\n\n return \"\\\"\"\n + DEFAULT_SCRIPT_FILE\n + \"\\\"\"\n + exportModules\n + commitMessage\n + gitUserName\n + gitUserEmail\n + autoPullBefore\n + autoPullAfter\n + autoPush\n + exportFolder\n + exportMode\n + excludeLibs\n + commitMode\n + ignoreUncleanMode\n + copyAndUnzip\n + \" \\\"\"\n + configFilePath\n + \"\\\"\";\n }", "public static bridgegroup_vlan_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Writes batch of data to the source @param batch @throws InterruptedException
[ "@Override\n public Object put(List<Map.Entry> batch) throws InterruptedException {\n if (initializeClusterSource()) {\n return clusterSource.put(batch);\n }\n return null;\n }" ]
[ "public void add(int ds, Object value) throws SerializationException, InvalidDataSetException {\r\n\t\tif (value == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tDataSetInfo dsi = dsiFactory.create(ds);\r\n\t\tbyte[] data = dsi.getSerializer().serialize(value, activeSerializationContext);\r\n\t\tDataSet dataSet = new DefaultDataSet(dsi, data);\r\n\t\tdataSets.add(dataSet);\r\n\t}", "public int getMinutesPerMonth()\n {\n return m_minutesPerMonth == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerMonth()) : m_minutesPerMonth.intValue();\n }", "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 }", "public static base_response reset(nitro_service client, Interface resource) throws Exception {\n\t\tInterface resetresource = new Interface();\n\t\tresetresource.id = resource.id;\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}", "public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)\n {\n CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;\n\n switch (NumberHelper.getInt(value))\n {\n case 0:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n }\n\n return (result);\n }", "protected String extractHeaderComment( File xmlFile )\n throws MojoExecutionException\n {\n\n try\n {\n SAXParser parser = SAXParserFactory.newInstance().newSAXParser();\n SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler();\n parser.setProperty( \"http://xml.org/sax/properties/lexical-handler\", handler );\n parser.parse( xmlFile, handler );\n return handler.getHeaderComment();\n }\n catch ( Exception e )\n {\n throw new MojoExecutionException( \"Failed to parse XML from \" + xmlFile, e );\n }\n }", "public void remove(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if (index >= 0) {\n m_container.removeComponent(row);\n }\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }", "void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {\n assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;\n\n final PatchingHistory history = context.getHistory();\n for (final PatchElement element : patch.getElements()) {\n\n final PatchElementProvider provider = element.getProvider();\n final String name = provider.getName();\n final boolean addOn = provider.isAddOn();\n\n final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);\n final String cumulativePatchID = target.getCumulativePatchID();\n if (Constants.BASE.equals(cumulativePatchID)) {\n reenableRolledBackInBase(target);\n continue;\n }\n\n boolean found = false;\n final PatchingHistory.Iterator iterator = history.iterator();\n while (iterator.hasNextCP()) {\n final PatchingHistory.Entry entry = iterator.nextCP();\n final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);\n\n if (patchId != null && patchId.equals(cumulativePatchID)) {\n final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);\n for (final PatchElement originalElement : original.getElements()) {\n if (name.equals(originalElement.getProvider().getName())\n && addOn == originalElement.getProvider().isAddOn()) {\n PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);\n }\n }\n // Record a loader to have access to the current modules\n final DirectoryStructure structure = target.getDirectoryStructure();\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);\n context.recordContentLoader(patchId, loader);\n found = true;\n break;\n }\n }\n if (!found) {\n throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);\n }\n\n reenableRolledBackInBase(target);\n }\n }", "public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) {\n return (Set<E>) collectify(mapper, source, Set.class, targetElementType);\n }" ]
Generates a unique signature for an annotated type. Members without annotations are omitted to reduce the length of the signature @param <X> @param annotatedType @return hash of a signature for a concrete annotated type
[ "public static <X> String createTypeId(AnnotatedType<X> annotatedType) {\n String id = createTypeId(annotatedType.getJavaClass(), annotatedType.getAnnotations(), annotatedType.getMethods(), annotatedType.getFields(), annotatedType.getConstructors());\n String hash = hash(id);\n MetadataLogger.LOG.tracef(\"Generated AnnotatedType id hash for %s: %s\", id, hash);\n return hash;\n }" ]
[ "public static DMatrixRBlock initializeQ(DMatrixRBlock Q,\n int numRows , int numCols , int blockLength ,\n boolean compact) {\n int minLength = Math.min(numRows,numCols);\n if( compact ) {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,minLength,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != minLength ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n } else {\n if( Q == null ) {\n Q = new DMatrixRBlock(numRows,numRows,blockLength);\n MatrixOps_DDRB.setIdentity(Q);\n } else {\n if( Q.numRows != numRows || Q.numCols != numRows ) {\n throw new IllegalArgumentException(\"Unexpected matrix dimension. Found \"+Q.numRows+\" \"+Q.numCols);\n } else {\n MatrixOps_DDRB.setIdentity(Q);\n }\n }\n }\n return Q;\n }", "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 static DoubleMatrix cholesky(DoubleMatrix A) {\n DoubleMatrix result = A.dup();\n int info = NativeBlas.dpotrf('U', A.rows, result.data, 0, A.rows);\n if (info < 0) {\n throw new LapackArgumentException(\"DPOTRF\", -info);\n } else if (info > 0) {\n throw new LapackPositivityException(\"DPOTRF\", \"Minor \" + info + \" was negative. Matrix must be positive definite.\");\n }\n clearLower(result);\n return result;\n }", "public static cachepolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_policybinding_binding obj = new cachepolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_policybinding_binding response[] = (cachepolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String takeWhile(GString self, @ClosureParams(value=SimpleType.class, options=\"char\") Closure condition) {\n return (String) takeWhile(self.toString(), condition);\n }", "private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,\n BeatGrid beatGrid) {\n final int beatNumber = newDeviceUpdate.getBeatNumber();\n final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();\n\n // If we have just stopped, see if we are near a cue (assuming that information is available), and if so,\n // the best assumption is that the DJ jumped to that cue.\n if (lastTrackUpdate.playing && noLongerPlaying) {\n final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);\n if (jumpedTo != null) return jumpedTo.cueTime;\n }\n\n // Handle the special case where we were not playing either in the previous or current update, but the DJ\n // might have jumped to a different place in the track.\n if (!lastTrackUpdate.playing) {\n if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved\n return lastTrackUpdate.milliseconds;\n } else {\n if (noLongerPlaying) { // Have jumped without playing.\n if (beatNumber < 0) {\n return -1; // We don't know the position any more; weird to get into this state and still have a grid?\n }\n // As a heuristic, assume we are right before the beat?\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n }\n }\n }\n\n // One way or another, we are now playing.\n long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;\n long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);\n long interpolated = (lastTrackUpdate.reverse)?\n (lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;\n if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {\n return interpolated; // Our calculations still look plausible\n }\n // The player has jumped or drifted somewhere unexpected, correct.\n if (newDeviceUpdate.isPlayingForwards()) {\n return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);\n } else {\n return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));\n }\n }", "private static void dumpRelationList(List<Relation> relations)\n {\n if (relations != null && relations.isEmpty() == false)\n {\n if (relations.size() > 1)\n {\n System.out.print('\"');\n }\n boolean first = true;\n for (Relation relation : relations)\n {\n if (!first)\n {\n System.out.print(',');\n }\n first = false;\n System.out.print(relation.getTargetTask().getID());\n Duration lag = relation.getLag();\n if (relation.getType() != RelationType.FINISH_START || lag.getDuration() != 0)\n {\n System.out.print(relation.getType());\n }\n\n if (lag.getDuration() != 0)\n {\n if (lag.getDuration() > 0)\n {\n System.out.print(\"+\");\n }\n System.out.print(lag);\n }\n }\n if (relations.size() > 1)\n {\n System.out.print('\"');\n }\n }\n }", "public IExternalAccess getAgentsExternalAccess(String agent_name) {\n\n return cmsService.getExternalAccess(getAgentID(agent_name)).get(\n new ThreadSuspendable());\n }", "public static vpnvserver_auditnslogpolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_auditnslogpolicy_binding obj = new vpnvserver_auditnslogpolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_auditnslogpolicy_binding response[] = (vpnvserver_auditnslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Calculates the text height for the indicator value and sets its x-coordinate.
[ "private void calculateValueTextHeight() {\n Rect valueRect = new Rect();\n Rect legendRect = new Rect();\n String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? \" \" + mIndicatorTextUnit : \"\");\n\n // calculate the boundaries for both texts\n mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect);\n mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect);\n\n // calculate string positions in overlay\n mValueTextHeight = valueRect.height();\n mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding);\n mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f));\n\n int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width();\n\n // check if text reaches over screen\n if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) {\n mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding));\n mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding));\n } else {\n mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding);\n }\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 String findAlias(String entityAlias, List<String> propertyPathWithoutAlias) {\n\t\tRelationshipAliasTree aliasTree = relationshipAliases.get( entityAlias );\n\t\tif ( aliasTree == null ) {\n\t\t\treturn null;\n\t\t}\n\t\tRelationshipAliasTree associationAlias = aliasTree;\n\t\tfor ( int i = 0; i < propertyPathWithoutAlias.size(); i++ ) {\n\t\t\tassociationAlias = associationAlias.findChild( propertyPathWithoutAlias.get( i ) );\n\t\t\tif ( associationAlias == null ) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn associationAlias.getAlias();\n\t}", "public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)\n\t\t\tthrows XPathExpressionException, IOException {\n\t\tDocument dom = DomUtils.asDocument(domStr);\n\t\treturn evaluateXpathExpression(dom, xpathExpr);\n\t}", "SimpleJsonEncoder appendToJSONUnquoted(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n sb.append(value);\n }\n return this;\n }", "public ParallelTaskBuilder setTargetHostsFromJsonPath(String jsonPath,\n String sourcePath, HostsSourceType sourceType)\n throws TargetHostsLoadException {\n\n this.targetHosts = targetHostBuilder.setTargetHostsFromJsonPath(jsonPath, sourcePath,\n sourceType);\n return this;\n\n }", "private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }", "public B importContext(AbstractContext context){\n Objects.requireNonNull(context);\n return importContext(context, false);\n }", "public static String getCorrelationId(Message message) {\n String correlationId = (String) message.get(CORRELATION_ID_KEY);\n if(null == correlationId) {\n correlationId = readCorrelationId(message);\n }\n if(null == correlationId) {\n correlationId = readCorrelationIdSoap(message);\n }\n return correlationId;\n }", "public static <T> Set<T> toSet(Iterator<? extends T> iterator) {\n\t\treturn Sets.newLinkedHashSet(toIterable(iterator));\n\t}" ]
This method writes task data to a Planner file. @throws JAXBException on xml creation errors
[ "private void writeTasks() throws JAXBException\n {\n Tasks tasks = m_factory.createTasks();\n m_plannerProject.setTasks(tasks);\n List<net.sf.mpxj.planner.schema.Task> taskList = tasks.getTask();\n for (Task task : m_projectFile.getChildTasks())\n {\n writeTask(task, taskList);\n }\n }" ]
[ "public static void main(String[] args) {\n try {\n new StartMain(args).go();\n } catch(Throwable t) {\n WeldSELogger.LOG.error(\"Application exited with an exception\", t);\n System.exit(1);\n }\n }", "public static String nameFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).name() : null;\n }", "private void setQR(DMatrixRMaj Q , DMatrixRMaj R , int growRows ) {\n if( Q.numRows != Q.numCols ) {\n throw new IllegalArgumentException(\"Q should be square.\");\n }\n\n this.Q = Q;\n this.R = R;\n\n m = Q.numRows;\n n = R.numCols;\n\n if( m+growRows > maxRows || n > maxCols ) {\n if( autoGrow ) {\n declareInternalData(m+growRows,n);\n } else {\n throw new IllegalArgumentException(\"Autogrow has been set to false and the maximum number of rows\" +\n \" or columns has been exceeded.\");\n }\n }\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 static int toIntWithDefault(String value, int defaultValue) {\n\n int result = defaultValue;\n try {\n result = Integer.parseInt(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n // Do nothing, return default.\n }\n return result;\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}", "public static int byteSizeOf(Bitmap bitmap) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n return bitmap.getAllocationByteCount();\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {\n return bitmap.getByteCount();\n } else {\n return bitmap.getRowBytes() * bitmap.getHeight();\n }\n }", "public static <T extends Publisher> T getPublisher(AbstractProject<?, ?> project, Class<T> type) {\n // Search for a publisher of the given type in the project and return it if found:\n T publisher = new PublisherFindImpl<T>().find(project, type);\n if (publisher != null) {\n return publisher;\n }\n // If not found, the publisher might be wrapped by a \"Flexible Publish\" publisher. The below searches for it inside the\n // Flexible Publisher:\n publisher = new PublisherFlexible<T>().find(project, type);\n return publisher;\n }", "public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {\n io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);\n return new Processor(p);\n }" ]
A simple convinience function that decomposes the matrix but automatically checks the input ti make sure is not being modified. @param decomp Decomposition which is being wrapped @param M THe matrix being decomposed. @param <T> Matrix type. @return If the decomposition was successful or not.
[ "public static <T extends DMatrix> boolean decomposeSafe(DecompositionInterface<T> decomp, T M ) {\n if( decomp.inputModified() ) {\n return decomp.decompose(M.<T>copy());\n } else {\n return decomp.decompose(M);\n }\n }" ]
[ "public static final <T> T getSingle( Iterable<T> it ) {\n if( ! it.iterator().hasNext() )\n return null;\n\n final Iterator<T> iterator = it.iterator();\n T o = iterator.next();\n if(iterator.hasNext())\n throw new IllegalStateException(\"Found multiple items in iterator over \" + o.getClass().getName() );\n\n return o;\n }", "public static lbvserver get(nitro_service service, String name) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\tobj.set_name(name);\n\t\tlbvserver response = (lbvserver) obj.get_resource(service);\n\t\treturn response;\n\t}", "private static Predicate join(final String joinWord, final List<Predicate> preds) {\n return new Predicate() {\n public void init(AbstractSqlCreator creator) {\n for (Predicate p : preds) {\n p.init(creator);\n }\n }\n public String toSql() {\n StringBuilder sb = new StringBuilder()\n .append(\"(\");\n boolean first = true;\n for (Predicate p : preds) {\n if (!first) {\n sb.append(\" \").append(joinWord).append(\" \");\n }\n sb.append(p.toSql());\n first = false;\n }\n return sb.append(\")\").toString();\n }\n };\n }", "public static GVRSceneObject loadModel(final GVRContext gvrContext,\n final String modelFile) throws IOException {\n return loadModel(gvrContext, modelFile, new HashMap<String, Integer>());\n }", "private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }", "public static boolean isTodoItem(final Document todoItemDoc) {\n return todoItemDoc.containsKey(ID_KEY)\n && todoItemDoc.containsKey(TASK_KEY)\n && todoItemDoc.containsKey(CHECKED_KEY);\n }", "public static Node removePartitionsFromNode(final Node node,\n final Set<Integer> donatedPartitions) {\n List<Integer> deepCopy = new ArrayList<Integer>(node.getPartitionIds());\n deepCopy.removeAll(donatedPartitions);\n return updateNode(node, deepCopy);\n }", "@SuppressWarnings(\"deprecation\")\n @RequestMapping(value = \"/api/backup\", method = RequestMethod.GET)\n public\n @ResponseBody\n String getBackup(Model model, HttpServletResponse response) throws Exception {\n response.addHeader(\"Content-Disposition\", \"attachment; filename=backup.json\");\n response.setContentType(\"application/json\");\n\n Backup backup = BackupService.getInstance().getBackupData();\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();\n\n return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);\n }", "public static base_response add(nitro_service client, appfwjsoncontenttype resource) throws Exception {\n\t\tappfwjsoncontenttype addresource = new appfwjsoncontenttype();\n\t\taddresource.jsoncontenttypevalue = resource.jsoncontenttypevalue;\n\t\taddresource.isregex = resource.isregex;\n\t\treturn addresource.add_resource(client);\n\t}" ]
Controls whether we report that we are playing. This will only have an impact when we are sending status and beat packets. @param playing {@code true} if we should seem to be playing
[ "public void setPlaying(boolean playing) {\n\n if (this.playing.get() == playing) {\n return;\n }\n\n this.playing.set(playing);\n\n if (playing) {\n metronome.jumpToBeat(whereStopped.get().getBeat());\n if (isSendingStatus()) { // Need to also start the beat sender.\n beatSender.set(new BeatSender(metronome));\n }\n } else {\n final BeatSender activeSender = beatSender.get();\n if (activeSender != null) { // We have a beat sender we need to stop.\n activeSender.shutDown();\n beatSender.set(null);\n }\n whereStopped.set(metronome.getSnapshot());\n }\n }" ]
[ "public static CharSequence getAt(CharSequence text, IntRange range) {\n return getAt(text, (Range) range);\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 }", "public String getHostAddress() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostAddress();\n }\n return ((InetAddress)addr).getHostAddress();\n }", "private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {\n final String DUMMY_PROP=\"dummywrite\";\n instance.put(DUMMY_PROP,\"test\");\n instance.flush();\n instance.remove(DUMMY_PROP);\n instance.flush();\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal);\n }", "public static ServiceName moduleServiceName(ModuleIdentifier identifier) {\n if (!identifier.getName().startsWith(MODULE_PREFIX)) {\n throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);\n }\n return MODULE_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());\n }", "public static base_response add(nitro_service client, dnsaaaarec resource) throws Exception {\n\t\tdnsaaaarec addresource = new dnsaaaarec();\n\t\taddresource.hostname = resource.hostname;\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.ttl = resource.ttl;\n\t\treturn addresource.add_resource(client);\n\t}", "public void beforeBatch(PreparedStatement stmt) throws PlatformException\r\n {\r\n // Check for Oracle batching support\r\n final Method methodSetExecuteBatch;\r\n final Method methodSendBatch;\r\n methodSetExecuteBatch = ClassHelper.getMethod(stmt, \"setExecuteBatch\", PARAM_TYPE_INTEGER);\r\n methodSendBatch = ClassHelper.getMethod(stmt, \"sendBatch\", null);\r\n\r\n final boolean statementBatchingSupported = methodSetExecuteBatch != null && methodSendBatch != null;\r\n if (statementBatchingSupported)\r\n {\r\n try\r\n {\r\n // Set number of statements per batch\r\n methodSetExecuteBatch.invoke(stmt, PARAM_STATEMENT_BATCH_SIZE);\r\n m_batchStatementsInProgress.put(stmt, methodSendBatch);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new PlatformException(e.getLocalizedMessage(), e);\r\n }\r\n }\r\n else\r\n {\r\n super.beforeBatch(stmt);\r\n }\r\n }", "public static base_responses add(nitro_service client, gslbservice resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice addresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new gslbservice();\n\t\t\t\taddresources[i].servicename = resources[i].servicename;\n\t\t\t\taddresources[i].cnameentry = resources[i].cnameentry;\n\t\t\t\taddresources[i].ip = resources[i].ip;\n\t\t\t\taddresources[i].servername = resources[i].servername;\n\t\t\t\taddresources[i].servicetype = resources[i].servicetype;\n\t\t\t\taddresources[i].port = resources[i].port;\n\t\t\t\taddresources[i].publicip = resources[i].publicip;\n\t\t\t\taddresources[i].publicport = resources[i].publicport;\n\t\t\t\taddresources[i].maxclient = resources[i].maxclient;\n\t\t\t\taddresources[i].healthmonitor = resources[i].healthmonitor;\n\t\t\t\taddresources[i].sitename = resources[i].sitename;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].cip = resources[i].cip;\n\t\t\t\taddresources[i].cipheader = resources[i].cipheader;\n\t\t\t\taddresources[i].sitepersistence = resources[i].sitepersistence;\n\t\t\t\taddresources[i].cookietimeout = resources[i].cookietimeout;\n\t\t\t\taddresources[i].siteprefix = resources[i].siteprefix;\n\t\t\t\taddresources[i].clttimeout = resources[i].clttimeout;\n\t\t\t\taddresources[i].svrtimeout = resources[i].svrtimeout;\n\t\t\t\taddresources[i].maxbandwidth = resources[i].maxbandwidth;\n\t\t\t\taddresources[i].downstateflush = resources[i].downstateflush;\n\t\t\t\taddresources[i].maxaaausers = resources[i].maxaaausers;\n\t\t\t\taddresources[i].monthreshold = resources[i].monthreshold;\n\t\t\t\taddresources[i].hashid = resources[i].hashid;\n\t\t\t\taddresources[i].comment = resources[i].comment;\n\t\t\t\taddresources[i].appflowlog = resources[i].appflowlog;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Checks whether a built of the indices is necessary. @param cms The appropriate CmsObject instance. @return true, if the spellcheck indices have to be rebuilt, otherwise false
[ "public static boolean updatingIndexNecessesary(CmsObject cms) {\n\n // Set request to the offline project.\n setCmsOfflineProject(cms);\n\n // Check whether the spellcheck index directories are empty.\n // If they are, the index has to be built obviously.\n if (isSolrSpellcheckIndexDirectoryEmpty()) {\n return true;\n }\n\n // Compare the most recent date of a dictionary with the oldest timestamp\n // that determines when an index has been built.\n long dateMostRecentDictionary = getMostRecentDate(cms);\n long dateOldestIndexWrite = getOldestIndexDate(cms);\n\n return dateMostRecentDictionary > dateOldestIndexWrite;\n }" ]
[ "public Column getColumn(String columnName) {\n if (columnName == null) {\n return null;\n }\n for (Column column : columns) {\n if (columnName.equals(column.getData())) {\n return column;\n }\n }\n return null;\n }", "public Rule CriteriaOnlyFindQuery() {\n\t\treturn Sequence( !peek().isCliQuery(), JsonParameter( JsonObject() ) , peek().setOperation( Operation.FIND ), peek().setCriteria( match() ) );\n\t}", "@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}", "public void getDataDTD(Writer output) throws DataTaskException\r\n {\r\n try\r\n {\r\n output.write(\"<!ELEMENT dataset (\\n\");\r\n for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)\r\n {\r\n String elementName = (String)it.next();\r\n\r\n output.write(\" \");\r\n output.write(elementName);\r\n output.write(\"*\");\r\n output.write(it.hasNext() ? \" |\\n\" : \"\\n\");\r\n }\r\n output.write(\")>\\n<!ATTLIST dataset\\n name CDATA #REQUIRED\\n>\\n\");\r\n for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)\r\n {\r\n String elementName = (String)it.next();\r\n List classDescs = _preparedModel.getClassDescriptorsMappingTo(elementName);\r\n\r\n if (classDescs == null)\r\n {\r\n output.write(\"\\n<!-- Indirection table\");\r\n }\r\n else\r\n {\r\n output.write(\"\\n<!-- Mapped to : \");\r\n for (Iterator classDescIt = classDescs.iterator(); classDescIt.hasNext();)\r\n {\r\n ClassDescriptor classDesc = (ClassDescriptor)classDescIt.next();\r\n \r\n output.write(classDesc.getClassNameOfObject());\r\n if (classDescIt.hasNext())\r\n {\r\n output.write(\"\\n \");\r\n }\r\n }\r\n }\r\n output.write(\" -->\\n<!ELEMENT \");\r\n output.write(elementName);\r\n output.write(\" EMPTY>\\n<!ATTLIST \");\r\n output.write(elementName);\r\n output.write(\"\\n\");\r\n\r\n for (Iterator attrIt = _preparedModel.getAttributeNames(elementName); attrIt.hasNext();)\r\n {\r\n String attrName = (String)attrIt.next();\r\n\r\n output.write(\" \");\r\n output.write(attrName);\r\n output.write(\" CDATA #\");\r\n output.write(_preparedModel.isRequired(elementName, attrName) ? \"REQUIRED\" : \"IMPLIED\");\r\n output.write(\"\\n\");\r\n }\r\n output.write(\">\\n\");\r\n }\r\n }\r\n catch (IOException ex)\r\n {\r\n throw new DataTaskException(ex);\r\n }\r\n }", "public static void writeObject(File file, Object object) throws IOException {\n FileOutputStream fileOut = new FileOutputStream(file);\n ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));\n try {\n out.writeObject(object);\n out.flush();\n // Force sync\n fileOut.getFD().sync();\n } finally {\n IoUtils.safeClose(out);\n }\n }", "public static base_response add(nitro_service client, dnssuffix resource) throws Exception {\n\t\tdnssuffix addresource = new dnssuffix();\n\t\taddresource.Dnssuffix = resource.Dnssuffix;\n\t\treturn addresource.add_resource(client);\n\t}", "public ItemRequest<Section> delete(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"DELETE\");\n }", "public AnnotationVisitor visitLocalVariableAnnotation(int typeRef,\n TypePath typePath, Label[] start, Label[] end, int[] index,\n String desc, boolean visible) {\n if (mv != null) {\n return mv.visitLocalVariableAnnotation(typeRef, typePath, start,\n end, index, desc, visible);\n }\n return null;\n }", "public void moveDown(I_CmsEditableGroupRow row) {\n\n int index = m_container.getComponentIndex(row);\n if ((index >= 0) && (index < (m_container.getComponentCount() - 1))) {\n m_container.removeComponent(row);\n m_container.addComponent(row, index + 1);\n }\n updateButtonBars();\n }" ]
Returns the index of the first invalid character of the zone, or -1 if the zone is valid @param sequence @return
[ "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}" ]
[ "public static<A, B, C, Z> Function3<A, B, C, Z> lift(Func3<A, B, C, Z> f) {\n\treturn bridge.lift(f);\n }", "@SuppressWarnings(\"checkstyle:illegalcatch\")\n private boolean sendMessage(final byte[] messageToSend) {\n try {\n connectionPool.execute(new PooledObjectConsumer<TcpConnection>() {\n @Override\n public void accept(final TcpConnection tcpConnection) throws IOException {\n tcpConnection.write(messageToSend);\n }\n });\n } catch (final Exception e) {\n addError(String.format(\"Error sending message via tcp://%s:%s\",\n getGraylogHost(), getGraylogPort()), e);\n\n return false;\n }\n\n return true;\n }", "protected boolean appendWhereStatement(StringBuilder sb, List<ArgumentHolder> argList, WhereOperation operation)\n\t\t\tthrows SQLException {\n\t\tif (where == null) {\n\t\t\treturn operation == WhereOperation.FIRST;\n\t\t}\n\t\toperation.appendBefore(sb);\n\t\twhere.appendSql((addTableName ? getTableName() : null), sb, argList);\n\t\toperation.appendAfter(sb);\n\t\treturn false;\n\t}", "public static BoxStoragePolicyAssignment.Info getAssignmentForTarget(final BoxAPIConnection api,\n String resolvedForType, String resolvedForID) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"resolved_for_type\", resolvedForType)\n .appendParam(\"resolved_for_id\", resolvedForID);\n URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.GET);\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api,\n response.getJsonObject().get(\"entries\").asArray().get(0).asObject().get(\"id\").asString());\n BoxStoragePolicyAssignment.Info info = storagePolicyAssignment.new\n Info(response.getJsonObject().get(\"entries\").asArray().get(0).asObject());\n\n return info;\n }", "public void loadClass(String className) throws Exception {\n ClassInformation classInfo = classInformation.get(className);\n\n logger.info(\"Loading plugin.: {}, {}\", className, classInfo.pluginPath);\n\n // get URL for proxylib\n // need to load this also otherwise the annotations cannot be found later on\n File libFile = new File(proxyLibPath);\n URL libUrl = libFile.toURI().toURL();\n\n // store the last modified time of the plugin\n File pluginDirectoryFile = new File(classInfo.pluginPath);\n classInfo.lastModified = pluginDirectoryFile.lastModified();\n\n // load the plugin directory\n URL classURL = new File(classInfo.pluginPath).toURI().toURL();\n\n URL[] urls = new URL[] {classURL};\n URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());\n\n // load the class\n Class<?> cls = child.loadClass(className);\n\n // put loaded class into classInfo\n classInfo.loadedClass = cls;\n classInfo.loaded = true;\n\n classInformation.put(className, classInfo);\n\n logger.info(\"Loaded plugin: {}, {} method(s)\", cls.toString(), cls.getDeclaredMethods().length);\n }", "public void setVolume(float volume)\n {\n // Save this in case this audio source is not being played yet\n mVolume = volume;\n if (isPlaying() && (getSourceId() != GvrAudioEngine.INVALID_ID))\n {\n // This will actually work only if the sound file is being played\n mAudioListener.getAudioEngine().setSoundVolume(getSourceId(), getVolume());\n }\n }", "@UiThread\n public void expandParentRange(int startParentPosition, int parentCount) {\n int endParentPosition = startParentPosition + parentCount;\n for (int i = startParentPosition; i < endParentPosition; i++) {\n expandParent(i);\n }\n }", "public <V> V attach(final AttachmentKey<V> key, final V value) {\n assert key != null;\n return key.cast(contextAttachments.put(key, value));\n }", "public float getBitangentY(int vertex) {\n if (!hasTangentsAndBitangents()) {\n throw new IllegalStateException(\"mesh has no bitangents\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_bitangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }" ]
sets the initialization method for this descriptor
[ "private synchronized void setInitializationMethod(Method newMethod)\r\n {\r\n if (newMethod != null)\r\n {\r\n // make sure it's a no argument method\r\n if (newMethod.getParameterTypes().length > 0)\r\n {\r\n throw new MetadataException(\r\n \"Initialization methods must be zero argument methods: \"\r\n + newMethod.getClass().getName()\r\n + \".\"\r\n + newMethod.getName());\r\n }\r\n\r\n // make it accessible if it's not already\r\n if (!newMethod.isAccessible())\r\n {\r\n newMethod.setAccessible(true);\r\n }\r\n }\r\n this.initializationMethod = newMethod;\r\n }" ]
[ "protected void setBandsFinalHeight() {\n log.debug(\"Setting bands final height...\");\n\n List<JRBand> bands = new ArrayList<JRBand>();\n\n Utils.addNotNull(bands, design.getPageHeader());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getColumnHeader());\n Utils.addNotNull(bands, design.getColumnFooter());\n Utils.addNotNull(bands, design.getSummary());\n Utils.addNotNull(bands, design.getBackground());\n bands.addAll(((JRDesignSection) design.getDetailSection()).getBandsList());\n Utils.addNotNull(bands, design.getLastPageFooter());\n Utils.addNotNull(bands, design.getTitle());\n Utils.addNotNull(bands, design.getPageFooter());\n Utils.addNotNull(bands, design.getNoData());\n\n for (JRGroup jrgroup : design.getGroupsList()) {\n DJGroup djGroup = (DJGroup) getReferencesMap().get(jrgroup.getName());\n JRDesignSection headerSection = (JRDesignSection) jrgroup.getGroupHeaderSection();\n JRDesignSection footerSection = (JRDesignSection) jrgroup.getGroupFooterSection();\n if (djGroup != null) {\n for (JRBand headerBand : headerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) headerBand, djGroup.getHeaderHeight(), djGroup.isFitHeaderHeightToContent());\n\n }\n for (JRBand footerBand : footerSection.getBandsList()) {\n setBandFinalHeight((JRDesignBand) footerBand, djGroup.getFooterHeight(), djGroup.isFitFooterHeightToContent());\n\n }\n } else {\n bands.addAll(headerSection.getBandsList());\n bands.addAll(footerSection.getBandsList());\n }\n }\n\n for (JRBand jrDesignBand : bands) {\n setBandFinalHeight((JRDesignBand) jrDesignBand);\n }\n }", "public ItemDocumentBuilder withSiteLink(String title, String siteKey,\n\t\t\tItemIdValue... badges) {\n\t\twithSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));\n\t\treturn this;\n\t}", "public void applyToBackground(View view) {\n if (mColorInt != 0) {\n view.setBackgroundColor(mColorInt);\n } else if (mColorRes != -1) {\n view.setBackgroundResource(mColorRes);\n }\n }", "public LBuffer slice(long from, long to) {\n if(from > to)\n throw new IllegalArgumentException(String.format(\"invalid range %,d to %,d\", from, to));\n\n long size = to - from;\n LBuffer b = new LBuffer(size);\n copyTo(from, b, 0, size);\n return b;\n }", "private static int getSqlInLimit()\r\n {\r\n try\r\n {\r\n PersistenceBrokerConfiguration config = (PersistenceBrokerConfiguration) PersistenceBrokerFactory\r\n .getConfigurator().getConfigurationFor(null);\r\n return config.getSqlInLimit();\r\n }\r\n catch (ConfigurationException e)\r\n {\r\n return 200;\r\n }\r\n }", "@Override\n public void setCursorDepth(float depth)\n {\n super.setCursorDepth(depth);\n if (mRayModel != null)\n {\n mRayModel.getTransform().setScaleZ(mCursorDepth);\n }\n }", "private void deleteByQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\n {\n if (logger.isDebugEnabled())\n {\n logger.debug(\"deleteByQuery \" + cld.getClassNameOfObject() + \", \" + query);\n }\n\n if (query instanceof QueryBySQL)\n {\n String sql = ((QueryBySQL) query).getSql();\n this.dbAccess.executeUpdateSQL(sql, cld);\n }\n else\n {\n // if query is Identity based transform it to a criteria based query first\n if (query instanceof QueryByIdentity)\n {\n QueryByIdentity qbi = (QueryByIdentity) query;\n Object oid = qbi.getExampleObject();\n // make sure it's an Identity\n if (!(oid instanceof Identity))\n {\n oid = serviceIdentity().buildIdentity(oid);\n }\n query = referencesBroker.getPKQuery((Identity) oid);\n }\n\n if (!cld.isInterface())\n {\n this.dbAccess.executeDelete(query, cld);\n }\n\n // if class is an extent, we have to delete all extent classes too\n String lastUsedTable = cld.getFullTableName();\n if (cld.isExtent())\n {\n Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();\n\n while (extents.hasNext())\n {\n ClassDescriptor extCld = (ClassDescriptor) extents.next();\n\n // read same table only once\n if (!extCld.getFullTableName().equals(lastUsedTable))\n {\n lastUsedTable = extCld.getFullTableName();\n this.dbAccess.executeDelete(query, extCld);\n }\n }\n }\n\n }\n }", "public void delete(final String referenceId) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaDelete<PrintJobStatusExtImpl> delete =\n builder.createCriteriaDelete(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);\n delete.where(builder.equal(root.get(\"referenceId\"), referenceId));\n getSession().createQuery(delete).executeUpdate();\n }", "protected void calculateBarPositions(int _DataSize) {\n\n int dataSize = mScrollEnabled ? mVisibleBars : _DataSize;\n float barWidth = mBarWidth;\n float margin = mBarMargin;\n\n if (!mFixedBarWidth) {\n // calculate the bar width if the bars should be dynamically displayed\n barWidth = (mAvailableScreenSize / _DataSize) - margin;\n } else {\n\n if(_DataSize < mVisibleBars) {\n dataSize = _DataSize;\n }\n\n // calculate margin between bars if the bars have a fixed width\n float cumulatedBarWidths = barWidth * dataSize;\n float remainingScreenSize = mAvailableScreenSize - cumulatedBarWidths;\n\n margin = remainingScreenSize / dataSize;\n }\n\n boolean isVertical = this instanceof VerticalBarChart;\n\n int calculatedSize = (int) ((barWidth * _DataSize) + (margin * _DataSize));\n int contentWidth = isVertical ? mGraphWidth : calculatedSize;\n int contentHeight = isVertical ? calculatedSize : mGraphHeight;\n\n mContentRect = new Rect(0, 0, contentWidth, contentHeight);\n mCurrentViewport = new RectF(0, 0, mGraphWidth, mGraphHeight);\n\n calculateBounds(barWidth, margin);\n mLegend.invalidate();\n mGraph.invalidate();\n }" ]
Try to provide an escaped, ready-to-use shell line to repeat a given command line.
[ "private String escapeAndJoin(String[] commandline) {\n // TODO: we should try to escape special characters here, depending on the OS.\n StringBuilder b = new StringBuilder();\n Pattern specials = Pattern.compile(\"[\\\\ ]\");\n for (String arg : commandline) {\n if (b.length() > 0) {\n b.append(\" \");\n }\n\n if (specials.matcher(arg).find()) {\n b.append('\"').append(arg).append('\"');\n } else {\n b.append(arg);\n }\n }\n return b.toString();\n }" ]
[ "public static boolean reconnectContext(RedirectException re, CommandContext ctx) {\n boolean reconnected = false;\n try {\n ConnectionInfo info = ctx.getConnectionInfo();\n ControllerAddress address = null;\n if (info != null) {\n address = info.getControllerAddress();\n }\n if (address != null && isHttpsRedirect(re, address.getProtocol())) {\n LOG.debug(\"Trying to reconnect an http to http upgrade\");\n try {\n ctx.connectController();\n reconnected = true;\n } catch (Exception ex) {\n LOG.warn(\"Exception reconnecting\", ex);\n // Proper https redirect but error.\n // Ignoring it.\n }\n }\n } catch (URISyntaxException ex) {\n LOG.warn(\"Invalid URI: \", ex);\n // OK, invalid redirect.\n }\n return reconnected;\n }", "public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }", "List<Message> getFullTrackList(final CdjStatus.TrackSourceSlot slot, final Client client, final int sortOrder)\n throws IOException, InterruptedException, TimeoutException {\n // Send the metadata menu request\n if (client.tryLockingForMenuOperations(MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n Message response = client.menuRequest(Message.KnownType.TRACK_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slot,\n new NumberField(sortOrder));\n final long count = response.getMenuResultsCount();\n if (count == Message.NO_MENU_RESULTS_AVAILABLE || count == 0) {\n return Collections.emptyList();\n }\n\n // Gather all the metadata menu items\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, response);\n }\n finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock the player for menu operations\");\n }\n }", "public static void pushImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pushImageCmd(imageTag).withAuthConfig(authConfig).exec(new PushImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\n }\n }", "public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc));\n final ClientResponse response = resource\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = FAILED_TO_GET_CORPORATE_FILTERS;\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<String>>(){});\n\n }", "public static base_response delete(nitro_service client, String selectorname) throws Exception {\n\t\tcacheselector deleteresource = new cacheselector();\n\t\tdeleteresource.selectorname = selectorname;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "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}", "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}", "public void process(ProjectFile file, Var2Data varData, byte[] fixedData) throws IOException\n {\n Props props = getProps(varData);\n //System.out.println(props);\n if (props != null)\n {\n String viewName = MPPUtility.removeAmpersands(props.getUnicodeString(VIEW_NAME));\n byte[] listData = props.getByteArray(VIEW_CONTENTS);\n List<Integer> uniqueIdList = new LinkedList<Integer>();\n if (listData != null)\n {\n for (int index = 0; index < listData.length; index += 4)\n {\n Integer uniqueID = Integer.valueOf(MPPUtility.getInt(listData, index));\n\n //\n // Ensure that we have a valid task, and that if we have and\n // ID of zero, this is the first task shown.\n //\n if (file.getTaskByUniqueID(uniqueID) != null && (uniqueID.intValue() != 0 || index == 0))\n {\n uniqueIdList.add(uniqueID);\n }\n }\n }\n\n int filterID = MPPUtility.getShort(fixedData, 128);\n\n ViewState state = new ViewState(file, viewName, uniqueIdList, filterID);\n file.getViews().setViewState(state);\n }\n }" ]
Tests the string edit distance function.
[ "public static void main(String[] args) {\r\n\r\n String[] s = {\"there once was a man\", \"this one is a manic\", \"hey there\", \"there once was a mane\", \"once in a manger.\", \"where is one match?\", \"Jo3seph Smarr!\", \"Joseph R Smarr\"};\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.println(\"s1: \" + s[i]);\r\n System.out.println(\"s2: \" + s[j]);\r\n System.out.println(\"edit distance: \" + editDistance(s[i], s[j]));\r\n System.out.println(\"LCS: \" + longestCommonSubstring(s[i], s[j]));\r\n System.out.println(\"LCCS: \" + longestCommonContiguousSubstring(s[i], s[j]));\r\n System.out.println();\r\n }\r\n }\r\n }" ]
[ "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 ClosableIterator<Tuple> callStoredProcedure(EmbeddedCacheManager embeddedCacheManager, String storedProcedureName, ProcedureQueryParameters queryParameters, ClassLoaderService classLoaderService ) {\n\t\tvalidate( queryParameters );\n\t\tCache<String, String> cache = embeddedCacheManager.getCache( STORED_PROCEDURES_CACHE_NAME, true );\n\t\tString className = cache.getOrDefault( storedProcedureName, storedProcedureName );\n\t\tCallable<?> callable = instantiate( storedProcedureName, className, classLoaderService );\n\t\tsetParams( storedProcedureName, queryParameters, callable );\n\t\tObject res = execute( storedProcedureName, embeddedCacheManager, callable );\n\t\treturn extractResultSet( storedProcedureName, res );\n\t}", "static void doDifference(\n Map<String, String> left,\n Map<String, String> right,\n Map<String, String> onlyOnLeft,\n Map<String, String> onlyOnRight,\n Map<String, String> updated\n ) {\n onlyOnRight.clear();\n onlyOnRight.putAll(right);\n for (Map.Entry<String, String> entry : left.entrySet()) {\n String leftKey = entry.getKey();\n String leftValue = entry.getValue();\n if (right.containsKey(leftKey)) {\n String rightValue = onlyOnRight.remove(leftKey);\n if (!leftValue.equals(rightValue)) {\n updated.put(leftKey, leftValue);\n }\n } else {\n onlyOnLeft.put(leftKey, leftValue);\n }\n }\n }", "private Component createMainComponent() throws IOException, CmsException {\n\n VerticalLayout mainComponent = new VerticalLayout();\n mainComponent.setSizeFull();\n mainComponent.addStyleName(\"o-message-bundle-editor\");\n m_table = createTable();\n Panel navigator = new Panel();\n navigator.setSizeFull();\n navigator.setContent(m_table);\n navigator.addActionHandler(new CmsMessageBundleEditorTypes.TableKeyboardHandler(m_table));\n navigator.addStyleName(\"v-panel-borderless\");\n\n mainComponent.addComponent(m_options.getOptionsComponent());\n mainComponent.addComponent(navigator);\n mainComponent.setExpandRatio(navigator, 1f);\n m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());\n return mainComponent;\n }", "private UserAlias getUserAlias(Object attribute)\r\n\t{\r\n\t\tif (m_userAlias != null)\r\n\t\t{\r\n\t\t\treturn m_userAlias;\r\n\t\t}\r\n\t\tif (!(attribute instanceof String))\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_alias == null)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (m_aliasPath == null)\r\n\t\t{\r\n\t\t\tboolean allPathsAliased = true;\r\n\t\t\treturn new UserAlias(m_alias, (String)attribute, allPathsAliased);\r\n\t\t}\r\n\t\treturn new UserAlias(m_alias, (String)attribute, m_aliasPath);\r\n\t}", "private static void addEcc(int[] fullstream, int[] datastream, int version, int data_cw, int blocks) {\n\n int ecc_cw = QR_TOTAL_CODEWORDS[version - 1] - data_cw;\n int short_data_block_length = data_cw / blocks;\n int qty_long_blocks = data_cw % blocks;\n int qty_short_blocks = blocks - qty_long_blocks;\n int ecc_block_length = ecc_cw / blocks;\n int i, j, length_this_block, posn;\n\n int[] data_block = new int[short_data_block_length + 2];\n int[] ecc_block = new int[ecc_block_length + 2];\n int[] interleaved_data = new int[data_cw + 2];\n int[] interleaved_ecc = new int[ecc_cw + 2];\n\n posn = 0;\n\n for (i = 0; i < blocks; i++) {\n if (i < qty_short_blocks) {\n length_this_block = short_data_block_length;\n } else {\n length_this_block = short_data_block_length + 1;\n }\n\n for (j = 0; j < ecc_block_length; j++) {\n ecc_block[j] = 0;\n }\n\n for (j = 0; j < length_this_block; j++) {\n data_block[j] = datastream[posn + j];\n }\n\n ReedSolomon rs = new ReedSolomon();\n rs.init_gf(0x11d);\n rs.init_code(ecc_block_length, 0);\n rs.encode(length_this_block, data_block);\n\n for (j = 0; j < ecc_block_length; j++) {\n ecc_block[j] = rs.getResult(j);\n }\n\n for (j = 0; j < short_data_block_length; j++) {\n interleaved_data[(j * blocks) + i] = data_block[j];\n }\n\n if (i >= qty_short_blocks) {\n interleaved_data[(short_data_block_length * blocks) + (i - qty_short_blocks)] = data_block[short_data_block_length];\n }\n\n for (j = 0; j < ecc_block_length; j++) {\n interleaved_ecc[(j * blocks) + i] = ecc_block[ecc_block_length - j - 1];\n }\n\n posn += length_this_block;\n }\n\n for (j = 0; j < data_cw; j++) {\n fullstream[j] = interleaved_data[j];\n }\n for (j = 0; j < ecc_cw; j++) {\n fullstream[j + data_cw] = interleaved_ecc[j];\n }\n }", "public static void plotCharts(List<Chart> charts){\n\t\tint numRows =1;\n\t\tint numCols =1;\n\t\tif(charts.size()>1){\n\t\t\tnumRows = (int) Math.ceil(charts.size()/2.0);\n\t\t\tnumCols = 2;\n\t\t}\n\t\t\n\t final JFrame frame = new JFrame(\"\");\n\t frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);\n frame.getContentPane().setLayout(new GridLayout(numRows, numCols));\n\t for (Chart chart : charts) {\n\t if (chart != null) {\n\t JPanel chartPanel = new XChartPanel(chart);\n\t frame.add(chartPanel);\n\t }\n\t else {\n\t JPanel chartPanel = new JPanel();\n\t frame.getContentPane().add(chartPanel);\n\t }\n\n\t }\n\t // Display the window.\n frame.pack();\n frame.setVisible(true);\n\t}", "public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}", "public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{\n\t\thanode_routemonitor_binding obj = new hanode_routemonitor_binding();\n\t\tobj.set_id(id);\n\t\thanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Get a property as a string or defaultValue. @param key the property name @param defaultValue the default value
[ "@Override\n public final String optString(final String key, final String defaultValue) {\n String result = optString(key);\n return result == null ? defaultValue : result;\n }" ]
[ "private void populateResourceAssignment(Record record, ResourceAssignment assignment) throws MPXJException\n {\n //\n // Handle malformed MPX files - ensure that we can locate the resource\n // using either the Unique ID attribute or the ID attribute.\n //\n Resource resource = m_projectFile.getResourceByUniqueID(record.getInteger(12));\n if (resource == null)\n {\n resource = m_projectFile.getResourceByID(record.getInteger(0));\n }\n\n assignment.setUnits(record.getUnits(1));\n assignment.setWork(record.getDuration(2));\n assignment.setBaselineWork(record.getDuration(3));\n assignment.setActualWork(record.getDuration(4));\n assignment.setOvertimeWork(record.getDuration(5));\n assignment.setCost(record.getCurrency(6));\n assignment.setBaselineCost(record.getCurrency(7));\n assignment.setActualCost(record.getCurrency(8));\n assignment.setStart(record.getDateTime(9));\n assignment.setFinish(record.getDateTime(10));\n assignment.setDelay(record.getDuration(11));\n\n //\n // Calculate the remaining work\n //\n Duration work = assignment.getWork();\n Duration actualWork = assignment.getActualWork();\n if (work != null && actualWork != null)\n {\n if (work.getUnits() != actualWork.getUnits())\n {\n actualWork = actualWork.convertUnits(work.getUnits(), m_projectFile.getProjectProperties());\n }\n\n assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));\n }\n\n if (resource != null)\n {\n assignment.setResourceUniqueID(resource.getUniqueID());\n resource.addResourceAssignment(assignment);\n }\n\n m_eventManager.fireAssignmentReadEvent(assignment);\n }", "public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }", "public static final Color getColor(byte[] data, int offset)\n {\n Color result = null;\n\n if (getByte(data, offset + 3) == 0)\n {\n int r = getByte(data, offset);\n int g = getByte(data, offset + 1);\n int b = getByte(data, offset + 2);\n result = new Color(r, g, b);\n }\n\n return result;\n }", "public static FullTypeSignature getTypeSignature(String typeSignatureString,\n\t\t\tboolean useInternalFormFullyQualifiedName) {\n\t\tString key;\n\t\tif (!useInternalFormFullyQualifiedName) {\n\t\t\tkey = typeSignatureString.replace('.', '/')\n\t\t\t\t\t.replace('$', '.');\n\t\t} else {\n\t\t\tkey = typeSignatureString;\n\t\t}\n\n\t\t// we always use the internal form as a key for cache\n\t\tFullTypeSignature typeSignature = typeSignatureCache\n\t\t\t\t.get(key);\n\t\tif (typeSignature == null) {\n\t\t\tClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser(\n\t\t\t\t\ttypeSignatureString);\n\t\t\ttypeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);\n\t\t\ttypeSignature = typeSignatureParser.parseTypeSignature();\n\t\t\ttypeSignatureCache.put(typeSignatureString, typeSignature);\n\t\t}\n\t\treturn typeSignature;\n\t}", "private void createSimpleCubeSixMeshes(GVRContext gvrContext,\n boolean facingOut, String vertexDesc, ArrayList<GVRTexture> textureList)\n {\n GVRSceneObject[] children = new GVRSceneObject[6];\n GVRMesh[] meshes = new GVRMesh[6];\n GVRVertexBuffer vbuf = new GVRVertexBuffer(gvrContext, vertexDesc, SIMPLE_VERTICES.length / 3);\n\n if (facingOut)\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_OUTWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_OUTWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_OUTWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_OUTWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_OUTWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_OUTWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_OUTWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_OUTWARD_BOTTOM_INDICES);\n }\n else\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_INWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_INWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_INWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_INWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_INWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_INWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_INWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_INWARD_BOTTOM_INDICES);\n }\n\n for (int i = 0; i < 6; i++)\n {\n children[i] = new GVRSceneObject(gvrContext, meshes[i], textureList.get(i));\n addChildObject(children[i]);\n }\n\n // attached an empty renderData for parent object, so that we can set some common properties\n GVRRenderData renderData = new GVRRenderData(gvrContext);\n attachRenderData(renderData);\n }", "public boolean isFinished(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.executedProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\n }", "public String getAccuracyDescription(int numDigits) {\r\n NumberFormat nf = NumberFormat.getNumberInstance();\r\n nf.setMaximumFractionDigits(numDigits);\r\n Triple<Double, Integer, Integer> accu = getAccuracyInfo();\r\n return nf.format(accu.first()) + \" (\" + accu.second() + \"/\" + (accu.second() + accu.third()) + \")\";\r\n }", "public static <K, V> HashMap<K, V> newEmptyHashMap(Iterable<?> iterable) {\n if(iterable instanceof Collection<?>)\n return Maps.newHashMapWithExpectedSize(((Collection<?>) iterable).size());\n return Maps.newHashMap();\n }", "public static base_response update(nitro_service client, rnatparam resource) throws Exception {\n\t\trnatparam updateresource = new rnatparam();\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\treturn updateresource.update_resource(client);\n\t}" ]
Read a two byte integer from the data. @param offset current offset into data block @param data data block @return int value
[ "protected int readShort(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 16; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }" ]
[ "private AlbumArt findArtInMemoryCaches(DataReference artReference) {\n // First see if we can find the new track in the hot cache as a hot cue\n for (AlbumArt cached : hotCache.values()) {\n if (cached.artReference.equals(artReference)) { // Found a hot cue hit, use it.\n return cached;\n }\n }\n\n // Not in the hot cache, see if it is in our LRU cache\n return artCache.get(artReference);\n }", "public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable,\n final Collection<ControlFlowBlock> controlFlowBlocks) {\n return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks));\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<PaxDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<PaxDate>) super.zonedDateTime(temporal);\n }", "private FieldConversion[] getPkFieldConversion(ClassDescriptor cld)\r\n {\r\n FieldDescriptor[] pks = cld.getPkFields();\r\n FieldConversion[] fc = new FieldConversion[pks.length]; \r\n \r\n for (int i= 0; i < pks.length; i++)\r\n {\r\n fc[i] = pks[i].getFieldConversion();\r\n }\r\n \r\n return fc;\r\n }", "protected TokenList.Token parseBlockNoParentheses(TokenList tokens, Sequence sequence, boolean insideMatrixConstructor) {\n\n // search for matrix bracket operations\n if( !insideMatrixConstructor ) {\n parseBracketCreateMatrix(tokens, sequence);\n }\n\n // First create sequences from anything involving a colon\n parseSequencesWithColons(tokens, sequence );\n\n // process operators depending on their priority\n parseNegOp(tokens, sequence);\n parseOperationsL(tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.POWER, Symbol.ELEMENT_POWER}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.TIMES, Symbol.RDIVIDE, Symbol.LDIVIDE, Symbol.ELEMENT_TIMES, Symbol.ELEMENT_DIVIDE}, tokens, sequence);\n parseOperationsLR(new Symbol[]{Symbol.PLUS, Symbol.MINUS}, tokens, sequence);\n\n // Commas are used in integer sequences. Can be used to force to compiler to treat - as negative not\n // minus. They can now be removed since they have served their purpose\n stripCommas(tokens);\n\n // now construct rest of the lists and combine them together\n parseIntegerLists(tokens);\n parseCombineIntegerLists(tokens);\n\n if( !insideMatrixConstructor ) {\n if (tokens.size() > 1) {\n System.err.println(\"Remaining tokens: \"+tokens.size);\n TokenList.Token t = tokens.first;\n while( t != null ) {\n System.err.println(\" \"+t);\n t = t.next;\n }\n throw new RuntimeException(\"BUG in parser. There should only be a single token left\");\n }\n return tokens.first;\n } else {\n return null;\n }\n }", "private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException\n {\n net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();\n taskList.add(plannerTask);\n plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));\n plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));\n plannerTask.setName(getString(mpxjTask.getName()));\n plannerTask.setNote(mpxjTask.getNotes());\n plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));\n plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));\n plannerTask.setScheduling(getScheduling(mpxjTask.getType()));\n plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));\n if (mpxjTask.getMilestone())\n {\n plannerTask.setType(\"milestone\");\n }\n else\n {\n plannerTask.setType(\"normal\");\n }\n plannerTask.setWork(getDurationString(mpxjTask.getWork()));\n plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));\n\n ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();\n if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)\n {\n Constraint plannerConstraint = m_factory.createConstraint();\n plannerTask.setConstraint(plannerConstraint);\n if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)\n {\n plannerConstraint.setType(\"start-no-earlier-than\");\n }\n else\n {\n if (mpxjConstraintType == ConstraintType.MUST_START_ON)\n {\n plannerConstraint.setType(\"must-start-on\");\n }\n }\n\n plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));\n }\n\n //\n // Write predecessors\n //\n writePredecessors(mpxjTask, plannerTask);\n\n m_eventManager.fireTaskWrittenEvent(mpxjTask);\n\n //\n // Write child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();\n for (Task task : mpxjTask.getChildTasks())\n {\n writeTask(task, childTaskList);\n }\n }", "public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}", "public Map<String, EntityDocument> wbGetEntities(\n\t\t\tWbGetEntitiesActionData properties)\n\t\t\tthrows MediaWikiApiErrorException, IOException {\n\t\treturn wbGetEntities(properties.ids, properties.sites,\n\t\t\t\tproperties.titles, properties.props, properties.languages,\n\t\t\t\tproperties.sitefilter);\n\t}", "public void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }" ]
Returns a TypeConverter for a given class. @param cls The class for which the TypeConverter should be fetched.
[ "@SuppressWarnings(\"unchecked\")\n public static <E> TypeConverter<E> typeConverterFor(Class<E> cls) throws NoSuchTypeConverterException {\n TypeConverter<E> typeConverter = TYPE_CONVERTERS.get(cls);\n if (typeConverter == null) {\n throw new NoSuchTypeConverterException(cls);\n }\n return typeConverter;\n }" ]
[ "int getDelay(int n) {\n int delay = -1;\n if ((n >= 0) && (n < header.frameCount)) {\n delay = header.frames.get(n).delay;\n }\n return delay;\n }", "private boolean removeKeyForAllLanguages(String key) {\n\n try {\n if (hasDescriptor()) {\n lockDescriptor();\n }\n loadAllRemainingLocalizations();\n lockAllLocalizations(key);\n } catch (CmsException | IOException e) {\n LOG.warn(\"Not able lock all localications for bundle.\", e);\n return false;\n }\n if (!hasDescriptor()) {\n\n for (Entry<Locale, SortedProperties> entry : m_localizations.entrySet()) {\n SortedProperties localization = entry.getValue();\n if (localization.containsKey(key)) {\n localization.remove(key);\n m_changedTranslations.add(entry.getKey());\n }\n }\n }\n return true;\n }", "public T withAlias(String text, String languageCode) {\n\t\twithAlias(factory.getMonolingualTextValue(text, languageCode));\n\t\treturn getThis();\n\t}", "private void computeCosts() {\n cost = Long.MAX_VALUE;\n for (QueueItem item : queueSpans) {\n cost = Math.min(cost, item.sequenceSpans.spans.cost());\n }\n }", "public void seekToHolidayYear(String holidayString, String yearString) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary());\n }", "public void rotateWithPivot(float w, float x, float y, float z,\n float pivotX, float pivotY, float pivotZ) {\n getTransform().rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ);\n if (mTransformCache.rotateWithPivot(w, x, y, z, pivotX, pivotY, pivotZ)) {\n onTransformChanged();\n }\n }", "private String getHierarchyTable(ClassDescriptorDef classDef)\r\n {\r\n ArrayList queue = new ArrayList();\r\n String tableName = null;\r\n\r\n queue.add(classDef);\r\n\r\n while (!queue.isEmpty())\r\n {\r\n ClassDescriptorDef curClassDef = (ClassDescriptorDef)queue.get(0);\r\n\r\n queue.remove(0);\r\n\r\n if (curClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true))\r\n {\r\n if (tableName != null)\r\n {\r\n if (!tableName.equals(curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE)))\r\n {\r\n return null;\r\n }\r\n }\r\n else\r\n {\r\n tableName = curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE);\r\n }\r\n }\r\n for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();)\r\n {\r\n curClassDef = (ClassDescriptorDef)it.next();\r\n\r\n if (curClassDef.getReference(\"super\") == null)\r\n {\r\n queue.add(curClassDef);\r\n }\r\n }\r\n }\r\n return tableName;\r\n }", "public void validateOperations(final List<ModelNode> operations) {\n if (operations == null) {\n return;\n }\n\n for (ModelNode operation : operations) {\n try {\n validateOperation(operation);\n } catch (RuntimeException e) {\n if (exitOnError) {\n throw e;\n } else {\n System.out.println(\"---- Operation validation error:\");\n System.out.println(e.getMessage());\n }\n\n }\n }\n }", "public ExecutionChain setErrorCallback(ErrorCallback callback) {\n if (state.get() == State.RUNNING) {\n throw new IllegalStateException(\n \"Invalid while ExecutionChain is running\");\n }\n errorCallback = callback;\n return this;\n }" ]